repo_name
stringlengths
7
70
file_path
stringlengths
9
215
context
list
import_statement
stringlengths
47
10.3k
token_num
int64
643
100k
cropped_code
stringlengths
62
180k
all_code
stringlengths
62
224k
next_line
stringlengths
9
1.07k
gold_snippet_index
int64
0
117
created_at
stringlengths
25
25
level
stringclasses
9 values
EnigmaGuest/fnk-server
service-common/service-common-db/src/main/java/fun/isite/service/common/db/impl/BaseService.java
[ { "identifier": "LogicException", "path": "service-common/service-common-bean/src/main/java/fun/isite/service/common/bean/exception/LogicException.java", "snippet": "@EqualsAndHashCode(callSuper = true)\n@Data\npublic class LogicException extends RuntimeException{\n private String message;\n\n private IResponseCode code;\n\n public LogicException(String message) {\n this.message = message;\n }\n\n public LogicException(IResponseCode code) {\n this.code = code;\n }\n\n public LogicException(String message, IResponseCode code) {\n this.message = message;\n this.code = code;\n }\n}" }, { "identifier": "SplitPageDTO", "path": "service-common/service-common-db/src/main/java/fun/isite/service/common/db/dto/SplitPageDTO.java", "snippet": "@Data\n@Schema(name = \"SplitPageDTO\", description = \"分页查询条件\")\npublic class SplitPageDTO implements Serializable {\n /**\n * 当前页码\n */\n @Schema(name = \"page\", description = \"当前页码\")\n private int page = 1;\n\n /**\n * 每页数量大小\n */\n @Schema(name = \"pageSize\", description = \"每页数量大小\")\n private int pageSize = 10;\n\n /**\n * 正序查询\n */\n @Schema(name = \"asc\", description = \"正序查询\")\n private boolean asc = false;\n\n /**\n * 查询条件-ID\n */\n @Schema(name = \"id\", description = \"查询条件-ID\")\n private Long id;\n\n /**\n * 查询条件-创建时间\n */\n @Schema(name = \"createTime\", description = \"查询条件-创建时间\")\n private String createTime;\n\n /**\n * 查询条件-更新时间\n */\n @Schema(name = \"updateTime\", description = \"查询条件-更新时间\")\n private String updateTime;\n}" }, { "identifier": "BaseEntity", "path": "service-common/service-common-db/src/main/java/fun/isite/service/common/db/entity/BaseEntity.java", "snippet": "@EqualsAndHashCode(callSuper = true)\n@Data\n@NoArgsConstructor\n@AllArgsConstructor\npublic abstract class BaseEntity<T extends Model<T>> extends Model<T> {\n\n @TableId\n @JsonFormat(shape = JsonFormat.Shape.STRING)\n @Schema(name = \"id\", description = \"主键ID\")\n private String id;\n\n @TableField(fill = FieldFill.INSERT)\n @Schema(name = \"createTime\", description = \"创建时间\")\n private Date createTime;\n\n @TableField(fill = FieldFill.INSERT_UPDATE)\n @Schema(name = \"updatedTime\", description = \"最后更新时间\")\n private Date updateTime;\n\n @TableLogic\n @Schema(name = \"deleted\",description = \"删除标记\")\n @JsonIgnore\n private short deleted;\n}" }, { "identifier": "CustomBasicPageQuery", "path": "service-common/service-common-db/src/main/java/fun/isite/service/common/db/interf/CustomBasicPageQuery.java", "snippet": "public interface CustomBasicPageQuery<T> {\n /**\n * 自定义查询\n *\n * @param wrapper 条件包装\n */\n void query(LambdaQueryWrapper<T> wrapper);\n}" }, { "identifier": "IBaseService", "path": "service-common/service-common-db/src/main/java/fun/isite/service/common/db/service/IBaseService.java", "snippet": "public interface IBaseService<T extends BaseEntity<T>> extends IService<T> {\n\n T getById(Serializable id, @Nullable Consumer<LambdaQueryWrapper<T>> wrapperConsumer);\n\n /**\n * 获取第一条记录\n *\n * @param queryWrapper 查询条件\n * @return 查询结果\n */\n T getFirst(LambdaQueryWrapper<T> queryWrapper);\n\n /**\n * 获取第一条记录\n *\n * @param queryWrapper 查询条件\n * @return 查询结果\n * @see IBaseService#getFirst(LambdaQueryWrapper)\n */\n T getFirst(QueryWrapper<T> queryWrapper);\n\n\n /**\n * 根据字段匹配获取第一条数据 <br>\n * 例如:用户名在全局是唯一的,则为getByField(User::getUsername, username)\n *\n * @param field 字段\n * @param value 字段值\n * @return 记录\n */\n T getByField(SFunction<T, ?> field, String value);\n\n /**\n * 基础分页查询方法\n *\n * @param dto 查询数据\n * @param orderByField 排序字段\n * @param customQuery 自定义查询条件组合\n * @return 分页查询数据\n */\n PageVO<T> basicPage(SplitPageDTO dto, SFunction<T, ?> orderByField, CustomBasicPageQuery<T> customQuery);\n\n /**\n * 重置基础字段\n *\n * @param t 对象\n */\n void resetBaseField(T t);\n\n /**\n * 创建新的数据\n *\n * @param req 数据体\n * @return 数据\n */\n T create(T req);\n\n /**\n * 批量创建新的数据\n *\n * @param reqs 数据体\n * @return 数据\n */\n List<T> create(List<T> reqs);\n\n /**\n * 更新数据\n *\n * @param id ID\n * @param req 数据体\n * @return 数据\n */\n T update(String id, T req);\n\n\n /**\n * 更新数据\n *\n * @param id ID\n * @param req 数据体\n * @param query 附加查询条件\n * @return 数据\n */\n T update(String id, T req, @Nullable Consumer<LambdaQueryWrapper<T>> query);\n\n /**\n * 删除数据\n *\n * @param id ID\n */\n void removeSingle(String id);\n\n /**\n * 删除数据\n *\n * @param query 附加查询条件\n * @param id ID\n */\n void removeSingle(String id, @Nullable Consumer<LambdaQueryWrapper<T>> query);\n\n /**\n * 批量删除数据\n *\n * @param idList ID列表\n */\n void remove(List<String> idList);\n\n /**\n * 批量删除数据\n *\n * @param idList ID列表\n * @param query 附加查询条件\n */\n void remove(List<String> idList, @Nullable Consumer<LambdaQueryWrapper<T>> query);\n\n /**\n * 查询指定ID数据的详情\n *\n * @param id ID\n * @return 数据\n */\n T detail(String id);\n\n /**\n * 查询指定数据的详情\n *\n * @return 数据\n */\n T detail(Consumer<LambdaQueryWrapper<T>> consumer);\n\n /**\n * 查询指定ID数据的详情\n *\n * @param id ID\n * @param query 附加查询条件\n * @return 数据\n */\n T detail(String id, @Nullable Consumer<LambdaQueryWrapper<T>> query);\n\n\n\n /**\n * 获取最后一条记录根据创建时间\n *\n * @param customQuery 自定义查询\n * @return 记录\n */\n T getLastByCreateTime(@Nullable CustomBasicPageQuery<T> customQuery);\n\n /**\n * 获取服务模型名称\n *\n * @return 模型名称\n */\n String getServiceModelName();\n\n /**\n * 获取服务模型的缓存ID\n *\n * @param t 模型\n * @return 缓存ID\n */\n String getServiceModelCacheId(T t);\n\n /**\n * 获取模型hash存储的缓存建值\n * 当此值不为null时,为开启缓存\n *\n * @return 是否开启\n */\n String getModelHashCacheKey();\n\n\n\n\n\n /**\n * 分页数据转换为VO分页数据\n *\n * @param page 分页数据结构\n * @param targetClass 目标类\n * @param <V> 类型\n * @return VO分页数据结构\n */\n <V> PageVO<V> pageToVO(PageVO<T> page, Class<V> targetClass);\n}" }, { "identifier": "PageVO", "path": "service-common/service-common-db/src/main/java/fun/isite/service/common/db/vo/PageVO.java", "snippet": "@Data\n@Schema(name = \"PageVO\", description = \"分页查询结果\")\n@NoArgsConstructor\npublic class PageVO<T> {\n @Schema(name = \"records\", description = \"分页查询结果\")\n private List<T> records;\n\n @Schema(name = \"total\", description = \"总记录数\")\n private long total;\n\n @Schema(name = \"size\", description = \"每页数量大小\")\n private long size;\n\n @Schema(name = \"current\", description = \"当前页码\")\n private long current;\n\n @Schema(name = \"orders\", description = \"正序查询\")\n private List<OrderItem> orders;\n\n @Schema(name = \"searchCount\", description = \"是否进行 count 查询\")\n private Boolean searchCount;\n\n @Schema(name = \"pages\", description = \"总页数\")\n private long pages;\n\n public PageVO(IPage<T> page) {\n this.records = page.getRecords();\n this.total = page.getTotal();\n this.size = page.getSize();\n this.current = page.getCurrent();\n this.orders = page.orders();\n this.searchCount = page.searchCount();\n this.pages = page.getPages();\n }\n\n public PageVO(IPage<?> page, List<T> records) {\n this.records = records;\n this.total = page.getTotal();\n this.size = page.getSize();\n this.current = page.getCurrent();\n this.orders = page.orders();\n this.searchCount = page.searchCount();\n this.pages = page.getPages();\n }\n}" }, { "identifier": "AssertUtils", "path": "service-common/service-common-tools/src/main/java/fun/isite/service/common/tools/lang/AssertUtils.java", "snippet": "public class AssertUtils {\n public static void isTrue(Boolean expression, String message) {\n if (expression) {\n throw new LogicException(message);\n }\n }\n\n public static void isFalse(Boolean expression, String message) {\n if (!expression) {\n throw new LogicException(message);\n }\n }\n\n public static void isLeZero(Integer expression, String message) {\n if (expression <= 0) {\n throw new LogicException(message);\n }\n }\n\n public static void isNull(Object obj, String message) {\n if (obj == null || BeanUtil.isEmpty(obj)) {\n throw new LogicException(message);\n }\n }\n\n public static void isNotNull(Object obj, String message) {\n if (BeanUtil.isNotEmpty(obj)) {\n throw new LogicException(message);\n }\n }\n\n public static void isEmpty(String str, String message) {\n if (StrUtil.isEmpty(str)) {\n throw new LogicException(message);\n }\n }\n\n public static void isEmpty(Collection<?> collection, String message) {\n if (CollUtil.isEmpty(collection)) {\n throw new LogicException(message);\n }\n }\n\n public static void isEmpty(Iterable<?> iterable, String message) {\n if (CollUtil.isEmpty(iterable)) {\n throw new LogicException(message);\n }\n }\n\n public static void isEmpty(Map<?, ?> map, String message) {\n if (CollUtil.isEmpty(map)) {\n throw new LogicException(message);\n }\n }\n\n public static void isEmpty(List<?> list, String message) {\n if (CollUtil.isEmpty(list)) {\n throw new LogicException(message);\n }\n }\n\n public static void isBlank(String str, String message) {\n if (StrUtil.isBlank(str)) {\n throw new LogicException(message);\n }\n }\n}" }, { "identifier": "RedisUtils", "path": "service-common/service-common-tools/src/main/java/fun/isite/service/common/tools/utils/RedisUtils.java", "snippet": "@Component\npublic class RedisUtils {\n /**\n * 唯一实例\n */\n @Getter\n private static RedisUtils INSTANCE;\n\n public RedisUtils(RedisTemplate<String, Object> redisTemplate) {\n this.redisTemplate = redisTemplate;\n }\n\n @PostConstruct\n public void init() {\n INSTANCE = this;\n }\n\n @Getter\n private final RedisTemplate<String, Object> redisTemplate;\n\n\n /**\n * 判断key是否存在\n *\n * @param key 键\n * @return true 存在 false不存在\n */\n public boolean hasKey(String key) {\n Boolean res = redisTemplate.hasKey(key);\n if (res == null) {\n return false;\n }\n return res;\n }\n\n\n /**\n * 删除缓存\n *\n * @param key 可以传一个值 或多个\n */\n public void del(String... key) {\n if (key != null && key.length > 0) {\n if (key.length == 1) {\n redisTemplate.delete(key[0]);\n } else {\n redisTemplate.delete(Arrays.asList(key));\n }\n }\n }\n public void del(String key) {\n if (key != null ) {\n redisTemplate.delete(key);\n }\n }\n public void del(Collection<String> keys) {\n redisTemplate.delete(keys);\n }\n\n\n /**\n * 普通缓存获取\n *\n * @param key 键\n * @return 值\n */\n public Object get(String key) {\n return key == null ? null : redisTemplate.opsForValue().get(key);\n }\n\n /**\n * 普通缓存获取\n *\n * @param key 键\n * @return 值\n */\n public <T> T get(String key, Class<T> clazz) {\n Object res = this.get(key);\n if (res != null && res.getClass().equals(clazz)) {\n return clazz.cast(res);\n }\n return null;\n }\n\n /**\n * 普通缓存获取\n *\n * @param keys 键\n * @return 值\n */\n public <T> List<T> multiGet(Class<T> clazz, Collection<String> keys) {\n List<Object> res = redisTemplate.opsForValue().multiGet(keys);\n if (res != null) {\n List<T> result = new ArrayList<>();\n for (Object item : res) {\n if (item.getClass().equals(clazz)) {\n result.add(clazz.cast(item));\n }\n }\n return result;\n }\n return null;\n }\n\n /**\n * @param key 键\n * @return 值\n */\n public <T extends Serializable> List<T> getList(String key, Class<T> clazz) {\n List<Object> res = this.redisTemplate.opsForList().range(key, 0, -1);\n if (CollUtil.isNotEmpty(res)) {\n List<T> finalRes = new ArrayList<>();\n for (Object re : res) {\n if (re.getClass().equals(clazz)) {\n finalRes.add(clazz.cast(re));\n }\n }\n return finalRes;\n }\n return null;\n }\n\n /**\n * 设置LIST集合\n *\n * @param key\n * @param list\n * @return\n */\n public <T extends Serializable> boolean setList(String key, Collection<T> list) {\n try {\n if (list == null) {\n return false;\n }\n for (T t : list) {\n redisTemplate.opsForList().leftPush(key, t);\n }\n return true;\n } catch (Exception e) {\n e.printStackTrace();\n return false;\n }\n }\n\n public boolean lisAdd(String key, Object val) {\n try {\n redisTemplate.opsForList().leftPush(key, val);\n return true;\n } catch (Exception e) {\n e.printStackTrace();\n return false;\n }\n }\n\n /**\n * 普通缓存放入\n *\n * @param key 键\n * @param value 值\n * @return true成功 false失败\n */\n public <T extends Serializable> boolean set(String key, T value) {\n try {\n redisTemplate.opsForValue().set(key, value);\n return true;\n } catch (Exception e) {\n e.printStackTrace();\n return false;\n }\n }\n\n /**\n * 普通缓存放入并设置时间\n *\n * @param key 键\n * @param hKey 值\n * @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期\n * @return true成功 false 失败\n */\n public boolean set(String key, Serializable hKey, long time, TimeUnit timeUnit) {\n try {\n if (time > 0) {\n redisTemplate.opsForValue().set(key, hKey, time, timeUnit);\n } else {\n set(key, hKey);\n }\n return true;\n } catch (Exception e) {\n e.printStackTrace();\n return false;\n }\n }\n\n\n private <T> T objectToClass(Object object, Class<T> clazz) {\n if (object != null && object.getClass().equals(clazz)) {\n return clazz.cast(object);\n }\n return null;\n }\n\n /**\n * HashGet\n *\n * @param key 键 不能为null\n * @param hKey 项 不能为null\n * @return 值\n */\n public <T> T hGet(String key, Serializable hKey, Class<T> clazz) {\n return objectToClass(redisTemplate.opsForHash().get(key, String.valueOf(hKey)), clazz);\n }\n\n /**\n * 获取hashKey对应的所有键值\n *\n * @param key 键\n * @return 对应的多个键值\n */\n public <K, V> Map<K, V> hmGet(String key, Class<K> classK, Class<V> classV) {\n Map<Object, Object> entries = redisTemplate.opsForHash().entries(key);\n Map<K, V> res = new HashMap<>();\n for (Object o : entries.keySet()) {\n K k = objectToClass(o, classK);\n if (k != null) {\n V val = objectToClass(entries.get(o), classV);\n if (val != null) {\n res.put(k, val);\n }\n }\n }\n return res;\n }\n\n /**\n * HashSet\n *\n * @param key 键\n * @param map 对应多个键值\n * @return true 成功 false 失败\n */\n public <K extends Serializable, V extends Serializable> boolean hmSet(String key, Map<K, V> map) {\n try {\n redisTemplate.opsForHash().putAll(key, map);\n return true;\n } catch (Exception e) {\n e.printStackTrace();\n return false;\n }\n }\n\n /**\n * HashSet 并设置时间\n *\n * @param key 键\n * @param map 对应多个键值\n * @param time 时间(秒)\n * @return true成功 false失败\n */\n public <T extends Serializable, E extends Serializable> boolean hmSet(String key, Map<T, E> map, long time, TimeUnit timeUnit) {\n try {\n redisTemplate.opsForHash().putAll(key, map);\n if (time > 0) {\n redisTemplate.expire(key, time, timeUnit);\n }\n return true;\n } catch (Exception e) {\n e.printStackTrace();\n return false;\n }\n }\n\n /**\n * 向一张hash表中放入数据,如果不存在将创建\n *\n * @param key 键\n * @param hKey 项\n * @param value 值\n * @return true 成功 false失败\n */\n public boolean hSet(String key, Serializable hKey, Object value) {\n try {\n redisTemplate.opsForHash().put(key, String.valueOf(hKey), value);\n return true;\n } catch (Exception e) {\n e.printStackTrace();\n return false;\n }\n }\n\n /**\n * 向一张hash表中放入数据,如果不存在将创建\n *\n * @param key 键\n * @param hKey 项\n * @param value 值\n * @param time 时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间\n * @return true 成功 false失败\n */\n public boolean hSet(String key, Serializable hKey, Object value, long time, TimeUnit timeUnit) {\n try {\n redisTemplate.opsForHash().put(key, String.valueOf(hKey), value);\n if (time > 0) {\n redisTemplate.expire(key, time, timeUnit);\n }\n return true;\n } catch (Exception e) {\n e.printStackTrace();\n return false;\n }\n }\n\n /**\n * 删除hash表中的值\n *\n * @param key 键 不能为null\n * @param item 项 可以使多个 不能为null\n */\n public void hDel(String key, Object... item) {\n redisTemplate.opsForHash().delete(key, item);\n }\n\n /**\n * 判断hash表中是否有该项的值\n *\n * @param key 键 不能为null\n * @param item 项 不能为null\n * @return true 存在 false不存在\n */\n public boolean hHasKey(String key, Serializable item) {\n return redisTemplate.opsForHash().hasKey(key, item);\n }\n\n /**\n * hash递增 如果不存在,就会创建一个 并把新增后的值返回\n *\n * @param key 键\n * @param item 项\n * @param by 要增加几(大于0)\n * @return\n */\n public double hIncr(String key, String item, double by) {\n return redisTemplate.opsForHash().increment(key, item, by);\n }\n\n /**\n * hash递减\n *\n * @param key 键\n * @param item 项\n * @param by 要减少记(小于0)\n * @return\n */\n public double hDecr(String key, String item, double by) {\n return redisTemplate.opsForHash().increment(key, item, -by);\n }\n\n\n /**\n * 模糊删除\n *\n * @param ex\n */\n public void likeDel(String ex) {\n Set<String> keys = redisTemplate.keys(ex);\n if (CollUtil.isNotEmpty(keys)) {\n redisTemplate.delete(keys);\n }\n }\n\n public Set<String> keys(String ex) {\n return redisTemplate.keys(ex);\n }\n\n\n /**\n * 向指定key的set集合中添加一个值\n *\n * @param key redis的key\n * @param val set集合的值\n * @return\n */\n public boolean setAdd(String key, Object val) {\n try {\n redisTemplate.opsForSet().add(key, val);\n return true;\n } catch (Exception e) {\n e.printStackTrace();\n return false;\n }\n }\n\n public <T extends Serializable> List<T> getSet(String key, Class<T> clazz) {\n if (Boolean.FALSE.equals(this.redisTemplate.hasKey(key))) {\n return null;\n }\n List<Object> res = this.redisTemplate.opsForSet().pop(key, -1);\n if (CollUtil.isNotEmpty(res)) {\n List<T> finalRes = new ArrayList<>();\n for (Object re : res) {\n if (re.getClass().equals(clazz)) {\n finalRes.add(clazz.cast(re));\n }\n }\n return finalRes;\n }\n return null;\n }\n\n /**\n * set集合中是否存在指定数据\n *\n * @param key\n * @param val\n * @return\n */\n public boolean setHas(String key, Object val) {\n if (hasKey(key)) {\n return Boolean.TRUE.equals(redisTemplate.opsForSet().isMember(key, val));\n } else {\n return false;\n }\n }\n\n public boolean streamAdd() {\n redisTemplate.opsForStream().add(null);\n return false;\n }\n}" } ]
import cn.hutool.core.collection.CollUtil; import cn.hutool.core.util.ArrayUtil; import cn.hutool.core.util.StrUtil; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.baomidou.mybatisplus.core.toolkit.support.SFunction; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import fun.isite.service.common.bean.exception.LogicException; import fun.isite.service.common.db.dto.SplitPageDTO; import fun.isite.service.common.db.entity.BaseEntity; import fun.isite.service.common.db.interf.CustomBasicPageQuery; import fun.isite.service.common.db.service.IBaseService; import fun.isite.service.common.db.vo.PageVO; import fun.isite.service.common.tools.lang.AssertUtils; import fun.isite.service.common.tools.utils.RedisUtils; import jakarta.annotation.Nullable; import org.springframework.beans.BeanUtils; import org.springframework.transaction.annotation.Transactional; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.function.Consumer;
8,095
AssertUtils.isFalse(model.updateById(), "更新" + getServiceModelName() + "失败"); this.redisHashSet(false, req); return model; } @Override public void removeSingle(String id) { this.removeSingle(id, null); } @Override public void removeSingle(String id, @Nullable Consumer<LambdaQueryWrapper<T>> query) { String msg = "删除" + getServiceModelName() + "失败"; if (query == null) { AssertUtils.isFalse(this.removeById(id), msg); } else { AssertUtils.isFalse(this.remove(this.getIdCustomQueryConsumer(id, query)), msg); } this.redisHashSet(true, null, CollUtil.newArrayList(id)); } @Override @Transactional(rollbackFor = Exception.class) public void remove(List<String> idList) { this.remove(idList, null); } @Override @Transactional(rollbackFor = Exception.class) public void remove(List<String> idList, @Nullable Consumer<LambdaQueryWrapper<T>> query) { String msg = "批量" + getServiceModelName() + "删除失败"; if (query == null) { AssertUtils.isFalse(this.removeBatchByIds(idList), msg); } else { LambdaQueryWrapper<T> wrapper = new LambdaQueryWrapper<T>().setEntityClass(this.getEntityClass()) .in(T::getId, idList); query.accept(wrapper); AssertUtils.isFalse(this.remove(wrapper), msg); } this.redisHashSet(true, null, idList); } @Override public T detail(String id) { return this.detail(id, null); } @Override public T detail(Consumer<LambdaQueryWrapper<T>> consumer) { LambdaQueryWrapper<T> wrapper = new LambdaQueryWrapper<T>().setEntityClass(this.getEntityClass()); consumer.accept(wrapper); return this.getFirst(wrapper); } @Override public T detail(String id, @Nullable Consumer<LambdaQueryWrapper<T>> query) { T model; if (query == null) { model = this.redisHashGet(id); if (model != null) { return model; } model = this.getById(id); } else { model = this.getFirst(this.getIdCustomQueryConsumer(id, query)); } AssertUtils.isNull(model, "目标" + getServiceModelName() + "不存在"); return model; } private T redisHashGet(String id) { String cacheKey = this.getModelHashCacheKey(); RedisUtils redisUtil = RedisUtils.getINSTANCE(); if (cacheKey != null && redisUtil != null) { return redisUtil.hGet(cacheKey, id, getEntityClass()); } return null; } @Override public T getLastByCreateTime(@Nullable CustomBasicPageQuery<T> customQuery) { LambdaQueryWrapper<T> wrapper = new LambdaQueryWrapper<>(getEntityClass()).orderByDesc(T::getCreateTime); if (customQuery != null) { customQuery.query(wrapper); } return this.getFirst(wrapper); } @Override public String getServiceModelName() { return ""; } @Override public String getServiceModelCacheId(T t) { return t.getId(); } @Override public String getModelHashCacheKey() { return null; } @Override public <V> PageVO<V> pageToVO(PageVO<T> page, Class<V> targetClass) { final PageVO<V> res = new PageVO<>(); try { BeanUtils.copyProperties(page, res, "records"); List<V> records = new ArrayList<>(page.getRecords().size()); for (T record : page.getRecords()) { final V v = targetClass.newInstance(); BeanUtils.copyProperties(record, v); records.add(v); } res.setRecords(records); } catch (Exception e) { log.error("分页数据转换失败", e);
package fun.isite.service.common.db.impl; /** * @author Enigma */ public class BaseService<M extends BaseMapper<T>, T extends BaseEntity<T>> extends ServiceImpl<M, T> implements IBaseService<T> { public final static String[] BASE_ENTITY_FIELDS = {"id", "create_time", "update_time", "deleted"}; public final static String LIMIT_ONE = "limit 1"; @Override public T getFirst(QueryWrapper<T> queryWrapper) { if (queryWrapper != null) { queryWrapper.last(LIMIT_ONE); } return this.getOne(queryWrapper); } @Override public T getById(Serializable id, @Nullable Consumer<LambdaQueryWrapper<T>> wrapperConsumer) { LambdaQueryWrapper<T> wrapper = new LambdaQueryWrapper<T>().setEntityClass(this.getEntityClass()) .eq(T::getId, id); if(wrapperConsumer!=null){ wrapperConsumer.accept(wrapper); } wrapper.last(LIMIT_ONE); return this.getOne(wrapper); } @Override public T getFirst(LambdaQueryWrapper<T> queryWrapper) { if (queryWrapper != null) { queryWrapper.last(LIMIT_ONE); } return this.getOne(queryWrapper); } @Override public T getByField(SFunction<T, ?> field, String value) { return this.getFirst(new LambdaQueryWrapper<T>().eq(field, value)); } @Override public PageVO<T> basicPage(SplitPageDTO dto, SFunction<T, ?> orderByField, CustomBasicPageQuery<T> customQuery) { QueryWrapper<T> wrapper = new QueryWrapper<>(); wrapper.like(dto.getId() != null, "id", dto.getId()); wrapper.ge(StrUtil.isNotBlank(dto.getCreateTime()), "create_time", dto.getCreateTime()); wrapper.ge(StrUtil.isNotBlank(dto.getUpdateTime()), "update_time", dto.getUpdateTime()); LambdaQueryWrapper<T> lambdaQueryWrapper = wrapper.lambda(); lambdaQueryWrapper.orderBy(orderByField != null, dto.isAsc(), orderByField); if (customQuery != null) { customQuery.query(lambdaQueryWrapper); } int pageSize = dto.getPageSize(); if (pageSize < 0) { pageSize = 1000; } return new PageVO<>(this.page(new Page<>(dto.getPage(), pageSize), wrapper)); } @Override public void resetBaseField(T t) { if (t != null) { t.setId(null); t.setCreateTime(null); t.setUpdateTime(null); t.setDeleted((short) 0); } } private LambdaQueryWrapper<T> getIdCustomQueryConsumer(String id, Consumer<LambdaQueryWrapper<T>> consumer) { LambdaQueryWrapper<T> wrapper = new LambdaQueryWrapper<T>().setEntityClass(this.getEntityClass()) .eq(T::getId, id); if (consumer != null) { consumer.accept(wrapper); } return wrapper; } @Override public T create(T req) { this.resetBaseField(req); AssertUtils.isFalse(req.insert(), "创建" + getServiceModelName() + "失败"); this.redisHashSet(false, req); return req; } @Override @Transactional(rollbackFor = Exception.class) public List<T> create(List<T> reqs) { reqs.forEach(this::resetBaseField); AssertUtils.isFalse(this.saveBatch(reqs), "批量创建" + getServiceModelName() + "失败"); this.redisHashSet(false, reqs, null); return reqs; } @Override public T update(String id, T req) { return this.update(id, req, null); } @Override public T update(String id, T req, @Nullable Consumer<LambdaQueryWrapper<T>> query) { T model = this.detail(id, query); BeanUtils.copyProperties(req, model, BASE_ENTITY_FIELDS); AssertUtils.isFalse(model.updateById(), "更新" + getServiceModelName() + "失败"); this.redisHashSet(false, req); return model; } @Override public void removeSingle(String id) { this.removeSingle(id, null); } @Override public void removeSingle(String id, @Nullable Consumer<LambdaQueryWrapper<T>> query) { String msg = "删除" + getServiceModelName() + "失败"; if (query == null) { AssertUtils.isFalse(this.removeById(id), msg); } else { AssertUtils.isFalse(this.remove(this.getIdCustomQueryConsumer(id, query)), msg); } this.redisHashSet(true, null, CollUtil.newArrayList(id)); } @Override @Transactional(rollbackFor = Exception.class) public void remove(List<String> idList) { this.remove(idList, null); } @Override @Transactional(rollbackFor = Exception.class) public void remove(List<String> idList, @Nullable Consumer<LambdaQueryWrapper<T>> query) { String msg = "批量" + getServiceModelName() + "删除失败"; if (query == null) { AssertUtils.isFalse(this.removeBatchByIds(idList), msg); } else { LambdaQueryWrapper<T> wrapper = new LambdaQueryWrapper<T>().setEntityClass(this.getEntityClass()) .in(T::getId, idList); query.accept(wrapper); AssertUtils.isFalse(this.remove(wrapper), msg); } this.redisHashSet(true, null, idList); } @Override public T detail(String id) { return this.detail(id, null); } @Override public T detail(Consumer<LambdaQueryWrapper<T>> consumer) { LambdaQueryWrapper<T> wrapper = new LambdaQueryWrapper<T>().setEntityClass(this.getEntityClass()); consumer.accept(wrapper); return this.getFirst(wrapper); } @Override public T detail(String id, @Nullable Consumer<LambdaQueryWrapper<T>> query) { T model; if (query == null) { model = this.redisHashGet(id); if (model != null) { return model; } model = this.getById(id); } else { model = this.getFirst(this.getIdCustomQueryConsumer(id, query)); } AssertUtils.isNull(model, "目标" + getServiceModelName() + "不存在"); return model; } private T redisHashGet(String id) { String cacheKey = this.getModelHashCacheKey(); RedisUtils redisUtil = RedisUtils.getINSTANCE(); if (cacheKey != null && redisUtil != null) { return redisUtil.hGet(cacheKey, id, getEntityClass()); } return null; } @Override public T getLastByCreateTime(@Nullable CustomBasicPageQuery<T> customQuery) { LambdaQueryWrapper<T> wrapper = new LambdaQueryWrapper<>(getEntityClass()).orderByDesc(T::getCreateTime); if (customQuery != null) { customQuery.query(wrapper); } return this.getFirst(wrapper); } @Override public String getServiceModelName() { return ""; } @Override public String getServiceModelCacheId(T t) { return t.getId(); } @Override public String getModelHashCacheKey() { return null; } @Override public <V> PageVO<V> pageToVO(PageVO<T> page, Class<V> targetClass) { final PageVO<V> res = new PageVO<>(); try { BeanUtils.copyProperties(page, res, "records"); List<V> records = new ArrayList<>(page.getRecords().size()); for (T record : page.getRecords()) { final V v = targetClass.newInstance(); BeanUtils.copyProperties(record, v); records.add(v); } res.setRecords(records); } catch (Exception e) { log.error("分页数据转换失败", e);
throw new LogicException("分页数据转换失败");
0
2023-12-26 01:55:01+00:00
12k
codingmiao/hppt
sc/src/main/java/org/wowtools/hppt/sc/StartSc.java
[ { "identifier": "AesCipherUtil", "path": "common/src/main/java/org/wowtools/hppt/common/util/AesCipherUtil.java", "snippet": "@Slf4j\npublic class AesCipherUtil {\n\n public final Encryptor encryptor;\n\n public final Descriptor descriptor;\n\n\n public AesCipherUtil(String strKey, long ts) {\n strKey = strKey + (ts / (30 * 60 * 1000));\n SecretKey key = generateKey(strKey);\n this.encryptor = new Encryptor(key);\n this.descriptor = new Descriptor(key);\n }\n\n /**\n * 加密器\n */\n public static final class Encryptor {\n private final Cipher cipher;\n\n private Encryptor(SecretKey key) {\n try {\n cipher = Cipher.getInstance(\"AES\");\n cipher.init(Cipher.ENCRYPT_MODE, key);\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }\n\n public byte[] encrypt(byte[] bytes) {\n try {\n return cipher.doFinal(bytes);\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }\n\n }\n\n /**\n * 解密器\n */\n public static final class Descriptor {\n private final Cipher cipher;\n\n private Descriptor(SecretKey key) {\n try {\n cipher = Cipher.getInstance(\"AES\");\n cipher.init(Cipher.DECRYPT_MODE, key);\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }\n\n public byte[] decrypt(byte[] bytes) {\n try {\n return cipher.doFinal(bytes);\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }\n\n }\n\n private static final int n = 16;\n\n private static SecretKey generateKey(String input) {\n try {\n KeyGenerator kgen = KeyGenerator.getInstance(\"AES\");// 创建AES的Key生产者\n SecureRandom secureRandom = SecureRandom.getInstance(\"SHA1PRNG\");\n secureRandom.setSeed(input.getBytes());\n kgen.init(128, secureRandom);\n\n SecretKey secretKey = kgen.generateKey();// 根据用户密码,生成一个密钥\n return secretKey;\n } catch (NoSuchAlgorithmException e) {\n throw new RuntimeException(e);\n }\n }\n\n\n}" }, { "identifier": "BytesUtil", "path": "common/src/main/java/org/wowtools/hppt/common/util/BytesUtil.java", "snippet": "public class BytesUtil {\n /**\n * 按每个数组的最大长度限制,将一个数组拆分为多个\n *\n * @param originalArray 原数组\n * @param maxChunkSize 最大长度限制\n * @return 拆分结果\n */\n public static byte[][] splitBytes(byte[] originalArray, int maxChunkSize) {\n int length = originalArray.length;\n int numOfChunks = (int) Math.ceil((double) length / maxChunkSize);\n byte[][] splitArrays = new byte[numOfChunks][];\n\n for (int i = 0; i < numOfChunks; i++) {\n int start = i * maxChunkSize;\n int end = Math.min((i + 1) * maxChunkSize, length);\n int chunkSize = end - start;\n\n byte[] chunk = new byte[chunkSize];\n System.arraycopy(originalArray, start, chunk, 0, chunkSize);\n\n splitArrays[i] = chunk;\n }\n\n return splitArrays;\n }\n\n /**\n * 合并字节集合为一个byte[]\n *\n * @param collection 字节集合\n * @return byte[]\n */\n public static byte[] merge(Collection<byte[]> collection) {\n byte[] bytes;\n try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {\n for (byte[] byteArray : collection) {\n byteArrayOutputStream.write(byteArray);\n }\n bytes = byteArrayOutputStream.toByteArray();\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n return bytes;\n }\n\n /**\n * bytes转base64字符串\n *\n * @param bytes bytes\n * @return base64字符串\n */\n public static String bytes2base64(byte[] bytes) {\n return Base64.getEncoder().encodeToString(bytes);\n }\n\n /**\n * base64字符串转bytes\n *\n * @param base64 base64字符串\n * @return bytes\n */\n public static byte[] base642bytes(String base64) {\n return Base64.getDecoder().decode(base64);\n }\n\n // 使用GZIP压缩字节数组\n public static byte[] compress(byte[] input) throws IOException {\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n try (GZIPOutputStream gzipOutputStream = new GZIPOutputStream(baos)) {\n gzipOutputStream.write(input);\n }\n return baos.toByteArray();\n }\n\n // 使用GZIP解压缩字节数组\n public static byte[] decompress(byte[] compressed) throws IOException {\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n ByteArrayInputStream bais = new ByteArrayInputStream(compressed);\n try (java.util.zip.GZIPInputStream gzipInputStream = new java.util.zip.GZIPInputStream(bais)) {\n byte[] buffer = new byte[1024];\n int len;\n while ((len = gzipInputStream.read(buffer)) > 0) {\n baos.write(buffer, 0, len);\n }\n }\n return baos.toByteArray();\n }\n\n public static ByteBuf bytes2byteBuf(ChannelHandlerContext ctx, byte[] bytes) {\n ByteBuf byteBuf = ctx.alloc().buffer(bytes.length, bytes.length);\n byteBuf.writeBytes(bytes);\n return byteBuf;\n }\n\n //把字节写入ChannelHandlerContext\n public static void writeToChannelHandlerContext(ChannelHandlerContext ctx, byte[] bytes) {\n ByteBuf byteBuf = bytes2byteBuf(ctx, bytes);\n ctx.writeAndFlush(byteBuf);\n }\n\n public static byte[] byteBuf2bytes(ByteBuf byteBuf) {\n byte[] bytes = new byte[byteBuf.readableBytes()];\n byteBuf.readBytes(bytes);\n return bytes;\n }\n\n\n\n}" }, { "identifier": "Constant", "path": "common/src/main/java/org/wowtools/hppt/common/util/Constant.java", "snippet": "public class Constant {\n public static final ObjectMapper jsonObjectMapper = new ObjectMapper();\n\n public static final ObjectMapper ymlMapper = new ObjectMapper(new YAMLFactory());\n\n public static final String sessionIdJoinFlag = \",\";\n\n //ss端执行的命令代码\n public static final class SsCommands {\n //关闭Session 0逗号连接需要的SessionId\n public static final char CloseSession = '0';\n\n //保持Session活跃 1逗号连接需要的SessionId\n public static final char ActiveSession = '1';\n }\n\n //Sc端执行的命令代码\n public static final class ScCommands {\n //检查客户端的Session是否还活跃 0逗号连接需要的SessionId\n public static final char CheckSessionActive = '0';\n\n //关闭客户端连接 1逗号连接需要的SessionId\n public static final char CloseSession = '1';\n }\n\n //Cs端执行的命令代码\n public static final class CsCommands {\n //检查客户端的Session是否还活跃 0逗号连接需要的SessionId\n public static final char CheckSessionActive = '0';\n\n //关闭客户端连接 1逗号连接需要的SessionId\n public static final char CloseSession = '1';\n }\n\n //cc端执行的命令代码\n public static final class CcCommands {\n //关闭Session 0逗号连接需要的SessionId\n public static final char CloseSession = '0';\n\n //保持Session活跃 1逗号连接需要的SessionId\n public static final char ActiveSession = '1';\n\n //新建会话 2sessionId host port\n public static final char CreateSession = '2';\n }\n\n}" }, { "identifier": "HttpUtil", "path": "common/src/main/java/org/wowtools/hppt/common/util/HttpUtil.java", "snippet": "@Slf4j\npublic class HttpUtil {\n\n private static final okhttp3.MediaType bytesMediaType = okhttp3.MediaType.parse(\"application/octet-stream\");\n\n private static final OkHttpClient okHttpClient;\n\n static {\n okHttpClient = new OkHttpClient.Builder()\n .sslSocketFactory(sslSocketFactory(), x509TrustManager())\n // 是否开启缓存\n .retryOnConnectionFailure(false)\n .connectionPool(pool())\n .connectTimeout(30L, TimeUnit.SECONDS)\n .readTimeout(30L, TimeUnit.SECONDS)\n .writeTimeout(30L, TimeUnit.SECONDS)\n .hostnameVerifier((hostname, session) -> true)\n // 设置代理\n// .proxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(\"127.0.0.1\", 8888)))\n // 拦截器\n// .addInterceptor()\n .build();\n\n }\n\n\n public static Response doGet(String url) {\n Request.Builder builder = new Request.Builder();\n Request request = builder.url(url).build();\n return execute(request);\n }\n\n public static Response doPost(String url) {\n RequestBody body = RequestBody.create(bytesMediaType, new byte[0]);\n Request request = new Request.Builder().url(url).post(body).build();\n return execute(request);\n }\n\n public static Response doPost(String url, byte[] bytes) {\n RequestBody body = RequestBody.create(bytesMediaType, bytes);\n Request request = new Request.Builder().url(url).post(body).build();\n return execute(request);\n }\n\n\n public static Response execute(Request request) {\n java.io.InterruptedIOException interruptedIOException = null;\n for (int i = 0; i < 5; i++) {\n try {\n return okHttpClient.newCall(request).execute();\n } catch (java.io.InterruptedIOException e) {\n interruptedIOException = e;\n try {\n Thread.sleep(10);\n } catch (Exception ex) {\n log.debug(\"发送请求sleep被打断\");\n }\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n throw new RuntimeException(interruptedIOException);\n\n }\n\n\n private static X509TrustManager x509TrustManager() {\n return new X509TrustManager() {\n @Override\n public void checkClientTrusted(X509Certificate[] chain, String authType) {\n }\n\n @Override\n public void checkServerTrusted(X509Certificate[] chain, String authType) {\n }\n\n @Override\n public X509Certificate[] getAcceptedIssuers() {\n return new X509Certificate[0];\n }\n };\n }\n\n private static SSLSocketFactory sslSocketFactory() {\n try {\n // 信任任何链接\n SSLContext sslContext = SSLContext.getInstance(\"TLS\");\n sslContext.init(null, new TrustManager[]{x509TrustManager()}, new SecureRandom());\n return sslContext.getSocketFactory();\n } catch (NoSuchAlgorithmException | KeyManagementException e) {\n throw new RuntimeException(e);\n }\n }\n\n private static ConnectionPool pool() {\n return new ConnectionPool(5, 1L, TimeUnit.MINUTES);\n }\n\n}" }, { "identifier": "ScConfig", "path": "sc/src/main/java/org/wowtools/hppt/sc/pojo/ScConfig.java", "snippet": "public class ScConfig {\n public static final class Forward {\n /**\n * 本机代理端口\n */\n public int localPort;\n /**\n * 远程ip或域名\n */\n public String remoteHost;\n /**\n * 远程端口\n */\n public int remotePort;\n\n }\n\n /**\n * 客户端id,每个sc.jar用一个,不要重复\n */\n public String clientId;\n\n /**\n * 服务端http地址,可以填nginx转发过的地址\n */\n public String serverUrl;\n\n /**\n * 开始时闲置几毫秒发一次http请求,越短延迟越低但越耗性能\n */\n public long initSleepTime = 1000;\n\n /**\n * 当收到空消息时,闲置毫秒数增加多少毫秒\n */\n public long addSleepTime = 1000;\n\n /**\n * 闲置毫秒数最大到多少毫秒\n */\n public long maxSleepTime = 60000;\n\n /**\n * 向服务端发数据请求体的字节数最大值\n * 有时会出现413 Request Entity Too Large问题,没办法改nginx的话就用这个值限制\n */\n public int maxSendBodySize = Integer.MAX_VALUE;\n\n /**\n * 是否启用压缩,默认启用 需和服务端保持一致\n */\n public boolean enableCompress = true;\n\n /**\n * 是否启用内容加密,默认启用 需和服务端保持一致\n */\n public boolean enableEncrypt = true;\n\n /**\n * 端口转发\n */\n public ArrayList<Forward> forwards;\n\n\n}" }, { "identifier": "ClientPort", "path": "sc/src/main/java/org/wowtools/hppt/sc/service/ClientPort.java", "snippet": "@Slf4j\npublic class ClientPort {\n\n @FunctionalInterface\n public interface OnClientConn {\n void on(ClientPort clientPort, ChannelHandlerContext channelHandlerContext);\n }\n\n private final OnClientConn onClientConn;\n\n private final ClientPort clientPort = this;\n\n public ClientPort(int localPort, OnClientConn onClientConn) {\n this.onClientConn = onClientConn;\n\n EventLoopGroup bossGroup = new NioEventLoopGroup(1);\n EventLoopGroup workerGroup = new NioEventLoopGroup();\n\n Thread.startVirtualThread(() -> {\n try {\n int bufferSize = StartSc.config.maxSendBodySize * 100 / 1024 * 1024;\n ServerBootstrap b = new ServerBootstrap();\n b.group(bossGroup, workerGroup)\n .channel(NioServerSocketChannel.class)\n .option(ChannelOption.SO_BACKLOG, 128)\n .childOption(ChannelOption.SO_SNDBUF, bufferSize)\n .childOption(ChannelOption.SO_RCVBUF, bufferSize)\n// .handler(new LoggingHandler(LogLevel.INFO))\n .childHandler(new ChannelInitializer<SocketChannel>() {\n @Override\n protected void initChannel(SocketChannel ch) {\n// ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO));\n ch.pipeline().addLast(new SimpleHandler());\n ch.config().setRecvByteBufAllocator(new FixedRecvByteBufAllocator(bufferSize));\n ch.config().setSendBufferSize(bufferSize);\n }\n });\n\n // 绑定端口,启动服务器\n b.bind(localPort).sync().channel().closeFuture().sync();\n } catch (Exception e) {\n throw new RuntimeException(e);\n } finally {\n bossGroup.shutdownGracefully();\n workerGroup.shutdownGracefully();\n }\n });\n }\n\n private final Map<ChannelHandlerContext, ClientSession> clientSessionMapByCtx = new ConcurrentHashMap<>();\n\n private class SimpleHandler extends ByteToMessageDecoder {\n\n @Override\n public void channelActive(ChannelHandlerContext channelHandlerContext) throws Exception {\n log.debug(\"client channelActive {}\", channelHandlerContext.hashCode());\n super.channelActive(channelHandlerContext);\n //用户发起新连接 触发onClientConn事件\n onClientConn.on(clientPort, channelHandlerContext);\n }\n\n @Override\n public void channelInactive(ChannelHandlerContext ctx) throws Exception {\n log.debug(\"client channelInactive {}\", ctx.hashCode());\n super.channelInactive(ctx);\n ClientSession clientSession = clientSessionMapByCtx.get(ctx);\n if (null != clientSession) {\n ClientSessionManager.disposeClientSession(clientSession, \"client channelInactive\");\n }\n }\n\n @Override\n public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {\n log.debug(\"client exceptionCaught {}\", ctx.hashCode(), cause);\n ClientSession clientSession = clientSessionMapByCtx.get(ctx);\n if (null != clientSession) {\n ClientSessionManager.disposeClientSession(clientSession, \"client exceptionCaught\");\n }\n }\n\n @Override\n protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) {\n byte[] bytes = BytesUtil.byteBuf2bytes(byteBuf);\n ClientSession clientSession = clientSessionMapByCtx.get(channelHandlerContext);\n if (null != clientSession) {\n //触发数据回调事件 转发数据到真实端口\n log.debug(\"ClientSession {} 收到客户端发送字节数 {}\", clientSession.getSessionId(), bytes.length);\n clientSession.sendBytes(bytes);\n }\n }\n }\n\n public ClientSession createClientSession(int sessionId, ChannelHandlerContext channelHandlerContext) {\n ClientSession clientSession = new ClientSession(sessionId, channelHandlerContext);\n log.debug(\"ClientSession {} 初始化完成 {}\", clientSession.getSessionId(), channelHandlerContext.hashCode());\n clientSessionMapByCtx.put(channelHandlerContext, clientSession);\n return clientSession;\n }\n}" }, { "identifier": "ClientSession", "path": "sc/src/main/java/org/wowtools/hppt/sc/service/ClientSession.java", "snippet": "@Slf4j\npublic class ClientSession {\n private final int sessionId;\n private final ChannelHandlerContext channelHandlerContext;\n\n private final BlockingQueue<byte[]> clientSessionSendQueue = new ArrayBlockingQueue<>(1024);\n\n\n public ClientSession(int sessionId, ChannelHandlerContext channelHandlerContext) {\n this.sessionId = sessionId;\n this.channelHandlerContext = channelHandlerContext;\n ClientSessionService.awakenSendThread();\n }\n\n /**\n * 发bytes到客户端\n *\n * @param bytes bytes\n */\n public void putBytes(byte[] bytes) {\n log.debug(\"ClientSession {} 收到服务端发来的字节数 {}\", sessionId, bytes.length);\n BytesUtil.writeToChannelHandlerContext(channelHandlerContext,bytes);\n }\n\n /**\n * 发消息到真实端口 实际上是发到队列中,等待服http发送线程取走,所以会发生阻塞\n *\n * @param bytes bytes\n */\n public void sendBytes(byte[] bytes) {\n try {\n clientSessionSendQueue.put(bytes);\n } catch (InterruptedException e) {\n throw new RuntimeException(e);\n }\n ClientSessionService.awakenSendThread();\n }\n\n public int getSessionId() {\n return sessionId;\n }\n\n public ChannelHandlerContext getChannelHandlerContext() {\n return channelHandlerContext;\n }\n\n public void close() {\n channelHandlerContext.close();\n }\n\n /**\n * 取出需要发送到服务端的SessionBytes\n *\n * @return 无数据则返回null\n */\n public byte[] fetchSendSessionBytes() {\n List<byte[]> list = new LinkedList<>();\n clientSessionSendQueue.drainTo(list);\n if (list.isEmpty()) {\n return null;\n }\n return BytesUtil.merge(list);\n }\n}" }, { "identifier": "ClientSessionManager", "path": "sc/src/main/java/org/wowtools/hppt/sc/service/ClientSessionManager.java", "snippet": "@Slf4j\npublic class ClientSessionManager {\n public static final Map<Integer, ClientSession> clientSessionMap = new ConcurrentHashMap<>();\n\n private static List<Integer> closedClientSessions = new LinkedList<>();\n\n private static final Object closeLock = new Object();\n\n public static ClientSession createClientSession(int sessionId, ClientPort clientPort, ChannelHandlerContext channelHandlerContext) {\n ClientSession clientSession = clientPort.createClientSession(sessionId, channelHandlerContext);\n clientSessionMap.put(sessionId, clientSession);\n ClientSessionService.awakenSendThread();\n return clientSession;\n }\n\n public static void disposeClientSession(ClientSession clientSession, String type) {\n clientSession.close();\n log.info(\"ClientSession {} close,type [{}]\", clientSession.getSessionId(), type);\n if (null != clientSessionMap.remove(clientSession.getSessionId())) {\n synchronized (closeLock) {\n closedClientSessions.add(clientSession.getSessionId());\n }\n ClientSessionService.awakenSendThread();\n }\n }\n\n public static List<Integer> fetchClosedClientSessions() {\n if (closedClientSessions.isEmpty()) {\n return null;\n }\n List<Integer> res;\n synchronized (closeLock) {\n res = List.copyOf(closedClientSessions);\n closedClientSessions = new LinkedList<>();\n }\n return res;\n }\n\n public static boolean notHaveClosedClientSession() {\n return closedClientSessions.isEmpty();\n }\n}" }, { "identifier": "ClientSessionService", "path": "sc/src/main/java/org/wowtools/hppt/sc/service/ClientSessionService.java", "snippet": "@Slf4j\npublic class ClientSessionService {\n\n private static final String initUri = StartSc.config.serverUrl + \"/init\";\n private static final String talkUri = StartSc.config.serverUrl + \"/talk?c=\" + StartSc.loginCode;\n private static long sleepTime = StartSc.config.initSleepTime - StartSc.config.addSleepTime;\n private static long noSleepLimitTime = 0;\n private static final AtomicBoolean sleeping = new AtomicBoolean(false);\n\n private static final Thread sendThread;\n\n //服务端发来的查询客户端sessionId是否还存在的id队列\n private static final BlockingQueue<Integer> serverQuerySessionIdQueue = new ArrayBlockingQueue<>(10000);\n\n\n /**\n * 拉起一个服务端会话,返回服务端会话id\n *\n * @param remoteHost remoteHost\n * @param remotePort remotePort\n * @return 服务端会话id\n */\n public static int initServerSession(String remoteHost, int remotePort) {\n String body = StartSc.loginCode + \":\" + remoteHost + \":\" + remotePort;\n String res;\n try (Response response = HttpUtil.doPost(initUri, body.getBytes(StandardCharsets.UTF_8))) {\n assert response.body() != null;\n res = response.body().string();\n } catch (Exception e) {\n throw new RuntimeException(\"获取sessionId异常\", e);\n }\n return Integer.parseInt(res);\n }\n\n static {\n //读取clientSendQueue的值,发送http请求分发到ss端\n sendThread = new Thread(() -> {\n while (true) {\n try {\n /* 发请求 */\n boolean isEmpty = sendToSs();\n\n /* 睡眠发送线程策略 */\n if (ClientSessionManager.clientSessionMap.isEmpty()\n && serverQuerySessionIdQueue.isEmpty()\n && ClientSessionManager.notHaveClosedClientSession()\n ) {\n //无客户端,长睡直到被唤醒\n log.info(\"无客户端连接,且无命令要发送,睡眠发送线程\");\n sleepTime = Long.MAX_VALUE;\n\n } else if (noSleepLimitTime > System.currentTimeMillis()) {\n //线程刚刚被唤醒,不睡眠\n sleepTime = StartSc.config.initSleepTime;\n log.debug(\"线程刚刚被唤醒 {}\", sleepTime);\n } else if (isEmpty) {\n //收发数据包都为空,逐步增加睡眠时间\n if (sleepTime < StartSc.config.maxSleepTime) {\n sleepTime += StartSc.config.addSleepTime;\n }\n log.debug(\"收发数据包都为空,逐步增加睡眠时间 {}\", sleepTime);\n } else {\n sleepTime = StartSc.config.initSleepTime;\n log.debug(\"正常包 {}\", sleepTime);\n }\n if (sleepTime > 0) {\n sleeping.set(true);\n try {\n log.debug(\"sleep {}\", sleepTime);\n Thread.sleep(sleepTime);\n } catch (InterruptedException e) {\n log.info(\"发送进程被唤醒\");\n } finally {\n sleeping.set(false);\n }\n }\n } catch (Exception e) {\n log.warn(\"发消息到服务端发生异常\", e);\n sleeping.set(true);\n try {\n Thread.sleep(StartSc.config.maxSleepTime);\n } catch (InterruptedException e1) {\n log.info(\"发送进程被唤醒\");\n } finally {\n sleeping.set(false);\n }\n }\n }\n\n });\n sendThread.start();\n }\n\n\n /**\n * 唤醒发送线程\n */\n public static void awakenSendThread() {\n if (sleeping.get()) {\n try {\n sleepTime = StartSc.config.initSleepTime;\n noSleepLimitTime = System.currentTimeMillis() + StartSc.config.addSleepTime;\n sendThread.interrupt();\n log.info(\"唤醒发送线程\");\n } catch (Exception e) {\n log.warn(\"唤醒线程异常\", e);\n }\n }\n }\n\n /**\n * 发请求\n *\n * @return 是否为空包 即发送和接收都是空\n * @throws Exception Exception\n */\n private static boolean sendToSs() throws Exception {\n boolean isEmpty = true;\n List<ProtoMessage.BytesPb> bytePbList = new LinkedList<>();\n //发字节\n ClientSessionManager.clientSessionMap.forEach((clientId, clientSession) -> {\n byte[] bytes = clientSession.fetchSendSessionBytes();\n if (bytes != null) {\n bytePbList.add(ProtoMessage.BytesPb.newBuilder()\n .setSessionId(clientSession.getSessionId())\n .setBytes(ByteString.copyFrom(bytes))\n .build()\n );\n }\n });\n if (!bytePbList.isEmpty()) {\n isEmpty = false;\n }\n //发命令\n List<String> commands = new LinkedList<>();\n {\n StringBuilder closeSession = new StringBuilder().append(Constant.SsCommands.CloseSession);\n StringBuilder activeSession = new StringBuilder().append(Constant.SsCommands.ActiveSession);\n\n List<Integer> sessionIds = new LinkedList<>();\n serverQuerySessionIdQueue.drainTo(sessionIds);\n for (Integer sessionId : sessionIds) {\n if (ClientSessionManager.clientSessionMap.containsKey(sessionId)) {\n activeSession.append(sessionId).append(Constant.sessionIdJoinFlag);\n } else {\n closeSession.append(sessionId).append(Constant.sessionIdJoinFlag);\n }\n }\n\n List<Integer> closedClientSessions = ClientSessionManager.fetchClosedClientSessions();\n if (null != closedClientSessions) {\n for (Integer sessionId : closedClientSessions) {\n closeSession.append(sessionId).append(Constant.sessionIdJoinFlag);\n }\n }\n\n if (closeSession.length() > 1) {\n commands.add(closeSession.toString());\n }\n if (activeSession.length() > 1) {\n commands.add(activeSession.toString());\n }\n }\n cutSendToSs(bytePbList, commands);\n return isEmpty;\n }\n\n //如果请求体过大,会出现413 Request Entity Too Large,拆分一下发送\n private static boolean cutSendToSs(List<ProtoMessage.BytesPb> bytePbs, List<String> commands) throws Exception {\n List<ProtoMessage.BytesPb> bytesPbList = new LinkedList<>();\n List<String> commandList = new LinkedList<>();\n int requestBodyLength = 0;\n\n while (!bytePbs.isEmpty()) {\n if (bytePbs.getFirst().getBytes().size() > StartSc.config.maxSendBodySize) {\n //单个bytePb包含的字节数就超过限制了,那把bytes拆小\n ProtoMessage.BytesPb bytePb = bytePbs.removeFirst();\n byte[][] splitBytes = BytesUtil.splitBytes(bytePb.getBytes().toByteArray(), StartSc.config.maxSendBodySize);\n for (int i = splitBytes.length - 1; i >= 0; i--) {\n bytePbs.addFirst(ProtoMessage.BytesPb.newBuilder()\n .setBytes(ByteString.copyFrom(splitBytes[i]))\n .setSessionId(bytePb.getSessionId())\n .build());\n }\n } else {\n requestBodyLength += bytePbs.getFirst().getBytes().size();\n if (requestBodyLength > StartSc.config.maxSendBodySize) {\n break;\n }\n bytesPbList.add(bytePbs.removeFirst());\n }\n\n }\n\n while (!commands.isEmpty()) {\n if (commands.getFirst().length() > StartSc.config.maxSendBodySize) {\n throw new RuntimeException(\"maxSendBodySize 的值过小导致无法发送命令,请调整\");\n }\n requestBodyLength += commands.getFirst().length();//注意,这里限定了命令只能是ASCII字符\n if (requestBodyLength > StartSc.config.maxSendBodySize) {\n break;\n }\n commandList.add(commands.removeFirst());\n }\n log.debug(\"requestBodyLength {}\", requestBodyLength);\n boolean isEmpty = subSendToSs(bytesPbList, commandList);\n if (bytePbs.isEmpty() && commands.isEmpty()) {\n return isEmpty;\n } else {\n return cutSendToSs(bytePbs, commands);\n }\n }\n\n\n //发送和接收\n private static boolean subSendToSs(List<ProtoMessage.BytesPb> bytesPbList, List<String> commandList) throws Exception {\n boolean isEmpty = true;\n\n ProtoMessage.MessagePb.Builder messagePbBuilder = ProtoMessage.MessagePb.newBuilder();\n if (!bytesPbList.isEmpty()) {\n messagePbBuilder.addAllBytesPbList(bytesPbList);\n }\n if (!commandList.isEmpty()) {\n messagePbBuilder.addAllCommandList(commandList);\n }\n byte[] requestBody = messagePbBuilder.build().toByteArray();\n\n //压缩、加密\n if (StartSc.config.enableCompress) {\n requestBody = BytesUtil.compress(requestBody);\n }\n if (StartSc.config.enableEncrypt) {\n requestBody = StartSc.aesCipherUtil.encryptor.encrypt(requestBody);\n }\n\n log.debug(\"发送数据 bytesPbs {} commands {} 字节数 {}\", bytesPbList.size(), commandList.size(), requestBody.length);\n Response response;\n\n if (log.isDebugEnabled()) {\n long t = System.currentTimeMillis();\n response = HttpUtil.doPost(talkUri, requestBody);\n log.debug(\"发送http请求耗时 {}\", System.currentTimeMillis() - t);\n } else {\n response = HttpUtil.doPost(talkUri, requestBody);\n }\n\n //响应结果转protobuf再从pbf中取出来加入对应的队列中\n assert response.body() != null;\n byte[] responseBody = response.body().bytes();\n response.close();\n\n ProtoMessage.MessagePb rMessagePb;\n try {\n //解密、解压\n if (StartSc.config.enableEncrypt) {\n responseBody = StartSc.aesCipherUtil.descriptor.decrypt(responseBody);\n }\n if (StartSc.config.enableCompress) {\n responseBody = BytesUtil.decompress(responseBody);\n }\n log.debug(\"收到服务端发回字节数 {}\", responseBody.length);\n rMessagePb = ProtoMessage.MessagePb.parseFrom(responseBody);\n } catch (Exception e) {\n log.warn(\"服务端响应错误 {}\", new String(responseBody, StandardCharsets.UTF_8), e);\n Thread.sleep(10000);\n return true;\n }\n\n //收字节\n List<ProtoMessage.BytesPb> rBytesPbListList = rMessagePb.getBytesPbListList();\n if (!rBytesPbListList.isEmpty()) {\n isEmpty = false;\n for (ProtoMessage.BytesPb bytesPb : rBytesPbListList) {\n ClientSession clientSession = ClientSessionManager.clientSessionMap.get(bytesPb.getSessionId());\n if (clientSession != null) {\n clientSession.putBytes(bytesPb.getBytes().toByteArray());\n } else {\n //客户端没有这个session 通知服务端关闭\n serverQuerySessionIdQueue.put(bytesPb.getSessionId());\n }\n }\n }\n\n //收命令\n for (String command : rMessagePb.getCommandListList()) {\n log.debug(\"收到服务端命令 {} \", command);\n char type = command.charAt(0);\n switch (type) {\n case Constant.ScCommands.CloseSession -> {\n String[] strSessionIds = command.substring(1).split(Constant.sessionIdJoinFlag);\n for (String strSessionId : strSessionIds) {\n ClientSession clientSession = ClientSessionManager.clientSessionMap.get(Integer.parseInt(strSessionId));\n if (null != clientSession) {\n ClientSessionManager.disposeClientSession(clientSession, \"服务端发送关闭命令\");\n }\n }\n }\n case Constant.ScCommands.CheckSessionActive -> {\n String[] strSessionIds = command.substring(1).split(Constant.sessionIdJoinFlag);\n for (String strSessionId : strSessionIds) {\n serverQuerySessionIdQueue.put(Integer.parseInt(strSessionId));\n }\n }\n }\n }\n\n return isEmpty;\n }\n\n\n}" } ]
import lombok.extern.slf4j.Slf4j; import okhttp3.Response; import org.apache.logging.log4j.core.config.Configurator; import org.wowtools.common.utils.ResourcesReader; import org.wowtools.hppt.common.util.AesCipherUtil; import org.wowtools.hppt.common.util.BytesUtil; import org.wowtools.hppt.common.util.Constant; import org.wowtools.hppt.common.util.HttpUtil; import org.wowtools.hppt.sc.pojo.ScConfig; import org.wowtools.hppt.sc.service.ClientPort; import org.wowtools.hppt.sc.service.ClientSession; import org.wowtools.hppt.sc.service.ClientSessionManager; import org.wowtools.hppt.sc.service.ClientSessionService; import java.io.File; import java.net.URLEncoder; import java.nio.charset.StandardCharsets;
8,314
package org.wowtools.hppt.sc; /** * @author liuyu * @date 2023/11/25 */ @Slf4j public class StartSc { public static final ScConfig config;
package org.wowtools.hppt.sc; /** * @author liuyu * @date 2023/11/25 */ @Slf4j public class StartSc { public static final ScConfig config;
public static final AesCipherUtil aesCipherUtil;
0
2023-12-22 14:14:27+00:00
12k
3arthqu4ke/phobot
src/main/java/me/earth/phobot/PhobotPlugin.java
[ { "identifier": "GotoCommand", "path": "src/main/java/me/earth/phobot/commands/GotoCommand.java", "snippet": "public class GotoCommand extends AbstractPhobotCommand {\n public GotoCommand(Phobot phobot) {\n super(\"goto\", \"Go to the specified location.\", phobot);\n }\n\n @Override\n public void build(LiteralArgumentBuilder<CommandSource> builder) {\n builder.executes(ctx -> {\n if (mc.player != null) {\n mc.gui.getChat().addMessage(Component.literal(\"Use 'goto <position>' to go to a position. Your current position is \" + mc.player.blockPosition()));\n }\n\n return Command.SINGLE_SUCCESS;\n }).then(arg(\"position\", new Vec3Argument()).executes(ctx -> {\n if (mc.player != null) {\n Vec3 startPos = mc.player.position();\n Vec3 pos = ctx.getArgument(\"position\", Vec3.class);\n MeshNode start = phobot.getNavigationMeshManager().getMap().values().stream().min(Comparator.comparingDouble(n -> n.distanceSq(startPos))).orElse(null);\n MeshNode goal = phobot.getNavigationMeshManager().getMap().values().stream().min(Comparator.comparingDouble(n -> n.distanceSq(pos))).orElse(null);\n if (start != null && goal != null) {\n mc.gui.getChat().addMessage(Component.literal(\"Going from \" + start + \" to \" + goal));\n Algorithm<MeshNode> algorithm = new AStar<>(start, goal);\n var future = CancellationTaskUtil.runWithTimeOut(algorithm, phobot.getTaskService(), 10_000, phobot.getExecutorService());\n AlgorithmRenderer.render(future, pingBypass.getEventBus(), algorithm);\n future.thenAccept(list -> {\n if (list == null) {\n // fail!\n return;\n }\n\n Path<MeshNode> path = new Path<>(startPos, pos, BlockPos.containing(startPos), BlockPos.containing(pos), Collections.emptySet(), Algorithm.reverse(list), MeshNode.class);\n pingBypass.getEventBus().subscribe(new PathRenderer(path, pingBypass));\n mc.submit(() -> mc.gui.getChat().addMessage(Component.literal(\"Found path from \" + start + \" to \" + goal)));\n phobot.getPathfinder().getMovementPathfinder().follow(phobot, path);\n });\n }\n }\n\n //phobot.getPathfinder().gotoPosition(pos, MovementNodeMapper.INSTANCE, false);\n }));\n }\n\n}" }, { "identifier": "KitCommand", "path": "src/main/java/me/earth/phobot/commands/KitCommand.java", "snippet": "public class KitCommand extends AbstractCommand {\n public KitCommand() {\n super(\"kit\", \"Gives you a kit.\");\n }\n\n @Override\n public void build(LiteralArgumentBuilder<CommandSource> builder) {\n builder.executes(ctx -> {\n LocalPlayer player = ctx.getSource().getMinecraft().player;\n if (player != null) {\n ItemStack helmet = new ItemStack(Items.NETHERITE_HELMET);\n unbreakingAndMending(helmet);\n helmet.enchant(Enchantments.ALL_DAMAGE_PROTECTION, 4);\n helmet.enchant(Enchantments.AQUA_AFFINITY, 1);\n helmet.enchant(Enchantments.RESPIRATION, 3);\n\n ItemStack chest = new ItemStack(Items.NETHERITE_CHESTPLATE);\n unbreakingAndMending(chest);\n chest.enchant(Enchantments.ALL_DAMAGE_PROTECTION, 4);\n\n ItemStack legs = new ItemStack(Items.NETHERITE_LEGGINGS);\n unbreakingAndMending(legs);\n legs.enchant(Enchantments.BLAST_PROTECTION, 4);\n\n ItemStack boots = new ItemStack(Items.NETHERITE_BOOTS);\n unbreakingAndMending(boots);\n boots.enchant(Enchantments.ALL_DAMAGE_PROTECTION, 4);\n boots.enchant(Enchantments.FALL_PROTECTION, 4);\n boots.enchant(Enchantments.SOUL_SPEED, 3);\n // boots.enchant(Enchantments.DEPTH_STRIDER, 3);\n\n ItemStack sword = new ItemStack(Items.NETHERITE_SWORD);\n unbreakingAndMending(sword);\n sword.enchant(Enchantments.SHARPNESS, 5);\n sword.enchant(Enchantments.FIRE_ASPECT, 2);\n sword.enchant(Enchantments.KNOCKBACK, 2);\n\n ItemStack pick = new ItemStack(Items.NETHERITE_PICKAXE);\n unbreakingAndMending(pick);\n pick.enchant(Enchantments.BLOCK_EFFICIENCY, 5);\n pick.enchant(Enchantments.BLOCK_FORTUNE, 3);\n\n ShulkerBoxBlockEntity shulkerBoxBlockEntity = new ShulkerBoxBlockEntity(BlockPos.ZERO, Blocks.SHULKER_BOX.defaultBlockState());\n shulkerBoxBlockEntity.setItem(0, helmet);\n shulkerBoxBlockEntity.setItem(1, chest);\n shulkerBoxBlockEntity.setItem(2, legs);\n shulkerBoxBlockEntity.setItem(3, boots);\n shulkerBoxBlockEntity.setItem(4, sword);\n shulkerBoxBlockEntity.setItem(5, pick);\n shulkerBoxBlockEntity.setItem(6, new ItemStack(Items.CHORUS_FRUIT, 64));\n shulkerBoxBlockEntity.setItem(7, new ItemStack(Items.OBSIDIAN, 64));\n shulkerBoxBlockEntity.setItem(8, new ItemStack(Items.ENDER_CHEST, 64));\n for (int i = 9; i < 16; i++) {\n shulkerBoxBlockEntity.setItem(i, new ItemStack(Items.EXPERIENCE_BOTTLE, 64));\n }\n\n for (int i = 16; i < 18; i++) {\n shulkerBoxBlockEntity.setItem(i, new ItemStack(Items.TOTEM_OF_UNDYING));\n }\n\n for (int i = 18; i < 25; i++) {\n shulkerBoxBlockEntity.setItem(i, new ItemStack(Items.END_CRYSTAL, 64));\n }\n\n for (int i = 25; i < 27; i++) {\n shulkerBoxBlockEntity.setItem(i, new ItemStack(Items.ENCHANTED_GOLDEN_APPLE, 64));\n }\n\n CompoundTag tag = shulkerBoxBlockEntity.saveWithFullMetadata();\n ItemStack stack = new ItemStack(Items.SHULKER_BOX);\n BlockItem.setBlockEntityData(stack, shulkerBoxBlockEntity.getType(), tag);\n\n player.getInventory().setItem(0, stack);\n if (player.isCreative()) {\n player.connection.send(new ServerboundSetCreativeModeSlotPacket(36, stack));\n } else if (ctx.getSource().getMinecraft().isSingleplayer()) {\n IntegratedServer server = ctx.getSource().getMinecraft().getSingleplayerServer();\n if (server != null) {\n Player singlePlayer = server.getPlayerList().getPlayer(player.getUUID());\n if (singlePlayer != null) {\n singlePlayer.getInventory().setItem(0, stack);\n }\n }\n }\n }\n\n return Command.SINGLE_SUCCESS;\n });\n }\n\n private void unbreakingAndMending(ItemStack stack) {\n stack.enchant(Enchantments.UNBREAKING, 3);\n stack.enchant(Enchantments.MENDING, 1);\n }\n\n}" }, { "identifier": "TeleportCommand", "path": "src/main/java/me/earth/phobot/commands/TeleportCommand.java", "snippet": "public class TeleportCommand extends AbstractPbCommand {\n public TeleportCommand(PingBypass pingBypass) {\n super(\"Teleport\", \"Teleports you somewhere.\", pingBypass, pingBypass.getMinecraft());\n }\n\n @Override\n public void build(LiteralArgumentBuilder<CommandSource> builder) {\n builder.then(arg(\"position\", new Vec3Argument()).executes(ctx -> {\n Vec3 pos = ctx.getArgument(\"position\", Vec3.class);\n LocalPlayer player = mc.player;\n if (player != null) {\n pingBypass.getChat().send(Component.literal(\"Teleporting you to \" + PositionUtil.toSimpleString(pos)).withStyle(ChatFormatting.GREEN));\n player.setPos(pos);\n } else {\n pingBypass.getChat().send(Component.literal(\"You need to be ingame to use this command.\").withStyle(ChatFormatting.RED));\n }\n }));\n }\n\n}" }, { "identifier": "HoleManager", "path": "src/main/java/me/earth/phobot/holes/HoleManager.java", "snippet": "public class HoleManager extends AbstractInvalidationManager<Hole, ConfigWithMinMaxHeight> implements HoleBlocks, HoleOffsets {\n public HoleManager(ConfigWithMinMaxHeight config, Map<BlockPos, Hole> map) {\n super(config, map);\n }\n\n @Override\n protected AbstractInvalidationTask<?, ?> getChunkTask(LevelChunk levelChunk, ChunkWorker chunk) {\n return new HoleTask(mc, levelChunk, chunk, config.getMaxHeight(), config.getMinHeight(), this);\n }\n\n @Override\n protected ChunkWorker getChunkWorker(LevelChunk chunk) {\n return ((ChunkWorkerProvider) chunk).phobot$getHoleChunkWorker();\n }\n\n @Override\n protected void addPostWorkingTask(BlockPos pos, BlockState state, ChunkWorker worker, LevelChunk chunk) {\n worker.addTask(() -> {\n Block block = state.getBlock();\n if (noBlastBlocks().contains(block)) {\n BlockHoleTask onBlockAdded = new BlockHoleTask(mc, chunk.getLevel(), this);\n onBlockAdded.setPos(pos);\n onBlockAdded.setChunk(worker);\n onBlockAdded.execute();\n } else if (state.getCollisionShape(mc.level, pos).isEmpty()) {\n AirHoleTask onAirAdded = new AirHoleTask(mc, chunk.getLevel(), this);\n onAirAdded.setPos(pos);\n onAirAdded.setChunk(worker);\n onAirAdded.execute();\n }\n });\n }\n\n @Override\n protected void invalidate(MutPos pos, BlockState state, ChunkWorker chunk) {\n if (noBlastBlocks().contains(state.getBlock())) {\n invalidate(BLOCK_OFFSETS);\n } else if (state.getCollisionShape(mc.level, pos).isEmpty()) {\n invalidate(AIR_OFFSETS);\n } else {\n int x = mutPos.getX();\n int y = mutPos.getY();\n int z = mutPos.getZ();\n invalidate(AIR_OFFSETS);\n mutPos.set(x, y, z);\n invalidate(BLOCK_OFFSETS);\n }\n }\n\n private void invalidate(Vec3i... offsets) {\n for (Vec3i vec3i : offsets) {\n mutPos.incrementX(vec3i.getX());\n mutPos.incrementY(vec3i.getY());\n mutPos.incrementZ(vec3i.getZ());\n Hole hole = map.get(mutPos);\n if (hole != null && hole.isAirPart(mutPos)) {\n // TODO: remove hole properly with all of its offsets!\n map.remove(mutPos);\n hole.invalidate();\n }\n }\n }\n\n}" }, { "identifier": "AntiCheat", "path": "src/main/java/me/earth/phobot/modules/client/anticheat/AntiCheat.java", "snippet": "@Getter\npublic class AntiCheat extends ModuleImpl {\n private final Setting<Integer> actions = number(\"Actions\", 8, 1, 100, \"Block placement actions to perform per tick.\");\n private final Setting<Double> miningRange = precise(\"MiningRange\", 5.25, 0.1, 6.0, \"Range within which you can mine blocks.\");\n\n private final Setting<StrictDirection.Type> strictDirection = constant(\"StrictDirection\", StrictDirection.Type.Grim, \"Strict direction checks.\");\n private final Setting<StrictDirection.Type> miningStrictDirection = constant(\"MiningStrictDirection\", StrictDirection.Type.NCP, \"There seems to be no strict direction check for mining on Grim.\");\n private final Setting<StrictDirection.Type> crystalStrictDirection = constant(\"CrystalStrictDirection\", StrictDirection.Type.NCP, \"There seems to be no strict direction check for placing crystals on Grim.\");\n\n private final Setting<Boolean> miningRotations = bool(\"MiningRotations\", true, \"Rotates when mining.\");\n private final Setting<Boolean> blockRotations = bool(\"BlockRotations\", true, \"Rotates when placing blocks.\");\n private final Setting<Boolean> crystalRotations = bool(\"CrystalRotations\", false, \"Rotates when placing crystals.\");\n private final Setting<Boolean> attackRotations = bool(\"AttackRotations\", false, \"Rotates when attacking.\");\n\n private final Setting<Integer> maxBuildHeight = number(\"MaxBuildHeight\", 100, -64, 320, \"Maximum buildheight of the server.\");\n private final Setting<Integer> inventoryDelay = number(\"InventoryDelay\", 75, 0, 500, \"Delay between inventory clicks. (I could spam SWAP packets as slow as 67ms on CC).\");\n private final Setting<Integer> updates = number(\"Updates\", 1, 1, 10, \"Frequency with which entities get updated. CrystalPvP.cc seems to send an update packet every tick.\");\n private final Setting<Double> lagbackThreshold = precise(\"LagBackThreshold\", 3.0, 1.0, 10.0, \"If a player moves this amount during a tick we consider it a lagback/teleport.\");\n private final Setting<Boolean> cC = bool(\"CC\", false, \"We automatically detect if a server is crystalpvp.cc, but with this you can manually use cc settings on other servers.\");\n private final Setting<Boolean> closeInv = bool(\"CloseInventory\", false, \"If we have to send a ServerboundContainerClosePacket after every inventory click.\");\n private final Setting<Boolean> opposite = bool(\"Opposite\", true, \"Allows to raytrace through a block and place on the other side.\");\n private final Setting<RaytraceOptimization> raytraceOptimization = constant(\"Optimization\", RaytraceOptimization.None, \"Mode cc makes some raytrace optimizations for the FFA world.\");\n private final DamageCalculator defaultCalculator = new DamageCalculator(Raytracer.level());\n private final DamageCalculator ccCalculator = new DamageCalculator(Raytracer.cc());\n private final ServerService serverService;\n\n public AntiCheat(PingBypass pingBypass, ServerService serverService) {\n super(pingBypass, \"AntiCheat\", Categories.CLIENT, \"Configures the AntiCheat.\");\n this.serverService = serverService;\n }\n\n public DamageCalculator getDamageCalculator() {\n return raytraceOptimization.getValue() == RaytraceOptimization.CC ? ccCalculator : defaultCalculator;\n }\n\n public boolean isAboveBuildHeight(LocalPlayer player) {\n return player.getY() > maxBuildHeight.getValue();\n }\n\n public boolean isAboveBuildHeight(double y) {\n return y > maxBuildHeight.getValue();\n }\n\n public boolean isCC() {\n return serverService.isCurrentServerCC() || cC.getValue();\n }\n\n public double getMiningRangeSq() {\n return Mth.square(miningRange.getValue());\n }\n\n public StrictDirection getStrictDirectionCheck() {\n return getStrictDirectionCheck(strictDirection);\n }\n\n public StrictDirection getMiningStrictDirectionCheck() {\n return getStrictDirectionCheck(miningStrictDirection);\n }\n\n public StrictDirection getCrystalStrictDirectionCheck() {\n return getStrictDirectionCheck(crystalStrictDirection);\n }\n\n public StrictDirection getStrictDirectionCheck(HoldsValue<StrictDirection.Type> type) {\n return switch (type.getValue()) {\n case NCP -> NCP.INSTANCE;\n case Grim -> Grim.INSTANCE;\n default -> Vanilla.INSTANCE;\n };\n }\n\n public enum RaytraceOptimization {\n None,\n CC\n }\n\n}" }, { "identifier": "AutoCrystal", "path": "src/main/java/me/earth/phobot/modules/combat/autocrystal/AutoCrystal.java", "snippet": "public class AutoCrystal extends CrystalPlacingModule {\n public AutoCrystal(Phobot phobot, SurroundService surroundService) {\n super(phobot, surroundService, \"AutoCrystal\", Categories.COMBAT, \"Automatically places crystals. The settings were designed specifically for a ping of about 30ms.\");\n }\n\n}" }, { "identifier": "Pathfinder", "path": "src/main/java/me/earth/phobot/pathfinder/Pathfinder.java", "snippet": "@Slf4j\n@Getter\npublic class Pathfinder extends SubscriberImpl {\n private final NavigationMeshManager navigationMeshManager;\n private final MovementPathfinder movementPathfinder;\n\n public Pathfinder(PingBypass pingBypass, NavigationMeshManager navigationMeshManager, MovementService movementService, ExecutorService executor) {\n this.navigationMeshManager = navigationMeshManager;\n this.movementPathfinder = new VisualizingMovementPathfinder(pingBypass); // TODO: subscribe?\n }\n\n}" }, { "identifier": "AlgorithmRenderer", "path": "src/main/java/me/earth/phobot/pathfinder/algorithm/AlgorithmRenderer.java", "snippet": "public class AlgorithmRenderer<T extends PathfindingNode<T>> extends SubscriberImpl {\n private final RenderableAlgorithm<T> algorithm;\n\n public AlgorithmRenderer(RenderableAlgorithm<T> algorithm) {\n this.algorithm = algorithm;\n listen(new Listener<RenderEvent>() {\n @Override\n public void onEvent(RenderEvent event) {\n render(event);\n }\n });\n }\n\n public void render(RenderEvent event) {\n T current = algorithm.getCurrent();\n if (current != null) {\n Renderer.startLines(1.5f, true);\n event.getLineColor().set(Color.RED);\n event.getBoxColor().set(Color.RED);\n event.getAabb().set(current.getRenderX() - 0.125, current.getRenderY() - 0.125, current.getRenderZ() - 0.125,\n current.getRenderX() + 0.125, current.getRenderY() + 0.125, current.getRenderZ() + 0.125);\n Renderer.drawAABBOutline(event);\n if (algorithm instanceof MovementPathfindingAlgorithm movementPathfindingAlgorithm && !((MovementNode) current).isGoal()) {\n MeshNode mesh = movementPathfindingAlgorithm.getPath().getPath().get(((MovementNode) current).targetNodeIndex());\n event.getLineColor().set(Color.CYAN);\n event.getAabb().set(mesh.getRenderX() - 0.125, mesh.getRenderY() - 0.125, mesh.getRenderZ() - 0.125,\n mesh.getRenderX() + 0.125, mesh.getRenderY() + 0.125, mesh.getRenderZ() + 0.125);\n Renderer.drawAABBOutline(event);\n event.getLineColor().set(Color.RED);\n }\n\n T goal = algorithm.getGoal();\n if (goal != null) {\n event.getAabb().set(goal.getRenderX() - 0.125, goal.getRenderY() - 0.125, goal.getRenderZ() - 0.125,\n goal.getRenderX() + 0.125, goal.getRenderY() + 0.125, goal.getRenderZ() + 0.125);\n Renderer.drawAABBOutline(event);\n }\n\n for (int i = 0; i < 10_000_000; i++) { // just to ensure this does not become infinite for any reason\n T previous = algorithm.getCameFrom(current);\n if (previous != null) {\n event.getTo().set(current.getRenderX(), current.getRenderY(), current.getRenderZ());\n event.getFrom().set(previous.getRenderX(), previous.getRenderY(), previous.getRenderZ());\n Renderer.drawLine(event);\n current = previous;\n } else {\n Renderer.end(true);\n return;\n }\n }\n\n Renderer.end(true);\n }\n }\n\n public static <T extends PathfindingNode<T>> void render(CompletableFuture<?> future, EventBus eventBus, Algorithm<T> algorithm) {\n AlgorithmRenderer<T> renderer = new AlgorithmRenderer<>(algorithm);\n eventBus.subscribe(renderer);\n future.whenComplete((r,t) -> eventBus.unsubscribe(renderer));\n }\n\n}" }, { "identifier": "NavigationMeshManager", "path": "src/main/java/me/earth/phobot/pathfinder/mesh/NavigationMeshManager.java", "snippet": "@Slf4j\n@Getter\npublic class NavigationMeshManager extends AbstractInvalidationManager<MeshNode, ConfigWithMinMaxHeight> {\n private final XZMap<Set<MeshNode>> xZMap;\n private final Movement movement;\n\n public NavigationMeshManager(ConfigWithMinMaxHeight config, Movement movement, Map<BlockPos, MeshNode> map, XZMap<Set<MeshNode>> xZMap) {\n super(config, map);\n this.xZMap = xZMap;\n this.movement = movement;\n }\n\n @Override\n protected AbstractInvalidationTask<?, ?> getChunkTask(LevelChunk lvlChunk, ChunkWorker chunk) {\n return new MeshTask(mc, lvlChunk, chunk, config.getMaxHeight(), config.getMinHeight(), this);\n }\n\n @Override\n protected ChunkWorker getChunkWorker(LevelChunk chunk) {\n return ((ChunkWorkerProvider) chunk).phobot$getGraphChunkWorker();\n }\n\n @Override\n protected void addPostWorkingTask(BlockPos pos, BlockState state, ChunkWorker worker, LevelChunk chunk) {\n if (pos.getY() <= getConfig().getMaxHeight() && pos.getY() >= getConfig().getMinHeight()) {\n if (state.getCollisionShape(mc.level, pos).isEmpty()) {\n worker.addTask(new AirBlockTask(mc, chunk.getLevel(), worker, this, pos));\n } else {\n worker.addTask(new SolidBlockTask(mc, chunk.getLevel(), worker, this, pos));\n }\n }\n }\n\n @Override\n protected void addInvalidateTask(BlockPos pos, BlockState state, ChunkWorker worker) {\n // NOP, BlockChangeTask does that\n }\n\n @Override\n protected void invalidate(MutPos pos, BlockState state, ChunkWorker chunk) {\n // NOP, BlockChangeTask does that\n }\n\n @Override\n protected void removeInvalids(LevelChunk chunk) {\n MutPos pos = new MutPos();\n for (int x = chunk.getPos().getMinBlockX(); x <= chunk.getPos().getMaxBlockX(); x++) {\n for (int z = chunk.getPos().getMinBlockZ(); z <= chunk.getPos().getMaxBlockZ(); z++) {\n Set<MeshNode> nodes = xZMap.get(x, z);\n if (nodes != null) {\n nodes.forEach(node -> {\n pos.set(node.getX(), node.getY(), node.getZ());\n map.remove(pos);\n });\n\n xZMap.remove(x, z);\n }\n }\n }\n }\n\n @Override\n protected void reset() {\n super.reset();\n xZMap.clear();\n }\n\n}" }, { "identifier": "InventoryService", "path": "src/main/java/me/earth/phobot/services/inventory/InventoryService.java", "snippet": "@Slf4j\n@Getter\npublic class InventoryService extends SubscriberImpl {\n private final AtomicBoolean lockedIntoEating = new AtomicBoolean();\n private final AtomicBoolean lockedIntoTotem = new AtomicBoolean();\n private final AtomicBoolean switchBack = new AtomicBoolean(true);\n private final AtomicBoolean mining = new AtomicBoolean();\n private final Lock lock = new ReentrantLock();\n private final AntiCheat antiCheat;\n private final Minecraft mc;\n\n private InventoryContext playerUpdateContext;\n\n public InventoryService(AntiCheat antiCheat) {\n this.antiCheat = antiCheat;\n this.mc = antiCheat.getPingBypass().getMinecraft();\n listen(new SafeListener<PreMotionPlayerUpdateEvent>(mc, Integer.MAX_VALUE) {\n @Override\n public void onEvent(PreMotionPlayerUpdateEvent event, LocalPlayer player, ClientLevel level, MultiPlayerGameMode gameMode) {\n if (mc.isSameThread()) {\n // locking the lock without a \"finally\" for the entire UpdateEvent is dangerous, but also the only way to lock around it.\n // I hope the GameloopEvent and ShutDownEvents are enough to catch any exceptions happening.\n lock.lock();\n playerUpdateContext = new InventoryContext(InventoryService.this, player, gameMode);\n }\n }\n });\n\n listen(new SafeListener<PostMotionPlayerUpdateEvent>(mc, Integer.MIN_VALUE) {\n @Override\n public void onEvent(PostMotionPlayerUpdateEvent event, LocalPlayer player, ClientLevel level, MultiPlayerGameMode gameMode) {\n releasePlayerUpdateLock();\n }\n });\n\n listen(new SafeListener<GameloopEvent>(mc) {\n @Override\n public void onEvent(GameloopEvent event, LocalPlayer player, ClientLevel level, MultiPlayerGameMode gameMode) {\n if (playerUpdateContext != null) {\n log.warn(\"PlayerUpdateLock has not been released until next GameloopEvent, has someone cancelled the PlayerUpdateEvent?\");\n releasePlayerUpdateLock();\n }\n }\n });\n\n listen(new Listener<ShutdownEvent>() {\n @Override\n public void onEvent(ShutdownEvent event) {\n if (playerUpdateContext != null) {\n log.warn(\"PlayerUpdateLock has not been released until ShutDown, has someone cancelled the PlayerUpdateEvent?\");\n releasePlayerUpdateLock();\n }\n }\n });\n }\n\n public void use(Consumer<InventoryContext> action) {\n use(action, false);\n }\n\n public void use(Consumer<InventoryContext> action, boolean useNestedContext) {\n NullabilityUtil.safe(mc, (player, level, gameMode) -> {\n if (playerUpdateContext != null && mc.isSameThread()) {\n if (useNestedContext) {\n InventoryContext context = new InventoryContext(this, player, gameMode);\n action.accept(context);\n context.end();\n } else {\n action.accept(playerUpdateContext);\n }\n } else {\n try {\n lock.lock();\n InventoryContext context = new InventoryContext(this, player, gameMode);\n action.accept(context);\n context.end();\n } finally {\n lock.unlock();\n }\n }\n });\n }\n\n public void releasePlayerUpdateLock() {\n if (playerUpdateContext != null && mc.isSameThread()) {\n playerUpdateContext.end();\n\n try {\n lock.unlock();\n } catch (IllegalMonitorStateException e) {\n log.error(\"Failed to unlock lock unexpectedly\", e);\n }\n\n playerUpdateContext = null;\n }\n }\n\n}" }, { "identifier": "XZMap", "path": "src/main/java/me/earth/phobot/util/collections/XZMap.java", "snippet": "public class XZMap<T> implements Map<Long, T> {\n @Delegate\n private final Map<Long, T> map;\n\n public XZMap(Map<Long, T> map) {\n this.map = map;\n }\n\n public T get(int x, int z) {\n return map.get(getKey(x, z));\n }\n\n public T getOrDefault(int x, int z, T defaultValue) {\n return map.getOrDefault(getKey(x, z), defaultValue);\n }\n\n public T getOrDefault(Vec3i key, T defaultValue) {\n return getOrDefault(key.getX(), key.getZ(), defaultValue);\n }\n\n public T get(Vec3i key) {\n return get(key.getX(), key.getZ());\n }\n\n public T put(int x, int z, T value) {\n return map.put(getKey(x, z), value);\n }\n\n public T put(Vec3i key, T value) {\n return put(key.getX(), key.getZ(), value);\n }\n\n public T computeIfAbsent(int x, int z, Function<? super Long, ? extends T> mappingFunction) {\n return map.computeIfAbsent(getKey(x, z), mappingFunction);\n }\n\n public T computeIfAbsent(Vec3i key, Function<? super Long, ? extends T> mappingFunction) {\n return computeIfAbsent(key.getX(), key.getZ(), mappingFunction);\n }\n\n public T remove(int x, int z) {\n return map.remove(getKey(x, z));\n }\n\n public T remove(Vec3i key) {\n return remove(key.getX(), key.getZ());\n }\n\n public long getKey(int x, int z) {\n return (((long) x) << 32) | (z & 0xffffffffL);\n }\n\n}" } ]
import me.earth.phobot.commands.GotoCommand; import me.earth.phobot.commands.KitCommand; import me.earth.phobot.commands.TeleportCommand; import me.earth.phobot.holes.HoleManager; import me.earth.phobot.modules.client.*; import me.earth.phobot.modules.client.anticheat.AntiCheat; import me.earth.phobot.modules.combat.*; import me.earth.phobot.modules.combat.autocrystal.AutoCrystal; import me.earth.phobot.modules.misc.*; import me.earth.phobot.modules.movement.*; import me.earth.phobot.pathfinder.Pathfinder; import me.earth.phobot.pathfinder.algorithm.AlgorithmRenderer; import me.earth.phobot.pathfinder.mesh.NavigationMeshManager; import me.earth.phobot.services.*; import me.earth.phobot.services.inventory.InventoryService; import me.earth.phobot.util.collections.XZMap; import me.earth.pingbypass.PingBypass; import me.earth.pingbypass.api.event.api.Subscriber; import me.earth.pingbypass.api.plugin.impl.AbstractUnloadablePlugin; import me.earth.pingbypass.api.plugin.impl.PluginUnloadingService; import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicInteger;
7,402
package me.earth.phobot; @SuppressWarnings("unused") public class PhobotPlugin extends AbstractUnloadablePlugin { private Phobot phobot; @Override public void load(PingBypass pingBypass, PluginUnloadingService unloadingService) { ExecutorService executor = getExecutorService(); Phobot phobot = initalizePhobot(pingBypass, executor, unloadingService); registerCommands(pingBypass, phobot, unloadingService); registerModules(pingBypass, phobot, unloadingService); unloadingService.runOnUnload(executor::shutdown); PhobotApi.setPhobot(phobot); this.phobot = phobot; } @Override public void unload() { super.unload(); if (Objects.equals(PhobotApi.getPhobot(), phobot)) { if (phobot != null) { phobot.getInventoryService().releasePlayerUpdateLock(); } PhobotApi.setPhobot(null); this.phobot = null; } } private Phobot initalizePhobot(PingBypass pingBypass, ExecutorService executor, PluginUnloadingService unloadingService) { WorldVersionService worldVersionService = subscribe(unloadingService, new WorldVersionService()); MovementService movementService = new MovementService(); Holes holes = new Holes(pingBypass, executor); unloadingService.registerModule(holes); HoleManager holeManager = subscribe(unloadingService, new HoleManager(holes, new ConcurrentHashMap<>())); new HolesRenderListener(holeManager, holes).getListeners().forEach(holes::listen); ProtectionCacheService protectionCacheService = subscribe(unloadingService, new ProtectionCacheService(pingBypass.getMinecraft())); AttackService attackService = subscribe(unloadingService, new AttackService(pingBypass.getMinecraft())); TotemPopService totemPopService = subscribe(unloadingService, new TotemPopService(pingBypass.getMinecraft())); DamageService damageService = subscribe(unloadingService, new DamageService(protectionCacheService, pingBypass.getMinecraft())); Pathfinding pathfinding = new Pathfinding(pingBypass, executor); unloadingService.registerModule(pathfinding); NavigationMeshManager navigationMeshManager = subscribe(unloadingService, new NavigationMeshManager(pathfinding, movementService.getMovement(), new ConcurrentHashMap<>(), new XZMap<>(new ConcurrentHashMap<>()))); pathfinding.listen(new GraphDebugRenderer(navigationMeshManager, pathfinding, pingBypass.getMinecraft()));
package me.earth.phobot; @SuppressWarnings("unused") public class PhobotPlugin extends AbstractUnloadablePlugin { private Phobot phobot; @Override public void load(PingBypass pingBypass, PluginUnloadingService unloadingService) { ExecutorService executor = getExecutorService(); Phobot phobot = initalizePhobot(pingBypass, executor, unloadingService); registerCommands(pingBypass, phobot, unloadingService); registerModules(pingBypass, phobot, unloadingService); unloadingService.runOnUnload(executor::shutdown); PhobotApi.setPhobot(phobot); this.phobot = phobot; } @Override public void unload() { super.unload(); if (Objects.equals(PhobotApi.getPhobot(), phobot)) { if (phobot != null) { phobot.getInventoryService().releasePlayerUpdateLock(); } PhobotApi.setPhobot(null); this.phobot = null; } } private Phobot initalizePhobot(PingBypass pingBypass, ExecutorService executor, PluginUnloadingService unloadingService) { WorldVersionService worldVersionService = subscribe(unloadingService, new WorldVersionService()); MovementService movementService = new MovementService(); Holes holes = new Holes(pingBypass, executor); unloadingService.registerModule(holes); HoleManager holeManager = subscribe(unloadingService, new HoleManager(holes, new ConcurrentHashMap<>())); new HolesRenderListener(holeManager, holes).getListeners().forEach(holes::listen); ProtectionCacheService protectionCacheService = subscribe(unloadingService, new ProtectionCacheService(pingBypass.getMinecraft())); AttackService attackService = subscribe(unloadingService, new AttackService(pingBypass.getMinecraft())); TotemPopService totemPopService = subscribe(unloadingService, new TotemPopService(pingBypass.getMinecraft())); DamageService damageService = subscribe(unloadingService, new DamageService(protectionCacheService, pingBypass.getMinecraft())); Pathfinding pathfinding = new Pathfinding(pingBypass, executor); unloadingService.registerModule(pathfinding); NavigationMeshManager navigationMeshManager = subscribe(unloadingService, new NavigationMeshManager(pathfinding, movementService.getMovement(), new ConcurrentHashMap<>(), new XZMap<>(new ConcurrentHashMap<>()))); pathfinding.listen(new GraphDebugRenderer(navigationMeshManager, pathfinding, pingBypass.getMinecraft()));
Pathfinder pathfinder = subscribe(unloadingService, new Pathfinder(pingBypass, navigationMeshManager, movementService, executor));
6
2023-12-22 14:32:16+00:00
12k
ArmanKhanDev/FakepixelDungeonHelper
build/sources/main/java/io/github/quantizr/handlers/ConfigHandler.java
[ { "identifier": "DungeonRooms", "path": "build/sources/main/java/io/github/quantizr/DungeonRooms.java", "snippet": "@Mod(modid = DungeonRooms.MODID, version = DungeonRooms.VERSION)\npublic class DungeonRooms\n{\n public static final String MODID = \"FDH\";\n public static final String VERSION = \"2.0\";\n\n Minecraft mc = Minecraft.getMinecraft();\n public static Logger logger;\n\n public static JsonObject roomsJson;\n public static JsonObject waypointsJson;\n static boolean updateChecked = false;\n public static boolean usingSBPSecrets = false;\n public static String guiToOpen = null;\n public static KeyBinding[] keyBindings = new KeyBinding[2];\n public static String hotkeyOpen = \"gui\";\n static int tickAmount = 1;\n public static List<String> motd = null;\n\n @EventHandler\n public void preInit(final FMLPreInitializationEvent event) {\n ClientCommandHandler.instance.registerCommand(new DungeonRoomCommand());\n logger = LogManager.getLogger(\"DungeonRooms\");\n }\n\n @EventHandler\n public void init(FMLInitializationEvent event) {\n MinecraftForge.EVENT_BUS.register(this);\n MinecraftForge.EVENT_BUS.register(new AutoRoom());\n MinecraftForge.EVENT_BUS.register(new Waypoints());\n\n ConfigHandler.reloadConfig();\n\n try {\n ResourceLocation roomsLoc = new ResourceLocation( \"dungeonrooms\",\"dungeonrooms.json\");\n InputStream roomsIn = Minecraft.getMinecraft().getResourceManager().getResource(roomsLoc).getInputStream();\n BufferedReader roomsReader = new BufferedReader(new InputStreamReader(roomsIn));\n\n ResourceLocation waypointsLoc = new ResourceLocation( \"dungeonrooms\",\"secretlocations.json\");\n InputStream waypointsIn = Minecraft.getMinecraft().getResourceManager().getResource(waypointsLoc).getInputStream();\n BufferedReader waypointsReader = new BufferedReader(new InputStreamReader(waypointsIn));\n\n Gson gson = new Gson();\n roomsJson = gson.fromJson(roomsReader, JsonObject.class);\n logger.info(\"DungeonRooms: Loaded dungeonrooms.json\");\n\n waypointsJson = gson.fromJson(waypointsReader, JsonObject.class);\n logger.info(\"DungeonRooms: Loaded secretlocations.json\");\n } catch (IOException e) {\n e.printStackTrace();\n }\n\n keyBindings[0] = new KeyBinding(\"Open Room Images in DSG/SBP\", Keyboard.KEY_O, \"FakepixelDungeonHelper Mod\");\n keyBindings[1] = new KeyBinding(\"Open Waypoint Menu\", Keyboard.KEY_P, \"FakepixelDungeonHelper Mod\");\n for (KeyBinding keyBinding : keyBindings) {\n ClientRegistry.registerKeyBinding(keyBinding);\n }\n }\n\n @EventHandler\n public void postInit(final FMLPostInitializationEvent event) {\n usingSBPSecrets = Loader.isModLoaded(\"sbp\");\n DungeonRooms.logger.info(\"FDH: SBP Dungeon Secrets detection: \" + usingSBPSecrets);\n }\n\n /*\n Update Checker taken from Danker's Skyblock Mod (https://github.com/bowser0000/SkyblockMod/).\n This code was released under GNU General Public License v3.0 and remains under said license.\n Modified by Quantizr (_risk) in Feb. 2021.\n */\n @SubscribeEvent\n public void onJoin(EntityJoinWorldEvent event) {\n EntityPlayer player = Minecraft.getMinecraft().thePlayer;\n\n if (!updateChecked) {\n updateChecked = true;\n\n // MULTI THREAD DRIFTING\n new Thread(() -> {\n try {\n DungeonRooms.logger.info(\"FDH: Checking for updates...\");\n\n URL url = new URL(\"https://discord.com/fakepixel\");\n URLConnection request = url.openConnection();\n request.connect();\n JsonParser json = new JsonParser();\n JsonObject latestRelease = json.parse(new InputStreamReader((InputStream) request.getContent())).getAsJsonObject();\n\n String latestTag = latestRelease.get(\"tag_name\").getAsString();\n DefaultArtifactVersion currentVersion = new DefaultArtifactVersion(VERSION);\n DefaultArtifactVersion latestVersion = new DefaultArtifactVersion(latestTag.substring(1));\n\n if (currentVersion.compareTo(latestVersion) < 0) {\n String releaseURL = \"https://discord.gg/Fakepixel\";\n ChatComponentText update = new ChatComponentText(EnumChatFormatting.GREEN + \"\" + EnumChatFormatting.BOLD + \" [UPDATE] \");\n update.setChatStyle(update.getChatStyle().setChatClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL, releaseURL)));\n\n try {\n Thread.sleep(2000);\n } catch (InterruptedException ex) {\n ex.printStackTrace();\n }\n player.addChatMessage(new ChatComponentText(EnumChatFormatting.RED + \"FakepixelDungeonHelper Mod is outdated. Please update to \" + latestTag + \".\\n\").appendSibling(update));\n }\n } catch (IOException e) {\n player.addChatMessage(new ChatComponentText(EnumChatFormatting.RED + \"An error has occured. See logs for more details.\"));\n e.printStackTrace();\n }\n\n try {\n URL url = new URL(\"https://gist.githubusercontent.com/Quantizr/0af2afd91cd8b1aa22e42bc2d65cfa75/raw/\");\n BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), \"UTF-8\"));\n String line;\n motd = new ArrayList<>();\n while ((line = in.readLine()) != null) {\n motd.add(line);\n }\n in.close();\n } catch (IOException e) {\n player.addChatMessage(new ChatComponentText(EnumChatFormatting.RED + \"An error has occured. See logs for more details.\"));\n e.printStackTrace();\n }\n }).start();\n }\n }\n\n @SubscribeEvent\n public void renderPlayerInfo(final RenderGameOverlayEvent.Post event) {\n if (event.type != RenderGameOverlayEvent.ElementType.ALL) return;\n if (Utils.inDungeons) {\n if (AutoRoom.guiToggled) {\n AutoRoom.renderText();\n }\n if (AutoRoom.coordToggled) {\n AutoRoom.renderCoord();\n }\n }\n }\n\n @SubscribeEvent\n public void onTick(TickEvent.ClientTickEvent event) {\n if (event.phase != TickEvent.Phase.START) return;\n World world = mc.theWorld;\n EntityPlayerSP player = mc.thePlayer;\n\n tickAmount++;\n\n // Checks every second\n if (tickAmount % 20 == 0) {\n if (player != null) {\n Utils.checkForSkyblock();\n Utils.checkForDungeons();\n tickAmount = 0;\n }\n }\n }\n\n @SubscribeEvent\n public void onKey(InputEvent.KeyInputEvent event) {\n EntityPlayerSP player = Minecraft.getMinecraft().thePlayer;\n if (keyBindings[0].isPressed()) {\n if (!Utils.inDungeons) {\n player.addChatMessage(new ChatComponentText(EnumChatFormatting.RED\n + \"FDH: Use this hotkey in dungeons\"));\n return;\n }\n switch (hotkeyOpen) {\n case \"gui\":\n OpenLink.checkForLink(\"gui\");\n break;\n case \"dsg\":\n OpenLink.checkForLink(\"dsg\");\n break;\n case \"sbp\":\n OpenLink.checkForLink(\"sbp\");\n break;\n default:\n player.addChatMessage(new ChatComponentText(EnumChatFormatting.RED\n + \"FDH: hotkeyOpen config value improperly set, do \\\"/room set <gui | dsg | sbp>\\\" to change the value\"));\n break;\n }\n }\n if (keyBindings[1].isPressed()) {\n DungeonRooms.guiToOpen = \"waypoints\";\n }\n }\n\n // Delay GUI by 1 tick\n @SubscribeEvent\n public void onRenderTick(TickEvent.RenderTickEvent event) {\n if (guiToOpen != null) {\n switch (guiToOpen) {\n case \"link\":\n mc.displayGuiScreen(new LinkGUI());\n break;\n case \"waypoints\":\n mc.displayGuiScreen(new WaypointsGUI());\n break;\n }\n guiToOpen = null;\n }\n }\n}" }, { "identifier": "AutoRoom", "path": "build/sources/main/java/io/github/quantizr/core/AutoRoom.java", "snippet": "public class AutoRoom {\n Minecraft mc = Minecraft.getMinecraft();\n\n static int tickAmount = 1;\n public static List<String> autoTextOutput = null;\n public static boolean chatToggled = false;\n public static boolean guiToggled = true;\n public static boolean coordToggled = false;\n public static String lastRoomHash = null;\n public static JsonObject lastRoomJson;\n public static String lastRoomName = null;\n private static boolean newRoom = false;\n public static int worldLoad = 0;\n\n public static int scaleX = 50;\n public static int scaleY = 5;\n\n private final Executor executor = Executors.newFixedThreadPool(5);\n\n @SubscribeEvent\n public void onTick(TickEvent.ClientTickEvent event) {\n if (event.phase != TickEvent.Phase.START) return;\n World world = mc.theWorld;\n EntityPlayerSP player = mc.thePlayer;\n\n tickAmount++;\n if (worldLoad < 200) { //10 seconds\n worldLoad++;\n }\n\n // Checks every 1.5 seconds\n if (tickAmount % 30 == 0 && Utils.inDungeons && worldLoad == 200) {\n executor.execute(() -> {\n if (AutoRoom.chatToggled || AutoRoom.guiToggled || Waypoints.enabled){\n List<String> autoText = autoText();\n if (autoText != null) {\n autoTextOutput = autoText;\n }\n }\n if (AutoRoom.chatToggled) {\n toggledChat();\n }\n });\n tickAmount = 0;\n }\n }\n\n @SubscribeEvent\n public void onWorldChange(WorldEvent.Load event) {\n Utils.inDungeons = false;\n Utils.originBlock = null;\n Utils.originCorner = null;\n worldLoad = 0;\n Waypoints.allSecretsMap.clear();\n\n Random random = new Random();\n List<String> output = new ArrayList<>();\n\n if (random.nextBoolean()) {\n if (DungeonRooms.motd != null) {\n if (!DungeonRooms.motd.isEmpty()) {\n output.addAll(DungeonRooms.motd);\n }\n }\n }\n if (output.isEmpty()) {\n output.add(\"FDH: \" + EnumChatFormatting.GREEN+ \"Press the hotkey \\\"\" + GameSettings.getKeyDisplayString(DungeonRooms.keyBindings[1].getKeyCode()) +\"\\\" to configure\");\n output.add(EnumChatFormatting.GREEN + \"Secret Waypoints settings.\");\n output.add(EnumChatFormatting.WHITE + \"(You can change the keybinds in Minecraft controls menu)\");\n }\n autoTextOutput = output;\n\n }\n\n @SubscribeEvent\n public void onWorldUnload(WorldEvent.Unload event) {\n Utils.inDungeons = false;\n }\n\n public static List<String> autoText() {\n List<String> output = new ArrayList<>();\n EntityPlayer player = Minecraft.getMinecraft().thePlayer;\n int x = (int) Math.floor(player.posX);\n int y = (int) Math.floor(player.posY);\n int z = (int) Math.floor(player.posZ);\n\n int top = Utils.dungeonTop(x, y, z);\n String blockFrequencies = Utils.blockFrequency(x, top, z, true);\n if (blockFrequencies == null) return output; //if not in room (under hallway or render distance too low)\n String MD5 = Utils.getMD5(blockFrequencies);\n String floorFrequencies = Utils.floorFrequency(x, top, z);\n String floorHash = Utils.getMD5(floorFrequencies);\n String text = \"FDH: You are in \" + EnumChatFormatting.GREEN;\n\n if (MD5.equals(\"16370f79b2cad049096f881d5294aee6\") && !floorHash.equals(\"94fb12c91c4b46bd0c254edadaa49a3d\")) {\n floorHash = \"e617eff1d7b77faf0f8dd53ec93a220f\"; //exception for box room because floorhash changes when you walk on it\n }\n\n if (MD5.equals(lastRoomHash) && lastRoomJson != null && floorHash != null) {\n if (lastRoomJson.get(\"floorhash\") != null) {\n if (floorHash.equals(lastRoomJson.get(\"floorhash\").getAsString())) {\n newRoom = false;\n return null;\n }\n } else {\n newRoom = false;\n return null;\n }\n }\n\n newRoom = true;\n lastRoomHash = MD5;\n //Setting this to true may prevent waypoint flicker, but may cause waypoints to break if Hypixel bugs out\n Waypoints.allFound = false;\n\n if (DungeonRooms.roomsJson.get(MD5) == null && Utils.getSize(x,top,z).equals(\"1x1\")) {\n output.add(EnumChatFormatting.LIGHT_PURPLE + \"FDH: If you see this message in game (and did not create ghost blocks), send a\");\n output.add(EnumChatFormatting.LIGHT_PURPLE + \"screenshot and the room name to #bug-report channel in the Discord\");\n output.add(EnumChatFormatting.AQUA + MD5);\n output.add(EnumChatFormatting.AQUA + floorHash);\n output.add(\"FDH: You are probably in: \");\n output.add(EnumChatFormatting.GREEN + \"Literally no idea, all the rooms should have been found\");\n lastRoomJson = null;\n return output;\n } else if (DungeonRooms.roomsJson.get(MD5) == null) {\n lastRoomJson = null;\n return output;\n }\n\n JsonArray MD5Array = DungeonRooms.roomsJson.get(MD5).getAsJsonArray();\n int arraySize = MD5Array.size();\n\n if (arraySize >= 2) {\n boolean floorHashFound = false;\n List<String> chatMessages = new ArrayList<>();\n\n for(int i = 0; i < arraySize; i++){\n JsonObject roomObject = MD5Array.get(i).getAsJsonObject();\n JsonElement jsonFloorHash = roomObject.get(\"floorhash\");\n if (floorHash != null && jsonFloorHash != null){\n if (floorHash.equals(jsonFloorHash.getAsString())){\n String name = roomObject.get(\"name\").getAsString();\n String category = roomObject.get(\"category\").getAsString();\n int secrets = roomObject.get(\"secrets\").getAsInt();\n String fairysoul = \"\";\n if (roomObject.get(\"fairysoul\") != null) {\n fairysoul = EnumChatFormatting.WHITE + \" - \" + EnumChatFormatting.LIGHT_PURPLE + \"Fairy Soul\";\n }\n output.add(text + category + \" - \" + name + fairysoul);\n JsonElement notes = roomObject.get(\"notes\");\n if (notes != null) {\n output.add(EnumChatFormatting.GREEN + notes.getAsString());\n }\n if (DungeonRooms.waypointsJson.get(name) == null && secrets != 0 && Waypoints.enabled) {\n output.add(EnumChatFormatting.RED + \"No waypoints available\");\n output.add(EnumChatFormatting.RED + \"Press \\\"\" + GameSettings.getKeyDisplayString(DungeonRooms.keyBindings[0].getKeyCode()) +\"\\\" to view images\");\n }\n lastRoomJson = roomObject;\n floorHashFound = true;\n }\n } else {\n String name = roomObject.get(\"name\").getAsString();\n String category = roomObject.get(\"category\").getAsString();\n int secrets = roomObject.get(\"secrets\").getAsInt();\n String fairysoul = \"\";\n if (roomObject.get(\"fairysoul\") != null) {\n fairysoul = EnumChatFormatting.WHITE + \" - \" + EnumChatFormatting.LIGHT_PURPLE + \"Fairy Soul\";\n }\n chatMessages.add(EnumChatFormatting.GREEN + category + \" - \" + name + fairysoul);\n JsonElement notes = roomObject.get(\"notes\");\n if (notes != null) {\n chatMessages.add(EnumChatFormatting.GREEN + notes.getAsString());\n }\n if (DungeonRooms.waypointsJson.get(name) == null && secrets != 0 && Waypoints.enabled) {\n output.add(EnumChatFormatting.RED + \"No waypoints available\");\n output.add(EnumChatFormatting.RED + \"Press \\\"\" + GameSettings.getKeyDisplayString(DungeonRooms.keyBindings[0].getKeyCode()) +\"\\\" to view images\");\n }\n }\n }\n if (!floorHashFound) {\n output.add(\"FDH: You are probably in one of the following: \");\n output.add(EnumChatFormatting.AQUA + \"(check # of secrets to narrow down rooms)\");\n output.addAll(chatMessages);\n output.add(EnumChatFormatting.LIGHT_PURPLE + \"FDH: If you see this message in game (and did not create ghost blocks), send a\");\n output.add(EnumChatFormatting.LIGHT_PURPLE + \"screenshot and the room name to #bug-report channel in the Discord\");\n output.add(EnumChatFormatting.AQUA + MD5);\n output.add(EnumChatFormatting.AQUA + floorHash);\n lastRoomJson = null;\n }\n } else {\n JsonObject roomObject = MD5Array.get(0).getAsJsonObject();\n String name = roomObject.get(\"name\").getAsString();\n String category = roomObject.get(\"category\").getAsString();\n int secrets = roomObject.get(\"secrets\").getAsInt();\n String fairysoul = \"\";\n if (roomObject.get(\"fairysoul\") != null) {\n fairysoul = EnumChatFormatting.WHITE + \" - \" + EnumChatFormatting.LIGHT_PURPLE + \"Fairy Soul\";\n }\n output.add(text + category + \" - \" + name + fairysoul);\n JsonElement notes = roomObject.get(\"notes\");\n if (notes != null) {\n output.add(EnumChatFormatting.GREEN + notes.getAsString());\n }\n if (DungeonRooms.waypointsJson.get(name) == null && secrets != 0 && Waypoints.enabled) {\n output.add(EnumChatFormatting.RED + \"No waypoints available\");\n output.add(EnumChatFormatting.RED + \"Press \\\"\" + GameSettings.getKeyDisplayString(DungeonRooms.keyBindings[0].getKeyCode()) +\"\\\" to view images\");\n }\n lastRoomJson = roomObject;\n }\n\n //Store/Retrieve which waypoints to enable\n if (lastRoomJson != null && lastRoomJson.get(\"name\") != null) {\n lastRoomName = lastRoomJson.get(\"name\").getAsString();\n Waypoints.allSecretsMap.putIfAbsent(lastRoomName, new ArrayList<>(Collections.nCopies(9, true)));\n Waypoints.secretsList = Waypoints.allSecretsMap.get(lastRoomName);\n } else {\n lastRoomName = null;\n }\n\n return output;\n }\n\n public static void toggledChat() {\n if (!newRoom) return;\n EntityPlayer player = Minecraft.getMinecraft().thePlayer;\n if (autoTextOutput == null) return;\n if (autoTextOutput.isEmpty()) return;\n for (String message:autoTextOutput) {\n player.addChatMessage(new ChatComponentText(message));\n }\n }\n\n public static void renderText() {\n if (autoTextOutput == null) return;\n if (autoTextOutput.isEmpty()) return;\n Minecraft mc = Minecraft.getMinecraft();\n ScaledResolution scaledResolution = new ScaledResolution(mc);\n int y = 0;\n for (String message:autoTextOutput) {\n int roomStringWidth = mc.fontRendererObj.getStringWidth(message);\n TextRenderer.drawText(mc, message, ((scaledResolution.getScaledWidth() * scaleX) / 100) - (roomStringWidth / 2),\n ((scaledResolution.getScaledHeight() * scaleY) / 100) + y, 1D, true);\n y += mc.fontRendererObj.FONT_HEIGHT;\n }\n }\n\n public static void renderCoord() {\n Minecraft mc = Minecraft.getMinecraft();\n EntityPlayerSP player = mc.thePlayer;\n ScaledResolution scaledResolution = new ScaledResolution(mc);\n\n BlockPos relativeCoord = Utils.actualToRelative(new BlockPos(player.posX,player.posY,player.posZ));\n if (relativeCoord == null) return;\n\n List<String> coordDisplay = new ArrayList<>();\n coordDisplay.add(\"Direction: \" + Utils.originCorner);\n coordDisplay.add(\"Origin: \" + Utils.originBlock.getX() + \",\" + Utils.originBlock.getY() + \",\" + Utils.originBlock.getZ());\n coordDisplay.add(\"Relative Pos.: \"+ relativeCoord.getX() + \",\" + relativeCoord.getY() + \",\" + relativeCoord.getZ());\n int yPos = 0;\n for (String message:coordDisplay) {\n int roomStringWidth = mc.fontRendererObj.getStringWidth(message);\n TextRenderer.drawText(mc, message, ((scaledResolution.getScaledWidth() * 95) / 100) - (roomStringWidth),\n ((scaledResolution.getScaledHeight() * 5) / 100) + yPos, 1D, true);\n yPos += mc.fontRendererObj.FONT_HEIGHT;\n }\n }\n}" }, { "identifier": "Waypoints", "path": "build/sources/main/java/io/github/quantizr/core/Waypoints.java", "snippet": "public class Waypoints {\n public static boolean enabled = true;\n\n public static boolean showEntrance = true;\n public static boolean showSuperboom = true;\n public static boolean showSecrets = true;\n public static boolean showFairySouls = true;\n\n public static boolean sneakToDisable = true;\n\n public static boolean disableWhenAllFound = true;\n public static boolean allFound = false;\n\n public static boolean showWaypointText = true;\n public static boolean showBoundingBox = true;\n public static boolean showBeacon = true;\n\n public static int secretNum = 0;\n public static int completedSecrets = 0;\n\n public static Map<String, List<Boolean>> allSecretsMap = new HashMap<>();\n public static List<Boolean> secretsList = new ArrayList<>(Arrays.asList(new Boolean[9]));\n\n static long lastSneakTime = 0;\n\n\n @SubscribeEvent\n public void onWorldRender(RenderWorldLastEvent event) {\n if (!enabled) return;\n String roomName = AutoRoom.lastRoomName;\n if (AutoRoom.lastRoomJson != null && roomName != null && secretsList != null) {\n secretNum = AutoRoom.lastRoomJson.get(\"secrets\").getAsInt();\n if (DungeonRooms.waypointsJson.get(roomName) != null) {\n JsonArray secretsArray = DungeonRooms.waypointsJson.get(roomName).getAsJsonArray();\n int arraySize = secretsArray.size();\n for(int i = 0; i < arraySize; i++) {\n JsonObject secretsObject = secretsArray.get(i).getAsJsonObject();\n\n boolean display = true;\n for(int j = 1; j <= secretNum; j++) {\n if (!secretsList.get(j-1)) {\n if (secretsObject.get(\"secretName\").getAsString().contains(String.valueOf(j))) {\n display = false;\n break;\n }\n }\n }\n if (!display) continue;\n\n if (disableWhenAllFound && allFound && !secretsObject.get(\"category\").getAsString().equals(\"fairysoul\")) continue;\n\n Color color;\n switch (secretsObject.get(\"category\").getAsString()) {\n case \"entrance\":\n if (!showEntrance) continue;\n color = new Color(0, 255, 0);\n break;\n case \"superboom\":\n if (!showSuperboom) continue;\n color = new Color(255, 0, 0);\n break;\n case \"chest\":\n if (!showSecrets) continue;\n color = new Color(2, 213, 250);\n break;\n case \"item\":\n if (!showSecrets) continue;\n color = new Color(2, 64, 250);\n break;\n case \"bat\":\n if (!showSecrets) continue;\n color = new Color(142, 66, 0);\n break;\n case \"wither\":\n if (!showSecrets) continue;\n color = new Color(30, 30, 30);\n break;\n case \"lever\":\n if (!showSecrets) continue;\n color = new Color(250, 217, 2);\n break;\n case \"fairysoul\":\n if (!showFairySouls) continue;\n color = new Color(255, 85, 255);\n break;\n default:\n color = new Color(190, 255, 252);\n }\n\n Entity viewer = Minecraft.getMinecraft().getRenderViewEntity();\n double viewerX = viewer.lastTickPosX + (viewer.posX - viewer.lastTickPosX) * event.partialTicks;\n double viewerY = viewer.lastTickPosY + (viewer.posY - viewer.lastTickPosY) * event.partialTicks;\n double viewerZ = viewer.lastTickPosZ + (viewer.posZ - viewer.lastTickPosZ) * event.partialTicks;\n\n BlockPos pos = Utils.relativeToActual(new BlockPos(secretsObject.get(\"x\").getAsInt(), secretsObject.get(\"y\").getAsInt(), secretsObject.get(\"z\").getAsInt()));\n if (pos == null) continue;\n double x = pos.getX() - viewerX;\n double y = pos.getY() - viewerY;\n double z = pos.getZ() - viewerZ;\n double distSq = x*x + y*y + z*z;\n\n GlStateManager.disableDepth();\n GlStateManager.disableCull();\n if (showBoundingBox) WaypointUtils.drawFilledBoundingBox(new AxisAlignedBB(x, y, z, x + 1, y + 1, z + 1), color, 0.4f);\n GlStateManager.disableTexture2D();\n if (showBeacon && distSq > 5*5) WaypointUtils.renderBeaconBeam(x, y + 1, z, color.getRGB(), 0.25f, event.partialTicks);\n if (showWaypointText) WaypointUtils.renderWaypointText(secretsObject.get(\"secretName\").getAsString(), pos.up(2), event.partialTicks);\n GlStateManager.disableLighting();\n GlStateManager.enableTexture2D();\n GlStateManager.enableDepth();\n GlStateManager.enableCull();\n }\n }\n }\n }\n\n\n @SubscribeEvent(priority = EventPriority.HIGHEST)\n public void onChat(ClientChatReceivedEvent event) {\n if (!Utils.inDungeons || !enabled) return;;\n // Action Bar\n if (event.type == 2) {\n String[] actionBarSections = event.message.getUnformattedText().split(\" {3,}\");\n\n for (String section : actionBarSections) {\n if (section.contains(\"Secrets\") && section.contains(\"/\")) {\n String cleanedSection = StringUtils.stripControlCodes(section);\n String[] splitSecrets = cleanedSection.split(\"/\");\n\n completedSecrets = Integer.parseInt(splitSecrets[0].replaceAll(\"[^0-9]\", \"\"));\n int totalSecrets = Integer.parseInt(splitSecrets[1].replaceAll(\"[^0-9]\", \"\"));\n\n allFound = (totalSecrets == secretNum && completedSecrets == secretNum);\n break;\n }\n }\n }\n }\n\n @SubscribeEvent\n public void onInteract(PlayerInteractEvent event) {\n if (!Utils.inDungeons || !enabled) return;\n if (disableWhenAllFound && allFound) return;\n\n if (event.action == PlayerInteractEvent.Action.RIGHT_CLICK_BLOCK) {\n Block block = event.world.getBlockState(event.pos).getBlock();\n if (block != Blocks.chest && block != Blocks.skull) return;\n if (AutoRoom.lastRoomJson != null && AutoRoom.lastRoomName != null) {\n secretNum = AutoRoom.lastRoomJson.get(\"secrets\").getAsInt();\n if (DungeonRooms.waypointsJson.get(AutoRoom.lastRoomName) != null) {\n JsonArray secretsArray = DungeonRooms.waypointsJson.get(AutoRoom.lastRoomName).getAsJsonArray();\n int arraySize = secretsArray.size();\n for(int i = 0; i < arraySize; i++) {\n JsonObject secretsObject = secretsArray.get(i).getAsJsonObject();\n if (secretsObject.get(\"category\").getAsString().equals(\"chest\") || secretsObject.get(\"category\").getAsString().equals(\"wither\")) {\n BlockPos pos = Utils.relativeToActual(new BlockPos(secretsObject.get(\"x\").getAsInt(), secretsObject.get(\"y\").getAsInt(), secretsObject.get(\"z\").getAsInt()));\n if (pos == null) return;\n if (pos.equals(event.pos)) {\n for(int j = 1; j <= secretNum; j++) {\n if (secretsObject.get(\"secretName\").getAsString().contains(String.valueOf(j))) {\n Waypoints.secretsList.set(j-1, false);\n Waypoints.allSecretsMap.replace(AutoRoom.lastRoomName, Waypoints.secretsList);\n DungeonRooms.logger.info(\"FDH: Detected \" + secretsObject.get(\"category\").getAsString() + \" click, turning off waypoint for secret #\" + j);\n break;\n }\n }\n }\n }\n }\n }\n }\n }\n }\n\n @SubscribeEvent\n public void onReceivePacket(PacketEvent.ReceiveEvent event) {\n if (!Utils.inDungeons || !enabled) return;\n if (disableWhenAllFound && allFound) return;\n Minecraft mc = Minecraft.getMinecraft();\n\n if (event.packet instanceof S0DPacketCollectItem) {\n S0DPacketCollectItem packet = (S0DPacketCollectItem) event.packet;\n Entity entity = mc.theWorld.getEntityByID(packet.getCollectedItemEntityID());\n if (entity instanceof EntityItem) {\n EntityItem item = (EntityItem) entity;\n entity = mc.theWorld.getEntityByID(packet.getEntityID());\n if (entity == null) return;\n String name = item.getEntityItem().getDisplayName();\n if (name.contains(\"Decoy\") || name.contains(\"Defuse Kit\") || name.contains(\"Dungeon Chest Key\") ||\n name.contains(\"Healing VIII\") || name.contains(\"Inflatable Jerry\") || name.contains(\"Spirit Leap\") ||\n name.contains(\"Training Weights\") || name.contains(\"Trap\") || name.contains(\"Treasure Talisman\")) {\n if (!entity.getCommandSenderEntity().getName().equals(mc.thePlayer.getName())) {\n //Do nothing if someone else picks up the item in order to follow Hypixel rules\n return;\n }\n if (AutoRoom.lastRoomJson != null && AutoRoom.lastRoomName != null) {\n secretNum = AutoRoom.lastRoomJson.get(\"secrets\").getAsInt();\n if (DungeonRooms.waypointsJson.get(AutoRoom.lastRoomName) != null) {\n JsonArray secretsArray = DungeonRooms.waypointsJson.get(AutoRoom.lastRoomName).getAsJsonArray();\n int arraySize = secretsArray.size();\n for(int i = 0; i < arraySize; i++) {\n JsonObject secretsObject = secretsArray.get(i).getAsJsonObject();\n if (secretsObject.get(\"category\").getAsString().equals(\"item\") || secretsObject.get(\"category\").getAsString().equals(\"bat\")) {\n BlockPos pos = Utils.relativeToActual(new BlockPos(secretsObject.get(\"x\").getAsInt(), secretsObject.get(\"y\").getAsInt(), secretsObject.get(\"z\").getAsInt()));\n if (pos == null) return;\n if (entity.getDistanceSq(pos) <= 36D) {\n for(int j = 1; j <= secretNum; j++) {\n if (secretsObject.get(\"secretName\").getAsString().contains(String.valueOf(j))) {\n if (!Waypoints.secretsList.get(j-1)) continue;\n Waypoints.secretsList.set(j-1, false);\n Waypoints.allSecretsMap.replace(AutoRoom.lastRoomName, Waypoints.secretsList);\n DungeonRooms.logger.info(\"FDH: \" + entity.getCommandSenderEntity().getName() + \" picked up \" + StringUtils.stripControlCodes(name) + \" from a \" + secretsObject.get(\"category\").getAsString() + \" secret, turning off waypoint for secret #\" + j);\n return;\n }\n }\n }\n }\n }\n }\n }\n }\n }\n }\n }\n\n\n //Disable waypoint within 4 blocks away on sneak\n @SubscribeEvent\n public void onKey(InputEvent.KeyInputEvent event) {\n if (!Utils.inDungeons || !enabled || !sneakToDisable) return;\n EntityPlayerSP player = Minecraft.getMinecraft().thePlayer;\n if (FMLClientHandler.instance().getClient().gameSettings.keyBindSneak.isPressed()) {\n if (System.currentTimeMillis() - lastSneakTime < 1000) { //check for two taps in under a second\n if (AutoRoom.lastRoomJson != null && AutoRoom.lastRoomName != null) {\n secretNum = AutoRoom.lastRoomJson.get(\"secrets\").getAsInt();\n if (DungeonRooms.waypointsJson.get(AutoRoom.lastRoomName) != null) {\n JsonArray secretsArray = DungeonRooms.waypointsJson.get(AutoRoom.lastRoomName).getAsJsonArray();\n int arraySize = secretsArray.size();\n for(int i = 0; i < arraySize; i++) {\n JsonObject secretsObject = secretsArray.get(i).getAsJsonObject();\n if (secretsObject.get(\"category\").getAsString().equals(\"chest\") || secretsObject.get(\"category\").getAsString().equals(\"wither\")\n || secretsObject.get(\"category\").getAsString().equals(\"item\") || secretsObject.get(\"category\").getAsString().equals(\"bat\")) {\n BlockPos pos = Utils.relativeToActual(new BlockPos(secretsObject.get(\"x\").getAsInt(), secretsObject.get(\"y\").getAsInt(), secretsObject.get(\"z\").getAsInt()));\n if (pos == null) return;\n if (player.getDistanceSq(pos) <= 16D) {\n for(int j = 1; j <= secretNum; j++) {\n if (secretsObject.get(\"secretName\").getAsString().contains(String.valueOf(j))) {\n if (!Waypoints.secretsList.get(j-1)) continue;\n Waypoints.secretsList.set(j-1, false);\n Waypoints.allSecretsMap.replace(AutoRoom.lastRoomName, Waypoints.secretsList);\n DungeonRooms.logger.info(\"FDH: Player sneaked near \" + secretsObject.get(\"category\").getAsString() + \" secret, turning off waypoint for secret #\" + j);\n return;\n }\n }\n }\n }\n }\n }\n }\n }\n lastSneakTime = System.currentTimeMillis();\n }\n }\n}" } ]
import io.github.quantizr.DungeonRooms; import io.github.quantizr.core.AutoRoom; import io.github.quantizr.core.Waypoints; import net.minecraftforge.common.config.ConfigCategory; import net.minecraftforge.common.config.Configuration; import java.io.File;
9,916
public static void writeIntConfig(String category, String key, int value) { config = new Configuration(new File(file)); try { config.load(); int set = config.get(category, key, value).getInt(); config.getCategory(category).get(key).set(value); } catch (Exception ex) { ex.printStackTrace(); } finally { config.save(); } } public static void writeDoubleConfig(String category, String key, double value) { config = new Configuration(new File(file)); try { config.load(); double set = config.get(category, key, value).getDouble(); config.getCategory(category).get(key).set(value); } catch (Exception ex) { ex.printStackTrace(); } finally { config.save(); } } public static void writeStringConfig(String category, String key, String value) { config = new Configuration(new File(file)); try { config.load(); String set = config.get(category, key, value).getString(); config.getCategory(category).get(key).set(value); } catch (Exception ex) { ex.printStackTrace(); } finally { config.save(); } } public static void writeBooleanConfig(String category, String key, boolean value) { config = new Configuration(new File(file)); try { config.load(); boolean set = config.get(category, key, value).getBoolean(); config.getCategory(category).get(key).set(value); } catch (Exception ex) { ex.printStackTrace(); } finally { config.save(); } } public static boolean hasKey(String category, String key) { config = new Configuration(new File(file)); try { config.load(); if (!config.hasCategory(category)) return false; return config.getCategory(category).containsKey(key); } catch (Exception ex) { ex.printStackTrace(); } finally { config.save(); } return false; } public static void deleteCategory(String category) { config = new Configuration(new File(file)); try { config.load(); if (config.hasCategory(category)) { config.removeCategory(new ConfigCategory(category)); } } catch (Exception ex) { ex.printStackTrace(); } finally { config.save(); } } public static void reloadConfig() { if (!hasKey("toggles", "chatToggled")) writeBooleanConfig("toggles", "chatToggled", false); if (!hasKey("toggles", "guiToggled")) writeBooleanConfig("toggles", "guiToggled", true); if (!hasKey("toggles", "coordToggled")) writeBooleanConfig("toggles", "coordToggled", false); if (!hasKey("toggles", "waypointsToggled")) writeBooleanConfig("toggles", "waypointsToggled", true); if (!hasKey("waypoint", "showEntrance")) writeBooleanConfig("waypoint", "showEntrance", true); if (!hasKey("waypoint", "showSuperboom")) writeBooleanConfig("waypoint", "showSuperboom", true); if (!hasKey("waypoint", "showSecrets")) writeBooleanConfig("waypoint", "showSecrets", true); if (!hasKey("waypoint", "showFairySouls")) writeBooleanConfig("waypoint", "showFairySouls", true); if (!hasKey("waypoint", "sneakToDisable")) writeBooleanConfig("waypoint", "sneakToDisable", true); if (!hasKey("waypoint", "disableWhenAllFound")) writeBooleanConfig("waypoint", "disableWhenAllFound", true); if (!hasKey("waypoint", "showWaypointText")) writeBooleanConfig("waypoint", "showWaypointText", true); if (!hasKey("waypoint", "showBoundingBox")) writeBooleanConfig("waypoint", "showBoundingBox", true); if (!hasKey("waypoint", "showBeacon")) writeBooleanConfig("waypoint", "showBeacon", true); if (!hasKey("gui", "scaleX")) writeIntConfig("gui", "scaleX", 50); if (!hasKey("gui", "scaleY")) writeIntConfig("gui", "scaleY", 5); if (!hasKey("gui", "hotkeyOpen")) writeStringConfig("gui", "hotkeyOpen", "gui"); AutoRoom.chatToggled = getBoolean("toggles", "chatToggled"); AutoRoom.guiToggled = getBoolean("toggles", "guiToggled"); AutoRoom.coordToggled = getBoolean("toggles", "coordToggled"); Waypoints.enabled = getBoolean("toggles", "waypointsToggled"); Waypoints.showEntrance = getBoolean("waypoint", "showEntrance"); Waypoints.showSuperboom = getBoolean("waypoint", "showSuperboom"); Waypoints.showSecrets = getBoolean("waypoint", "showSecrets"); Waypoints.showFairySouls = getBoolean("waypoint", "showFairySouls"); Waypoints.sneakToDisable = getBoolean("waypoint", "sneakToDisable"); Waypoints.disableWhenAllFound = getBoolean("waypoint", "disableWhenAllFound"); Waypoints.showWaypointText = getBoolean("waypoint", "showWaypointText"); Waypoints.showBoundingBox = getBoolean("waypoint", "showBoundingBox"); Waypoints.showBeacon = getBoolean("waypoint", "showBeacon"); AutoRoom.scaleX = getInt("gui", "scaleX"); AutoRoom.scaleY = getInt("gui", "scaleY");
/* Taken from Danker's Skyblock Mod (https://github.com/bowser0000/SkyblockMod/). This file was released under GNU General Public License v3.0 and remains under said license. Modified by Quantizr (_risk) in Feb. 2021. */ package io.github.quantizr.handlers; public class ConfigHandler { public static Configuration config; private final static String file = "config/DungeonRooms.cfg"; public static void init() { config = new Configuration(new File(file)); try { config.load(); } catch (Exception ex) { ex.printStackTrace(); } finally { config.save(); } } public static int getInt(String category, String key) { config = new Configuration(new File(file)); try { config.load(); if (config.getCategory(category).containsKey(key)) { return config.get(category, key, 0).getInt(); } } catch (Exception ex) { ex.printStackTrace(); } finally { config.save(); } return 0; } public static double getDouble(String category, String key) { config = new Configuration(new File(file)); try { config.load(); if (config.getCategory(category).containsKey(key)) { return config.get(category, key, 0D).getDouble(); } } catch (Exception ex) { ex.printStackTrace(); } finally { config.save(); } return 0D; } public static String getString(String category, String key) { config = new Configuration(new File(file)); try { config.load(); if (config.getCategory(category).containsKey(key)) { return config.get(category, key, "").getString(); } } catch (Exception ex) { ex.printStackTrace(); } finally { config.save(); } return ""; } public static boolean getBoolean(String category, String key) { config = new Configuration(new File(file)); try { config.load(); if (config.getCategory(category).containsKey(key)) { return config.get(category, key, false).getBoolean(); } } catch (Exception ex) { ex.printStackTrace(); } finally { config.save(); } return true; } public static void writeIntConfig(String category, String key, int value) { config = new Configuration(new File(file)); try { config.load(); int set = config.get(category, key, value).getInt(); config.getCategory(category).get(key).set(value); } catch (Exception ex) { ex.printStackTrace(); } finally { config.save(); } } public static void writeDoubleConfig(String category, String key, double value) { config = new Configuration(new File(file)); try { config.load(); double set = config.get(category, key, value).getDouble(); config.getCategory(category).get(key).set(value); } catch (Exception ex) { ex.printStackTrace(); } finally { config.save(); } } public static void writeStringConfig(String category, String key, String value) { config = new Configuration(new File(file)); try { config.load(); String set = config.get(category, key, value).getString(); config.getCategory(category).get(key).set(value); } catch (Exception ex) { ex.printStackTrace(); } finally { config.save(); } } public static void writeBooleanConfig(String category, String key, boolean value) { config = new Configuration(new File(file)); try { config.load(); boolean set = config.get(category, key, value).getBoolean(); config.getCategory(category).get(key).set(value); } catch (Exception ex) { ex.printStackTrace(); } finally { config.save(); } } public static boolean hasKey(String category, String key) { config = new Configuration(new File(file)); try { config.load(); if (!config.hasCategory(category)) return false; return config.getCategory(category).containsKey(key); } catch (Exception ex) { ex.printStackTrace(); } finally { config.save(); } return false; } public static void deleteCategory(String category) { config = new Configuration(new File(file)); try { config.load(); if (config.hasCategory(category)) { config.removeCategory(new ConfigCategory(category)); } } catch (Exception ex) { ex.printStackTrace(); } finally { config.save(); } } public static void reloadConfig() { if (!hasKey("toggles", "chatToggled")) writeBooleanConfig("toggles", "chatToggled", false); if (!hasKey("toggles", "guiToggled")) writeBooleanConfig("toggles", "guiToggled", true); if (!hasKey("toggles", "coordToggled")) writeBooleanConfig("toggles", "coordToggled", false); if (!hasKey("toggles", "waypointsToggled")) writeBooleanConfig("toggles", "waypointsToggled", true); if (!hasKey("waypoint", "showEntrance")) writeBooleanConfig("waypoint", "showEntrance", true); if (!hasKey("waypoint", "showSuperboom")) writeBooleanConfig("waypoint", "showSuperboom", true); if (!hasKey("waypoint", "showSecrets")) writeBooleanConfig("waypoint", "showSecrets", true); if (!hasKey("waypoint", "showFairySouls")) writeBooleanConfig("waypoint", "showFairySouls", true); if (!hasKey("waypoint", "sneakToDisable")) writeBooleanConfig("waypoint", "sneakToDisable", true); if (!hasKey("waypoint", "disableWhenAllFound")) writeBooleanConfig("waypoint", "disableWhenAllFound", true); if (!hasKey("waypoint", "showWaypointText")) writeBooleanConfig("waypoint", "showWaypointText", true); if (!hasKey("waypoint", "showBoundingBox")) writeBooleanConfig("waypoint", "showBoundingBox", true); if (!hasKey("waypoint", "showBeacon")) writeBooleanConfig("waypoint", "showBeacon", true); if (!hasKey("gui", "scaleX")) writeIntConfig("gui", "scaleX", 50); if (!hasKey("gui", "scaleY")) writeIntConfig("gui", "scaleY", 5); if (!hasKey("gui", "hotkeyOpen")) writeStringConfig("gui", "hotkeyOpen", "gui"); AutoRoom.chatToggled = getBoolean("toggles", "chatToggled"); AutoRoom.guiToggled = getBoolean("toggles", "guiToggled"); AutoRoom.coordToggled = getBoolean("toggles", "coordToggled"); Waypoints.enabled = getBoolean("toggles", "waypointsToggled"); Waypoints.showEntrance = getBoolean("waypoint", "showEntrance"); Waypoints.showSuperboom = getBoolean("waypoint", "showSuperboom"); Waypoints.showSecrets = getBoolean("waypoint", "showSecrets"); Waypoints.showFairySouls = getBoolean("waypoint", "showFairySouls"); Waypoints.sneakToDisable = getBoolean("waypoint", "sneakToDisable"); Waypoints.disableWhenAllFound = getBoolean("waypoint", "disableWhenAllFound"); Waypoints.showWaypointText = getBoolean("waypoint", "showWaypointText"); Waypoints.showBoundingBox = getBoolean("waypoint", "showBoundingBox"); Waypoints.showBeacon = getBoolean("waypoint", "showBeacon"); AutoRoom.scaleX = getInt("gui", "scaleX"); AutoRoom.scaleY = getInt("gui", "scaleY");
DungeonRooms.hotkeyOpen = getString("gui", "hotkeyOpen");
0
2023-12-22 04:44:39+00:00
12k
HChenX/ClipboardList
app/src/main/java/com/hchen/clipboardlist/HookMain.java
[ { "identifier": "ClipboardList", "path": "app/src/main/java/com/hchen/clipboardlist/clipboard/ClipboardList.java", "snippet": "public class ClipboardList extends Hook {\n public static ArrayList<?> lastArray = new ArrayList<>();\n\n public static String lastFilePath;\n public ArrayList<?> mClipboardList;\n\n public static String filePath;\n\n @Override\n public void init() {\n findAndHookMethod(\"android.inputmethodservice.InputMethodModuleManager\",\n \"loadDex\", ClassLoader.class, String.class, new HookAction() {\n @SuppressLint(\"SdCardPath\")\n @Override\n protected void after(XC_MethodHook.MethodHookParam param) {\n // logE(TAG, \"get class: \" + param.args[0]);\n filePath = \"/data/user/0/\" + loadPackageParam.packageName + \"/files/array_list.dat\";\n lastFilePath = \"/data/user/0/\" + loadPackageParam.packageName + \"/files/last_list.dat\";\n getNoExpiredData((ClassLoader) param.args[0]);\n getView((ClassLoader) param.args[0]);\n clearArray((ClassLoader) param.args[0]);\n }\n }\n );\n\n }\n\n /*折旧*/\n public void getClipboardData(ClassLoader classLoader) {\n findAndHookMethod(\"com.miui.inputmethod.InputMethodUtil\",\n \"getClipboardData\", Context.class,\n new HookAction() {\n @Override\n protected void before(XC_MethodHook.MethodHookParam param) {\n Context context = (Context) param.args[0];\n Bundle call = context.getContentResolver().call(Uri.parse(\"content://com.miui.input.provider\"),\n \"getClipboardList\", (String) null, new Bundle());\n String string = call != null ? call.getString(\"savedClipboard\") : \"\";\n param.setResult(XposedHelpers.callStaticMethod(findClassIfExists(\"com.miui.inputmethod.InputMethodUtil\", classLoader),\n \"getNoExpiredData\", context, string, 0));\n }\n }\n );\n }\n\n public void getNoExpiredData(ClassLoader classLoader) {\n findAndHookMethod(\"com.miui.inputmethod.InputMethodUtil\", classLoader,\n \"getNoExpiredData\", Context.class, String.class, long.class, new HookAction() {\n @Override\n protected void before(XC_MethodHook.MethodHookParam param) {\n ArrayList mArray = new ArrayList<>();\n try {\n checkFile(filePath);\n checkFile(lastFilePath);\n /*获取原始list数据内容*/\n ArrayList<?> jsonToBean = jsonToBean((String) param.args[1], classLoader);\n if (jsonToBean.size() == 0) {\n /*防止在数据为空时误删数据库数据*/\n // resetFile();\n lastArray = new ArrayList<>();\n if (!isEmptyFile(filePath)) {\n mArray = jsonToLIst(filePath, classLoader);\n if (!mArray.isEmpty()) {\n param.setResult(mArray);\n return;\n }\n }\n param.setResult(new ArrayList<>());\n logW(tag, \"get saved clipboard list size is 0.\");\n return;\n }\n if (!isEmptyFile(lastFilePath)) {\n lastArray = jsonToLIst(lastFilePath, classLoader);\n }\n /*文件不为空说明有数据*/\n if (!isEmptyFile(filePath)) {\n /*数据库数据*/\n mArray = jsonToLIst(filePath, classLoader);\n if (!lastArray.isEmpty()) {\n /*虽说不太可能为空但还是检查一下*/\n if (mArray.isEmpty()) {\n logE(tag, \"mArray is empty it's bad\");\n param.setResult(new ArrayList<>());\n return;\n }\n Object oneLast = getContent(lastArray, 0);\n /*防止在只复制一个元素时重复开关界面引发的未知问题*/\n if (jsonToBean.size() < 2) {\n if (!getContent(jsonToBean, 0).equals(getContent(mArray, 0))) {\n mArray = addOrHw(mArray, getContent(jsonToBean, 0), jsonToBean);\n }\n param.setResult(mArray);\n return;\n }\n /*读取第一第二个数据判断操作*/\n Object oneArray = getContent(jsonToBean, 0);\n Object twoArray = getContent(jsonToBean, 1);\n if (!oneArray.equals(oneLast) && twoArray.equals(oneLast)) {\n /*第一个不同第二个相同说明可能换位或新增*/\n mArray = addOrHw(mArray, oneArray, jsonToBean);\n } else if (!oneArray.equals(oneLast) && !twoArray.equals(oneLast)) {\n /*两个不同为新增*/\n int have = -1;\n for (int i = 0; i < jsonToBean.size(); i++) {\n have++;\n if (getContent(jsonToBean, i).equals(oneLast)) {\n break;\n }\n }\n for (int i = 0; i < have; i++) {\n mArray.add(i, jsonToBean.get(i));\n }\n }\n /*else if (jsonToBean.hashCode() != lastArray.hashCode()) {\n // 很极端的情况,应该不会发生\n mArray.addAll(0, jsonToBean);\n }*/\n }\n /*置旧*/\n lastArray = jsonToBean;\n writeFile(lastFilePath, listToJson(lastArray));\n writeFile(filePath, listToJson(mArray));\n param.setResult(mArray);\n } else {\n /*置旧*/\n lastArray = jsonToBean;\n writeFile(lastFilePath, listToJson(lastArray));\n writeFile(filePath, listToJson(jsonToBean));\n param.setResult(jsonToBean);\n }\n } catch (Throwable throwable) {\n logE(tag, \"getContent is null: \" + throwable);\n param.setResult(mArray);\n }\n }\n }\n );\n }\n\n public void getView(ClassLoader classLoader) {\n findAndHookMethod(\"com.miui.inputmethod.InputMethodClipboardAdapter\",\n classLoader,\n \"getView\", int.class, View.class, ViewGroup.class,\n new HookAction() {\n @Override\n protected void after(XC_MethodHook.MethodHookParam param) {\n mClipboardList = (ArrayList<?>)\n XposedHelpers.getObjectField(param.thisObject, \"mClipboardList\");\n }\n }\n );\n\n hookAllMethods(\"com.miui.inputmethod.InputMethodUtil\", classLoader,\n \"setClipboardModelList\", new HookAction() {\n @Override\n protected void after(XC_MethodHook.MethodHookParam param) {\n ArrayList<?> arrayList = (ArrayList<?>) param.args[1];\n if (arrayList.isEmpty()) {\n lastArray = new ArrayList<>();\n resetFile(lastFilePath);\n } else {\n lastArray = arrayList;\n writeFile(lastFilePath, listToJson(arrayList));\n }\n writeFile(filePath, listToJson(arrayList));\n }\n }\n );\n\n }\n\n public void clearArray(ClassLoader classLoader) {\n findAndHookMethod(\"com.miui.inputmethod.InputMethodClipboardPhrasePopupView$3\", classLoader,\n \"onConfirm\",\n new HookAction() {\n @Override\n protected void before(XC_MethodHook.MethodHookParam param) {\n /*点击清除全部按键,清理所有数据*/\n lastArray = new ArrayList<>();\n }\n }\n );\n }\n\n /*添加或换位*/\n public ArrayList addOrHw(ArrayList mArray, Object oneArray, ArrayList<?> jsonToBean) throws Throwable {\n if (oneArray == null) {\n logE(tag, \"oneArray is null, mArray: \" + mArray + \" jsonToBean: \" + jsonToBean);\n return mArray;\n }\n boolean needAdd = false;\n boolean needHw = false;\n int run = -1;\n for (int i = 0; i < mArray.size(); i++) {\n run++;\n needAdd = true;\n /*如果数据库存在重复数据*/\n if (oneArray.equals(getContent(mArray, i))) {\n needHw = true;\n needAdd = false;\n break;\n }\n }\n if (needHw) {\n mArray.add(0, mArray.get(run));\n mArray.remove(run + 1);\n }\n if (needAdd)\n mArray.add(0, jsonToBean.get(0));\n return mArray;\n }\n\n public void checkFile(String path) {\n File file = new File(path);\n File parentDir = file.getParentFile();\n if (parentDir == null) {\n logE(tag, \"parentDir is null: \" + path);\n }\n if (parentDir != null && !parentDir.exists()) {\n if (parentDir.mkdirs()) {\n logI(tag, \"mkdirs: \" + parentDir);\n } else {\n logE(tag, \"mkdirs: \" + parentDir);\n }\n }\n if (!file.exists()) {\n try {\n if (file.createNewFile()) {\n writeFile(path, new JSONArray());\n setPermission(path);\n logI(tag, \"createNewFile: \" + file);\n } else {\n logE(tag, \"createNewFile: \" + file);\n }\n } catch (IOException e) {\n logE(tag, \"createNewFile: \" + e);\n }\n } else {\n setPermission(path);\n }\n }\n\n public void writeFile(String path, JSONArray jsonArray) {\n if (jsonArray == null) {\n logE(tag, \"write json is null\");\n return;\n }\n try (BufferedWriter writer = new BufferedWriter(new\n FileWriter(path, false))) {\n writer.write(jsonArray.toString());\n } catch (IOException e) {\n logE(tag, \"writeFile: \" + e);\n }\n }\n\n public boolean isEmptyFile(String path) {\n JSONArray jsonArray = readFile(path);\n return jsonArray.length() == 0;\n }\n\n public JSONArray readFile(String path) {\n try (BufferedReader reader = new BufferedReader(new\n FileReader(path))) {\n StringBuilder builder = new StringBuilder();\n String line;\n while ((line = reader.readLine()) != null) {\n builder.append(line);\n }\n String jsonString = builder.toString();\n if (\"\".equals(jsonString)) {\n jsonString = \"[]\";\n }\n JSONArray jsonArray = new JSONArray(jsonString);\n return jsonArray;\n } catch (IOException | JSONException e) {\n logE(tag, \"readFile: \" + e);\n }\n return new JSONArray();\n }\n\n public boolean resetFile(String path) {\n // 清空文件内容\n writeFile(path, new JSONArray());\n return isEmptyFile(path);\n }\n\n /*JSON到ArrayList*/\n public ArrayList jsonToLIst(String path, ClassLoader classLoader) {\n try {\n JSONArray mJson;\n ArrayList mArray = new ArrayList<>();\n mJson = readFile(path);\n if (mJson.length() == 0) {\n return new ArrayList<>();\n }\n for (int i = 0; i < mJson.length(); i++) {\n JSONObject jSONObject = mJson.getJSONObject(i);\n if (jSONObject != null) {\n mArray.add(XposedHelpers.callStaticMethod(\n XposedHelpers.findClassIfExists(\n \"com.miui.inputmethod.ClipboardContentModel\", classLoader),\n \"fromJSONObject\", jSONObject));\n }\n }\n return mArray;\n } catch (Throwable e) {\n logE(tag, \"jsonToLIst: \" + e);\n }\n return new ArrayList<>();\n }\n\n /*String到ArrayList,中转JSON*/\n public ArrayList<?> jsonToBean(String str, ClassLoader classLoader) {\n ArrayList arrayList = new ArrayList<>();\n try {\n JSONArray jSONArray = new JSONArray(str);\n for (int i = 0; i < jSONArray.length(); i++) {\n JSONObject jSONObject = jSONArray.getJSONObject(i);\n if (jSONObject != null) {\n arrayList.add(XposedHelpers.callStaticMethod(\n XposedHelpers.findClassIfExists(\n \"com.miui.inputmethod.ClipboardContentModel\", classLoader),\n \"fromJSONObject\", jSONObject));\n }\n }\n } catch (Throwable e2) {\n logE(tag, \"jsonToBean,parse JSON error: \" + e2);\n }\n return arrayList;\n }\n\n /*ArrayList到JSON*/\n public JSONArray listToJson(ArrayList<?> arrayList) {\n try {\n JSONArray jSONArray = new JSONArray();\n for (int i = 0; i < arrayList.size(); i++) {\n jSONArray.put(XposedHelpers.callMethod(arrayList.get(i), \"toJSONObject\"));\n }\n return jSONArray;\n } catch (Throwable throwable) {\n logE(tag, \"listToJson: \" + throwable);\n }\n return new JSONArray();\n }\n\n /*获取剪贴板内容*/\n public String getContent(ArrayList<?> arrayList, int num) throws Throwable {\n try {\n return (String) XposedHelpers.callMethod(arrayList.get(num), \"getContent\");\n } catch (Throwable throwable) {\n logE(tag, \"getContent array: \" + arrayList + \" num: \" + num + \" e: \" + throwable);\n throw new Throwable(\"callMethod getContent error: \" + throwable);\n }\n }\n\n public void setPermission(String paths) {\n // 指定文件的路径\n Path filePath = Paths.get(paths);\n\n try {\n // 获取当前文件的权限\n Set<PosixFilePermission> permissions = Files.getPosixFilePermissions(filePath);\n\n // 添加世界可读写权限\n permissions.add(PosixFilePermission.OTHERS_READ);\n permissions.add(PosixFilePermission.OTHERS_WRITE);\n permissions.add(PosixFilePermission.GROUP_READ);\n permissions.add(PosixFilePermission.GROUP_WRITE);\n\n // 设置新的权限\n Files.setPosixFilePermissions(filePath, permissions);\n } catch (IOException e) {\n logE(tag, \"setPermission: \" + e);\n }\n }\n}" }, { "identifier": "Hook", "path": "app/src/main/java/com/hchen/clipboardlist/hook/Hook.java", "snippet": "public abstract class Hook extends Log {\n public String tag = getClass().getSimpleName();\n\n public XC_LoadPackage.LoadPackageParam loadPackageParam;\n\n public abstract void init();\n\n public void runHook(XC_LoadPackage.LoadPackageParam loadPackageParam) {\n try {\n SetLoadPackageParam(loadPackageParam);\n init();\n logI(tag, \"Hook Done!\");\n } catch (Throwable s) {\n logE(tag, \"Unhandled errors: \" + s);\n }\n }\n\n public void SetLoadPackageParam(XC_LoadPackage.LoadPackageParam loadPackageParam) {\n this.loadPackageParam = loadPackageParam;\n }\n\n public Class<?> findClass(String className) throws XposedHelpers.ClassNotFoundError {\n return findClass(className, loadPackageParam.classLoader);\n }\n\n public Class<?> findClass(String className, ClassLoader classLoader) throws XposedHelpers.ClassNotFoundError {\n return XposedHelpers.findClass(className, classLoader);\n }\n\n public Class<?> findClassIfExists(String className) {\n try {\n return findClass(className);\n } catch (XposedHelpers.ClassNotFoundError e) {\n logE(tag, \"Class no found: \" + e);\n return null;\n }\n }\n\n public Class<?> findClassIfExists(String newClassName, String oldClassName) {\n try {\n return findClass(findClassIfExists(newClassName) != null ? newClassName : oldClassName);\n } catch (XposedHelpers.ClassNotFoundError e) {\n logE(tag, \"Find \" + newClassName + \" & \" + oldClassName + \" is null: \" + e);\n return null;\n }\n }\n\n public Class<?> findClassIfExists(String className, ClassLoader classLoader) {\n try {\n return findClass(className, classLoader);\n } catch (XposedHelpers.ClassNotFoundError e) {\n logE(tag, \"Class no found 2: \" + e);\n return null;\n }\n }\n\n public abstract static class HookAction extends XC_MethodHook {\n\n protected void before(MethodHookParam param) throws Throwable {\n }\n\n protected void after(MethodHookParam param) throws Throwable {\n }\n\n public HookAction() {\n super();\n }\n\n public HookAction(int priority) {\n super(priority);\n }\n\n public static HookAction returnConstant(final Object result) {\n return new HookAction(PRIORITY_DEFAULT) {\n @Override\n protected void before(MethodHookParam param) throws Throwable {\n super.before(param);\n param.setResult(result);\n }\n };\n }\n\n public static final HookAction DO_NOTHING = new HookAction(PRIORITY_HIGHEST * 2) {\n\n @Override\n protected void before(MethodHookParam param) throws Throwable {\n super.before(param);\n param.setResult(null);\n }\n\n };\n\n @Override\n protected void beforeHookedMethod(MethodHookParam param) {\n try {\n before(param);\n } catch (Throwable e) {\n logE(\"before\", \"\" + e);\n }\n }\n\n @Override\n protected void afterHookedMethod(MethodHookParam param) {\n try {\n after(param);\n } catch (Throwable e) {\n logE(\"after\", \"\" + e);\n }\n }\n }\n\n public abstract static class ReplaceHookedMethod extends HookAction {\n\n public ReplaceHookedMethod() {\n super();\n }\n\n public ReplaceHookedMethod(int priority) {\n super(priority);\n }\n\n protected abstract Object replace(MethodHookParam param) throws Throwable;\n\n @Override\n public void beforeHookedMethod(MethodHookParam param) {\n try {\n Object result = replace(param);\n param.setResult(result);\n } catch (Throwable t) {\n logE(\"replace\", \"\" + t);\n }\n }\n }\n\n public void hookMethod(Method method, HookAction callback) {\n try {\n if (method == null) {\n logE(tag, \"method is null\");\n return;\n }\n XposedBridge.hookMethod(method, callback);\n logI(tag, \"hookMethod: \" + method);\n } catch (Throwable e) {\n logE(tag, \"hookMethod: \" + method);\n }\n }\n\n public void findAndHookMethod(Class<?> clazz, String methodName, Object... parameterTypesAndCallback) {\n try {\n /*获取class*/\n if (parameterTypesAndCallback.length != 1) {\n Object[] newArray = new Object[parameterTypesAndCallback.length - 1];\n System.arraycopy(parameterTypesAndCallback, 0, newArray, 0, newArray.length);\n getDeclaredMethod(clazz, methodName, newArray);\n }\n XposedHelpers.findAndHookMethod(clazz, methodName, parameterTypesAndCallback);\n logI(tag, \"Hook: \" + clazz + \" method: \" + methodName);\n } catch (Throwable e) {\n logE(tag, \"Not find method: \" + methodName + \" in: \" + clazz);\n }\n }\n\n public void findAndHookMethod(String className, String methodName, Object... parameterTypesAndCallback) {\n findAndHookMethod(findClassIfExists(className), methodName, parameterTypesAndCallback);\n }\n\n public void findAndHookMethod(String className, ClassLoader classLoader, String methodName, Object... parameterTypesAndCallback) {\n findAndHookMethod(findClassIfExists(className, classLoader), methodName, parameterTypesAndCallback);\n }\n\n public void findAndHookConstructor(Class<?> clazz, Object... parameterTypesAndCallback) {\n try {\n XposedHelpers.findAndHookConstructor(clazz, parameterTypesAndCallback);\n logI(tag, \"Hook: \" + clazz);\n } catch (Throwable f) {\n logE(tag, \"findAndHookConstructor: \" + f + \" class: \" + clazz);\n }\n }\n\n public void findAndHookConstructor(String className, Object... parameterTypesAndCallback) {\n findAndHookConstructor(findClassIfExists(className), parameterTypesAndCallback);\n }\n\n public void hookAllMethods(String className, String methodName, HookAction callback) {\n try {\n Class<?> hookClass = findClassIfExists(className);\n hookAllMethods(hookClass, methodName, callback);\n } catch (Throwable e) {\n logE(tag, \"Hook The: \" + e);\n }\n }\n\n public void hookAllMethods(String className, ClassLoader classLoader, String methodName, HookAction callback) {\n try {\n Class<?> hookClass = findClassIfExists(className, classLoader);\n hookAllMethods(hookClass, methodName, callback);\n } catch (Throwable e) {\n logE(tag, \"Hook class: \" + className + \" method: \" + methodName + \" e: \" + e);\n }\n }\n\n public void hookAllMethods(Class<?> hookClass, String methodName, HookAction callback) {\n try {\n int Num = XposedBridge.hookAllMethods(hookClass, methodName, callback).size();\n logI(tag, \"Hook: \" + hookClass + \" methodName: \" + methodName + \" Num is: \" + Num);\n } catch (Throwable e) {\n logE(tag, \"Hook class: \" + hookClass.getSimpleName() + \" method: \" + methodName + \" e: \" + e);\n }\n }\n\n public void hookAllConstructors(String className, HookAction callback) {\n Class<?> hookClass = findClassIfExists(className);\n if (hookClass != null) {\n hookAllConstructors(hookClass, callback);\n }\n }\n\n public void hookAllConstructors(Class<?> hookClass, HookAction callback) {\n try {\n XposedBridge.hookAllConstructors(hookClass, callback);\n } catch (Throwable f) {\n logE(tag, \"hookAllConstructors: \" + f + \" class: \" + hookClass);\n }\n }\n\n public void hookAllConstructors(String className, ClassLoader classLoader, HookAction callback) {\n Class<?> hookClass = XposedHelpers.findClassIfExists(className, classLoader);\n if (hookClass != null) {\n hookAllConstructors(hookClass, callback);\n }\n }\n\n public Object callMethod(Object obj, String methodName, Object... args) {\n try {\n return XposedHelpers.callMethod(obj, methodName, args);\n } catch (Throwable e) {\n logE(tag, \"callMethod: \" + obj.toString() + \" method: \" + methodName + \" args: \" + Arrays.toString(args) + \" e: \" + e);\n return null;\n }\n }\n\n public Object callStaticMethod(Class<?> clazz, String methodName, Object... args) {\n try {\n return XposedHelpers.callStaticMethod(clazz, methodName, args);\n } catch (Throwable throwable) {\n logE(tag, \"callStaticMethod e: \" + throwable);\n return null;\n }\n }\n\n public Method getDeclaredMethod(String className, String method, Object... type) throws NoSuchMethodException {\n return getDeclaredMethod(findClassIfExists(className), method, type);\n }\n\n public Method getDeclaredMethod(Class<?> clazz, String method, Object... type) throws NoSuchMethodException {\n// String tag = \"getDeclaredMethod\";\n ArrayList<Method> haveMethod = new ArrayList<>();\n Method hqMethod = null;\n int methodNum;\n if (clazz == null) {\n logE(tag, \"find class is null: \" + method);\n throw new NoSuchMethodException(\"find class is null\");\n }\n for (Method getMethod : clazz.getDeclaredMethods()) {\n if (getMethod.getName().equals(method)) {\n haveMethod.add(getMethod);\n }\n }\n if (haveMethod.isEmpty()) {\n logE(tag, \"find method is null: \" + method);\n throw new NoSuchMethodException(\"find method is null\");\n }\n methodNum = haveMethod.size();\n if (type != null) {\n Class<?>[] classes = new Class<?>[type.length];\n Class<?> newclass = null;\n Object getType;\n for (int i = 0; i < type.length; i++) {\n getType = type[i];\n if (getType instanceof Class<?>) {\n newclass = (Class<?>) getType;\n }\n if (getType instanceof String) {\n newclass = findClassIfExists((String) getType);\n if (newclass == null) {\n logE(tag, \"get class error: \" + i);\n throw new NoSuchMethodException(\"get class error\");\n }\n }\n classes[i] = newclass;\n }\n boolean noError = true;\n for (int i = 0; i < methodNum; i++) {\n hqMethod = haveMethod.get(i);\n boolean allHave = true;\n if (hqMethod.getParameterTypes().length != classes.length) {\n if (methodNum - 1 == i) {\n logE(tag, \"class length bad: \" + Arrays.toString(hqMethod.getParameterTypes()));\n throw new NoSuchMethodException(\"class length bad\");\n } else {\n noError = false;\n continue;\n }\n }\n for (int t = 0; t < hqMethod.getParameterTypes().length; t++) {\n Class<?> getClass = hqMethod.getParameterTypes()[t];\n if (!getClass.getSimpleName().equals(classes[t].getSimpleName())) {\n allHave = false;\n break;\n }\n }\n if (!allHave) {\n if (methodNum - 1 == i) {\n logE(tag, \"type bad: \" + Arrays.toString(hqMethod.getParameterTypes())\n + \" input: \" + Arrays.toString(classes));\n throw new NoSuchMethodException(\"type bad\");\n } else {\n noError = false;\n continue;\n }\n }\n if (noError) {\n break;\n }\n }\n return hqMethod;\n } else {\n if (methodNum > 1) {\n logE(tag, \"no type method must only have one: \" + haveMethod);\n throw new NoSuchMethodException(\"no type method must only have one\");\n }\n }\n return haveMethod.get(0);\n }\n\n public void setDeclaredField(XC_MethodHook.MethodHookParam param, String iNeedString, Object iNeedTo) {\n if (param != null) {\n try {\n Field setString = param.thisObject.getClass().getDeclaredField(iNeedString);\n setString.setAccessible(true);\n try {\n setString.set(param.thisObject, iNeedTo);\n Object result = setString.get(param.thisObject);\n checkLast(\"getDeclaredField\", iNeedString, iNeedTo, result);\n } catch (IllegalAccessException e) {\n logE(tag, \"IllegalAccessException to: \" + iNeedString + \" Need to: \" + iNeedTo + \" :\" + e);\n }\n } catch (NoSuchFieldException e) {\n logE(tag, \"No such the: \" + iNeedString + \" : \" + e);\n }\n } else {\n logE(tag, \"Param is null Code: \" + iNeedString + \" & \" + iNeedTo);\n }\n }\n\n public void checkLast(String setObject, Object fieldName, Object value, Object last) {\n if (value != null && last != null) {\n if (value == last || value.equals(last)) {\n logSI(tag, setObject + \" Success! set \" + fieldName + \" to \" + value);\n } else {\n logSE(tag, setObject + \" Failed! set \" + fieldName + \" to \" + value + \" hope: \" + value + \" but: \" + last);\n }\n } else {\n logSE(tag, setObject + \" Error value: \" + value + \" or last: \" + last + \" is null\");\n }\n }\n\n public Object getObjectField(Object obj, String fieldName) {\n try {\n return XposedHelpers.getObjectField(obj, fieldName);\n } catch (Throwable e) {\n logE(tag, \"getObjectField: \" + obj.toString() + \" field: \" + fieldName);\n return null;\n }\n }\n\n public Object getStaticObjectField(Class<?> clazz, String fieldName) {\n try {\n return XposedHelpers.getStaticObjectField(clazz, fieldName);\n } catch (Throwable e) {\n logE(tag, \"getStaticObjectField: \" + clazz.getSimpleName() + \" field: \" + fieldName);\n return null;\n }\n }\n\n public void setStaticObjectField(Class<?> clazz, String fieldName, Object value) {\n try {\n XposedHelpers.setStaticObjectField(clazz, fieldName, value);\n } catch (Throwable e) {\n logE(tag, \"setStaticObjectField: \" + clazz.getSimpleName() + \" field: \" + fieldName + \" value: \" + value);\n }\n }\n\n public void setInt(Object obj, String fieldName, int value) {\n checkAndHookField(obj, fieldName,\n () -> XposedHelpers.setIntField(obj, fieldName, value),\n () -> checkLast(\"setInt\", fieldName, value,\n XposedHelpers.getIntField(obj, fieldName)));\n }\n\n public void setBoolean(Object obj, String fieldName, boolean value) {\n checkAndHookField(obj, fieldName,\n () -> XposedHelpers.setBooleanField(obj, fieldName, value),\n () -> checkLast(\"setBoolean\", fieldName, value,\n XposedHelpers.getBooleanField(obj, fieldName)));\n }\n\n public void setObject(Object obj, String fieldName, Object value) {\n checkAndHookField(obj, fieldName,\n () -> XposedHelpers.setObjectField(obj, fieldName, value),\n () -> checkLast(\"setObject\", fieldName, value,\n XposedHelpers.getObjectField(obj, fieldName)));\n }\n\n public void checkDeclaredMethod(String className, String name, Class<?>... parameterTypes) throws NoSuchMethodException {\n Class<?> hookClass = findClassIfExists(className);\n if (hookClass != null) {\n hookClass.getDeclaredMethod(name, parameterTypes);\n return;\n }\n throw new NoSuchMethodException();\n }\n\n public void checkDeclaredMethod(Class<?> clazz, String name, Class<?>... parameterTypes) throws NoSuchMethodException {\n if (clazz != null) {\n clazz.getDeclaredMethod(name, parameterTypes);\n return;\n }\n throw new NoSuchMethodException();\n }\n\n public void checkAndHookField(Object obj, String fieldName, Runnable setField, Runnable checkLast) {\n try {\n obj.getClass().getDeclaredField(fieldName);\n setField.run();\n checkLast.run();\n } catch (Throwable e) {\n logE(tag, \"No such field: \" + fieldName + \" in param: \" + obj + \" : \" + e);\n }\n }\n\n public static Context findContext() {\n Context context;\n try {\n context = (Application) XposedHelpers.callStaticMethod(XposedHelpers.findClass(\n \"android.app.ActivityThread\", null),\n \"currentApplication\");\n if (context == null) {\n Object currentActivityThread = XposedHelpers.callStaticMethod(XposedHelpers.findClass(\"android.app.ActivityThread\",\n null),\n \"currentActivityThread\");\n if (currentActivityThread != null)\n context = (Context) XposedHelpers.callMethod(currentActivityThread,\n \"getSystemContext\");\n }\n return context;\n } catch (Throwable e) {\n logE(\"findContext\", \"null: \" + e);\n }\n return null;\n }\n\n public static String getProp(String key, String defaultValue) {\n try {\n return (String) XposedHelpers.callStaticMethod(XposedHelpers.findClass(\"android.os.SystemProperties\",\n null),\n \"get\", key, defaultValue);\n } catch (Throwable throwable) {\n logE(\"getProp\", \"key get e: \" + key + \" will return default: \" + defaultValue + \" e:\" + throwable);\n return defaultValue;\n }\n }\n\n public static void setProp(String key, String val) {\n try {\n XposedHelpers.callStaticMethod(XposedHelpers.findClass(\"android.os.SystemProperties\",\n null),\n \"set\", key, val);\n } catch (Throwable throwable) {\n logE(\"setProp\", \"set key e: \" + key + \" e:\" + throwable);\n }\n }\n\n}" }, { "identifier": "Log", "path": "app/src/main/java/com/hchen/clipboardlist/hook/Log.java", "snippet": "public class Log {\n public static final String hookMain = \"[HChen]\";\n public static final String mHook = \"[HChen:\";\n public static final String mode = \"]\";\n\n public static void logI(String tag, String Log) {\n XposedBridge.log(hookMain + \"[\" + tag + \"]: \" + \"I: \" + Log);\n }\n\n public static void logI(String name, String tag, String Log) {\n XposedBridge.log(mHook + name + mode + \"[\" + tag + \"]: \" + \"I: \" + Log);\n }\n\n public static void logW(String tag, String Log) {\n XposedBridge.log(hookMain + \"[\" + tag + \"]: \" + \"W: \" + Log);\n }\n\n public static void logE(String tag, String Log) {\n XposedBridge.log(hookMain + \"[\" + tag + \"]: \" + \"E: \" + Log);\n }\n\n public static void logSI(String name, String tag, String log) {\n android.util.Log.i(mHook + name + mode, \"[\" + tag + \"]: I: \" + log);\n }\n\n public static void logSI(String tag, String log) {\n android.util.Log.i(hookMain, \"[\" + tag + \"]: I: \" + log);\n }\n\n public static void logSW(String tag, String log) {\n android.util.Log.w(hookMain, \"[\" + tag + \"]: W: \" + log);\n }\n\n public void logSE(String tag, String log) {\n android.util.Log.e(hookMain, \"[\" + tag + \"]: E: \" + log);\n }\n}" }, { "identifier": "UnlockIme", "path": "app/src/main/java/com/hchen/clipboardlist/unlockIme/UnlockIme.java", "snippet": "public class UnlockIme extends Hook {\n\n private final String[] miuiImeList = new String[]{\n \"com.iflytek.inputmethod.miui\",\n \"com.sohu.inputmethod.sogou.xiaomi\",\n \"com.baidu.input_mi\",\n \"com.miui.catcherpatch\"\n };\n\n private int navBarColor = 0;\n\n @Override\n public void init() {\n if (getProp(\"ro.miui.support_miui_ime_bottom\", \"0\").equals(\"1\")) {\n startHook(loadPackageParam);\n }\n }\n\n private void startHook(LoadPackageParam param) {\n // 检查是否为小米定制输入法\n boolean isNonCustomize = true;\n for (String isMiui : miuiImeList) {\n if (isMiui.equals(param.packageName)) {\n isNonCustomize = false;\n break;\n }\n }\n if (isNonCustomize) {\n Class<?> sInputMethodServiceInjector = findClassIfExists(\"android.inputmethodservice.InputMethodServiceInjector\");\n if (sInputMethodServiceInjector == null)\n sInputMethodServiceInjector = findClassIfExists(\"android.inputmethodservice.InputMethodServiceStubImpl\");\n if (sInputMethodServiceInjector != null) {\n hookSIsImeSupport(sInputMethodServiceInjector);\n hookIsXiaoAiEnable(sInputMethodServiceInjector);\n setPhraseBgColor(sInputMethodServiceInjector);\n } else {\n logE(tag, \"Class not found: InputMethodServiceInjector\");\n }\n }\n hookDeleteNotSupportIme(\"android.inputmethodservice.InputMethodServiceInjector$MiuiSwitchInputMethodListener\",\n param.classLoader);\n\n // 获取常用语的ClassLoader\n boolean finalIsNonCustomize = isNonCustomize;\n findAndHookMethod(\"android.inputmethodservice.InputMethodModuleManager\",\n \"loadDex\", ClassLoader.class, String.class,\n new HookAction() {\n @Override\n protected void after(MethodHookParam param) {\n getSupportIme((ClassLoader) param.args[0]);\n hookDeleteNotSupportIme(\"com.miui.inputmethod.InputMethodBottomManager$MiuiSwitchInputMethodListener\", (ClassLoader) param.args[0]);\n if (finalIsNonCustomize) {\n Class<?> InputMethodBottomManager = findClassIfExists(\"com.miui.inputmethod.InputMethodBottomManager\", (ClassLoader) param.args[0]);\n if (InputMethodBottomManager != null) {\n hookSIsImeSupport(InputMethodBottomManager);\n hookIsXiaoAiEnable(InputMethodBottomManager);\n } else {\n logE(tag, \"Class not found: com.miui.inputmethod.InputMethodBottomManager\");\n }\n }\n }\n }\n );\n }\n\n /**\n * 跳过包名检查,直接开启输入法优化\n *\n * @param clazz 声明或继承字段的类\n */\n private void hookSIsImeSupport(Class<?> clazz) {\n try {\n setStaticObjectField(clazz, \"sIsImeSupport\", 1);\n } catch (Throwable throwable) {\n logE(tag, \"Hook field sIsImeSupport: \" + throwable);\n }\n }\n\n /**\n * 小爱语音输入按钮失效修复\n *\n * @param clazz 声明或继承方法的类\n */\n private void hookIsXiaoAiEnable(Class<?> clazz) {\n try {\n hookAllMethods(clazz, \"isXiaoAiEnable\", returnConstant(false));\n } catch (Throwable throwable) {\n logE(tag, \"Hook method isXiaoAiEnable: \" + throwable);\n }\n }\n\n /**\n * 在适当的时机修改抬高区域背景颜色\n *\n * @param clazz 声明或继承字段的类\n */\n private void setPhraseBgColor(Class<?> clazz) {\n try {\n findAndHookMethod(\"com.android.internal.policy.PhoneWindow\",\n \"setNavigationBarColor\", int.class,\n new HookAction() {\n @Override\n protected void after(MethodHookParam param) {\n if ((int) param.args[0] == 0) return;\n navBarColor = (int) param.args[0];\n customizeBottomViewColor(clazz);\n }\n }\n );\n hookAllMethods(clazz, \"addMiuiBottomView\",\n new HookAction() {\n @Override\n protected void after(MethodHookParam param) {\n customizeBottomViewColor(clazz);\n }\n }\n );\n } catch (Throwable throwable) {\n logE(tag, \"Set the color of the MiuiBottomView: \" + throwable);\n }\n }\n\n /**\n * 将导航栏颜色赋值给输入法优化的底图\n *\n * @param clazz 声明或继承字段的类\n */\n private void customizeBottomViewColor(Class<?> clazz) {\n try {\n if (navBarColor != 0) {\n int color = -0x1 - navBarColor;\n callStaticMethod(clazz, \"customizeBottomViewColor\", true, navBarColor, color | -0x1000000, color | 0x66000000);\n }\n } catch (Throwable e) {\n logE(tag, \"Call customizeBottomViewColor: \" + e);\n }\n }\n\n /**\n * 针对A10的修复切换输入法列表\n *\n * @param className 声明或继承方法的类的名称\n */\n private void hookDeleteNotSupportIme(String className, ClassLoader classLoader) {\n try {\n hookAllMethods(findClassIfExists(className, classLoader), \"deleteNotSupportIme\", returnConstant(null));\n } catch (Throwable throwable) {\n logE(tag, \"Hook method deleteNotSupportIme: \" + throwable);\n }\n }\n\n /**\n * 使切换输入法界面显示第三方输入法\n *\n * @param classLoader\n */\n private void getSupportIme(ClassLoader classLoader) {\n try {\n findAndHookMethod(\"com.miui.inputmethod.InputMethodBottomManager\",\n classLoader, \"getSupportIme\",\n new HookAction() {\n\n @Override\n protected void before(MethodHookParam param) {\n List<?> getEnabledInputMethodList = (List<?>) callMethod(getObjectField(getStaticObjectField(\n findClassIfExists(\"com.miui.inputmethod.InputMethodBottomManager\", classLoader),\n \"sBottomViewHelper\"), \"mImm\"), \"getEnabledInputMethodList\");\n param.setResult(getEnabledInputMethodList);\n }\n }\n );\n } catch (Throwable e) {\n logE(tag, \"Hook method getSupportIme: \" + e);\n }\n }\n}" } ]
import android.content.Context; import android.view.inputmethod.InputMethodInfo; import android.view.inputmethod.InputMethodManager; import com.hchen.clipboardlist.clipboard.ClipboardList; import com.hchen.clipboardlist.hook.Hook; import com.hchen.clipboardlist.hook.Log; import com.hchen.clipboardlist.unlockIme.UnlockIme; import java.util.ArrayList; import java.util.List; import de.robv.android.xposed.IXposedHookLoadPackage; import de.robv.android.xposed.callbacks.XC_LoadPackage.LoadPackageParam;
10,065
package com.hchen.clipboardlist; public class HookMain implements IXposedHookLoadPackage { public static List<String> mAppsUsingInputMethod = new ArrayList<>(); @Override public void handleLoadPackage(LoadPackageParam lpparam) { if (mAppsUsingInputMethod.isEmpty()) {
package com.hchen.clipboardlist; public class HookMain implements IXposedHookLoadPackage { public static List<String> mAppsUsingInputMethod = new ArrayList<>(); @Override public void handleLoadPackage(LoadPackageParam lpparam) { if (mAppsUsingInputMethod.isEmpty()) {
mAppsUsingInputMethod = getAppsUsingInputMethod(Hook.findContext());
1
2023-12-22 15:07:33+00:00
12k
danielfeitopin/MUNICS-SAPP-P1
src/main/java/es/storeapp/web/controller/UserController.java
[ { "identifier": "User", "path": "src/main/java/es/storeapp/business/entities/User.java", "snippet": "@Entity(name = Constants.USER_ENTITY)\n@Table(name = Constants.USERS_TABLE)\npublic class User implements Serializable {\n\n private static final long serialVersionUID = 570528466125178223L;\n\n public User() {\n }\n\n public User(String name, String email, String password, String address, String image) {\n this.name = name;\n this.email = email;\n this.password = password;\n this.address = address;\n this.image = image;\n }\n \n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long userId;\n \n @NotBlank(message = \"Name cannot be null\")\n @Column(name = \"name\", nullable = false, unique = false)\n private String name;\n \n @Email(message = \"Email should be valid\")\n @NotBlank(message = \"Email cannot be null\")\n @Column(name = \"email\", nullable = false, unique = true)\n private String email;\n \n @Column(name = \"password\", nullable = false)\n private String password;\n\n @NotBlank(message = \"address cannot be null\")\n @Column(name = \"address\", nullable = false)\n private String address;\n\n @Column(name = \"resetPasswordToken\")\n private String resetPasswordToken;\n \n @Embedded\n @AttributeOverrides(value = {\n @AttributeOverride(name = \"card\", column = @Column(name = \"card\")),\n @AttributeOverride(name = \"cvv\", column = @Column(name = \"CVV\")),\n @AttributeOverride(name = \"expirationMonth\", column = @Column(name = \"expirationMonth\")),\n @AttributeOverride(name = \"expirationYear\", column = @Column(name = \"expirationYear\"))\n })\n private CreditCard card;\n \n @Column(name = \"image\")\n private String image;\n \n @OneToMany(mappedBy = \"user\")\n private List<Comment> comments = new ArrayList<>();\n \n public Long getUserId() {\n return userId;\n }\n\n public void setUserId(Long userId) {\n this.userId = userId;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getEmail() {\n return email;\n }\n\n public void setEmail(String email) {\n this.email = email;\n }\n\n public String getPassword() {\n return password;\n }\n\n public void setPassword(String password) {\n this.password = password;\n }\n\n public String getAddress() {\n return address;\n }\n\n public void setAddress(String address) {\n this.address = address;\n }\n\n public String getImage() {\n return image;\n }\n\n public void setImage(String image) {\n this.image = image;\n }\n\n public CreditCard getCard() {\n return card;\n }\n\n public void setCard(CreditCard card) {\n this.card = card;\n }\n\n public List<Comment> getComments() {\n return comments;\n }\n\n public void setComments(List<Comment> comments) {\n this.comments = comments;\n }\n\n public String getResetPasswordToken() {\n return resetPasswordToken;\n }\n\n public void setResetPasswordToken(String resetPasswordToken) {\n this.resetPasswordToken = resetPasswordToken;\n }\n\n @Override\n public String toString() {\n return String.format(\"User{userId=%s, name=%s, email=%s, password=%s, address=%s, resetPasswordToken=%s, card=%s, image=%s}\", \n userId, name, email, password, address, resetPasswordToken, card, image);\n }\n\n}" }, { "identifier": "AuthenticationException", "path": "src/main/java/es/storeapp/business/exceptions/AuthenticationException.java", "snippet": "public class AuthenticationException extends Exception {\n \n private static final long serialVersionUID = 9047626511480506926L;\n\n public AuthenticationException(String message) {\n super(message);\n }\n \n}" }, { "identifier": "DuplicatedResourceException", "path": "src/main/java/es/storeapp/business/exceptions/DuplicatedResourceException.java", "snippet": "public class DuplicatedResourceException extends Exception {\n \n private static final long serialVersionUID = 6896927410877749980L;\n\n private final String resource;\n private final String value;\n\n public DuplicatedResourceException(String resource, String value, String message) {\n super(message);\n this.resource = resource;\n this.value = value;\n }\n\n public Object getResource() {\n return resource;\n }\n\n public Object getValue() {\n return value;\n }\n \n}" }, { "identifier": "InstanceNotFoundException", "path": "src/main/java/es/storeapp/business/exceptions/InstanceNotFoundException.java", "snippet": "public class InstanceNotFoundException extends Exception {\n\n private static final long serialVersionUID = -4208426212843868046L;\n\n private final Long id;\n private final String type;\n\n public InstanceNotFoundException(Long id, String type, String message) {\n super(message);\n this.id = id;\n this.type = type;\n }\n\n public Object getId() {\n return id;\n }\n\n public String getType() {\n return type;\n }\n \n}" }, { "identifier": "ServiceException", "path": "src/main/java/es/storeapp/business/exceptions/ServiceException.java", "snippet": "public class ServiceException extends Exception {\n \n private static final long serialVersionUID = -5772226522820952867L;\n\n public ServiceException(String message) {\n super(message);\n }\n \n}" }, { "identifier": "UserService", "path": "src/main/java/es/storeapp/business/services/UserService.java", "snippet": "@Service\npublic class UserService {\n\n private static final EscapingLoggerWrapper logger = new EscapingLoggerWrapper(UserService.class);\n\n @Autowired\n ConfigurationParameters configurationParameters;\n\n @Autowired\n private UserRepository userRepository;\n\n @Autowired\n private MessageSource messageSource;\n\n @Autowired\n ExceptionGenerationUtils exceptionGenerationUtils;\n\n private File resourcesDir;\n\n @PostConstruct\n public void init() {\n resourcesDir = new File(configurationParameters.getResources());\n }\n\n @Transactional(readOnly = true)\n public User findByEmail(String email) {\n return userRepository.findByEmail(email);\n }\n\n @Transactional(readOnly = true)\n public User login(String email, String clearPassword) throws AuthenticationException {\n if (!userRepository.existsUser(email)) {\n throw exceptionGenerationUtils.toAuthenticationException(Constants.AUTH_INVALID_USER_MESSAGE, email);\n }\n User user = userRepository.findByEmail(email);\n if (!BCrypt.checkpw(clearPassword, user.getPassword())) {\n throw exceptionGenerationUtils.toAuthenticationException(Constants.AUTH_INVALID_PASSWORD_MESSAGE, email);\n }\n return user;\n }\n\n @Transactional()\n public void sendResetPasswordEmail(String email, String url, Locale locale)\n throws AuthenticationException, ServiceException {\n User user = userRepository.findByEmail(email);\n if (user == null) {\n return;\n }\n String token = UUID.randomUUID().toString();\n\n try {\n\n System.setProperty(\"mail.smtp.ssl.protocols\", \"TLSv1.2\");\n\n HtmlEmail htmlEmail = new HtmlEmail();\n htmlEmail.setHostName(configurationParameters.getMailHost());\n htmlEmail.setSmtpPort(configurationParameters.getMailPort());\n htmlEmail.setSslSmtpPort(Integer.toString(configurationParameters.getMailPort()));\n htmlEmail.setAuthentication(configurationParameters.getMailUserName(),\n configurationParameters.getMailPassword());\n htmlEmail.setSSLOnConnect(configurationParameters.getMailSslEnable() != null\n && configurationParameters.getMailSslEnable());\n if (configurationParameters.getMailStartTlsEnable()) {\n htmlEmail.setStartTLSEnabled(true);\n htmlEmail.setStartTLSRequired(true);\n }\n htmlEmail.addTo(email, user.getName());\n htmlEmail.setFrom(configurationParameters.getMailFrom());\n htmlEmail.setSubject(messageSource.getMessage(Constants.MAIL_SUBJECT_MESSAGE,\n new Object[]{user.getName()}, locale));\n\n String link = url + Constants.PARAMS\n + Constants.TOKEN_PARAM + Constants.PARAM_VALUE + token + Constants.NEW_PARAM_VALUE\n + Constants.EMAIL_PARAM + Constants.PARAM_VALUE + email;\n\n htmlEmail.setHtmlMsg(messageSource.getMessage(Constants.MAIL_TEMPLATE_MESSAGE,\n new Object[]{user.getName(), link}, locale));\n\n htmlEmail.setTextMsg(messageSource.getMessage(Constants.MAIL_HTML_NOT_SUPPORTED_MESSAGE,\n new Object[0], locale));\n\n htmlEmail.send();\n } catch (Exception ex) {\n logger.error(ex.getMessage(), ex);\n throw new ServiceException(ex.getMessage());\n }\n\n user.setResetPasswordToken(token);\n userRepository.update(user);\n }\n\n @Transactional\n public User create(String name, String email, String password, String address,\n String image, byte[] imageContents) throws DuplicatedResourceException {\n if (userRepository.findByEmail(email) != null) {\n throw exceptionGenerationUtils.toDuplicatedResourceException(Constants.EMAIL_FIELD, email,\n Constants.DUPLICATED_INSTANCE_MESSAGE);\n }\n User user = userRepository.create(new User(name, email, BCrypt.hashpw(password, BCrypt.gensalt()), address, image));\n saveProfileImage(user.getUserId(), image, imageContents);\n return user;\n }\n\n @Transactional\n public User update(Long id, String name, String email, String address, String image, byte[] imageContents)\n throws DuplicatedResourceException, InstanceNotFoundException, ServiceException {\n User user = userRepository.findById(id);\n User emailUser = userRepository.findByEmail(email);\n if (emailUser != null && !Objects.equals(emailUser.getUserId(), user.getUserId())) {\n throw exceptionGenerationUtils.toDuplicatedResourceException(Constants.EMAIL_FIELD, email,\n Constants.DUPLICATED_INSTANCE_MESSAGE);\n }\n user.setName(name);\n user.setEmail(email);\n user.setAddress(address);\n if (image != null && image.trim().length() > 0 && imageContents != null) {\n try {\n deleteProfileImage(id, user.getImage());\n } catch (Exception ex) {\n logger.error(ex.getMessage(), ex);\n }\n saveProfileImage(id, image, imageContents);\n user.setImage(image);\n }\n return userRepository.update(user);\n }\n\n @Transactional\n public User changePassword(Long id, String oldPassword, String password)\n throws InstanceNotFoundException, AuthenticationException {\n User user = userRepository.findById(id);\n if (user == null) {\n throw exceptionGenerationUtils.toAuthenticationException(\n Constants.AUTH_INVALID_USER_MESSAGE, id.toString());\n }\n if (userRepository.findByEmailAndPassword(user.getEmail(), BCrypt.hashpw(oldPassword, BCrypt.gensalt())) == null) {\n throw exceptionGenerationUtils.toAuthenticationException(Constants.AUTH_INVALID_PASSWORD_MESSAGE,\n id.toString());\n }\n user.setPassword(BCrypt.hashpw(password, BCrypt.gensalt()));\n return userRepository.update(user);\n }\n\n @Transactional\n public User changePassword(String email, String password, String token) throws AuthenticationException {\n User user = userRepository.findByEmail(email);\n if (user == null) {\n throw exceptionGenerationUtils.toAuthenticationException(Constants.AUTH_INVALID_USER_MESSAGE, email);\n }\n if (user.getResetPasswordToken() == null || !user.getResetPasswordToken().equals(token)) {\n throw exceptionGenerationUtils.toAuthenticationException(Constants.AUTH_INVALID_TOKEN_MESSAGE, email);\n }\n user.setPassword(BCrypt.hashpw(password, BCrypt.gensalt()));\n user.setResetPasswordToken(null);\n return userRepository.update(user);\n }\n\n @Transactional\n public User removeImage(Long id) throws InstanceNotFoundException, ServiceException {\n User user = userRepository.findById(id);\n try {\n deleteProfileImage(id, user.getImage());\n } catch (IOException ex) {\n logger.error(ex.getMessage(), ex);\n throw new ServiceException(ex.getMessage());\n }\n user.setImage(null);\n return userRepository.update(user);\n }\n\n @Transactional\n public byte[] getImage(Long id) throws InstanceNotFoundException {\n User user = userRepository.findById(id);\n try {\n return getProfileImage(id, user.getImage());\n } catch (IOException ex) {\n logger.error(ex.getMessage(), ex);\n return null;\n }\n }\n\n private void saveProfileImage(Long id, String image, byte[] imageContents) {\n if (image != null && image.trim().length() > 0 && imageContents != null) {\n File userDir = new File(resourcesDir, id.toString());\n userDir.mkdirs();\n File profilePicture = new File(userDir, image);\n try (FileOutputStream outputStream = new FileOutputStream(profilePicture);) {\n IOUtils.copy(new ByteArrayInputStream(imageContents), outputStream);\n } catch (Exception e) {\n logger.error(e.getMessage(), e);\n }\n }\n }\n\n private void deleteProfileImage(Long id, String image) throws IOException {\n if (image != null && image.trim().length() > 0) {\n File userDir = new File(resourcesDir, id.toString());\n File profilePicture = new File(userDir, image);\n Files.delete(profilePicture.toPath());\n }\n }\n\n private byte[] getProfileImage(Long id, String image) throws IOException {\n if (image != null && image.trim().length() > 0) {\n File userDir = new File(resourcesDir, id.toString());\n File profilePicture = new File(userDir, image);\n try (FileInputStream input = new FileInputStream(profilePicture)) {\n return IOUtils.toByteArray(input);\n }\n }\n return null;\n }\n\n}" }, { "identifier": "Constants", "path": "src/main/java/es/storeapp/common/Constants.java", "snippet": "public class Constants {\n\n private Constants() {\n }\n \n /* Messages */\n \n public static final String AUTH_INVALID_USER_MESSAGE = \"auth.invalid.user\";\n public static final String AUTH_INVALID_PASSWORD_MESSAGE = \"auth.invalid.password\";\n public static final String AUTH_INVALID_TOKEN_MESSAGE = \"auth.invalid.token\";\n public static final String REGISTRATION_INVALID_PARAMS_MESSAGE = \"registration.invalid.parameters\";\n public static final String UPDATE_PROFILE_INVALID_PARAMS_MESSAGE = \"update.profile.invalid.parameters\";\n public static final String CHANGE_PASSWORD_INVALID_PARAMS_MESSAGE = \"change.password.invalid.parameters\";\n public static final String RESET_PASSWORD_INVALID_PARAMS_MESSAGE = \"reset.password.invalid.parameters\";\n public static final String LOGIN_INVALID_PARAMS_MESSAGE = \"login.invalid.parameters\";\n public static final String INSTANCE_NOT_FOUND_MESSAGE = \"instance.not.found.exception\";\n public static final String DUPLICATED_INSTANCE_MESSAGE = \"duplicated.instance.exception\";\n public static final String DUPLICATED_COMMENT_MESSAGE = \"duplicated.comment.exception\";\n public static final String INVALID_PROFILE_IMAGE_MESSAGE = \"invalid.profile.image\";\n public static final String INVALID_STATE_EXCEPTION_MESSAGE = \"invalid.state\";\n public static final String INVALID_EMAIL_MESSAGE = \"invalid.email\";\n \n public static final String PRODUCT_ADDED_TO_THE_SHOPPING_CART = \"product.added.to.the.cart\";\n public static final String PRODUCT_REMOVED_FROM_THE_SHOPPING_CART = \"product.removed.from.the.cart\";\n public static final String PRODUCT_ALREADY_IN_SHOPPING_CART = \"product.already.in.cart\";\n public static final String PRODUCT_NOT_IN_SHOPPING_CART = \"product.not.in.cart\";\n public static final String EMPTY_SHOPPING_CART = \"shopping.cart.empty\";\n public static final String PRODUCT_COMMENT_CREATED = \"product.comment.created\";\n \n public static final String ORDER_AUTOGENERATED_NAME = \"order.name.autogenerated\";\n public static final String ORDER_SINGLE_PRODUCT_AUTOGENERATED_NAME_MESSAGE = \"order.name.single.product.autogenerated\";\n public static final String CREATE_ORDER_INVALID_PARAMS_MESSAGE = \"create.order.invalid.parameters\";\n public static final String PAY_ORDER_INVALID_PARAMS_MESSAGE = \"pay.order.invalid.parameters\";\n public static final String CANCEL_ORDER_INVALID_PARAMS_MESSAGE = \"cancel.order.invalid.parameters\";\n \n public static final String ORDER_CREATED_MESSAGE = \"order.created\";\n public static final String ORDER_PAYMENT_COMPLETE_MESSAGE = \"order.payment.completed\";\n public static final String ORDER_CANCEL_COMPLETE_MESSAGE = \"order.cancellation.completed\";\n \n public static final String REGISTRATION_SUCCESS_MESSAGE = \"registration.success\";\n public static final String PROFILE_UPDATE_SUCCESS = \"profile.updated.success\";\n public static final String CHANGE_PASSWORD_SUCCESS = \"change.password.success\";\n \n public static final String MAIL_SUBJECT_MESSAGE = \"mail.subject\";\n public static final String MAIL_TEMPLATE_MESSAGE = \"mail.template\";\n public static final String MAIL_HTML_NOT_SUPPORTED_MESSAGE = \"mail.html.not.supported\";\n public static final String MAIL_SUCCESS_MESSAGE = \"mail.sent.success\";\n public static final String MAIL_NOT_CONFIGURED_MESSAGE = \"mail.not.configured\";\n \n /* Web Endpoints */\n \n public static final String ROOT_ENDPOINT = \"/\";\n public static final String ALL_ENDPOINTS = \"/**\";\n public static final String LOGIN_ENDPOINT = \"/login\";\n public static final String LOGOUT_ENDPOINT = \"/logout\";\n public static final String USER_PROFILE_ALL_ENDPOINTS = \"/profile/**\";\n public static final String USER_PROFILE_ENDPOINT = \"/profile\";\n public static final String USER_PROFILE_IMAGE_ENDPOINT = \"/profile/image\";\n public static final String USER_PROFILE_IMAGE_REMOVE_ENDPOINT = \"/profile/image/remove\";\n public static final String REGISTRATION_ENDPOINT = \"/registration\";\n public static final String ORDERS_ALL_ENDPOINTS = \"/orders/**\";\n public static final String ORDERS_ENDPOINT = \"/orders\";\n public static final String ORDER_ENDPOINT = \"/orders/{id}\";\n public static final String ORDER_ENDPOINT_TEMPLATE = \"/orders/{0}\";\n public static final String ORDER_CONFIRM_ENDPOINT = \"/orders/complete\";\n public static final String ORDER_PAYMENT_ENDPOINT = \"/orders/{id}/pay\";\n public static final String ORDER_PAYMENT_ENDPOINT_TEMPLATE = \"/orders/{0}/pay\";\n public static final String ORDER_CANCEL_ENDPOINT = \"/orders/{id}/cancel\";\n public static final String PRODUCTS_ENDPOINT = \"/products\";\n public static final String PRODUCT_ENDPOINT = \"/products/{id}\";\n public static final String PRODUCT_TEMPLATE = \"/products/{0}\";\n public static final String CHANGE_PASSWORD_ENDPOINT = \"/changePassword\";\n public static final String RESET_PASSWORD_ENDPOINT = \"/resetPassword\";\n public static final String SEND_EMAIL_ENDPOINT = \"/sendEmail\";\n public static final String CART_ADD_PRODUCT_ENDPOINT = \"/products/{id}/addToCart\";\n public static final String CART_REMOVE_PRODUCT_ENDPOINT = \"/products/{id}/removeFromCart\";\n public static final String CART_ENDPOINT = \"/cart\";\n public static final String COMMENT_PRODUCT_ENDPOINT = \"/products/{id}/rate\";\n public static final String EXTERNAL_RESOURCES = \"/resources/**\";\n public static final String LIBS_RESOURCES = \"/webjars/**\";\n public static final String SEND_REDIRECT = \"redirect:\";\n \n /* Web Pages */\n \n public static final String LOGIN_PAGE = \"Login\";\n public static final String HOME_PAGE = \"Index\";\n public static final String ERROR_PAGE = \"error\";\n public static final String PASSWORD_PAGE = \"ChangePassword\";\n public static final String SEND_EMAIL_PAGE = \"SendEmail\";\n public static final String RESET_PASSWORD_PAGE = \"ResetPassword\";\n public static final String USER_PROFILE_PAGE = \"Profile\";\n public static final String PRODUCTS_PAGE = \"Products\";\n public static final String PRODUCT_PAGE = \"Product\";\n public static final String SHOPPING_CART_PAGE = \"Cart\";\n public static final String ORDER_COMPLETE_PAGE = \"OrderConfirm\";\n public static final String ORDER_PAGE = \"Order\";\n public static final String ORDER_PAYMENT_PAGE = \"Payment\";\n public static final String ORDERS_PAGE = \"Orders\";\n public static final String PAYMENTS_PAGE = \"Orders\";\n public static final String COMMENT_PAGE = \"Comment\";\n \n /* Request/session/model Attributes */\n \n public static final String PARAMS = \"?\";\n public static final String PARAM_VALUE = \"=\";\n public static final String NEW_PARAM_VALUE = \"&\";\n public static final String USER_SESSION = \"user\";\n public static final String SHOPPING_CART_SESSION = \"shoppingCart\";\n public static final String ERROR_MESSAGE = \"errorMessage\";\n public static final String EXCEPTION = \"exception\";\n public static final String WARNING_MESSAGE = \"warningMessage\";\n public static final String SUCCESS_MESSAGE = \"successMessage\";\n public static final String MESSAGE = \"message\"; /* predefined */\n public static final String LOGIN_FORM = \"loginForm\";\n public static final String USER_PROFILE_FORM = \"userProfileForm\";\n public static final String PASSWORD_FORM = \"passwordForm\";\n public static final String RESET_PASSWORD_FORM = \"resetPasswordForm\";\n public static final String COMMENT_FORM = \"commentForm\";\n public static final String PAYMENT_FORM = \"paymentForm\";\n public static final String NEXT_PAGE = \"next\";\n public static final String CATEGORIES = \"categories\";\n public static final String PRODUCTS = \"products\";\n public static final String PRODUCTS_ARRAY = \"products[]\";\n public static final String PRODUCT = \"product\";\n public static final String ORDER_FORM = \"orderForm\";\n public static final String ORDERS = \"orders\";\n public static final String ORDER = \"order\";\n public static final String PAY_NOW = \"pay\";\n public static final String BUY_BY_USER = \"buyByUser\";\n public static final String EMAIL_PARAM = \"email\";\n public static final String TOKEN_PARAM = \"token\";\n \n /* Entities, attributes and tables */\n \n public static final String USER_ENTITY = \"User\";\n public static final String PRODUCT_ENTITY = \"Product\";\n public static final String CATEGORY_ENTITY = \"Category\";\n public static final String COMMENT_ENTITY = \"Comment\";\n public static final String ORDER_ENTITY = \"Order\";\n public static final String ORDER_LINE_ENTITY = \"OrderLine\";\n \n public static final String USERS_TABLE = \"Users\";\n public static final String PRODUCTS_TABLE = \"Products\";\n public static final String CATEGORIES_TABLE = \"Categories\";\n public static final String COMMENTS_TABLE = \"Comments\";\n public static final String ORDERS_TABLE = \"Orders\";\n public static final String ORDER_LINES_TABLE = \"OrderLines\";\n \n public static final String PRICE_FIELD = \"price\";\n public static final String NAME_FIELD = \"name\";\n public static final String EMAIL_FIELD = \"email\";\n \n /* Other */\n \n public static final String CONTENT_TYPE_HEADER = \"Content-Type\";\n public static final String CONTENT_DISPOSITION_HEADER = \"Content-Disposition\";\n public static final String CONTENT_DISPOSITION_HEADER_VALUE = \"attachment; filename={0}-{1}\";\n public static final String PERSISTENT_USER_COOKIE = \"user-info\";\n public static final String URL_FORMAT = \"{0}://{1}:{2}{3}{4}\";\n \n}" }, { "identifier": "UserInfo", "path": "src/main/java/es/storeapp/web/cookies/UserInfo.java", "snippet": "@XmlRootElement(name=\"UserInfo\")\n@XmlAccessorType(XmlAccessType.FIELD)\npublic class UserInfo {\n\n @XmlElement\n private String email;\n @XmlElement\n private String password;\n\n public UserInfo() {\n }\n\n public UserInfo(String email, String password) {\n this.email = email;\n this.password = password;\n }\n \n public String getEmail() {\n return email;\n }\n\n public void setEmail(String email) {\n this.email = email;\n }\n\n public String getPassword() {\n return password;\n }\n\n public void setPassword(String password) {\n this.password = password;\n }\n \n}" }, { "identifier": "ErrorHandlingUtils", "path": "src/main/java/es/storeapp/web/exceptions/ErrorHandlingUtils.java", "snippet": "@Component\npublic class ErrorHandlingUtils {\n\n private static final EscapingLoggerWrapper logger = new EscapingLoggerWrapper(ErrorHandlingUtils.class);\n\n @Autowired\n private MessageSource messageSource;\n \n public String handleInvalidFormError(BindingResult result, String template, \n Model model, Locale locale) {\n if(logger.isErrorEnabled()) {\n logger.error(result.toString());\n }\n String message = messageSource.getMessage(template, new Object[0], locale);\n model.addAttribute(Constants.ERROR_MESSAGE, message);\n return Constants.ERROR_PAGE;\n }\n \n public String handleInstanceNotFoundException(InstanceNotFoundException e, Model model, Locale locale) {\n logger.error(e.getMessage(), e);\n model.addAttribute(Constants.ERROR_MESSAGE, e.getMessage());\n model.addAttribute(Constants.EXCEPTION, e);\n return Constants.ERROR_PAGE;\n }\n \n public String handleDuplicatedResourceException(DuplicatedResourceException e, String targetPage,\n Model model, Locale locale) {\n logger.error(e.getMessage(), e);\n model.addAttribute(Constants.ERROR_MESSAGE, e.getMessage());\n model.addAttribute(Constants.EXCEPTION, e);\n return targetPage;\n }\n\n public String handleAuthenticationException(AuthenticationException e, String user, String targetPage,\n Model model, Locale locale) {\n logger.error(e.getMessage(), e);\n model.addAttribute(Constants.ERROR_MESSAGE, e.getMessage());\n model.addAttribute(Constants.EXCEPTION, e);\n return targetPage;\n }\n \n public String handleInvalidStateException(InvalidStateException e, Model model, Locale locale) {\n logger.error(e.getMessage(), e);\n model.addAttribute(Constants.ERROR_MESSAGE, e.getMessage());\n model.addAttribute(Constants.EXCEPTION, e);\n return Constants.ERROR_PAGE;\n }\n \n public String handleUnexpectedException(Exception e, Model model) {\n logger.error(e.getMessage(), e);\n model.addAttribute(Constants.ERROR_MESSAGE, e.getMessage());\n model.addAttribute(Constants.EXCEPTION, e);\n return Constants.ERROR_PAGE;\n }\n}" }, { "identifier": "LoginForm", "path": "src/main/java/es/storeapp/web/forms/LoginForm.java", "snippet": "public class LoginForm {\n \n @NotNull\n @Size(min=1)\n private String email;\n \n @NotNull\n @Size(min=1)\n private String password;\n\n private Boolean rememberMe;\n \n public String getEmail() {\n return email;\n }\n\n public void setEmail(String email) {\n this.email = email;\n }\n\n public String getPassword() {\n return password;\n }\n\n public void setPassword(String password) {\n this.password = password;\n }\n\n public Boolean getRememberMe() {\n return rememberMe;\n }\n\n public void setRememberMe(Boolean rememberMe) {\n this.rememberMe = rememberMe;\n }\n \n \n \n}" }, { "identifier": "ChangePasswordForm", "path": "src/main/java/es/storeapp/web/forms/ChangePasswordForm.java", "snippet": "public class ChangePasswordForm {\n \n private String oldPassword;\n private String password;\n\n public String getOldPassword() {\n return oldPassword;\n }\n\n public void setOldPassword(String oldPassword) {\n this.oldPassword = oldPassword;\n }\n\n public String getPassword() {\n return password;\n }\n\n public void setPassword(String password) {\n this.password = password;\n }\n\n}" }, { "identifier": "ResetPasswordForm", "path": "src/main/java/es/storeapp/web/forms/ResetPasswordForm.java", "snippet": "public class ResetPasswordForm {\n\n private String token;\n private String email;\n private String password;\n\n public String getToken() {\n return token;\n }\n\n public void setToken(String token) {\n this.token = token;\n }\n\n public String getEmail() {\n return email;\n }\n\n public void setEmail(String email) {\n this.email = email;\n }\n\n public String getPassword() {\n return password;\n }\n\n public void setPassword(String password) {\n this.password = password;\n }\n\n}" }, { "identifier": "UserProfileForm", "path": "src/main/java/es/storeapp/web/forms/UserProfileForm.java", "snippet": "public class UserProfileForm {\n\n @NotNull\n @Size(min=4)\n private String name;\n \n @NotNull\n private String email;\n \n private String password;\n \n @NotNull\n private String address;\n \n private MultipartFile image;\n\n public UserProfileForm() {\n }\n\n public UserProfileForm(String name, String email, String address) {\n this.name = name;\n this.email = email;\n this.address = address;\n }\n \n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getEmail() {\n return email;\n }\n\n public void setEmail(String email) {\n this.email = email;\n }\n\n public String getPassword() {\n return password;\n }\n\n public void setPassword(String password) {\n this.password = password;\n }\n\n public String getAddress() {\n return address;\n }\n\n public void setAddress(String address) {\n this.address = address;\n }\n\n public MultipartFile getImage() {\n return image;\n }\n\n public void setImage(MultipartFile image) {\n this.image = image;\n } \n \n}" }, { "identifier": "EscapingLoggerWrapper", "path": "src/main/java/es/storeapp/common/EscapingLoggerWrapper.java", "snippet": "public class EscapingLoggerWrapper {\n private final Logger wrappedLogger;\n\n public EscapingLoggerWrapper(Class<?> clazz) {\n this.wrappedLogger = LoggerFactory.getLogger(clazz);\n }\n\n // Implementa todos los métodos de la interfaz org.slf4j.Logger\n // y agrega la lógica de escape de caracteres antes de llamar a los métodos del logger subyacente\n\n public void info(String format, Object... arguments) {\n String escapedFormat = escapeCharacters(format);\n wrappedLogger.info(escapedFormat, arguments);\n }\n\n public void error(String format, Object... arguments) {\n String escapedFormat = escapeCharacters(format);\n wrappedLogger.error(escapedFormat, arguments);\n }\n\n public void debug(String format, Object... arguments) {\n String escapedFormat = escapeCharacters(format);\n wrappedLogger.debug(escapedFormat, arguments);\n }\n\n public void warn(String format, Object... arguments) {\n String escapedFormat = escapeCharacters(format);\n wrappedLogger.warn(escapedFormat, arguments);\n }\n\n public boolean isWarnEnabled(){\n return wrappedLogger.isWarnEnabled();\n }\n\n public boolean isDebugEnabled(){\n return wrappedLogger.isDebugEnabled();\n }\n\n public boolean isErrorEnabled(){\n return wrappedLogger.isErrorEnabled();\n }\n\n // Método de escape de caracteres\n private String escapeCharacters(String input) {\n String string = Encode.forHtml(input);//evita javascript inyection\n return Encode.forJava(string);//codifica los saltos de linea\n }\n}" } ]
import es.storeapp.business.entities.User; import es.storeapp.business.exceptions.AuthenticationException; import es.storeapp.business.exceptions.DuplicatedResourceException; import es.storeapp.business.exceptions.InstanceNotFoundException; import es.storeapp.business.exceptions.ServiceException; import es.storeapp.business.services.UserService; import es.storeapp.common.Constants; import es.storeapp.web.cookies.UserInfo; import es.storeapp.web.exceptions.ErrorHandlingUtils; import es.storeapp.web.forms.LoginForm; import es.storeapp.web.forms.ChangePasswordForm; import es.storeapp.web.forms.ResetPasswordForm; import es.storeapp.web.forms.UserProfileForm; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.text.MessageFormat; import java.util.Base64; import java.util.Locale; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import jakarta.servlet.http.Cookie; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpSession; import jakarta.validation.Valid; import es.storeapp.common.EscapingLoggerWrapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.MessageSource; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.CookieValue; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.SessionAttribute; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.mvc.support.RedirectAttributes;
7,878
package es.storeapp.web.controller; @Controller public class UserController { private static final EscapingLoggerWrapper logger = new EscapingLoggerWrapper(UserController.class); @Autowired private MessageSource messageSource; @Autowired private UserService userService; @Autowired ErrorHandlingUtils errorHandlingUtils; @GetMapping(Constants.LOGIN_ENDPOINT) public String doGetLoginPage(Model model) { model.addAttribute(Constants.LOGIN_FORM, new LoginForm()); return Constants.LOGIN_PAGE; } @GetMapping(Constants.LOGOUT_ENDPOINT) public String doLogout(HttpSession session, HttpServletResponse response, @CookieValue(value = Constants.PERSISTENT_USER_COOKIE, required = false) String userInfo) { if (userInfo != null) { Cookie userCookie = new Cookie(Constants.PERSISTENT_USER_COOKIE, null); userCookie.setHttpOnly(true); userCookie.setSecure(true); userCookie.setMaxAge(0); // remove response.addCookie(userCookie); } if (session != null) { session.invalidate(); } return Constants.SEND_REDIRECT + Constants.ROOT_ENDPOINT; } @GetMapping(Constants.REGISTRATION_ENDPOINT) public String doGetRegisterPage(Model model) { model.addAttribute(Constants.USER_PROFILE_FORM, new UserProfileForm()); return Constants.USER_PROFILE_PAGE; } @GetMapping(Constants.USER_PROFILE_ENDPOINT) public String doGetProfilePage(@SessionAttribute(Constants.USER_SESSION) User user, Model model) { UserProfileForm form = new UserProfileForm(user.getName(), user.getEmail(), user.getAddress()); model.addAttribute(Constants.USER_PROFILE_FORM, form); return Constants.USER_PROFILE_PAGE; } @GetMapping(Constants.CHANGE_PASSWORD_ENDPOINT) public String doGetChangePasswordPage(Model model, @SessionAttribute(Constants.USER_SESSION) User user) { ChangePasswordForm form = new ChangePasswordForm(); model.addAttribute(Constants.PASSWORD_FORM, form); return Constants.PASSWORD_PAGE; } @GetMapping(Constants.SEND_EMAIL_ENDPOINT) public String doGetSendEmailPage(Model model) { return Constants.SEND_EMAIL_PAGE; } @GetMapping(Constants.RESET_PASSWORD_ENDPOINT) public String doGetResetPasswordPage(@RequestParam(value = Constants.TOKEN_PARAM) String token, @RequestParam(value = Constants.EMAIL_PARAM) String email, Model model) {
package es.storeapp.web.controller; @Controller public class UserController { private static final EscapingLoggerWrapper logger = new EscapingLoggerWrapper(UserController.class); @Autowired private MessageSource messageSource; @Autowired private UserService userService; @Autowired ErrorHandlingUtils errorHandlingUtils; @GetMapping(Constants.LOGIN_ENDPOINT) public String doGetLoginPage(Model model) { model.addAttribute(Constants.LOGIN_FORM, new LoginForm()); return Constants.LOGIN_PAGE; } @GetMapping(Constants.LOGOUT_ENDPOINT) public String doLogout(HttpSession session, HttpServletResponse response, @CookieValue(value = Constants.PERSISTENT_USER_COOKIE, required = false) String userInfo) { if (userInfo != null) { Cookie userCookie = new Cookie(Constants.PERSISTENT_USER_COOKIE, null); userCookie.setHttpOnly(true); userCookie.setSecure(true); userCookie.setMaxAge(0); // remove response.addCookie(userCookie); } if (session != null) { session.invalidate(); } return Constants.SEND_REDIRECT + Constants.ROOT_ENDPOINT; } @GetMapping(Constants.REGISTRATION_ENDPOINT) public String doGetRegisterPage(Model model) { model.addAttribute(Constants.USER_PROFILE_FORM, new UserProfileForm()); return Constants.USER_PROFILE_PAGE; } @GetMapping(Constants.USER_PROFILE_ENDPOINT) public String doGetProfilePage(@SessionAttribute(Constants.USER_SESSION) User user, Model model) { UserProfileForm form = new UserProfileForm(user.getName(), user.getEmail(), user.getAddress()); model.addAttribute(Constants.USER_PROFILE_FORM, form); return Constants.USER_PROFILE_PAGE; } @GetMapping(Constants.CHANGE_PASSWORD_ENDPOINT) public String doGetChangePasswordPage(Model model, @SessionAttribute(Constants.USER_SESSION) User user) { ChangePasswordForm form = new ChangePasswordForm(); model.addAttribute(Constants.PASSWORD_FORM, form); return Constants.PASSWORD_PAGE; } @GetMapping(Constants.SEND_EMAIL_ENDPOINT) public String doGetSendEmailPage(Model model) { return Constants.SEND_EMAIL_PAGE; } @GetMapping(Constants.RESET_PASSWORD_ENDPOINT) public String doGetResetPasswordPage(@RequestParam(value = Constants.TOKEN_PARAM) String token, @RequestParam(value = Constants.EMAIL_PARAM) String email, Model model) {
ResetPasswordForm form = new ResetPasswordForm();
11
2023-12-24 19:24:49+00:00
12k
RoderickQiu/SUSTech_CSE_Projects
CS109_2022_Fall/Chess/Main.java
[ { "identifier": "ChessColor", "path": "CS109_2022_Fall/Chess/model/ChessColor.java", "snippet": "public enum ChessColor {\r\n BLACK(\"BLACK\", Color.decode(\"#251f1e\")), RED(\"RED\", Color.decode(\"#e83505\")), NONE(\"No Player\", Color.WHITE);\r\n\r\n private final String name;\r\n private final Color color;\r\n\r\n ChessColor(String name, Color color) {\r\n this.name = name;\r\n this.color = color;\r\n }\r\n\r\n public String getName() {\r\n return name;\r\n }\r\n\r\n public Color getColor() {\r\n return color;\r\n }\r\n}\r" }, { "identifier": "FileUtils", "path": "CS109_2022_Fall/Chess/utils/FileUtils.java", "snippet": "public class FileUtils {\n public static void saveDataToFile(String fileName, String data, String type) {\n BufferedWriter writer = null;\n File file = new File(System.getProperty(\"user.dir\") + getCorrectSlash() + fileName + \".\" + type);\n //如果文件不存在,则新建一个\n if (!file.exists()) {\n try {\n file.createNewFile();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n //写入\n try {\n writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, false), \"UTF-8\"));\n writer.write(data);\n } catch (IOException e) {\n e.printStackTrace();\n } finally {\n try {\n if (writer != null) {\n writer.close();\n }\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n System.out.println(\"文件写入成功!\");\n }\n\n public static String getDataFromFileInAbsolutePath(String fileName) {\n String Path = fileName;\n BufferedReader reader = null;\n String laststr = \"\";\n try {\n FileInputStream fileInputStream = new FileInputStream(Path);\n InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, \"UTF-8\");\n reader = new BufferedReader(inputStreamReader);\n String tempString = null;\n while ((tempString = reader.readLine()) != null) {\n laststr += tempString;\n }\n reader.close();\n } catch (IOException e) {\n e.printStackTrace();\n } finally {\n if (reader != null) {\n try {\n reader.close();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n }\n return laststr;\n }\n\n public static String getDataFromFile(String fileName) {\n String Path = System.getProperty(\"user.dir\") + getCorrectSlash() + fileName + \".json\";\n BufferedReader reader = null;\n String laststr = \"\";\n try {\n FileInputStream fileInputStream = new FileInputStream(Path);\n InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, \"UTF-8\");\n reader = new BufferedReader(inputStreamReader);\n String tempString = null;\n while ((tempString = reader.readLine()) != null) {\n laststr += tempString;\n }\n reader.close();\n } catch (IOException e) {\n e.printStackTrace();\n if (e.getMessage().contains(\"FileNotFound\")) { // File not yet created\n saveDataToFile(fileName, \"{}\", \"json\");\n }\n } finally {\n if (reader != null) {\n try {\n reader.close();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n }\n return laststr;\n }\n\n public static String getCorrectSlash() {\n if (System.getProperty(\"os.name\").toLowerCase().contains(\"windows\")) return \"\\\\\";\n else return \"/\";\n }\n}" }, { "identifier": "ChessGameFrame", "path": "CS109_2022_Fall/Chess/view/ChessGameFrame.java", "snippet": "public class ChessGameFrame extends JFrame {\r\n private final int WIDTH;\r\n private final int HEIGHT;\r\n public final int CHESSBOARD_SIZE;\r\n private GameController gameController;\r\n private static JLabel statusLabel, scoreLabel, blackEatenLabel, redEatenLabel;\r\n private static JPanel eatenPanel;\r\n public static String redEatenList, blackEatenList;\r\n private Gson gson = new Gson();\r\n private static EatenComponent[][] eatenComponents = new EatenComponent[2][7];\r\n private static String[][] nameList = {\r\n {\"將\", \"士\", \"象\", \"車\", \"馬\", \"卒\", \"砲\"},\r\n {\"帥\", \"仕\", \"相\", \"俥\", \"傌\", \"兵\", \"炮\"}};\r\n private static int redEaten[] = {0, 0, 0, 0, 0, 0, 0}, blackEaten[] = {0, 0, 0, 0, 0, 0, 0};\r\n\r\n public ChessGameFrame(int width, int height, int mode) {\r\n setTitle(\"翻翻棋~\");\r\n this.WIDTH = width;\r\n this.HEIGHT = height;\r\n this.CHESSBOARD_SIZE = HEIGHT * 4 / 5;\r\n \r\n redEatenList = \"\";\r\n blackEatenList = \"\";\r\n\r\n setResizable(false);\r\n setSize(WIDTH, HEIGHT);\r\n setLocationRelativeTo(null); // Center the window.\r\n getContentPane().setBackground(Color.WHITE);\r\n setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);\r\n setLayout(null);\r\n\r\n addChessboard(mode);\r\n addStatusLabel();\r\n addScoreLabel();\r\n addBlackEatenLabel();\r\n addRedEatenLabel();\r\n addEatenList();\r\n addBackButton();\r\n addLoadButton();\r\n addRefreshButton();\r\n addThemeButton();\r\n addBg();\r\n }\r\n\r\n\r\n /**\r\n * 在游戏窗体中添加棋盘\r\n */\r\n private void addChessboard(int mode) {\r\n Chessboard chessboard = new Chessboard(CHESSBOARD_SIZE / 2 + 100, CHESSBOARD_SIZE, mode);\r\n gameController = new GameController(chessboard);\r\n chessboard.setLocation(HEIGHT / 13, HEIGHT / 13);\r\n add(chessboard);\r\n }\r\n\r\n private void addEatenList() {\r\n eatenPanel = new JPanel();\r\n eatenPanel.setBounds(WIDTH * 11 / 15 + 2, (int) (HEIGHT / 13 * 6.04), 75, 185);\r\n GridLayout gridLayout = new GridLayout(7, 2);\r\n eatenPanel.setLayout(gridLayout);\r\n eatenPanel.setBackground(Color.WHITE);\r\n eatenPanel.setOpaque(false);//workaround keep opaque after repainted\r\n add(eatenPanel);\r\n\r\n setEatenList();\r\n }\r\n\r\n private static void setEatenList() {\r\n parseEatenLists();\r\n\r\n for (int j = 0; j < 7; j++) {\r\n for (int i = 0; i < 2; i++) {\r\n if (eatenComponents[i][j] != null) eatenPanel.remove(eatenComponents[i][j]);\r\n eatenComponents[i][j] = new EatenComponent(nameList[i][j],\r\n (i == 0) ? blackEaten[j] : redEaten[j], i, j, (i == 0) ? \"b\" : \"r\");\r\n eatenPanel.add(eatenComponents[i][j]);\r\n }\r\n }\r\n }\r\n\r\n private static void parseEatenLists() {\r\n Arrays.fill(redEaten, 0);\r\n Arrays.fill(blackEaten, 0);\r\n String[] red = redEatenList.split(\" \"), black = blackEatenList.split(\" \");\r\n for (String s : red) {\r\n switch (s) {\r\n case \"帥\" -> redEaten[0]++;\r\n case \"仕\" -> redEaten[1]++;\r\n case \"相\" -> redEaten[2]++;\r\n case \"俥\" -> redEaten[3]++;\r\n case \"傌\" -> redEaten[4]++;\r\n case \"兵\" -> redEaten[5]++;\r\n case \"炮\" -> redEaten[6]++;\r\n }\r\n }\r\n for (String s : black) {\r\n switch (s) {\r\n case \"將\" -> blackEaten[0]++;\r\n case \"士\" -> blackEaten[1]++;\r\n case \"象\" -> blackEaten[2]++;\r\n case \"車\" -> blackEaten[3]++;\r\n case \"馬\" -> blackEaten[4]++;\r\n case \"卒\" -> blackEaten[5]++;\r\n case \"砲\" -> blackEaten[6]++;\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * 在游戏窗体中添加标签\r\n */\r\n private void addStatusLabel() {\r\n statusLabel = new JLabel(\"红走棋\");\r\n statusLabel.setLocation(WIDTH * 11 / 15 + 5, (int) (HEIGHT / 13 * 10.65));\r\n statusLabel.setSize(200, 60);\r\n statusLabel.setFont(sansFont.deriveFont(Font.BOLD, 23));\r\n statusLabel.setForeground(Main.getThemeColor(\"indicatorRed\"));\r\n add(statusLabel);\r\n }\r\n\r\n private void addRedEatenLabel() {\r\n redEatenLabel = new JLabel();\r\n redEatenLabel.setLocation(WIDTH * 11 / 15 + 5, (int) (HEIGHT / 13 * 5.05));\r\n redEatenLabel.setSize(100, 200);\r\n redEatenLabel.setFont(sansFont.deriveFont(Font.BOLD, 14));\r\n redEatenLabel.setForeground(Main.getThemeColor(\"indicatorBlack\"));\r\n JlabelSetText(redEatenLabel, \"红被吃:----\");\r\n redEatenLabel.setFont(sansFont.deriveFont(Font.BOLD, 14));\r\n //add(redEatenLabel);\r\n }\r\n\r\n private void addBlackEatenLabel() {\r\n blackEatenLabel = new JLabel();\r\n blackEatenLabel.setLocation(WIDTH * 11 / 15 + 5, (int) (HEIGHT / 13 * 6.65));\r\n blackEatenLabel.setSize(100, 200);\r\n blackEatenLabel.setFont(sansFont.deriveFont(Font.BOLD, 14));\r\n blackEatenLabel.setForeground(Main.getThemeColor(\"indicatorBlack\"));\r\n JlabelSetText(blackEatenLabel, \"黑被吃:----\");\r\n blackEatenLabel.setFont(sansFont.deriveFont(Font.BOLD, 14));\r\n //add(blackEatenLabel);\r\n }\r\n\r\n public static void appendBlackEatenLabel(String str) {\r\n blackEatenList += \" \" + str;\r\n setEatenList();\r\n //JlabelSetText(blackEatenLabel, \"黑被吃:<br/>\" + blackEatenList);\r\n }\r\n\r\n public static void appendRedEatenLabel(String str) {\r\n redEatenList += \" \" + str;\r\n setEatenList();\r\n //JlabelSetText(redEatenLabel, \"红被吃:<br/>\" + redEatenList);\r\n }\r\n\r\n public static void popBlackEatenLabel() {\r\n blackEatenList = blackEatenList.substring(0, blackEatenList.lastIndexOf(\" \"));\r\n setEatenList();\r\n /*if (blackEatenList.strip().length() > 0)\r\n JlabelSetText(blackEatenLabel, \"黑被吃:<br/>\" + blackEatenList);\r\n else JlabelSetText(blackEatenLabel, \"黑被吃:----\");*/\r\n }\r\n\r\n public static void popRedEatenLabel() {\r\n redEatenList = redEatenList.substring(0, redEatenList.lastIndexOf(\" \"));\r\n setEatenList();\r\n /*if (redEatenList.strip().length() > 0)\r\n JlabelSetText(redEatenLabel, \"红被吃:<br/>\" + redEatenList);\r\n else JlabelSetText(redEatenLabel, \"红被吃:----\");*/\r\n }\r\n\r\n public static void setBlackEatenLabel(String str) {\r\n blackEatenList = str;\r\n setEatenList();\r\n //JlabelSetText(blackEatenLabel, \"黑被吃:<br/>\" + blackEatenList);\r\n }\r\n\r\n public static void setRedEatenLabel(String str) {\r\n redEatenList = str;\r\n setEatenList();\r\n //JlabelSetText(redEatenLabel, \"红被吃:<br/>\" + redEatenList);\r\n }\r\n\r\n\r\n private static void JlabelSetText(JLabel jLabel, String longString) {\r\n StringBuilder builder = new StringBuilder(\"<html>\" + longString.substring(0, 7));\r\n char[] chars = longString.toCharArray();\r\n FontMetrics fontMetrics = jLabel.getFontMetrics(jLabel.getFont());\r\n int start = 8;\r\n int len = 0;\r\n while (start + len < longString.length()) {\r\n while (true) {\r\n len++;\r\n if (start + len > longString.length()) break;\r\n if (fontMetrics.charsWidth(chars, start, len)\r\n > jLabel.getWidth()) {\r\n break;\r\n }\r\n }\r\n builder.append(chars, start, len - 1).append(\"<br/>\");\r\n start = start + len - 1;\r\n len = 0;\r\n }\r\n builder.append(chars, start, longString.length() - start);\r\n builder.append(\"</html>\");\r\n jLabel.setText(builder.toString());\r\n }\r\n\r\n private void addScoreLabel() {\r\n JLabel jLabel = new JLabel(\"红 - 黑\");\r\n jLabel.setLocation((int) (WIDTH * 11.14 / 15 + 5), (int) (HEIGHT / 13 * 9.3));\r\n jLabel.setSize(200, 60);\r\n jLabel.setFont(sansFont.deriveFont(Font.BOLD, 23));\r\n jLabel.setForeground(ChessColor.BLACK.getColor());\r\n add(jLabel);\r\n\r\n scoreLabel = new JLabel(\"00 - 00\");\r\n scoreLabel.setLocation(WIDTH * 11 / 15 + 5, (int) (HEIGHT / 13 * 9.85));\r\n scoreLabel.setSize(200, 60);\r\n scoreLabel.setFont(sansFont.deriveFont(Font.BOLD, 23));\r\n scoreLabel.setForeground(ChessColor.BLACK.getColor());\r\n add(scoreLabel);\r\n }\r\n\r\n public static JLabel getStatusLabel() {\r\n return statusLabel;\r\n }\r\n\r\n public static JLabel getScoreLabel() {\r\n return scoreLabel;\r\n }\r\n\r\n public static JLabel getBlackEatenLabel() {\r\n return blackEatenLabel;\r\n }\r\n\r\n public static JLabel getRedEatenLabel() {\r\n return redEatenLabel;\r\n }\r\n\r\n /**\r\n * 在游戏窗体中增加一个按钮,如果按下的话就会显示Hello, world!\r\n */\r\n\r\n private void addBackButton() {\r\n JButton button = new JButton(\"返回\");\r\n button.setFont(sansFont.deriveFont(Font.BOLD, 17));\r\n button.addActionListener((e) -> {\r\n Main.backStart();\r\n Main.playNotifyMusic(\"click\");\r\n });\r\n button.setLocation(WIDTH * 11 / 15, HEIGHT / 13);\r\n button.setSize(80, 40);\r\n StartFrame.setButtonBg(button, 80, 40);\r\n add(button);\r\n }\r\n\r\n private void addLoadButton() {\r\n JButton button = new JButton(\"存档\");\r\n button.setLocation(WIDTH * 11 / 15, HEIGHT / 13 + 45);\r\n button.setSize(80, 40);\r\n button.setFont(sansFont.deriveFont(Font.BOLD, 17));\r\n StartFrame.setButtonBg(button, 80, 40);\r\n add(button);\r\n\r\n button.addActionListener(e -> {\r\n System.out.println(\"Click load\");\r\n Main.playNotifyMusic(\"click\");\r\n int option = JOptionPane.showOptionDialog(this, \"选择是要保存存档还是导入存档?\", \"请选择\", JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, new Object[]{\"保存存档\", \"导入存档\"}, \"导入存档\");\r\n if (option == 1) {\r\n String path = JOptionPane.showInputDialog(this, \"在这里输入存档的文件绝对路径\");\r\n gameController.loadGSon(path);\r\n } else {\r\n gameController.toGSon();\r\n }\r\n });\r\n }\r\n\r\n private void addRefreshButton() {\r\n JButton button = new JButton(\"重置\");\r\n button.setLocation(WIDTH * 11 / 15, HEIGHT / 13 + 90);\r\n button.setSize(80, 40);\r\n button.setFont(sansFont.deriveFont(Font.BOLD, 17));\r\n StartFrame.setButtonBg(button, 80, 40);\r\n add(button);\r\n\r\n button.addActionListener(e -> {\r\n Main.playNotifyMusic(\"click\");\r\n Main.refreshGame();\r\n });\r\n }\r\n\r\n private void addThemeButton() {\r\n JButton button = new JButton(\"主题\");\r\n button.setLocation(WIDTH * 11 / 15, HEIGHT / 13 + 135);\r\n button.setSize(80, 40);\r\n button.setFont(sansFont.deriveFont(Font.BOLD, 17));\r\n StartFrame.setButtonBg(button, 80, 40);\r\n add(button);\r\n\r\n button.addActionListener(e -> {\r\n System.out.println(\"Click theme\");\r\n Main.playNotifyMusic(\"click\");\r\n String path = JOptionPane.showInputDialog(this, \"在下方输入主题的名字以选择主题(可选主题有像素、典雅、激情):\");\r\n\r\n if (path == null) {\r\n JOptionPane.showMessageDialog(this, \"不能输入空内容!\");\r\n } else if (path.equals(Main.themeList[0]) ||\r\n path.equals(Main.themeList[1]) ||\r\n path.equals(Main.themeList[2])) {\r\n log(\"SELECT \" + path);\r\n Main.theme = path;\r\n data.put(\"theme\", gson.toJsonTree(theme, new TypeToken<String>() {\r\n }.getType()));\r\n FileUtils.saveDataToFile(\"data\", gson.toJson(data), \"json\");\r\n Main.startGame(Main.mode);\r\n } else {\r\n JOptionPane.showMessageDialog(this, \"没有这个主题,请重新选择!\");\r\n }\r\n });\r\n }\r\n\r\n\r\n private void addBg() {\r\n InputStream stream = Main.class.getResourceAsStream(Main.getThemeResource(\"bg\"));\r\n JLabel lbBg = null;\r\n try {\r\n lbBg = new JLabel(ImageUtils.changeImageSize(new ImageIcon(stream.readAllBytes()), 0.3f));\r\n } catch (IOException e) {\r\n System.out.println(e.getMessage());\r\n }\r\n lbBg.setBounds(0, 0, WIDTH, HEIGHT);\r\n add(lbBg);\r\n }\r\n\r\n}\r" }, { "identifier": "RankFrame", "path": "CS109_2022_Fall/Chess/view/RankFrame.java", "snippet": "public class RankFrame extends JFrame {\n private final int WIDTH;\n private final int HEIGHT;\n private Gson gson = new Gson();\n\n public RankFrame(int width, int height) {\n setTitle(\"本地玩家排行\");\n this.WIDTH = width;\n this.HEIGHT = height;\n\n setSize(WIDTH, HEIGHT);\n setResizable(false);\n setLocationRelativeTo(null); // Center the window.\n getContentPane().setBackground(Color.WHITE);\n setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);\n setLayout(null);\n addBackButton();\n addList();\n\n addBg();\n }\n\n private void addList() {\n ArrayList<String> arr = new ArrayList<>();\n for (int i = 0; i < scoresList.size(); i++) {\n arr.add(\" \" + userList.get(i) + \" \" + scoresList.get(i));\n }\n arr.sort((o1, o2) -> Integer.compare(Integer.parseInt(o2.split(\" \")[2]),\n Integer.parseInt(o1.split(\" \")[2])));\n for (int i = 0; i < arr.size(); i++) {\n arr.set(i, \" \" + arr.get(i));\n }\n JList<String> list = new JList<>(arr.toArray(new String[0]));\n list.setBackground(new Color(0, 0, 0, 0));\n list.setOpaque(false);//workaround keep opaque after repainted\n list.setFont(sansFont.deriveFont(Font.PLAIN, 18));\n list.setBounds(HEIGHT / 13, HEIGHT / 13 + 12, HEIGHT * 2 / 5, HEIGHT * 4 / 5);\n add(list);\n\n // chess board as bg workaround\n InputStream stream = Main.class.getResourceAsStream(Main.getThemeResource(\"board\"));\n JLabel lbBg = null;\n try {\n lbBg = new JLabel(ImageUtils.changeToOriginalSize(new ImageIcon(stream.readAllBytes()), HEIGHT * 2 / 5, HEIGHT * 4 / 5));\n } catch (IOException e) {\n System.out.println(e.getMessage());\n }\n lbBg.setBounds(HEIGHT / 13, HEIGHT / 13, HEIGHT * 2 / 5, HEIGHT * 4 / 5);\n add(lbBg);\n }\n\n\n private void addBackButton() {\n JButton button = new JButton(\"返回\");\n StartFrame.setButtonBg(button, 80, 60);\n button.setFont(sansFont.deriveFont(Font.BOLD, 20));\n button.addActionListener((e) -> {\n Main.backStart();\n Main.playNotifyMusic(\"click\");\n });\n button.setLocation(WIDTH * 11 / 15, HEIGHT / 13);\n button.setSize(80, 60);\n add(button);\n }\n\n private void addBg() {\n /*JLabel lbBgBox = new JLabel(ImageUtils.changeToOriginalSize(new ImageIcon(\"src/Resources/box.png\"), (int) (WIDTH / 1.8), HEIGHT / 2));\n lbBgBox.setBounds((int) (WIDTH / 2 - WIDTH / 3.6), HEIGHT / 4, (int) (WIDTH / 1.8), HEIGHT / 2);\n add(lbBgBox);*/\n InputStream stream = Main.class.getResourceAsStream(Main.getThemeResource(\"bg\"));\n JLabel lbBg = null;\n try {\n lbBg = new JLabel(ImageUtils.changeImageSize(new ImageIcon(stream.readAllBytes()), 0.3f));\n } catch (IOException e) {\n System.out.println(e.getMessage());\n }\n lbBg.setBounds(0, 0, WIDTH, HEIGHT);\n add(lbBg);\n }\n}" }, { "identifier": "StartFrame", "path": "CS109_2022_Fall/Chess/view/StartFrame.java", "snippet": "public class StartFrame extends JFrame {\n private final int WIDTH;\n private final int HEIGHT;\n private Gson gson = new Gson();\n\n public StartFrame(int width, int height) {\n setTitle(\"翻翻棋~\");\n this.WIDTH = width;\n this.HEIGHT = height;\n\n setSize(WIDTH, HEIGHT);\n setResizable(false);\n setLocationRelativeTo(null); // Center the window.\n getContentPane().setBackground(Color.WHITE);\n setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);\n setLayout(null);\n\n addTitle();\n addStartButton();\n addRankButton();\n\n //hasLogon = true;\n if (!hasLogon)\n openUserSelectDialog();\n else\n setCurrentUser(currentUser);\n }\n\n private void openUserSelectDialog() {\n Object[] options = {\"登陆已有账号\", \"新建账号\"}; // 0 1\n int m = JOptionPane.showOptionDialog(null, \"请选择登陆已有账号还是新建账号\", \"翻翻棋\", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]);\n if (m == 0) {\n String n = JOptionPane.showInputDialog(\"请输入用户名\");\n if (n == null) {\n JOptionPane.showMessageDialog(null, \"登陆失败,输入用户名为空!\");\n openUserSelectDialog();\n } else if (userList.contains(n)) {\n JOptionPane.showMessageDialog(null, \"登陆成功\");\n currentUserId = userList.indexOf(n);\n setCurrentUser(n);\n } else {\n JOptionPane.showMessageDialog(null, \"登陆失败,没有这个用户!\");\n openUserSelectDialog();\n }\n } else {\n openNewUserDialog();\n }\n }\n\n private void openNewUserDialog() {\n String n = JOptionPane.showInputDialog(\"请输入要新增的用户的用户名\");\n if (n == null) {\n JOptionPane.showMessageDialog(null, \"新增失败,输入用户名为空\");\n openNewUserDialog();\n } else if (userList.contains(n)) {\n JOptionPane.showMessageDialog(null, \"新增失败,已经存在这个用户\");\n openNewUserDialog();\n } else {\n JOptionPane.showMessageDialog(null, \"新增成功!\");\n userList.add(n);\n scoresList.add(0);\n currentUserId = userList.size() - 1;\n data.put(\"userList\", gson.toJsonTree(userList, new TypeToken<ArrayList<String>>() {\n }.getType()));\n data.put(\"userScores\", gson.toJsonTree(scoresList, new TypeToken<ArrayList<Integer>>() {\n }.getType()));\n FileUtils.saveDataToFile(\"data\", gson.toJson(data), \"json\");\n setCurrentUser(n);\n }\n }\n\n private void setCurrentUser(String n) {\n currentUser = n;\n hasLogon = true;\n\n JLabel statusLabel = new JLabel(\"当前用户:\" + n + \" 胜局数:\" + scoresList.get(currentUserId));\n statusLabel.setLocation(WIDTH / 15, (int) (HEIGHT / 13 * 11.25));\n statusLabel.setSize(400, 60);\n statusLabel.setFont(sansFont.deriveFont(Font.BOLD, 17));\n statusLabel.setForeground(Main.getThemeColor(\"indicatorBlack\"));\n add(statusLabel);\n\n addBg();\n System.out.println(n);\n }\n\n private void addBg() {\n /*JLabel lbBgBox = new JLabel(ImageUtils.changeToOriginalSize(new ImageIcon(\"src/Resources/box.png\"), (int) (WIDTH / 1.8), HEIGHT / 2));\n lbBgBox.setBounds((int) (WIDTH / 2 - WIDTH / 3.6), HEIGHT / 4, (int) (WIDTH / 1.8), HEIGHT / 2);\n add(lbBgBox);*/\n InputStream stream = Main.class.getResourceAsStream(Main.getThemeResource(\"bg\"));\n JLabel lbBg = null;\n try {\n lbBg = new JLabel(ImageUtils.changeImageSize(new ImageIcon(stream.readAllBytes()), 0.3f));\n } catch (IOException e) {\n System.out.println(e.getMessage());\n }\n lbBg.setBounds(0, 0, WIDTH, HEIGHT);\n add(lbBg);\n }\n\n private void addTitle() {\n JLabel label = new JLabel(\"翻翻棋\");\n label.setFont(titleFont.deriveFont(Font.BOLD, 58));\n label.setForeground(Main.getThemeColor(\"title\"));\n label.setHorizontalAlignment(SwingConstants.CENTER);\n label.setAlignmentX(Component.CENTER_ALIGNMENT);\n label.setLocation(WIDTH / 2 - 150, HEIGHT / 3 - 45);\n label.setSize(300, 90);\n add(label);\n }\n\n public static boolean checkRecords(String records) {\n return records.equals(\"--\");\n }\n\n public static void setButtonBg(JButton button, int width, int height) {\n if (Main.theme.equals(\"像素\")) {\n InputStream stream = Main.class.getResourceAsStream(((float) width / (float) height > 1.6) ?\n Main.getThemeResource(\"md-btn\") : Main.getThemeResource(\"btn\"));\n try {\n button.setIcon(ImageUtils.changeToOriginalSize(new ImageIcon(stream.readAllBytes()), width, height));\n } catch (IOException e) {\n System.out.println(e.getMessage());\n }\n button.setHorizontalTextPosition(JButton.CENTER);\n button.setVerticalTextPosition(JButton.CENTER);\n button.setContentAreaFilled(false);\n button.setForeground(Color.WHITE);\n button.setFocusPainted(false);\n button.setBorderPainted(false);\n } else {\n //button.setBackground(Color.decode(\"#dddddd\"));\n }\n }\n\n private void addStartButton() {\n JButton button = new JButton(\"开始\");\n button.setSize(250, 70);\n InputStream stream = Main.class.getResourceAsStream(Main.getThemeResource(\"startbtn\"));\n try {\n button.setIcon(ImageUtils.changeToOriginalSize(new ImageIcon(stream.readAllBytes()), 250, 70));\n } catch (IOException e) {\n System.out.println(e.getMessage());\n }\n button.setHorizontalTextPosition(JButton.CENTER);\n button.setVerticalTextPosition(JButton.CENTER);\n button.setContentAreaFilled(false);\n button.setFont(titleFont.deriveFont(Font.BOLD, 32));\n button.setForeground(Color.WHITE);\n button.setLocation(WIDTH / 2 - 125, HEIGHT * 2 / 3 - 70);\n button.setFocusPainted(false);\n button.setBorderPainted(false);\n\n button.addActionListener((e) -> {\n int option = JOptionPane.showOptionDialog(this, \"选择什么游戏模式呢?\", \"请选择\", JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, new Object[]{\"AI 低难度\", \"AI 中难度\", \"本地 1v1\"}, \"AI 低难度\");\n if (option == -1) System.out.println(\"取消\");\n else if (option == 0)\n Main.startGame(1);\n else if (option == 1)\n Main.startGame(2);\n else\n Main.startGame(0);\n });\n\n add(button);\n }\n\n private void addRankButton() {\n JButton button = new JButton(\"排名\");\n setButtonBg(button, 80, 60);\n button.setLocation((int) (WIDTH * 11.8 / 15), (int) (HEIGHT * 11.1 / 13));\n button.setSize(80, 60);\n button.setFont(sansFont.deriveFont(Font.BOLD, 18));\n add(button);\n\n button.addActionListener(e -> {\n Main.playNotifyMusic(\"click\");\n Main.goRank();\n });\n }\n}" }, { "identifier": "log", "path": "CS109_2022_Fall/Chess/utils/GeneralUtils.java", "snippet": "public static void log(Object log) {\r\n System.out.println(log);\r\n}\r" } ]
import Chess.model.ChessColor; import Chess.utils.FileUtils; import Chess.view.ChessGameFrame; import Chess.view.RankFrame; import Chess.view.StartFrame; import com.formdev.flatlaf.FlatLightLaf; import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonParser; import com.google.gson.reflect.TypeToken; import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.Clip; import javax.sound.sampled.FloatControl; import javax.swing.*; import java.awt.*; import java.io.BufferedInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.Objects; import static Chess.utils.GeneralUtils.log;
7,417
package Chess; public class Main { private static ChessGameFrame gameFrame = null; private static StartFrame startFrame = null; public static Font titleFont, sansFont, serifFont; public static String theme = "像素", currentUser = ""; public static final String[] themeList = {"典雅", "激情", "像素"}; private static RankFrame rankFrame = null; public static boolean hasLogon = false; public static int currentUserId = 0, mode = 0; public static Map<String, JsonElement> data; public static ArrayList<String> userList = new ArrayList<>(); public static ArrayList<Integer> scoresList = new ArrayList<>(); public static void main(String[] args) { Gson gson = new Gson(); FlatLightLaf.setup();
package Chess; public class Main { private static ChessGameFrame gameFrame = null; private static StartFrame startFrame = null; public static Font titleFont, sansFont, serifFont; public static String theme = "像素", currentUser = ""; public static final String[] themeList = {"典雅", "激情", "像素"}; private static RankFrame rankFrame = null; public static boolean hasLogon = false; public static int currentUserId = 0, mode = 0; public static Map<String, JsonElement> data; public static ArrayList<String> userList = new ArrayList<>(); public static ArrayList<Integer> scoresList = new ArrayList<>(); public static void main(String[] args) { Gson gson = new Gson(); FlatLightLaf.setup();
String raw = FileUtils.getDataFromFile("data");
1
2023-12-31 05:50:13+00:00
12k
psobiech/opengr8on
tftp/src/test/java/pl/psobiech/opengr8on/tftp/TFTPTest.java
[ { "identifier": "ServerMode", "path": "tftp/src/main/java/pl/psobiech/opengr8on/tftp/TFTPServer.java", "snippet": "public enum ServerMode {\n GET_ONLY,\n PUT_ONLY,\n GET_AND_PUT,\n GET_AND_REPLACE\n //\n ;\n}" }, { "identifier": "TFTPException", "path": "tftp/src/main/java/pl/psobiech/opengr8on/tftp/exceptions/TFTPException.java", "snippet": "public class TFTPException extends RuntimeException {\n private final TFTPErrorType error;\n\n public TFTPException(TFTPErrorPacket errorPacket) {\n this(errorPacket.getError(), errorPacket.getMessage());\n }\n\n public TFTPException(TFTPErrorType error, IOException exception) {\n super(exception);\n\n this.error = error;\n }\n\n public TFTPException(TFTPErrorType error, String message) {\n super(message);\n\n this.error = error;\n }\n\n public TFTPException(TFTPErrorType error, String message, Throwable throwable) {\n super(message, throwable);\n\n this.error = error;\n }\n\n public TFTPException(String message) {\n super(message);\n\n this.error = TFTPErrorType.UNDEFINED;\n }\n\n public TFTPErrorPacket asError(InetAddress address, int port) {\n final String message;\n final Throwable cause = getCause();\n if (cause == null) {\n message = getMessage();\n } else {\n message = cause.getClass().getSimpleName() + \": \" + getMessage();\n }\n\n return new TFTPErrorPacket(\n address, port,\n getError(), message\n );\n }\n\n public TFTPErrorType getError() {\n return error;\n }\n}" }, { "identifier": "TFTPErrorType", "path": "tftp/src/main/java/pl/psobiech/opengr8on/tftp/packets/TFTPErrorType.java", "snippet": "public enum TFTPErrorType {\n UNDEFINED(0),\n FILE_NOT_FOUND(1),\n ACCESS_VIOLATION(2),\n OUT_OF_SPACE(3),\n ILLEGAL_OPERATION(4),\n UNKNOWN_TID(5),\n FILE_EXISTS(6),\n //\n ;\n\n private final int errorCode;\n\n TFTPErrorType(long errorCode) {\n if (errorCode < 0 || errorCode > 0xFFFFFFFFL) {\n throw new IllegalArgumentException();\n }\n\n this.errorCode = (int) (errorCode & 0xFFFFFFFFL);\n }\n\n public int errorCode() {\n return errorCode;\n }\n\n public static TFTPErrorType ofErrorCode(int errorCode) {\n for (TFTPErrorType value : values()) {\n if (value.errorCode() == errorCode) {\n return value;\n }\n }\n\n return UNDEFINED;\n }\n}" }, { "identifier": "TFTPPacket", "path": "tftp/src/main/java/pl/psobiech/opengr8on/tftp/packets/TFTPPacket.java", "snippet": "public abstract class TFTPPacket {\n protected static final int OPERATOR_TYPE_OFFSET = 1;\n\n public static final int SEGMENT_SIZE = 512;\n\n final TFTPPacketType type;\n\n private int port;\n\n private InetAddress address;\n\n TFTPPacket(TFTPPacketType type, InetAddress address, int port) {\n this.type = type;\n this.address = address;\n this.port = port;\n }\n\n public static TFTPPacket newTFTPPacket(Payload payload) throws TFTPPacketException {\n return TFTPPacketType.ofPacketType(payload.buffer()[OPERATOR_TYPE_OFFSET])\n .parse(payload);\n }\n\n public InetAddress getAddress() {\n return address;\n }\n\n public int getPort() {\n return port;\n }\n\n public TFTPPacketType getType() {\n return type;\n }\n\n public abstract DatagramPacket newDatagram();\n\n public abstract DatagramPacket newDatagram(byte[] data);\n\n public void setAddress(InetAddress address) {\n this.address = address;\n }\n\n public void setPort(int port) {\n this.port = port;\n }\n\n public static String readNullTerminatedString(byte[] buffer, int from, int to) {\n return new String(\n readNullTerminated(buffer, from, to), StandardCharsets.US_ASCII\n );\n }\n\n public static byte[] readNullTerminated(byte[] buffer, int from, int to) {\n int nullTerminator = -1;\n for (int i = from; i < to; i++) {\n if (buffer[i] == 0) {\n nullTerminator = i;\n break;\n }\n }\n\n if (nullTerminator < 0) {\n return Arrays.copyOfRange(buffer, from, to);\n }\n\n return Arrays.copyOfRange(buffer, from, nullTerminator);\n }\n\n public static int writeNullTerminatedString(String value, byte[] buffer, int offset) {\n final byte[] valueAsBytes = value.getBytes(StandardCharsets.US_ASCII);\n\n System.arraycopy(valueAsBytes, 0, buffer, offset, valueAsBytes.length);\n buffer[offset + valueAsBytes.length] = 0;\n\n return valueAsBytes.length + 1;\n }\n\n public static int readInt(byte[] buffer, int offset) {\n return asInt(buffer[offset], buffer[offset + 1]);\n }\n\n public static void writeInt(int value, byte[] buffer, int offset) {\n buffer[offset] = highNibble(value);\n buffer[offset + 1] = lowNibble(value);\n }\n\n public static byte highNibble(int value) {\n return (byte) ((value & 0xFFFF) >> (Integer.BYTES * 2));\n }\n\n public static byte lowNibble(int value) {\n return (byte) (value & 0xFF);\n }\n\n public static int asInt(byte highNibble, byte lowNibble) {\n return asInt(highNibble) << (Integer.BYTES * 2) | asInt(lowNibble);\n }\n\n private static int asInt(byte value) {\n return value & 0xFF;\n }\n\n @Override\n public String toString() {\n return address + \" \" + port + \" \" + type;\n }\n}" }, { "identifier": "FileUtil", "path": "common/src/main/java/pl/psobiech/opengr8on/util/FileUtil.java", "snippet": "public final class FileUtil {\n private static final Logger LOGGER = LoggerFactory.getLogger(FileUtil.class);\n\n private static final String TMPDIR_PROPERTY = \"java.io.tmpdir\";\n\n private static final String TEMPORARY_FILE_PREFIX = \"tmp_\";\n\n private static final Pattern DISALLOWED_FILENAME_CHARACTERS = Pattern.compile(\"[/\\\\\\\\:*?\\\"<>|\\0]+\");\n\n private static final Pattern WHITESPACE_CHARACTERS = Pattern.compile(\"\\\\s+\");\n\n private static final Path TEMPORARY_DIRECTORY;\n\n private static final TemporaryFileTracker FILE_TRACKER = new TemporaryFileTracker();\n\n static {\n try {\n TEMPORARY_DIRECTORY = Files.createTempDirectory(\n Paths.get(System.getProperty(TMPDIR_PROPERTY))\n .toAbsolutePath(),\n TEMPORARY_FILE_PREFIX\n );\n } catch (IOException e) {\n throw new UnexpectedException(e);\n }\n\n ThreadUtil.getInstance()\n .scheduleAtFixedRate(FILE_TRACKER::log, 1, 1, TimeUnit.MINUTES);\n\n mkdir(TEMPORARY_DIRECTORY);\n ThreadUtil.shutdownHook(() -> FileUtil.deleteRecursively(TEMPORARY_DIRECTORY));\n }\n\n private FileUtil() {\n // NOP\n }\n\n public static Path temporaryDirectory() {\n return temporaryDirectory(null);\n }\n\n public static Path temporaryDirectory(Path parentPath) {\n try {\n return Files.createTempDirectory(\n parentPath == null ? TEMPORARY_DIRECTORY : parentPath,\n TEMPORARY_FILE_PREFIX\n )\n .toAbsolutePath();\n } catch (IOException e) {\n throw new UnexpectedException(e);\n }\n }\n\n public static Path temporaryFile() {\n return temporaryFile(null, null);\n }\n\n public static Path temporaryFile(String fileName) {\n return temporaryFile(null, fileName);\n }\n\n public static Path temporaryFile(Path parentPath) {\n return temporaryFile(parentPath, null);\n }\n\n public static Path temporaryFile(Path parentPath, String fileName) {\n try {\n return FILE_TRACKER.tracked(\n Files.createTempFile(\n parentPath == null ? TEMPORARY_DIRECTORY : parentPath,\n TEMPORARY_FILE_PREFIX, sanitize(fileName)\n )\n .toAbsolutePath()\n );\n } catch (IOException e) {\n throw new UnexpectedException(e);\n }\n }\n\n public static void mkdir(Path path) {\n try {\n Files.createDirectories(path);\n } catch (IOException e) {\n throw new UnexpectedException(e);\n }\n }\n\n public static void touch(Path path) {\n try {\n Files.newOutputStream(path, StandardOpenOption.CREATE).close();\n } catch (IOException e) {\n throw new UnexpectedException(e);\n }\n }\n\n public static void linkOrCopy(Path from, Path to) {\n deleteQuietly(to);\n\n if (!SystemUtils.IS_OS_WINDOWS && !Files.exists(to)) {\n try {\n Files.createLink(to, from);\n\n return;\n } catch (Exception e) {\n // log exception and revert to copy\n LOGGER.trace(e.getMessage(), e);\n }\n }\n\n try {\n Files.copy(from, to, StandardCopyOption.REPLACE_EXISTING);\n } catch (IOException e) {\n throw new UnexpectedException(e);\n }\n }\n\n public static void deleteQuietly(Path... paths) {\n for (Path path : paths) {\n deleteQuietly(path);\n }\n }\n\n public static void deleteQuietly(Path path) {\n if (path == null) {\n return;\n }\n\n try {\n Files.deleteIfExists(path);\n } catch (IOException e) {\n final boolean isFileOrLinkOrDoesNotExist = !Files.isDirectory(path);\n if (isFileOrLinkOrDoesNotExist) {\n LOGGER.warn(e.getMessage(), e);\n } else if (LOGGER.isTraceEnabled()) {\n // directories might be not-empty, hence not removable\n LOGGER.trace(e.getMessage(), e);\n }\n }\n }\n\n public static void deleteRecursively(Path rootDirectory) {\n if (rootDirectory == null) {\n return;\n }\n\n try {\n Files.walkFileTree(rootDirectory, new SimpleFileVisitor<>() {\n @Override\n public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {\n FileUtil.deleteQuietly(file);\n\n return super.visitFile(file, attrs);\n }\n\n @Override\n public FileVisitResult postVisitDirectory(Path directory, IOException exc) throws IOException {\n FileUtil.deleteQuietly(directory);\n\n return super.postVisitDirectory(directory, exc);\n }\n });\n } catch (IOException e) {\n LOGGER.warn(e.getMessage(), e);\n }\n\n FileUtil.deleteQuietly(rootDirectory);\n }\n\n public static void closeQuietly(AutoCloseable... closeables) {\n for (AutoCloseable closeable : closeables) {\n closeQuietly(closeable);\n }\n }\n\n public static void closeQuietly(AutoCloseable closeable) {\n if (closeable == null) {\n return;\n }\n\n try {\n closeable.close();\n } catch (Exception e) {\n LOGGER.warn(e.getMessage(), e);\n }\n }\n\n public static String sanitize(String fileName) {\n fileName = StringUtils.stripToNull(fileName);\n if (fileName == null) {\n return null;\n }\n\n final String fileNameNoDisallowedCharacters = DISALLOWED_FILENAME_CHARACTERS.matcher(fileName)\n .replaceAll(\"_\");\n\n return WHITESPACE_CHARACTERS.matcher(fileNameNoDisallowedCharacters)\n .replaceAll(\"_\");\n }\n\n public static long size(Path path) {\n try {\n return Files.size(path);\n } catch (IOException e) {\n throw new UnexpectedException(e);\n }\n }\n\n public static class TemporaryFileTracker {\n private final Map<String, UnexpectedException> stacktraces = new HashMap<>();\n\n private final Map<Path, Boolean> reachablePaths = new WeakHashMap<>();\n\n private TemporaryFileTracker() {\n // NOP\n }\n\n public void log() {\n final Map<Path, UnexpectedException> unreachablePaths = new HashMap<>();\n\n synchronized (stacktraces) {\n final Iterator<Entry<String, UnexpectedException>> iterator = stacktraces.entrySet().iterator();\n while (iterator.hasNext()) {\n final Entry<String, UnexpectedException> entry = iterator.next();\n\n final Path path = Paths.get(entry.getKey());\n synchronized (reachablePaths) {\n if (reachablePaths.containsKey(path)) {\n continue;\n }\n }\n\n iterator.remove();\n\n if (Files.exists(path)) {\n unreachablePaths.put(path, entry.getValue());\n }\n }\n }\n\n for (Entry<Path, UnexpectedException> entry : unreachablePaths.entrySet()) {\n final Path path = entry.getKey();\n\n if (Files.exists(path)) {\n final UnexpectedException e = entry.getValue();\n\n LOGGER.warn(e.getMessage(), e);\n }\n }\n }\n\n public Path tracked(Path path) {\n final Path absolutePath = path.toAbsolutePath();\n final String absolutePathAsString = absolutePath.toString();\n\n final UnexpectedException stacktrace =\n new UnexpectedException(\"Temporary Path went out of scope, and the file was not removed: \" + absolutePathAsString);\n synchronized (stacktraces) {\n stacktraces.put(absolutePathAsString, stacktrace);\n }\n\n synchronized (reachablePaths) {\n reachablePaths.put(absolutePath, Boolean.TRUE);\n }\n\n return absolutePath;\n }\n }\n}" }, { "identifier": "IPv4AddressUtil", "path": "common/src/main/java/pl/psobiech/opengr8on/util/IPv4AddressUtil.java", "snippet": "public final class IPv4AddressUtil {\n private static final Logger LOGGER = LoggerFactory.getLogger(IPv4AddressUtil.class);\n\n private static final int PING_TIMEOUT = 2000;\n\n public static final Inet4Address BROADCAST_ADDRESS = parseIPv4(\"255.255.255.255\");\n\n public static final Set<Inet4Address> DEFAULT_BROADCAST_ADDRESSES = Set.of(\n BROADCAST_ADDRESS,\n parseIPv4(\"255.255.0.0\"),\n parseIPv4(\"255.0.0.0\")\n );\n\n public static final Set<String> HARDWARE_ADDRESS_PREFIX_BLACKLIST = Set.of(\n HexUtil.asString(0x000569), // VMware, Inc.\n HexUtil.asString(0x001c14), // VMware, Inc.\n HexUtil.asString(0x000c29), // VMware, Inc.\n HexUtil.asString(0x005056) // VMware, Inc.\n );\n\n public static final Set<String> NETWORK_INTERFACE_NAME_PREFIX_BLACKLIST = Set.of(\n \"vmnet\", \"vboxnet\"\n );\n\n private IPv4AddressUtil() {\n // NOP\n }\n\n public static Optional<NetworkInterfaceDto> getLocalIPv4NetworkInterfaceByNameOrAddress(String nameOrAddress) {\n final List<NetworkInterfaceDto> networkInterfaces = getLocalIPv4NetworkInterfaces();\n for (NetworkInterfaceDto networkInterface : networkInterfaces) {\n if (Objects.equals(networkInterface.getNetworkInterface().getName(), nameOrAddress)) {\n return Optional.of(networkInterface);\n }\n\n if (Objects.equals(networkInterface.getAddress().getHostAddress(), nameOrAddress)) {\n return Optional.of(networkInterface);\n }\n }\n\n return Optional.empty();\n }\n\n public static Optional<NetworkInterfaceDto> getLocalIPv4NetworkInterfaceByName(String name) {\n final List<NetworkInterfaceDto> networkInterfaces = getLocalIPv4NetworkInterfaces();\n for (NetworkInterfaceDto networkInterface : networkInterfaces) {\n if (Objects.equals(networkInterface.getNetworkInterface().getName(), name)) {\n return Optional.of(networkInterface);\n }\n }\n\n return Optional.empty();\n }\n\n public static Optional<NetworkInterfaceDto> getLocalIPv4NetworkInterfaceByIpAddress(String ipAddress) {\n final List<NetworkInterfaceDto> networkInterfaces = getLocalIPv4NetworkInterfaces();\n for (NetworkInterfaceDto networkInterface : networkInterfaces) {\n if (Objects.equals(networkInterface.getAddress().getHostAddress(), ipAddress)) {\n return Optional.of(networkInterface);\n }\n }\n\n return Optional.empty();\n }\n\n public static List<NetworkInterfaceDto> getLocalIPv4NetworkInterfaces() {\n final List<NetworkInterface> validNetworkInterfaces = allValidNetworkInterfaces();\n final List<NetworkInterfaceDto> networkInterfaces = new ArrayList<>(validNetworkInterfaces.size());\n for (NetworkInterface networkInterface : validNetworkInterfaces) {\n for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) {\n final InetAddress address = interfaceAddress.getAddress();\n if (!(address instanceof Inet4Address)) {\n continue;\n }\n\n final InetAddress broadcastAddress = interfaceAddress.getBroadcast();\n if (!(broadcastAddress instanceof Inet4Address)) {\n continue;\n }\n\n if (!address.isSiteLocalAddress()) {\n continue;\n }\n\n final int networkMask = getNetworkMaskFromPrefix(interfaceAddress.getNetworkPrefixLength());\n\n networkInterfaces.add(new NetworkInterfaceDto(\n (Inet4Address) address, (Inet4Address) broadcastAddress,\n networkMask,\n networkInterface\n ));\n }\n }\n\n return networkInterfaces;\n }\n\n private static int getNetworkMaskFromPrefix(short networkPrefixLength) {\n int networkMask = 0x00;\n for (int i = 0; i < Integer.SIZE - networkPrefixLength; i++) {\n networkMask += (1 << i);\n }\n\n networkMask ^= 0xFFFFFFFF;\n\n return networkMask;\n }\n\n private static List<NetworkInterface> allValidNetworkInterfaces() {\n final List<NetworkInterface> networkInterfaces;\n try {\n networkInterfaces = Collections.list(NetworkInterface.getNetworkInterfaces());\n } catch (SocketException e) {\n throw new UnexpectedException(e);\n }\n\n final List<NetworkInterface> validNetworkInterfaces = new ArrayList<>(networkInterfaces.size());\n for (NetworkInterface networkInterface : networkInterfaces) {\n try {\n if (!networkInterface.isUp()\n || networkInterface.isLoopback()\n || networkInterface.isPointToPoint()\n || isBlacklisted(networkInterface)\n ) {\n continue;\n }\n } catch (SocketException e) {\n LOGGER.warn(e.getMessage(), e);\n\n continue;\n }\n\n validNetworkInterfaces.add(networkInterface);\n }\n\n return validNetworkInterfaces;\n }\n\n private static boolean isBlacklisted(NetworkInterface networkInterface) throws SocketException {\n final String networkInterfaceName = networkInterface.getName();\n for (String blacklistedNetworkInterfaceNamePrefix : NETWORK_INTERFACE_NAME_PREFIX_BLACKLIST) {\n if (networkInterfaceName.startsWith(blacklistedNetworkInterfaceNamePrefix)) {\n return true;\n }\n }\n\n final byte[] hardwareAddress = networkInterface.getHardwareAddress();\n if (hardwareAddress == null) {\n return true;\n }\n\n return isHardwareAddressBlacklisted(hardwareAddress);\n }\n\n private static boolean isHardwareAddressBlacklisted(byte[] macAddress) {\n if (macAddress == null) {\n return true;\n }\n\n final String hardwareAddressPrefix = HexUtil.asString(Arrays.copyOf(macAddress, 3));\n\n return HARDWARE_ADDRESS_PREFIX_BLACKLIST.contains(hardwareAddressPrefix);\n }\n\n public static Inet4Address parseIPv4(String ipv4AddressAsString) {\n try {\n return (Inet4Address) InetAddress.getByAddress(\n getIPv4AsBytes(ipv4AddressAsString)\n );\n } catch (UnknownHostException e) {\n throw new UnexpectedException(e);\n }\n }\n\n public static Inet4Address parseIPv4(int ipv4AddressAsNumber) {\n try {\n final byte[] buffer = asBytes(ipv4AddressAsNumber);\n\n return (Inet4Address) InetAddress.getByAddress(buffer);\n } catch (UnknownHostException e) {\n throw new UnexpectedException(e);\n }\n }\n\n public static String getIPv4FromNumber(int ipv4AsNumber) {\n final byte[] buffer = asBytes(ipv4AsNumber);\n\n return IntStream.range(0, Integer.BYTES)\n .mapToObj(i -> String.valueOf(buffer[i] & 0xFF))\n .collect(Collectors.joining(\".\"));\n }\n\n private static byte[] asBytes(int ipv4AsNumber) {\n final ByteBuffer byteBuffer = ByteBuffer.allocate(Integer.BYTES);\n\n byteBuffer.putInt(ipv4AsNumber);\n byteBuffer.flip();\n\n return byteBuffer.array();\n }\n\n public static int getIPv4AsNumber(Inet4Address inetAddress) {\n return getIPv4AsNumber(inetAddress.getAddress());\n }\n\n public static int getIPv4AsNumber(String ipv4AddressAsString) {\n return getIPv4AsNumber(getIPv4AsBytes(ipv4AddressAsString));\n }\n\n public static int getIPv4AsNumber(byte[] ipv4AddressAsBytes) {\n if (ipv4AddressAsBytes.length != Integer.BYTES) {\n throw new UnexpectedException(\"Invalid IPv4 address: \" + Arrays.toString(ipv4AddressAsBytes));\n }\n\n return ByteBuffer.wrap(ipv4AddressAsBytes)\n .getInt();\n }\n\n private static byte[] getIPv4AsBytes(String ipv4AddressAsString) {\n final String[] ipAddressParts = Util.splitAtLeast(ipv4AddressAsString, \"\\\\.\", Integer.BYTES)\n .orElseThrow(() -> new UnexpectedException(\"Invalid IPv4 address: \" + ipv4AddressAsString));\n\n final byte[] addressAsBytes = new byte[Integer.BYTES];\n for (int i = 0; i < addressAsBytes.length; i++) {\n addressAsBytes[i] = (byte) Integer.parseInt(ipAddressParts[i]);\n }\n\n return addressAsBytes;\n }\n\n public static boolean ping(InetAddress inetAddress) {\n try {\n return inetAddress.isReachable(PING_TIMEOUT);\n } catch (IOException e) {\n LOGGER.warn(e.getMessage(), e);\n\n return false;\n }\n }\n\n public static final class NetworkInterfaceDto {\n private final Inet4Address address;\n\n private final Inet4Address broadcastAddress;\n\n private final int networkAddress;\n\n private final int networkMask;\n\n private final NetworkInterface networkInterface;\n\n public NetworkInterfaceDto(\n Inet4Address address, Inet4Address broadcastAddress,\n int networkMask,\n NetworkInterface networkInterface\n ) {\n this.address = address;\n\n final int addressAsNumber = IPv4AddressUtil.getIPv4AsNumber(address.getAddress());\n this.networkAddress = addressAsNumber & networkMask;\n\n assert IPv4AddressUtil.getIPv4AsNumber(broadcastAddress) == (networkAddress | (~networkMask));\n this.broadcastAddress = broadcastAddress;\n this.networkMask = networkMask;\n\n this.networkInterface = networkInterface;\n }\n\n public Inet4Address getAddress() {\n return address;\n }\n\n public Inet4Address getNetworkAddress() {\n return parseIPv4(networkAddress);\n }\n\n public Inet4Address getBroadcastAddress() {\n return broadcastAddress;\n }\n\n public int getNetworkMask() {\n return networkMask;\n }\n\n public NetworkInterface getNetworkInterface() {\n return networkInterface;\n }\n\n public boolean valid(Inet4Address address) {\n final int ipAsNumber = getIPv4AsNumber(address);\n\n return ipAsNumber > networkAddress && ipAsNumber < IPv4AddressUtil.getIPv4AsNumber(broadcastAddress);\n }\n\n public Optional<Inet4Address> nextAvailable(\n Inet4Address startingAddress,\n Duration timeout,\n Inet4Address currentAddress,\n Collection<Inet4Address> exclusionList\n ) {\n final List<Inet4Address> addresses = nextAvailableExcluding(startingAddress, timeout, 1, currentAddress, exclusionList);\n if (addresses.isEmpty()) {\n return Optional.empty();\n }\n\n return Optional.of(addresses.getFirst());\n }\n\n public List<Inet4Address> nextAvailableExcluding(\n Inet4Address startingAddress,\n Duration timeout,\n int limit,\n Inet4Address currentAddress,\n Collection<Inet4Address> exclusionList\n ) {\n final Set<Integer> excludedIpAddressNumbers = exclusionList.stream()\n .map(IPv4AddressUtil::getIPv4AsNumber)\n .collect(Collectors.toSet());\n\n final int currentIpAsNumber = getIPv4AsNumber(currentAddress);\n int ipAsNumber = getIPv4AsNumber(startingAddress);\n\n final List<Inet4Address> addresses = new ArrayList<>(limit);\n do {\n final long startedAt = System.nanoTime();\n\n final int addressAsNumber = ipAsNumber++;\n if (currentIpAsNumber == addressAsNumber) {\n addresses.add(currentAddress);\n continue;\n }\n\n if (excludedIpAddressNumbers.contains(addressAsNumber)) {\n continue;\n }\n\n final Inet4Address address = parseIPv4(addressAsNumber);\n if (!ping(address)) {\n addresses.add(address);\n }\n\n timeout = timeout.minusNanos(System.nanoTime() - startedAt);\n } while (timeout.isPositive() && addresses.size() < limit && !Thread.interrupted());\n\n return addresses;\n }\n\n @Override\n public String toString() {\n return \"NetworkInterfaceDto{\" +\n \"networkInterface=\" + ToStringUtil.toString(networkInterface) +\n \", address=\" + ToStringUtil.toString(address) +\n \", broadcastAddress=\" + ToStringUtil.toString(broadcastAddress) +\n \", networkAddress=\" + ToStringUtil.toString(parseIPv4(networkAddress)) +\n \", networkMask=\" + ToStringUtil.toString(parseIPv4(networkMask)) +\n '}';\n }\n }\n}" }, { "identifier": "RandomUtil", "path": "common/src/main/java/pl/psobiech/opengr8on/util/RandomUtil.java", "snippet": "public final class RandomUtil {\n private static final Logger LOGGER = LoggerFactory.getLogger(RandomUtil.class);\n\n private static final ThreadLocal<SecureRandom> WEAK_RANDOM_THREAD_LOCAL = ThreadLocal.withInitial(RandomUtil::createWeakRandom);\n\n private static final SecureRandom STRONG_RANDOM;\n\n private static final int UNIQUE_MAX_RETRIES = 32;\n\n private static final int BYTE_MASK = 0xFF;\n\n private static final int NIBBLE_MASK = 0x0F;\n\n private static final char[] HEX_DICTIONARY;\n\n static {\n try {\n STRONG_RANDOM = SecureRandom.getInstanceStrong();\n } catch (NoSuchAlgorithmException e) {\n throw new UnexpectedException(\"No strong random PRNG available\", e);\n }\n\n final char[] chars = new char[HexUtil.HEX_BASE];\n for (int i = 0; i < chars.length; i++) {\n chars[i] = Integer.toHexString(i).charAt(0);\n }\n\n HEX_DICTIONARY = chars;\n }\n\n private static synchronized SecureRandom createWeakRandom() {\n return new SecureRandom();\n }\n\n private RandomUtil() {\n // NOP\n }\n\n public static String unique(int length, Function<Integer, String> generatorFunction, Function<String, Boolean> existsFunction) {\n int retries = UNIQUE_MAX_RETRIES;\n\n String candidate;\n do {\n if (--retries < 0) {\n throw new UnexpectedException(\"Cannot generate unique value\");\n }\n\n candidate = generatorFunction.apply(length);\n } while (existsFunction.apply(candidate) && !Thread.interrupted());\n\n return candidate;\n }\n\n /**\n * @return random hex string (weak rng)\n */\n public static String hexString(int length) {\n return dictionaryString(random(false), length, HEX_DICTIONARY);\n }\n\n /**\n * @return random hex string\n */\n public static String hexString(Random random, int length) {\n return dictionaryString(random, length, HEX_DICTIONARY);\n }\n\n /**\n * @return random dictionary string\n */\n private static String dictionaryString(Random random, int length, char[] dictionary) {\n final StringBuilder sb = new StringBuilder();\n\n final byte[] randomBytes = bytes(random, Math.floorDiv(length + 1, 2));\n for (byte randomByte : randomBytes) {\n final int unsignedByte = randomByte & BYTE_MASK;\n\n sb.append(dictionary[unsignedByte & NIBBLE_MASK]);\n sb.append(dictionary[unsignedByte >> (Byte.SIZE / 2)]);\n }\n\n if (sb.length() > length) {\n sb.setLength(length);\n }\n\n return sb.toString();\n }\n\n /**\n * @return random array of bytes (weak rng)\n */\n public static byte[] bytes(int size) {\n return bytes(random(false), size);\n }\n\n /**\n * @return random array of bytes\n */\n public static byte[] bytes(Random random, int size) {\n final byte[] salt = new byte[size];\n random.nextBytes(salt);\n\n return salt;\n }\n\n public static SecureRandom random(boolean strong) {\n if (strong) {\n return RandomUtil.STRONG_RANDOM;\n }\n\n return RandomUtil.WEAK_RANDOM_THREAD_LOCAL.get();\n }\n}" }, { "identifier": "SocketUtil", "path": "common/src/main/java/pl/psobiech/opengr8on/util/SocketUtil.java", "snippet": "public class SocketUtil {\n public static final int DEFAULT_TIMEOUT = 9_000;\n\n private static final int IPTOS_RELIABILITY = 0x04;\n\n private SocketUtil() {\n // NOP\n }\n\n public static UDPSocket udpListener(InetAddress address, int port) {\n return new UDPSocket(\n address, port, false\n );\n }\n\n public static UDPSocket udpRandomPort(InetAddress address) {\n return new UDPSocket(\n address, 0, true\n );\n }\n\n public static class UDPSocket implements Closeable {\n private final InetAddress address;\n\n private final int port;\n\n private final boolean broadcast;\n\n private final ReentrantLock socketLock = new ReentrantLock();\n\n private DatagramSocket socket;\n\n public UDPSocket(InetAddress address, int port, boolean broadcast) {\n this.address = address;\n this.port = port;\n this.broadcast = broadcast;\n }\n\n public void open() {\n socketLock.lock();\n try {\n this.socket = new DatagramSocket(new InetSocketAddress(address, port));\n this.socket.setSoTimeout(DEFAULT_TIMEOUT);\n this.socket.setTrafficClass(IPTOS_RELIABILITY);\n\n this.socket.setBroadcast(broadcast);\n } catch (IOException e) {\n throw new UnexpectedException(e);\n } finally {\n socketLock.unlock();\n }\n }\n\n public InetAddress getLocalAddress() {\n return socket.getLocalAddress();\n }\n\n public int getLocalPort() {\n return socket.getLocalPort();\n }\n\n public void send(DatagramPacket packet) {\n socketLock.lock();\n try {\n socket.send(packet);\n } catch (IOException e) {\n throw new UnexpectedException(e);\n } finally {\n socketLock.unlock();\n }\n }\n\n public void discard(DatagramPacket packet) {\n socketLock.lock();\n try {\n socket.setSoTimeout(1);\n do {\n socket.receive(packet);\n } while (packet.getLength() > 0 && !Thread.interrupted());\n } catch (IOException e) {\n // NOP\n } finally {\n try {\n socket.setSoTimeout(DEFAULT_TIMEOUT);\n } catch (SocketException e) {\n // NOP\n }\n\n socketLock.unlock();\n }\n }\n\n public Optional<Payload> tryReceive(DatagramPacket packet, Duration timeout) {\n socketLock.lock();\n try {\n try {\n // defend against 0 to prevent infinite timeouts\n socket.setSoTimeout(Math.max(1, Math.toIntExact(timeout.toMillis())));\n socket.receive(packet);\n socket.setSoTimeout(DEFAULT_TIMEOUT);\n } catch (SocketTimeoutException e) {\n return Optional.empty();\n } catch (SocketException e) {\n if (UncheckedInterruptedException.wasSocketInterrupted(e)) {\n throw new UncheckedInterruptedException(e);\n }\n\n throw new UnexpectedException(e);\n } catch (IOException e) {\n throw new UnexpectedException(e);\n }\n\n return Optional.of(\n Payload.of(\n (Inet4Address) packet.getAddress(), packet.getPort(),\n Arrays.copyOfRange(\n packet.getData(),\n packet.getOffset(), packet.getOffset() + packet.getLength()\n )\n )\n );\n } finally {\n socketLock.unlock();\n }\n }\n\n @Override\n public void close() {\n socketLock.lock();\n try {\n FileUtil.closeQuietly(this.socket);\n\n this.socket = null;\n } finally {\n socketLock.unlock();\n }\n }\n }\n\n public record Payload(Inet4Address address, int port, byte[] buffer) {\n public static Payload of(Inet4Address ipAddress, int port, byte[] buffer) {\n return new Payload(ipAddress, port, buffer);\n }\n\n @Override\n public String toString() {\n return \"Payload{\" +\n \"address=\" + ToStringUtil.toString(address, port) +\n \", buffer=\" + ToStringUtil.toString(buffer) +\n '}';\n }\n }\n}" }, { "identifier": "UDPSocket", "path": "common/src/main/java/pl/psobiech/opengr8on/util/SocketUtil.java", "snippet": "public static class UDPSocket implements Closeable {\n private final InetAddress address;\n\n private final int port;\n\n private final boolean broadcast;\n\n private final ReentrantLock socketLock = new ReentrantLock();\n\n private DatagramSocket socket;\n\n public UDPSocket(InetAddress address, int port, boolean broadcast) {\n this.address = address;\n this.port = port;\n this.broadcast = broadcast;\n }\n\n public void open() {\n socketLock.lock();\n try {\n this.socket = new DatagramSocket(new InetSocketAddress(address, port));\n this.socket.setSoTimeout(DEFAULT_TIMEOUT);\n this.socket.setTrafficClass(IPTOS_RELIABILITY);\n\n this.socket.setBroadcast(broadcast);\n } catch (IOException e) {\n throw new UnexpectedException(e);\n } finally {\n socketLock.unlock();\n }\n }\n\n public InetAddress getLocalAddress() {\n return socket.getLocalAddress();\n }\n\n public int getLocalPort() {\n return socket.getLocalPort();\n }\n\n public void send(DatagramPacket packet) {\n socketLock.lock();\n try {\n socket.send(packet);\n } catch (IOException e) {\n throw new UnexpectedException(e);\n } finally {\n socketLock.unlock();\n }\n }\n\n public void discard(DatagramPacket packet) {\n socketLock.lock();\n try {\n socket.setSoTimeout(1);\n do {\n socket.receive(packet);\n } while (packet.getLength() > 0 && !Thread.interrupted());\n } catch (IOException e) {\n // NOP\n } finally {\n try {\n socket.setSoTimeout(DEFAULT_TIMEOUT);\n } catch (SocketException e) {\n // NOP\n }\n\n socketLock.unlock();\n }\n }\n\n public Optional<Payload> tryReceive(DatagramPacket packet, Duration timeout) {\n socketLock.lock();\n try {\n try {\n // defend against 0 to prevent infinite timeouts\n socket.setSoTimeout(Math.max(1, Math.toIntExact(timeout.toMillis())));\n socket.receive(packet);\n socket.setSoTimeout(DEFAULT_TIMEOUT);\n } catch (SocketTimeoutException e) {\n return Optional.empty();\n } catch (SocketException e) {\n if (UncheckedInterruptedException.wasSocketInterrupted(e)) {\n throw new UncheckedInterruptedException(e);\n }\n\n throw new UnexpectedException(e);\n } catch (IOException e) {\n throw new UnexpectedException(e);\n }\n\n return Optional.of(\n Payload.of(\n (Inet4Address) packet.getAddress(), packet.getPort(),\n Arrays.copyOfRange(\n packet.getData(),\n packet.getOffset(), packet.getOffset() + packet.getLength()\n )\n )\n );\n } finally {\n socketLock.unlock();\n }\n }\n\n @Override\n public void close() {\n socketLock.lock();\n try {\n FileUtil.closeQuietly(this.socket);\n\n this.socket = null;\n } finally {\n socketLock.unlock();\n }\n }\n}" } ]
import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Inet4Address; import java.nio.file.Files; import java.nio.file.Path; import java.util.Arrays; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.parallel.Execution; import org.junit.jupiter.api.parallel.ExecutionMode; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import pl.psobiech.opengr8on.tftp.TFTPServer.ServerMode; import pl.psobiech.opengr8on.tftp.exceptions.TFTPException; import pl.psobiech.opengr8on.tftp.packets.TFTPErrorType; import pl.psobiech.opengr8on.tftp.packets.TFTPPacket; import pl.psobiech.opengr8on.util.FileUtil; import pl.psobiech.opengr8on.util.IPv4AddressUtil; import pl.psobiech.opengr8on.util.RandomUtil; import pl.psobiech.opengr8on.util.SocketUtil; import pl.psobiech.opengr8on.util.SocketUtil.UDPSocket; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue;
10,160
/* * OpenGr8on, open source extensions to systems based on Grenton devices * Copyright (C) 2023 Piotr Sobiech * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package pl.psobiech.opengr8on.tftp; @Execution(ExecutionMode.CONCURRENT) class TFTPTest { private static final Inet4Address LOCALHOST = IPv4AddressUtil.parseIPv4("127.0.0.1"); private static ExecutorService executor = Executors.newCachedThreadPool(); private static Path rootDirectory; private static UDPSocket socket; private static TFTPServer server; private static Future<Void> serverFuture; private static TFTPClient client; private String LF = Character.toString(0x0A); private String CR = Character.toString(0x0D); @BeforeAll static void setUp() throws Exception { executor = Executors.newCachedThreadPool(); rootDirectory = FileUtil.temporaryDirectory(); FileUtil.mkdir(rootDirectory); socket = new UDPSocket(LOCALHOST, 0, false); server = new TFTPServer(LOCALHOST, ServerMode.GET_AND_PUT, rootDirectory, socket); serverFuture = server.start(); server.awaitInitialized(); client = new TFTPClient(SocketUtil.udpRandomPort(LOCALHOST), socket.getLocalPort()); client.open(); } @AfterAll static void tearDown() throws Exception { FileUtil.closeQuietly(client); serverFuture.cancel(true); try { serverFuture.get(); } catch (Exception e) { // } FileUtil.closeQuietly(server); executor.shutdownNow(); FileUtil.deleteRecursively(rootDirectory); } @ParameterizedTest @ValueSource( ints = { 0, 1, 1023, 1024, 1025, // multiple blocks 0xFFFF * TFTPPacket.SEGMENT_SIZE + 1025 // block number rollover } ) void uploadBinary(int fileSize) throws Exception { final Path temporaryPathFrom = FileUtil.temporaryFile(); final Path temporaryPathTo = FileUtil.temporaryFile(); try { fillWithRandomBytes(fileSize, temporaryPathFrom); final String fileName = "file_" + fileSize + ".bin"; final Path expectedPath = rootDirectory.resolve(fileName); assertFalse(Files.exists(expectedPath)); client.upload( LOCALHOST, TFTPTransferMode.OCTET, temporaryPathFrom, fileName ); client.download( LOCALHOST, TFTPTransferMode.OCTET, fileName, temporaryPathTo ); assertTrue(Files.exists(expectedPath)); assertEquals(fileSize, Files.size(expectedPath)); assertEquals(fileSize, Files.size(temporaryPathTo)); assertFilesSame(temporaryPathFrom, expectedPath); assertFilesSame(temporaryPathFrom, temporaryPathTo); } finally { FileUtil.deleteQuietly(temporaryPathFrom); FileUtil.deleteQuietly(temporaryPathTo); } } private static void fillWithRandomBytes(int bufferSize, Path temporaryPathFrom) throws IOException { int left = bufferSize; try (OutputStream outputStream = new BufferedOutputStream(Files.newOutputStream(temporaryPathFrom))) { while (left > 0) {
/* * OpenGr8on, open source extensions to systems based on Grenton devices * Copyright (C) 2023 Piotr Sobiech * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package pl.psobiech.opengr8on.tftp; @Execution(ExecutionMode.CONCURRENT) class TFTPTest { private static final Inet4Address LOCALHOST = IPv4AddressUtil.parseIPv4("127.0.0.1"); private static ExecutorService executor = Executors.newCachedThreadPool(); private static Path rootDirectory; private static UDPSocket socket; private static TFTPServer server; private static Future<Void> serverFuture; private static TFTPClient client; private String LF = Character.toString(0x0A); private String CR = Character.toString(0x0D); @BeforeAll static void setUp() throws Exception { executor = Executors.newCachedThreadPool(); rootDirectory = FileUtil.temporaryDirectory(); FileUtil.mkdir(rootDirectory); socket = new UDPSocket(LOCALHOST, 0, false); server = new TFTPServer(LOCALHOST, ServerMode.GET_AND_PUT, rootDirectory, socket); serverFuture = server.start(); server.awaitInitialized(); client = new TFTPClient(SocketUtil.udpRandomPort(LOCALHOST), socket.getLocalPort()); client.open(); } @AfterAll static void tearDown() throws Exception { FileUtil.closeQuietly(client); serverFuture.cancel(true); try { serverFuture.get(); } catch (Exception e) { // } FileUtil.closeQuietly(server); executor.shutdownNow(); FileUtil.deleteRecursively(rootDirectory); } @ParameterizedTest @ValueSource( ints = { 0, 1, 1023, 1024, 1025, // multiple blocks 0xFFFF * TFTPPacket.SEGMENT_SIZE + 1025 // block number rollover } ) void uploadBinary(int fileSize) throws Exception { final Path temporaryPathFrom = FileUtil.temporaryFile(); final Path temporaryPathTo = FileUtil.temporaryFile(); try { fillWithRandomBytes(fileSize, temporaryPathFrom); final String fileName = "file_" + fileSize + ".bin"; final Path expectedPath = rootDirectory.resolve(fileName); assertFalse(Files.exists(expectedPath)); client.upload( LOCALHOST, TFTPTransferMode.OCTET, temporaryPathFrom, fileName ); client.download( LOCALHOST, TFTPTransferMode.OCTET, fileName, temporaryPathTo ); assertTrue(Files.exists(expectedPath)); assertEquals(fileSize, Files.size(expectedPath)); assertEquals(fileSize, Files.size(temporaryPathTo)); assertFilesSame(temporaryPathFrom, expectedPath); assertFilesSame(temporaryPathFrom, temporaryPathTo); } finally { FileUtil.deleteQuietly(temporaryPathFrom); FileUtil.deleteQuietly(temporaryPathTo); } } private static void fillWithRandomBytes(int bufferSize, Path temporaryPathFrom) throws IOException { int left = bufferSize; try (OutputStream outputStream = new BufferedOutputStream(Files.newOutputStream(temporaryPathFrom))) { while (left > 0) {
final byte[] randomBuffer = RandomUtil.bytes(Math.min(left, 4096));
6
2023-12-23 09:56:14+00:00
12k
Pigmice2733/frc-2024
src/main/java/frc/robot/subsystems/Vision.java
[ { "identifier": "Constants", "path": "src/main/java/frc/robot/Constants.java", "snippet": "public final class Constants {\n public static final ShuffleboardTab DRIVER_TAB = Shuffleboard.getTab(\"Driver\");\n public static final ShuffleboardTab SWERVE_TAB = Shuffleboard.getTab(\"Drivetrain\");\n public static final ShuffleboardTab ARM_TAB = Shuffleboard.getTab(\"Arm\");\n public static final ShuffleboardTab CLIMBER_TAB = Shuffleboard.getTab(\"Climber\");\n public static final ShuffleboardTab INTAKE_TAB = Shuffleboard.getTab(\"Intake\");\n public static final ShuffleboardTab SHOOTER_TAB = Shuffleboard.getTab(\"Shooter\");\n public static final ShuffleboardTab VISION_TAB = Shuffleboard.getTab(\"Vision\");\n\n public static final double AXIS_THRESHOLD = 0.25;\n\n public static final class CANConfig {\n public static final int FRONT_LEFT_DRIVE = 11; // done\n public static final int FRONT_LEFT_STEER = 10;// done\n public static final int FRONT_RIGHT_DRIVE = 13;// done\n public static final int FRONT_RIGHT_STEER = 12;// done\n public static final int BACK_LEFT_DRIVE = 16;// done\n public static final int BACK_LEFT_STEER = 17;// done\n public static final int BACK_RIGHT_DRIVE = 14;// done\n public static final int BACK_RIGHT_STEER = 15;// done\n\n public static final int FRONT_LEFT_ABS_ENCODER = 20;// done\n public static final int FRONT_RIGHT_ABS_ENCODER = 24;// done\n public static final int BACK_LEFT_ABS_ENCODER = 22;// done\n public static final int BACK_RIGHT_ABS_ENCODER = 26;// done\n\n public static final int ARM = 30;\n\n public static final int CLIMBER_EXTENSION = 40;\n\n public static final int INTAKE_WHEELS = 50;\n public static final int INTAKE_PIVOT = 51;\n\n public static final int SHOOTER_MOTOR = 60;\n public static final int FEEDER_MOTOR = 61;\n }\n\n public final static class DrivetrainConfig {\n public static final double MAX_DRIVE_SPEED = 4.5; // max meters / second\n public static final double MAX_TURN_SPEED = 5; // max radians / second\n public static final double SLOWMODE_MULTIPLIER = 0.5;\n\n // distance from the center of one wheel to another\n public static final double TRACK_WIDTH_METERS = 0.5842;\n\n private final static SwerveDriveKinematics KINEMATICS = new SwerveDriveKinematics(\n new Translation2d(TRACK_WIDTH_METERS / 2,\n TRACK_WIDTH_METERS / 2), // Front left\n new Translation2d(TRACK_WIDTH_METERS / 2,\n -TRACK_WIDTH_METERS / 2), // Front right\n new Translation2d(-TRACK_WIDTH_METERS / 2,\n TRACK_WIDTH_METERS / 2), // Back left\n new Translation2d(-TRACK_WIDTH_METERS / 2,\n -TRACK_WIDTH_METERS / 2) // Back right\n );\n\n // Constants found in Sysid (volts)\n private static final SimpleMotorFeedforward DRIVE_FEED_FORWARD = new SimpleMotorFeedforward(\n 0.35493, 2.3014, 0.12872);\n\n // From what I have seen, it is common to only use a P value in path following\n private static final PathConstraints PATH_CONSTRAINTS = new PathConstraints(2, 2); // 3, 2.5\n private static final PIDController PATH_DRIVE_PID = new PIDController(0.3, 0, 0);\n private static final PIDController PATH_TURN_PID = new PIDController(0.31, 0, 0);\n\n // Offset from chassis center that the robot will rotate about\n private static final Translation2d ROTATION_CENTER_OFFSET = new Translation2d(0, 0);\n\n private static final MkSwerveModuleBuilder FRONT_LEFT_MODULE = new MkSwerveModuleBuilder()\n .withLayout(SWERVE_TAB\n .getLayout(\"Front Left\", BuiltInLayouts.kList)\n .withSize(1, 3)\n .withPosition(0, 0))\n .withGearRatio(SdsModuleConfigurations.MK4I_L2)\n .withDriveMotor(MotorType.NEO, CANConfig.FRONT_LEFT_DRIVE)\n .withSteerMotor(MotorType.NEO, CANConfig.FRONT_LEFT_STEER)\n .withSteerEncoderPort(CANConfig.FRONT_LEFT_ABS_ENCODER)\n .withSteerOffset(Math.toRadians(73));\n\n private static final MkSwerveModuleBuilder FRONT_RIGHT_MODULE = new MkSwerveModuleBuilder()\n .withLayout(SWERVE_TAB\n .getLayout(\"Front Right\", BuiltInLayouts.kList)\n .withSize(1, 3)\n .withPosition(1, 0))\n .withGearRatio(SdsModuleConfigurations.MK4I_L2)\n .withDriveMotor(MotorType.NEO, CANConfig.FRONT_RIGHT_DRIVE)\n .withSteerMotor(MotorType.NEO, CANConfig.FRONT_RIGHT_STEER)\n .withSteerEncoderPort(CANConfig.FRONT_RIGHT_ABS_ENCODER)\n .withSteerOffset(Math.toRadians(-99));\n\n private static final MkSwerveModuleBuilder BACK_LEFT_MODULE = new MkSwerveModuleBuilder()\n .withLayout(SWERVE_TAB\n .getLayout(\"Back Left\", BuiltInLayouts.kList)\n .withSize(1, 3)\n .withPosition(2, 0))\n .withGearRatio(SdsModuleConfigurations.MK4I_L2)\n .withDriveMotor(MotorType.NEO, CANConfig.BACK_LEFT_DRIVE)\n .withSteerMotor(MotorType.NEO, CANConfig.BACK_LEFT_STEER)\n .withSteerEncoderPort(CANConfig.BACK_LEFT_ABS_ENCODER)\n .withSteerOffset(Math.toRadians(219));\n\n private static final MkSwerveModuleBuilder BACK_RIGHT_MODULE = new MkSwerveModuleBuilder()\n .withLayout(SWERVE_TAB\n .getLayout(\"Back Right\", BuiltInLayouts.kList)\n .withSize(1, 3)\n .withPosition(3, 0))\n .withGearRatio(SdsModuleConfigurations.MK4I_L2)\n .withDriveMotor(MotorType.NEO, CANConfig.BACK_RIGHT_DRIVE)\n .withSteerMotor(MotorType.NEO, CANConfig.BACK_RIGHT_STEER)\n .withSteerEncoderPort(CANConfig.BACK_RIGHT_ABS_ENCODER)\n .withSteerOffset(Math.toRadians(-285));\n\n public static final SwerveConfig SWERVE_CONFIG = new SwerveConfig(\n FRONT_LEFT_MODULE, FRONT_RIGHT_MODULE, BACK_LEFT_MODULE,\n BACK_RIGHT_MODULE,\n PATH_CONSTRAINTS, PATH_DRIVE_PID, PATH_TURN_PID,\n MAX_DRIVE_SPEED, MAX_TURN_SPEED,\n SLOWMODE_MULTIPLIER, KINEMATICS, DRIVE_FEED_FORWARD, SWERVE_TAB,\n ROTATION_CENTER_OFFSET);\n }\n\n public final static class ArmConfig {\n public static final double P = 0;\n public static final double i = 0;\n public static final double D = 0;\n\n public static final double MAX_ACCELERATION = 0;\n public static final double MAX_VELOCITY = 0;\n\n public static final double MOTOR_POSITION_CONVERSION = 1;\n\n public static enum ArmState {\n HIGH(90),\n MIDDLE(45),\n DOWN(0);\n\n private double position;\n\n ArmState(double position) {\n this.position = position;\n }\n\n public double getPosition() {\n return position;\n }\n }\n }\n\n public final static class ClimberConfig {\n public static final double P = 0;\n public static final double I = 0;\n public static final double D = 0;\n\n public static final double MAX_ACCELERATION = 0;\n public static final double MAX_VELOCITY = 0;\n\n public static final double MOTOR_POSITION_CONVERSION = 1;\n\n public static enum ClimberState {\n UP(45),\n DOWN(0);\n\n private double position;\n\n ClimberState(double position) {\n this.position = position;\n }\n\n public double getPosition() {\n return position;\n }\n }\n }\n\n public final static class IntakeConfig {\n public static final double P = 0;\n public static final double I = 0;\n public static final double D = 0;\n\n public static final double MAX_ACCELERATION = 0;\n public static final double MAX_VELOCITY = 0;\n\n public static final double MOTOR_POSITION_CONVERSION = 1;\n\n public static final double WHEELS_SPEED = 0.3;\n\n public static enum IntakeState {\n UP(45),\n DOWN(0);\n\n private double position;\n\n IntakeState(double position) {\n this.position = position;\n }\n\n public double getPosition() {\n return position;\n }\n }\n }\n\n public final static class ShooterConfig {\n public static final double DEFAULT_FLYWHEEL_SPEED = 0.3;\n }\n\n public final static class VisionConfig {\n public final static String CAM_NAME = \"\";\n }\n\n /** Details for auto such as timings and speeds */\n public static class AutoConfig {\n public final static double INTAKE_MOVE_TIME = 3;\n public final static double INTAKE_FEED_TIME = 1;\n public final static double FLYWHEEL_SPINUP_TIME = 3;\n\n }\n}" }, { "identifier": "LimelightHelpers", "path": "src/main/java/frc/robot/LimelightHelpers.java", "snippet": "public class LimelightHelpers {\n\n public static class LimelightTarget_Retro {\n\n @JsonProperty(\"t6c_ts\")\n private double[] cameraPose_TargetSpace;\n\n @JsonProperty(\"t6r_fs\")\n private double[] robotPose_FieldSpace;\n\n @JsonProperty(\"t6r_ts\")\n private double[] robotPose_TargetSpace;\n\n @JsonProperty(\"t6t_cs\")\n private double[] targetPose_CameraSpace;\n\n @JsonProperty(\"t6t_rs\")\n private double[] targetPose_RobotSpace;\n\n public Pose3d getCameraPose_TargetSpace()\n {\n return toPose3D(cameraPose_TargetSpace);\n }\n public Pose3d getRobotPose_FieldSpace()\n {\n return toPose3D(robotPose_FieldSpace);\n }\n public Pose3d getRobotPose_TargetSpace()\n {\n return toPose3D(robotPose_TargetSpace);\n }\n public Pose3d getTargetPose_CameraSpace()\n {\n return toPose3D(targetPose_CameraSpace);\n }\n public Pose3d getTargetPose_RobotSpace()\n {\n return toPose3D(targetPose_RobotSpace);\n }\n\n public Pose2d getCameraPose_TargetSpace2D()\n {\n return toPose2D(cameraPose_TargetSpace);\n }\n public Pose2d getRobotPose_FieldSpace2D()\n {\n return toPose2D(robotPose_FieldSpace);\n }\n public Pose2d getRobotPose_TargetSpace2D()\n {\n return toPose2D(robotPose_TargetSpace);\n }\n public Pose2d getTargetPose_CameraSpace2D()\n {\n return toPose2D(targetPose_CameraSpace);\n }\n public Pose2d getTargetPose_RobotSpace2D()\n {\n return toPose2D(targetPose_RobotSpace);\n }\n\n @JsonProperty(\"ta\")\n public double ta;\n\n @JsonProperty(\"tx\")\n public double tx;\n\n @JsonProperty(\"txp\")\n public double tx_pixels;\n\n @JsonProperty(\"ty\")\n public double ty;\n\n @JsonProperty(\"typ\")\n public double ty_pixels;\n\n @JsonProperty(\"ts\")\n public double ts;\n\n public LimelightTarget_Retro() {\n cameraPose_TargetSpace = new double[6];\n robotPose_FieldSpace = new double[6];\n robotPose_TargetSpace = new double[6];\n targetPose_CameraSpace = new double[6];\n targetPose_RobotSpace = new double[6];\n }\n\n }\n\n public static class LimelightTarget_Fiducial {\n\n @JsonProperty(\"fID\")\n public double fiducialID;\n\n @JsonProperty(\"fam\")\n public String fiducialFamily;\n\n @JsonProperty(\"t6c_ts\")\n private double[] cameraPose_TargetSpace;\n\n @JsonProperty(\"t6r_fs\")\n private double[] robotPose_FieldSpace;\n\n @JsonProperty(\"t6r_ts\")\n private double[] robotPose_TargetSpace;\n\n @JsonProperty(\"t6t_cs\")\n private double[] targetPose_CameraSpace;\n\n @JsonProperty(\"t6t_rs\")\n private double[] targetPose_RobotSpace;\n\n public Pose3d getCameraPose_TargetSpace()\n {\n return toPose3D(cameraPose_TargetSpace);\n }\n public Pose3d getRobotPose_FieldSpace()\n {\n return toPose3D(robotPose_FieldSpace);\n }\n public Pose3d getRobotPose_TargetSpace()\n {\n return toPose3D(robotPose_TargetSpace);\n }\n public Pose3d getTargetPose_CameraSpace()\n {\n return toPose3D(targetPose_CameraSpace);\n }\n public Pose3d getTargetPose_RobotSpace()\n {\n return toPose3D(targetPose_RobotSpace);\n }\n\n public Pose2d getCameraPose_TargetSpace2D()\n {\n return toPose2D(cameraPose_TargetSpace);\n }\n public Pose2d getRobotPose_FieldSpace2D()\n {\n return toPose2D(robotPose_FieldSpace);\n }\n public Pose2d getRobotPose_TargetSpace2D()\n {\n return toPose2D(robotPose_TargetSpace);\n }\n public Pose2d getTargetPose_CameraSpace2D()\n {\n return toPose2D(targetPose_CameraSpace);\n }\n public Pose2d getTargetPose_RobotSpace2D()\n {\n return toPose2D(targetPose_RobotSpace);\n }\n \n @JsonProperty(\"ta\")\n public double ta;\n\n @JsonProperty(\"tx\")\n public double tx;\n\n @JsonProperty(\"txp\")\n public double tx_pixels;\n\n @JsonProperty(\"ty\")\n public double ty;\n\n @JsonProperty(\"typ\")\n public double ty_pixels;\n\n @JsonProperty(\"ts\")\n public double ts;\n \n public LimelightTarget_Fiducial() {\n cameraPose_TargetSpace = new double[6];\n robotPose_FieldSpace = new double[6];\n robotPose_TargetSpace = new double[6];\n targetPose_CameraSpace = new double[6];\n targetPose_RobotSpace = new double[6];\n }\n }\n\n public static class LimelightTarget_Barcode {\n\n }\n\n public static class LimelightTarget_Classifier {\n\n @JsonProperty(\"class\")\n public String className;\n\n @JsonProperty(\"classID\")\n public double classID;\n\n @JsonProperty(\"conf\")\n public double confidence;\n\n @JsonProperty(\"zone\")\n public double zone;\n\n @JsonProperty(\"tx\")\n public double tx;\n\n @JsonProperty(\"txp\")\n public double tx_pixels;\n\n @JsonProperty(\"ty\")\n public double ty;\n\n @JsonProperty(\"typ\")\n public double ty_pixels;\n\n public LimelightTarget_Classifier() {\n }\n }\n\n public static class LimelightTarget_Detector {\n\n @JsonProperty(\"class\")\n public String className;\n\n @JsonProperty(\"classID\")\n public double classID;\n\n @JsonProperty(\"conf\")\n public double confidence;\n\n @JsonProperty(\"ta\")\n public double ta;\n\n @JsonProperty(\"tx\")\n public double tx;\n\n @JsonProperty(\"txp\")\n public double tx_pixels;\n\n @JsonProperty(\"ty\")\n public double ty;\n\n @JsonProperty(\"typ\")\n public double ty_pixels;\n\n public LimelightTarget_Detector() {\n }\n }\n\n public static class Results {\n\n @JsonProperty(\"pID\")\n public double pipelineID;\n\n @JsonProperty(\"tl\")\n public double latency_pipeline;\n\n @JsonProperty(\"cl\")\n public double latency_capture;\n\n public double latency_jsonParse;\n\n @JsonProperty(\"ts\")\n public double timestamp_LIMELIGHT_publish;\n\n @JsonProperty(\"ts_rio\")\n public double timestamp_RIOFPGA_capture;\n\n @JsonProperty(\"v\")\n @JsonFormat(shape = Shape.NUMBER)\n public boolean valid;\n\n @JsonProperty(\"botpose\")\n public double[] botpose;\n\n @JsonProperty(\"botpose_wpired\")\n public double[] botpose_wpired;\n\n @JsonProperty(\"botpose_wpiblue\")\n public double[] botpose_wpiblue;\n\n @JsonProperty(\"t6c_rs\")\n public double[] camerapose_robotspace;\n\n public Pose3d getBotPose3d() {\n return toPose3D(botpose);\n }\n \n public Pose3d getBotPose3d_wpiRed() {\n return toPose3D(botpose_wpired);\n }\n \n public Pose3d getBotPose3d_wpiBlue() {\n return toPose3D(botpose_wpiblue);\n }\n\n public Pose2d getBotPose2d() {\n return toPose2D(botpose);\n }\n \n public Pose2d getBotPose2d_wpiRed() {\n return toPose2D(botpose_wpired);\n }\n \n public Pose2d getBotPose2d_wpiBlue() {\n return toPose2D(botpose_wpiblue);\n }\n\n @JsonProperty(\"Retro\")\n public LimelightTarget_Retro[] targets_Retro;\n\n @JsonProperty(\"Fiducial\")\n public LimelightTarget_Fiducial[] targets_Fiducials;\n\n @JsonProperty(\"Classifier\")\n public LimelightTarget_Classifier[] targets_Classifier;\n\n @JsonProperty(\"Detector\")\n public LimelightTarget_Detector[] targets_Detector;\n\n @JsonProperty(\"Barcode\")\n public LimelightTarget_Barcode[] targets_Barcode;\n\n public Results() {\n botpose = new double[6];\n botpose_wpired = new double[6];\n botpose_wpiblue = new double[6];\n camerapose_robotspace = new double[6];\n targets_Retro = new LimelightTarget_Retro[0];\n targets_Fiducials = new LimelightTarget_Fiducial[0];\n targets_Classifier = new LimelightTarget_Classifier[0];\n targets_Detector = new LimelightTarget_Detector[0];\n targets_Barcode = new LimelightTarget_Barcode[0];\n\n }\n }\n\n public static class LimelightResults {\n @JsonProperty(\"Results\")\n public Results targetingResults;\n\n public LimelightResults() {\n targetingResults = new Results();\n }\n }\n\n private static ObjectMapper mapper;\n\n /**\n * Print JSON Parse time to the console in milliseconds\n */\n static boolean profileJSON = false;\n\n static final String sanitizeName(String name) {\n if (name == \"\" || name == null) {\n return \"limelight\";\n }\n return name;\n }\n\n private static Pose3d toPose3D(double[] inData){\n if(inData.length < 6)\n {\n System.err.println(\"Bad LL 3D Pose Data!\");\n return new Pose3d();\n }\n return new Pose3d(\n new Translation3d(inData[0], inData[1], inData[2]),\n new Rotation3d(Units.degreesToRadians(inData[3]), Units.degreesToRadians(inData[4]),\n Units.degreesToRadians(inData[5])));\n }\n\n private static Pose2d toPose2D(double[] inData){\n if(inData.length < 6)\n {\n System.err.println(\"Bad LL 2D Pose Data!\");\n return new Pose2d();\n }\n Translation2d tran2d = new Translation2d(inData[0], inData[1]);\n Rotation2d r2d = new Rotation2d(Units.degreesToRadians(inData[5]));\n return new Pose2d(tran2d, r2d);\n }\n\n public static NetworkTable getLimelightNTTable(String tableName) {\n return NetworkTableInstance.getDefault().getTable(sanitizeName(tableName));\n }\n\n public static NetworkTableEntry getLimelightNTTableEntry(String tableName, String entryName) {\n return getLimelightNTTable(tableName).getEntry(entryName);\n }\n\n public static double getLimelightNTDouble(String tableName, String entryName) {\n return getLimelightNTTableEntry(tableName, entryName).getDouble(0.0);\n }\n\n public static void setLimelightNTDouble(String tableName, String entryName, double val) {\n getLimelightNTTableEntry(tableName, entryName).setDouble(val);\n }\n\n public static void setLimelightNTDoubleArray(String tableName, String entryName, double[] val) {\n getLimelightNTTableEntry(tableName, entryName).setDoubleArray(val);\n }\n\n public static double[] getLimelightNTDoubleArray(String tableName, String entryName) {\n return getLimelightNTTableEntry(tableName, entryName).getDoubleArray(new double[0]);\n }\n\n public static String getLimelightNTString(String tableName, String entryName) {\n return getLimelightNTTableEntry(tableName, entryName).getString(\"\");\n }\n\n public static URL getLimelightURLString(String tableName, String request) {\n String urlString = \"http://\" + sanitizeName(tableName) + \".local:5807/\" + request;\n URL url;\n try {\n url = new URL(urlString);\n return url;\n } catch (MalformedURLException e) {\n System.err.println(\"bad LL URL\");\n }\n return null;\n }\n /////\n /////\n\n public static double getTX(String limelightName) {\n return getLimelightNTDouble(limelightName, \"tx\");\n }\n\n public static double getTY(String limelightName) {\n return getLimelightNTDouble(limelightName, \"ty\");\n }\n\n public static double getTA(String limelightName) {\n return getLimelightNTDouble(limelightName, \"ta\");\n }\n\n public static double getLatency_Pipeline(String limelightName) {\n return getLimelightNTDouble(limelightName, \"tl\");\n }\n\n public static double getLatency_Capture(String limelightName) {\n return getLimelightNTDouble(limelightName, \"cl\");\n }\n\n public static double getCurrentPipelineIndex(String limelightName) {\n return getLimelightNTDouble(limelightName, \"getpipe\");\n }\n\n public static String getJSONDump(String limelightName) {\n return getLimelightNTString(limelightName, \"json\");\n }\n\n /**\n * Switch to getBotPose\n * \n * @param limelightName\n * @return\n */\n @Deprecated\n public static double[] getBotpose(String limelightName) {\n return getLimelightNTDoubleArray(limelightName, \"botpose\");\n }\n\n /**\n * Switch to getBotPose_wpiRed\n * \n * @param limelightName\n * @return\n */\n @Deprecated\n public static double[] getBotpose_wpiRed(String limelightName) {\n return getLimelightNTDoubleArray(limelightName, \"botpose_wpired\");\n }\n\n /**\n * Switch to getBotPose_wpiBlue\n * \n * @param limelightName\n * @return\n */\n @Deprecated\n public static double[] getBotpose_wpiBlue(String limelightName) {\n return getLimelightNTDoubleArray(limelightName, \"botpose_wpiblue\");\n }\n\n public static double[] getBotPose(String limelightName) {\n return getLimelightNTDoubleArray(limelightName, \"botpose\");\n }\n\n public static double[] getBotPose_wpiRed(String limelightName) {\n return getLimelightNTDoubleArray(limelightName, \"botpose_wpired\");\n }\n\n public static double[] getBotPose_wpiBlue(String limelightName) {\n return getLimelightNTDoubleArray(limelightName, \"botpose_wpiblue\");\n }\n\n public static double[] getBotPose_TargetSpace(String limelightName) {\n return getLimelightNTDoubleArray(limelightName, \"botpose_targetspace\");\n }\n\n public static double[] getCameraPose_TargetSpace(String limelightName) {\n return getLimelightNTDoubleArray(limelightName, \"camerapose_targetspace\");\n }\n\n public static double[] getTargetPose_CameraSpace(String limelightName) {\n return getLimelightNTDoubleArray(limelightName, \"targetpose_cameraspace\");\n }\n\n public static double[] getTargetPose_RobotSpace(String limelightName) {\n return getLimelightNTDoubleArray(limelightName, \"targetpose_robotspace\");\n }\n\n public static double[] getTargetColor(String limelightName) {\n return getLimelightNTDoubleArray(limelightName, \"tc\");\n }\n\n public static double getFiducialID(String limelightName) {\n return getLimelightNTDouble(limelightName, \"tid\");\n }\n\n public static double getNeuralClassID(String limelightName) {\n return getLimelightNTDouble(limelightName, \"tclass\");\n }\n\n /////\n /////\n\n public static Pose3d getBotPose3d(String limelightName) {\n double[] poseArray = getLimelightNTDoubleArray(limelightName, \"botpose\");\n return toPose3D(poseArray);\n }\n\n public static Pose3d getBotPose3d_wpiRed(String limelightName) {\n double[] poseArray = getLimelightNTDoubleArray(limelightName, \"botpose_wpired\");\n return toPose3D(poseArray);\n }\n\n public static Pose3d getBotPose3d_wpiBlue(String limelightName) {\n double[] poseArray = getLimelightNTDoubleArray(limelightName, \"botpose_wpiblue\");\n return toPose3D(poseArray);\n }\n\n public static Pose3d getBotPose3d_TargetSpace(String limelightName) {\n double[] poseArray = getLimelightNTDoubleArray(limelightName, \"botpose_targetspace\");\n return toPose3D(poseArray);\n }\n\n public static Pose3d getCameraPose3d_TargetSpace(String limelightName) {\n double[] poseArray = getLimelightNTDoubleArray(limelightName, \"camerapose_targetspace\");\n return toPose3D(poseArray);\n }\n\n public static Pose3d getTargetPose3d_CameraSpace(String limelightName) {\n double[] poseArray = getLimelightNTDoubleArray(limelightName, \"targetpose_cameraspace\");\n return toPose3D(poseArray);\n }\n\n public static Pose3d getTargetPose3d_RobotSpace(String limelightName) {\n double[] poseArray = getLimelightNTDoubleArray(limelightName, \"targetpose_robotspace\");\n return toPose3D(poseArray);\n }\n\n public static Pose3d getCameraPose3d_RobotSpace(String limelightName) {\n double[] poseArray = getLimelightNTDoubleArray(limelightName, \"camerapose_robotspace\");\n return toPose3D(poseArray);\n }\n\n /**\n * Gets the Pose2d for easy use with Odometry vision pose estimator\n * (addVisionMeasurement)\n * \n * @param limelightName\n * @return\n */\n public static Pose2d getBotPose2d_wpiBlue(String limelightName) {\n\n double[] result = getBotPose_wpiBlue(limelightName);\n return toPose2D(result);\n }\n\n /**\n * Gets the Pose2d for easy use with Odometry vision pose estimator\n * (addVisionMeasurement)\n * \n * @param limelightName\n * @return\n */\n public static Pose2d getBotPose2d_wpiRed(String limelightName) {\n\n double[] result = getBotPose_wpiRed(limelightName);\n return toPose2D(result);\n\n }\n\n /**\n * Gets the Pose2d for easy use with Odometry vision pose estimator\n * (addVisionMeasurement)\n * \n * @param limelightName\n * @return\n */\n public static Pose2d getBotPose2d(String limelightName) {\n\n double[] result = getBotPose(limelightName);\n return toPose2D(result);\n\n }\n\n public static boolean getTV(String limelightName) {\n return 1.0 == getLimelightNTDouble(limelightName, \"tv\");\n }\n\n /////\n /////\n\n public static void setPipelineIndex(String limelightName, int pipelineIndex) {\n setLimelightNTDouble(limelightName, \"pipeline\", pipelineIndex);\n }\n\n /**\n * The LEDs will be controlled by Limelight pipeline settings, and not by robot\n * code.\n */\n public static void setLEDMode_PipelineControl(String limelightName) {\n setLimelightNTDouble(limelightName, \"ledMode\", 0);\n }\n\n public static void setLEDMode_ForceOff(String limelightName) {\n setLimelightNTDouble(limelightName, \"ledMode\", 1);\n }\n\n public static void setLEDMode_ForceBlink(String limelightName) {\n setLimelightNTDouble(limelightName, \"ledMode\", 2);\n }\n\n public static void setLEDMode_ForceOn(String limelightName) {\n setLimelightNTDouble(limelightName, \"ledMode\", 3);\n }\n\n public static void setStreamMode_Standard(String limelightName) {\n setLimelightNTDouble(limelightName, \"stream\", 0);\n }\n\n public static void setStreamMode_PiPMain(String limelightName) {\n setLimelightNTDouble(limelightName, \"stream\", 1);\n }\n\n public static void setStreamMode_PiPSecondary(String limelightName) {\n setLimelightNTDouble(limelightName, \"stream\", 2);\n }\n\n public static void setCameraMode_Processor(String limelightName) {\n setLimelightNTDouble(limelightName, \"camMode\", 0);\n }\n public static void setCameraMode_Driver(String limelightName) {\n setLimelightNTDouble(limelightName, \"camMode\", 1);\n }\n\n\n /**\n * Sets the crop window. The crop window in the UI must be completely open for\n * dynamic cropping to work.\n */\n public static void setCropWindow(String limelightName, double cropXMin, double cropXMax, double cropYMin, double cropYMax) {\n double[] entries = new double[4];\n entries[0] = cropXMin;\n entries[1] = cropXMax;\n entries[2] = cropYMin;\n entries[3] = cropYMax;\n setLimelightNTDoubleArray(limelightName, \"crop\", entries);\n }\n\n public static void setCameraPose_RobotSpace(String limelightName, double forward, double side, double up, double roll, double pitch, double yaw) {\n double[] entries = new double[6];\n entries[0] = forward;\n entries[1] = side;\n entries[2] = up;\n entries[3] = roll;\n entries[4] = pitch;\n entries[5] = yaw;\n setLimelightNTDoubleArray(limelightName, \"camerapose_robotspace_set\", entries);\n }\n\n /////\n /////\n\n public static void setPythonScriptData(String limelightName, double[] outgoingPythonData) {\n setLimelightNTDoubleArray(limelightName, \"llrobot\", outgoingPythonData);\n }\n\n public static double[] getPythonScriptData(String limelightName) {\n return getLimelightNTDoubleArray(limelightName, \"llpython\");\n }\n\n /////\n /////\n\n /**\n * Asynchronously take snapshot.\n */\n public static CompletableFuture<Boolean> takeSnapshot(String tableName, String snapshotName) {\n return CompletableFuture.supplyAsync(() -> {\n return SYNCH_TAKESNAPSHOT(tableName, snapshotName);\n });\n }\n\n private static boolean SYNCH_TAKESNAPSHOT(String tableName, String snapshotName) {\n URL url = getLimelightURLString(tableName, \"capturesnapshot\");\n try {\n HttpURLConnection connection = (HttpURLConnection) url.openConnection();\n connection.setRequestMethod(\"GET\");\n if (snapshotName != null && snapshotName != \"\") {\n connection.setRequestProperty(\"snapname\", snapshotName);\n }\n\n int responseCode = connection.getResponseCode();\n if (responseCode == 200) {\n return true;\n } else {\n System.err.println(\"Bad LL Request\");\n }\n } catch (IOException e) {\n System.err.println(e.getMessage());\n }\n return false;\n }\n\n /**\n * Parses Limelight's JSON results dump into a LimelightResults Object\n */\n public static LimelightResults getLatestResults(String limelightName) {\n\n long start = System.nanoTime();\n LimelightHelpers.LimelightResults results = new LimelightHelpers.LimelightResults();\n if (mapper == null) {\n mapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);\n }\n\n try {\n results = mapper.readValue(getJSONDump(limelightName), LimelightResults.class);\n } catch (JsonProcessingException e) {\n System.err.println(\"lljson error: \" + e.getMessage());\n }\n\n long end = System.nanoTime();\n double millis = (end - start) * .000001;\n results.targetingResults.latency_jsonParse = millis;\n if (profileJSON) {\n System.out.printf(\"lljson: %.2f\\r\\n\", millis);\n }\n\n return results;\n }\n}" }, { "identifier": "VisionConfig", "path": "src/main/java/frc/robot/Constants.java", "snippet": "public final static class VisionConfig {\n public final static String CAM_NAME = \"\";\n}" }, { "identifier": "LimelightResults", "path": "src/main/java/frc/robot/LimelightHelpers.java", "snippet": "public static class LimelightResults {\n @JsonProperty(\"Results\")\n public Results targetingResults;\n\n public LimelightResults() {\n targetingResults = new Results();\n }\n}" }, { "identifier": "LimelightTarget_Fiducial", "path": "src/main/java/frc/robot/LimelightHelpers.java", "snippet": "public static class LimelightTarget_Fiducial {\n\n @JsonProperty(\"fID\")\n public double fiducialID;\n\n @JsonProperty(\"fam\")\n public String fiducialFamily;\n\n @JsonProperty(\"t6c_ts\")\n private double[] cameraPose_TargetSpace;\n\n @JsonProperty(\"t6r_fs\")\n private double[] robotPose_FieldSpace;\n\n @JsonProperty(\"t6r_ts\")\n private double[] robotPose_TargetSpace;\n\n @JsonProperty(\"t6t_cs\")\n private double[] targetPose_CameraSpace;\n\n @JsonProperty(\"t6t_rs\")\n private double[] targetPose_RobotSpace;\n\n public Pose3d getCameraPose_TargetSpace()\n {\n return toPose3D(cameraPose_TargetSpace);\n }\n public Pose3d getRobotPose_FieldSpace()\n {\n return toPose3D(robotPose_FieldSpace);\n }\n public Pose3d getRobotPose_TargetSpace()\n {\n return toPose3D(robotPose_TargetSpace);\n }\n public Pose3d getTargetPose_CameraSpace()\n {\n return toPose3D(targetPose_CameraSpace);\n }\n public Pose3d getTargetPose_RobotSpace()\n {\n return toPose3D(targetPose_RobotSpace);\n }\n\n public Pose2d getCameraPose_TargetSpace2D()\n {\n return toPose2D(cameraPose_TargetSpace);\n }\n public Pose2d getRobotPose_FieldSpace2D()\n {\n return toPose2D(robotPose_FieldSpace);\n }\n public Pose2d getRobotPose_TargetSpace2D()\n {\n return toPose2D(robotPose_TargetSpace);\n }\n public Pose2d getTargetPose_CameraSpace2D()\n {\n return toPose2D(targetPose_CameraSpace);\n }\n public Pose2d getTargetPose_RobotSpace2D()\n {\n return toPose2D(targetPose_RobotSpace);\n }\n \n @JsonProperty(\"ta\")\n public double ta;\n\n @JsonProperty(\"tx\")\n public double tx;\n\n @JsonProperty(\"txp\")\n public double tx_pixels;\n\n @JsonProperty(\"ty\")\n public double ty;\n\n @JsonProperty(\"typ\")\n public double ty_pixels;\n\n @JsonProperty(\"ts\")\n public double ts;\n \n public LimelightTarget_Fiducial() {\n cameraPose_TargetSpace = new double[6];\n robotPose_FieldSpace = new double[6];\n robotPose_TargetSpace = new double[6];\n targetPose_CameraSpace = new double[6];\n targetPose_RobotSpace = new double[6];\n }\n}" }, { "identifier": "Results", "path": "src/main/java/frc/robot/LimelightHelpers.java", "snippet": "public static class Results {\n\n @JsonProperty(\"pID\")\n public double pipelineID;\n\n @JsonProperty(\"tl\")\n public double latency_pipeline;\n\n @JsonProperty(\"cl\")\n public double latency_capture;\n\n public double latency_jsonParse;\n\n @JsonProperty(\"ts\")\n public double timestamp_LIMELIGHT_publish;\n\n @JsonProperty(\"ts_rio\")\n public double timestamp_RIOFPGA_capture;\n\n @JsonProperty(\"v\")\n @JsonFormat(shape = Shape.NUMBER)\n public boolean valid;\n\n @JsonProperty(\"botpose\")\n public double[] botpose;\n\n @JsonProperty(\"botpose_wpired\")\n public double[] botpose_wpired;\n\n @JsonProperty(\"botpose_wpiblue\")\n public double[] botpose_wpiblue;\n\n @JsonProperty(\"t6c_rs\")\n public double[] camerapose_robotspace;\n\n public Pose3d getBotPose3d() {\n return toPose3D(botpose);\n }\n \n public Pose3d getBotPose3d_wpiRed() {\n return toPose3D(botpose_wpired);\n }\n \n public Pose3d getBotPose3d_wpiBlue() {\n return toPose3D(botpose_wpiblue);\n }\n\n public Pose2d getBotPose2d() {\n return toPose2D(botpose);\n }\n \n public Pose2d getBotPose2d_wpiRed() {\n return toPose2D(botpose_wpired);\n }\n \n public Pose2d getBotPose2d_wpiBlue() {\n return toPose2D(botpose_wpiblue);\n }\n\n @JsonProperty(\"Retro\")\n public LimelightTarget_Retro[] targets_Retro;\n\n @JsonProperty(\"Fiducial\")\n public LimelightTarget_Fiducial[] targets_Fiducials;\n\n @JsonProperty(\"Classifier\")\n public LimelightTarget_Classifier[] targets_Classifier;\n\n @JsonProperty(\"Detector\")\n public LimelightTarget_Detector[] targets_Detector;\n\n @JsonProperty(\"Barcode\")\n public LimelightTarget_Barcode[] targets_Barcode;\n\n public Results() {\n botpose = new double[6];\n botpose_wpired = new double[6];\n botpose_wpiblue = new double[6];\n camerapose_robotspace = new double[6];\n targets_Retro = new LimelightTarget_Retro[0];\n targets_Fiducials = new LimelightTarget_Fiducial[0];\n targets_Classifier = new LimelightTarget_Classifier[0];\n targets_Detector = new LimelightTarget_Detector[0];\n targets_Barcode = new LimelightTarget_Barcode[0];\n\n }\n}" } ]
import com.pigmice.frc.lib.shuffleboard_helper.ShuffleboardHelper; import edu.wpi.first.math.geometry.Pose2d; import edu.wpi.first.wpilibj2.command.SubsystemBase; import frc.robot.Constants; import frc.robot.LimelightHelpers; import frc.robot.Constants.VisionConfig; import frc.robot.LimelightHelpers.LimelightResults; import frc.robot.LimelightHelpers.LimelightTarget_Fiducial; import frc.robot.LimelightHelpers.Results;
10,303
package frc.robot.subsystems; public class Vision extends SubsystemBase { private static String camName = VisionConfig.CAM_NAME; private Results targetingResults; private LimelightTarget_Fiducial bestTarget; private boolean hasTarget; public Vision() { ShuffleboardHelper.addOutput("Target X", Constants.VISION_TAB, () -> bestTarget == null ? 0 : bestTarget.tx); ShuffleboardHelper.addOutput("Target Y", Constants.VISION_TAB, () -> bestTarget == null ? 0 : bestTarget.ty); ShuffleboardHelper.addOutput("Bot Pose X", Constants.VISION_TAB, () -> targetingResults == null ? 0 : getEstimatedRobotPose().getX()); ShuffleboardHelper.addOutput("Bot Pose Y", Constants.VISION_TAB, () -> targetingResults == null ? 0 : getEstimatedRobotPose().getY()); ShuffleboardHelper.addOutput("Pose to tag X", Constants.VISION_TAB, () -> targetingResults == null ? 0 : getTranslationToBestTarget().getX()); ShuffleboardHelper.addOutput("Pose to tag Y", Constants.VISION_TAB, () -> targetingResults == null ? 0 : getTranslationToBestTarget().getY()); } @Override public void periodic() {
package frc.robot.subsystems; public class Vision extends SubsystemBase { private static String camName = VisionConfig.CAM_NAME; private Results targetingResults; private LimelightTarget_Fiducial bestTarget; private boolean hasTarget; public Vision() { ShuffleboardHelper.addOutput("Target X", Constants.VISION_TAB, () -> bestTarget == null ? 0 : bestTarget.tx); ShuffleboardHelper.addOutput("Target Y", Constants.VISION_TAB, () -> bestTarget == null ? 0 : bestTarget.ty); ShuffleboardHelper.addOutput("Bot Pose X", Constants.VISION_TAB, () -> targetingResults == null ? 0 : getEstimatedRobotPose().getX()); ShuffleboardHelper.addOutput("Bot Pose Y", Constants.VISION_TAB, () -> targetingResults == null ? 0 : getEstimatedRobotPose().getY()); ShuffleboardHelper.addOutput("Pose to tag X", Constants.VISION_TAB, () -> targetingResults == null ? 0 : getTranslationToBestTarget().getX()); ShuffleboardHelper.addOutput("Pose to tag Y", Constants.VISION_TAB, () -> targetingResults == null ? 0 : getTranslationToBestTarget().getY()); } @Override public void periodic() {
LimelightResults results = LimelightHelpers.getLatestResults(camName);
3
2023-12-30 06:06:45+00:00
12k
Deenu143/GradleParser
app/src/main/java/org/deenu/gradle/script/GradleScript.java
[ { "identifier": "Dependency", "path": "app/src/main/java/org/deenu/gradle/models/Dependency.java", "snippet": "public class Dependency {\n\n private String configuration;\n private String group;\n private String name;\n private String version;\n\n public Dependency(String group, String name, String version) {\n this.group = group;\n this.name = name;\n this.version = version;\n }\n\n public Dependency() {}\n\n public static Dependency fromString(String dependency) {\n String[] values = dependency.split(\":\");\n return new Dependency(values[0], values[1], values[2]);\n }\n\n public void setConfiguration(String configuration) {\n this.configuration = configuration;\n }\n\n public String getConfiguration() {\n return ((configuration != null) ? configuration : \"configuration\");\n }\n\n public void setGroup(String group) {\n this.group = group;\n }\n\n public String getGroup() {\n return group;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getName() {\n return name;\n }\n\n public void setVersion(String version) {\n this.version = version;\n }\n\n public String getVersion() {\n return version;\n }\n\n @Override\n public String toString() {\n return ((configuration != null) ? configuration : \"configuration\")\n + \":\"\n + group\n + \":\"\n + name\n + \":\"\n + version;\n }\n}" }, { "identifier": "FlatDir", "path": "app/src/main/java/org/deenu/gradle/models/FlatDir.java", "snippet": "public class FlatDir {\n\n private String flatdir;\n private List<String> flatdirs;\n\n public FlatDir(String flatdir) {\n this.flatdir = flatdir;\n this.flatdirs = new ArrayList<>();\n this.flatdirs.add(flatdir);\n }\n\n public FlatDir(List<String> flatdirs) {\n this.flatdirs = new ArrayList<>(flatdirs);\n }\n\n public List<String> getFlatDirs() {\n return flatdirs;\n }\n\n @Override\n public String toString() {\n return flatdir;\n }\n}" }, { "identifier": "Include", "path": "app/src/main/java/org/deenu/gradle/models/Include.java", "snippet": "public class Include {\n\n private String include;\n private List<String> includes;\n\n public Include(String include) {\n this.include = include;\n this.includes = new ArrayList<>();\n this.includes.add(include);\n }\n\n public Include(List<String> includes) {\n this.includes = new ArrayList<>(includes);\n }\n\n public List<String> getIncludes() {\n return includes;\n }\n\n @Override\n public String toString() {\n return include;\n }\n}" }, { "identifier": "Plugin", "path": "app/src/main/java/org/deenu/gradle/models/Plugin.java", "snippet": "public class Plugin {\n\n private String plugin;\n private List<String> plugins;\n\n public Plugin(String plugin) {\n this.plugin = plugin;\n this.plugins = new ArrayList<>();\n this.plugins.add(plugin);\n }\n\n public Plugin(List<String> plugins) {\n this.plugins = new ArrayList<>(plugins);\n }\n\n public List<String> getPlugins() {\n return plugins;\n }\n\n @Override\n public String toString() {\n return plugin;\n }\n}" }, { "identifier": "Repository", "path": "app/src/main/java/org/deenu/gradle/models/Repository.java", "snippet": "public class Repository {\n private String repositoryName;\n private String repositoryUrl;\n private Map<String, String> repositories;\n\n public Repository(String repositoryName, String repositoryUrl) {\n this.repositoryName = repositoryName;\n this.repositoryUrl = repositoryUrl;\n this.repositories = new HashMap<>();\n this.repositories.put(repositoryName, repositoryUrl);\n }\n\n public Repository(Map<String, String> repositories) {\n this.repositories = new HashMap<>(repositories);\n }\n\n public Map<String, String> getRepositories() {\n return repositories;\n }\n\n public String getRepositoryName() {\n return repositoryName;\n }\n\n public String getRepositoryUrl() {\n return repositoryUrl;\n }\n\n @Override\n public String toString() {\n return repositoryName + \":\" + repositoryUrl;\n }\n}" }, { "identifier": "UnsupportedFileException", "path": "app/src/main/java/org/deenu/gradle/parser/exception/UnsupportedFileException.java", "snippet": "public class UnsupportedFileException extends Exception {\n\n public UnsupportedFileException(String message, Throwable t) {\n super(message, t);\n }\n\n public UnsupportedFileException(Exception exception) {\n super(exception);\n }\n\n public UnsupportedFileException(String message) {\n super(message);\n }\n}" }, { "identifier": "GradleScriptVisitor", "path": "app/src/main/java/org/deenu/gradle/script/visitors/GradleScriptVisitor.java", "snippet": "public class GradleScriptVisitor extends CodeVisitorSupport {\n\n private Stack<Boolean> blockStatementStack = new Stack<>();\n\n private int pluginsLastLineNumber = -1;\n private String pluginsConfigurationName;\n private boolean inPlugins = false;\n private List<Plugin> plugins = new ArrayList<>();\n\n private int repositoriesLastLineNumber = -1;\n private String repositoriesConfigurationName;\n private boolean inRepositories = false;\n private List<Repository> repositories = new ArrayList<>();\n\n private int buildscriptRepositoriesLastLineNumber = -1;\n private String buildscriptRepositoriesConfigurationName;\n private boolean inBuildScriptRepositories = false;\n private List<Repository> buildscriptRepositories = new ArrayList<>();\n\n private int buildscriptLastLineNumber = -1;\n private String buildscriptConfigurationName;\n private boolean inBuildScript = false;\n\n private int allprojectsLastLineNumber = -1;\n private String allprojectsConfigurationName;\n private boolean inAllProjects = false;\n\n private int allprojectsRepositoriesLastLineNumber = -1;\n private String allprojectsRepositoriesConfigurationName;\n private boolean inAllProjectsRepositories = false;\n private List<Repository> allprojectsRepositories = new ArrayList<>();\n\n private String rootProjectName;\n private int includeLastLineNumber = -1;\n private String includeConfigurationName;\n private boolean inInclude = false;\n private List<Include> includes = new ArrayList<>();\n\n private int flatDirLastLineNumber = -1;\n private String flatDirConfigurationName;\n private boolean inFlatDir = false;\n\n private int allprojectsrepositoriesflatDirLastLineNumber = -1;\n private String allprojectsrepositoriesflatDirConfigurationName;\n private boolean inAllProjectsRepositoriesFlatDir = false;\n\n private int flatDirdirsLastLineNumber = -1;\n private String flatDirdirsConfigurationName;\n private boolean inFlatDirDirs = false;\n\n private int allprojectsrepositoriesflatDirdirsLastLineNumber = -1;\n private String allprojectsrepositoriesflatDirdirsConfigurationName;\n private boolean inAllProjectsRepositoriesFlatDirDirs = false;\n private List<FlatDir> allprojectsrepositoriesflatDirDirs = new ArrayList<>();\n\n private int pluginManagementLastLineNumber = -1;\n private String pluginManagementConfigurationName;\n private boolean inPluginManagement = false;\n\n private int pluginManagementRepositoriesLastLineNumber = -1;\n private String pluginManagementRepositoriesConfigurationName;\n private boolean inPluginManagementRepositories = false;\n private List<Repository> pluginManagementRepositories = new ArrayList<>();\n\n private int dependencyResolutionManagementLastLineNumber = -1;\n private String dependencyResolutionManagementConfigurationName;\n private boolean inDependencyResolutionManagement = false;\n\n private int dependencyResolutionManagementRepositoriesLastLineNumber = -1;\n private String dependencyResolutionManagementRepositoriesConfigurationName;\n private boolean inDependencyResolutionManagementRepositories = false;\n private List<Repository> dependencyResolutionManagementRepositories = new ArrayList<>();\n\n private int dependencyresolutionmanagementrepositoriesflatDirLastLineNumber = -1;\n private String dependencyresolutionmanagementrepositoriesflatDirConfigurationName;\n private boolean inDependencyResolutionManagementRepositoriesFlatDir = false;\n\n private int dependencyresolutionmanagementrepositoriesflatDirdirsLastLineNumber = -1;\n private String dependencyresolutionmanagementrepositoriesflatDirdirsConfigurationName;\n private boolean inDependencyResolutionManagementRepositoriesFlatDirDirs = false;\n private List<FlatDir> dependencyresolutionmanagementrepositoriesflatDirDirs = new ArrayList<>();\n\n private int dependenciesLastLineNumber = -1;\n private String dependenciesConfigurationName;\n private boolean inDependencies = false;\n private List<Dependency> dependencies = new ArrayList<>();\n\n private int buildscriptDependenciesLastLineNumber = -1;\n private String buildscriptDependenciesConfigurationName;\n private boolean inBuildScriptDependencies = false;\n private List<Dependency> buildscriptDependencies = new ArrayList<>();\n\n public int getPluginsLastLineNumber() {\n return pluginsLastLineNumber;\n }\n\n public List<Plugin> getPlugins() {\n return plugins;\n }\n\n public int getRepositoriesLastLineNumber() {\n return repositoriesLastLineNumber;\n }\n\n public List<Repository> getRepositories() {\n return repositories;\n }\n\n public int getBuildScriptLastLineNumber() {\n return buildscriptLastLineNumber;\n }\n\n public int getBuildScriptRepositoriesLastLineNumber() {\n return buildscriptRepositoriesLastLineNumber;\n }\n\n public List<Repository> getBuildScriptRepositories() {\n return buildscriptRepositories;\n }\n\n public int getAllProjectsLastLineNumber() {\n return allprojectsLastLineNumber;\n }\n\n public int getAllProjectsRepositoriesLastLineNumber() {\n return allprojectsRepositoriesLastLineNumber;\n }\n\n public List<Repository> getAllProjectsRepositories() {\n return allprojectsRepositories;\n }\n\n public int getFlatDirLastLineNumber() {\n return flatDirLastLineNumber;\n }\n\n public int getFlatDirDirsLastLineNumber() {\n return flatDirdirsLastLineNumber;\n }\n\n public int getAllProjectsRepositoriesFlatDirLastLineNumber() {\n return allprojectsrepositoriesflatDirLastLineNumber;\n }\n\n public int getAllProjectsRepositoriesFlatDirDirsLastLineNumber() {\n return allprojectsrepositoriesflatDirdirsLastLineNumber;\n }\n\n public List<FlatDir> getAllProjectsRepositoriesFlatDirDirs() {\n return allprojectsrepositoriesflatDirDirs;\n }\n\n public int getPluginManagementLastLineNumber() {\n return pluginManagementLastLineNumber;\n }\n\n public int getPluginManagementRepositoriesLastLineNumber() {\n return pluginManagementRepositoriesLastLineNumber;\n }\n\n public List<Repository> getPluginManagementRepositories() {\n return pluginManagementRepositories;\n }\n\n public int getDependencyResolutionManagementLastLineNumber() {\n return dependencyResolutionManagementLastLineNumber;\n }\n\n public int getDependencyResolutionManagementRepositoriesLastLineNumber() {\n return dependencyResolutionManagementRepositoriesLastLineNumber;\n }\n\n public List<Repository> getDependencyResolutionManagementRepositories() {\n return dependencyResolutionManagementRepositories;\n }\n\n public int getDependencyResolutionManagementRepositoriesFlatDirLastLineNumber() {\n return dependencyresolutionmanagementrepositoriesflatDirLastLineNumber;\n }\n\n public int getDependencyResolutionManagementRepositoriesFlatDirDirsLastLineNumber() {\n return dependencyresolutionmanagementrepositoriesflatDirdirsLastLineNumber;\n }\n\n public List<FlatDir> getDependencyResolutionManagementRepositoriesFlatDirDirs() {\n return dependencyresolutionmanagementrepositoriesflatDirDirs;\n }\n\n public int getDependenciesLastLineNumber() {\n return dependenciesLastLineNumber;\n }\n\n public List<Dependency> getDependencies() {\n return dependencies;\n }\n\n public int getBuildScriptDependenciesLastLineNumber() {\n return buildscriptDependenciesLastLineNumber;\n }\n\n public List<Dependency> getBuildScriptDependencies() {\n return buildscriptDependencies;\n }\n\n public String getRootProjectName() {\n return rootProjectName;\n }\n\n public int getIncludesLastLineNumber() {\n return includeLastLineNumber;\n }\n\n public List<Include> getIncludes() {\n return includes;\n }\n\n @Override\n public void visitArgumentlistExpression(ArgumentListExpression argumentListExpression) {\n\n List<Expression> expressions = argumentListExpression.getExpressions();\n if (expressions != null) {\n\n if ((expressions.size() == 1) && (expressions.get(0) instanceof ConstantExpression)) {\n ConstantExpression constantExpression = (ConstantExpression) expressions.get(0);\n\n if (constantExpression != null) {\n int lineNumber = constantExpression.getLineNumber();\n String expressionText = constantExpression.getText();\n\n if (expressionText != null\n && inPlugins\n && !inBuildScript\n && !inAllProjects\n && !inPluginManagement\n && !inDependencyResolutionManagement) {\n plugins.add(new Plugin(expressionText));\n }\n\n if (expressionText != null\n && repositoriesConfigurationName != null\n && inRepositories\n && !inBuildScript\n && !inAllProjects\n && !inPluginManagement\n && !inDependencyResolutionManagement\n && !inFlatDir) {\n repositories.add(new Repository(repositoriesConfigurationName, expressionText));\n }\n\n if (expressionText != null\n && repositoriesConfigurationName != null\n && inBuildScriptRepositories\n && !inAllProjectsRepositories\n && !inPluginManagementRepositories\n && !inDependencyResolutionManagementRepositories\n && !inFlatDir) {\n\n buildscriptRepositories.add(\n new Repository(repositoriesConfigurationName, expressionText));\n }\n\n if (expressionText != null\n && repositoriesConfigurationName != null\n && inAllProjectsRepositories\n && !inBuildScriptRepositories\n && !inPluginManagementRepositories\n && !inDependencyResolutionManagementRepositories\n && !inFlatDir) {\n allprojectsRepositories.add(\n new Repository(repositoriesConfigurationName, expressionText));\n }\n\n if (expressionText != null\n && repositoriesConfigurationName != null\n && inPluginManagementRepositories\n && !inAllProjectsRepositories\n && !inBuildScriptRepositories\n && !inDependencyResolutionManagementRepositories\n && !inFlatDir) {\n\n pluginManagementRepositories.add(\n new Repository(repositoriesConfigurationName, expressionText));\n }\n\n if (expressionText != null\n && repositoriesConfigurationName != null\n && inDependencyResolutionManagementRepositories\n && !inBuildScriptRepositories\n && !inPluginManagementRepositories\n && !inAllProjectsRepositories\n && !inFlatDir) {\n dependencyResolutionManagementRepositories.add(\n new Repository(repositoriesConfigurationName, expressionText));\n }\n\n if (expressionText != null\n && dependenciesConfigurationName != null\n && !inBuildScript\n && !inAllProjects\n && !inPluginManagement\n && !inDependencyResolutionManagement) {\n\n Dependency dependency = Dependency.fromString(expressionText);\n dependency.setConfiguration(dependenciesConfigurationName);\n dependencies.add(dependency);\n }\n\n if (expressionText != null\n && dependenciesConfigurationName != null\n && inBuildScript\n && !inAllProjects\n && !inPluginManagement\n && !inDependencyResolutionManagement) {\n Dependency dependency = Dependency.fromString(expressionText);\n dependency.setConfiguration(dependenciesConfigurationName);\n buildscriptDependencies.add(dependency);\n }\n\n if (expressionText != null && inInclude) {\n if (includes.isEmpty()) {\n includes.add(new Include(expressionText));\n }\n }\n }\n }\n }\n super.visitArgumentlistExpression(argumentListExpression);\n }\n\n @Override\n public void visitBinaryExpression(BinaryExpression binaryExpression) {\n Expression leftExpression = binaryExpression.getLeftExpression();\n Expression rightExpression = binaryExpression.getRightExpression();\n\n if (leftExpression != null && rightExpression != null) {\n String leftExpressionText = leftExpression.getText();\n String rightExpressionText = rightExpression.getText();\n\n if (leftExpressionText != null && rightExpressionText != null) {\n if (leftExpressionText.equals(\"rootProject.name\")) {\n rootProjectName = rightExpressionText;\n }\n }\n }\n\n super.visitBinaryExpression(binaryExpression);\n }\n\n @Override\n public void visitBlockStatement(BlockStatement blockStatement) {\n\n if (inPlugins) {\n blockStatementStack.push(true);\n super.visitBlockStatement(blockStatement);\n blockStatementStack.pop();\n\n } else if (inRepositories) {\n blockStatementStack.push(true);\n super.visitBlockStatement(blockStatement);\n blockStatementStack.pop();\n\n } else if (inBuildScriptRepositories) {\n blockStatementStack.push(true);\n super.visitBlockStatement(blockStatement);\n blockStatementStack.pop();\n\n } else if (inAllProjectsRepositories) {\n blockStatementStack.push(true);\n super.visitBlockStatement(blockStatement);\n blockStatementStack.pop();\n\n } else if (inAllProjectsRepositories && inAllProjectsRepositoriesFlatDirDirs) {\n\n blockStatementStack.push(true);\n super.visitBlockStatement(blockStatement);\n blockStatementStack.pop();\n\n } else if (inPluginManagementRepositories) {\n blockStatementStack.push(true);\n super.visitBlockStatement(blockStatement);\n blockStatementStack.pop();\n\n } else if (inDependencyResolutionManagementRepositories) {\n blockStatementStack.push(true);\n super.visitBlockStatement(blockStatement);\n blockStatementStack.pop();\n\n } else if (inDependencyResolutionManagementRepositories\n && inDependencyResolutionManagementRepositoriesFlatDirDirs) {\n blockStatementStack.push(true);\n super.visitBlockStatement(blockStatement);\n blockStatementStack.pop();\n\n } else if (inDependencies) {\n blockStatementStack.push(true);\n super.visitBlockStatement(blockStatement);\n blockStatementStack.pop();\n\n } else if (inBuildScriptDependencies) {\n blockStatementStack.push(true);\n super.visitBlockStatement(blockStatement);\n blockStatementStack.pop();\n\n } else {\n super.visitBlockStatement(blockStatement);\n }\n }\n\n @Override\n public void visitMethodCallExpression(MethodCallExpression methodCallExpression) {\n int lineNumber = methodCallExpression.getLineNumber();\n String methodName = methodCallExpression.getMethodAsString();\n\n if (lineNumber > pluginsLastLineNumber) {\n inPlugins = false;\n }\n\n if (lineNumber > repositoriesLastLineNumber) {\n inRepositories = false;\n }\n\n if (lineNumber > buildscriptLastLineNumber) {\n inBuildScript = false;\n }\n\n if (lineNumber > buildscriptRepositoriesLastLineNumber) {\n inBuildScriptRepositories = false;\n }\n\n if (lineNumber > allprojectsLastLineNumber) {\n inAllProjects = false;\n }\n\n if (lineNumber > allprojectsRepositoriesLastLineNumber) {\n inAllProjectsRepositories = false;\n }\n\n if (lineNumber > includeLastLineNumber) {\n inInclude = false;\n }\n\n if (lineNumber > flatDirLastLineNumber) {\n inFlatDir = false;\n }\n\n if (lineNumber > allprojectsrepositoriesflatDirLastLineNumber) {\n inAllProjectsRepositoriesFlatDir = false;\n }\n\n if (lineNumber > flatDirdirsLastLineNumber) {\n inFlatDirDirs = false;\n }\n\n if (lineNumber > allprojectsrepositoriesflatDirdirsLastLineNumber) {\n inAllProjectsRepositoriesFlatDirDirs = false;\n }\n\n if (lineNumber > pluginManagementLastLineNumber) {\n inPluginManagement = false;\n }\n\n if (lineNumber > pluginManagementRepositoriesLastLineNumber) {\n inPluginManagementRepositories = false;\n }\n\n if (lineNumber > dependencyResolutionManagementLastLineNumber) {\n inDependencyResolutionManagement = false;\n }\n\n if (lineNumber > dependencyResolutionManagementRepositoriesLastLineNumber) {\n inDependencyResolutionManagementRepositories = false;\n }\n\n if (lineNumber > dependencyresolutionmanagementrepositoriesflatDirLastLineNumber) {\n inDependencyResolutionManagementRepositoriesFlatDir = false;\n }\n\n if (lineNumber > dependencyresolutionmanagementrepositoriesflatDirdirsLastLineNumber) {\n inDependencyResolutionManagementRepositoriesFlatDirDirs = false;\n }\n\n if (lineNumber > dependenciesLastLineNumber) {\n inDependencies = false;\n }\n\n if (lineNumber > buildscriptDependenciesLastLineNumber) {\n inBuildScriptDependencies = false;\n }\n\n if (methodName.equals(\"plugins\")) {\n pluginsLastLineNumber = methodCallExpression.getLastLineNumber();\n inPlugins = true;\n }\n\n if (methodName.equals(\"repositories\")) {\n repositoriesLastLineNumber = methodCallExpression.getLastLineNumber();\n inRepositories = true;\n }\n\n if (methodName.equals(\"buildscript\")) {\n buildscriptLastLineNumber = methodCallExpression.getLastLineNumber();\n inBuildScript = true;\n }\n\n if (methodName.equals(\"allprojects\")) {\n allprojectsLastLineNumber = methodCallExpression.getLastLineNumber();\n inAllProjects = true;\n }\n\n if (methodName.equals(\"include\")) {\n includeLastLineNumber = methodCallExpression.getLastLineNumber();\n inInclude = true;\n }\n\n if (methodName.equals(\"flatDir\")) {\n flatDirLastLineNumber = methodCallExpression.getLastLineNumber();\n inFlatDir = true;\n }\n\n if (methodName.equals(\"dirs\")) {\n flatDirdirsLastLineNumber = methodCallExpression.getLastLineNumber();\n inFlatDirDirs = true;\n }\n\n if (methodName.equals(\"pluginManagement\")) {\n pluginManagementLastLineNumber = methodCallExpression.getLastLineNumber();\n inPluginManagement = true;\n }\n\n if (methodName.equals(\"dependencyResolutionManagement\")) {\n dependencyResolutionManagementLastLineNumber = methodCallExpression.getLastLineNumber();\n inDependencyResolutionManagement = true;\n }\n\n if (methodName.equals(\"dependencies\")) {\n dependenciesLastLineNumber = methodCallExpression.getLastLineNumber();\n inDependencies = true;\n }\n\n if (inBuildScript && inRepositories) {\n buildscriptRepositoriesLastLineNumber = methodCallExpression.getLastLineNumber();\n inBuildScriptRepositories = true;\n }\n\n if (inAllProjects && inRepositories) {\n allprojectsRepositoriesLastLineNumber = methodCallExpression.getLastLineNumber();\n inAllProjectsRepositories = true;\n }\n\n if (inAllProjects && inRepositories && inFlatDir) {\n allprojectsrepositoriesflatDirLastLineNumber = methodCallExpression.getLastLineNumber();\n inAllProjectsRepositoriesFlatDir = true;\n }\n\n if (inAllProjects && inRepositories && inFlatDir && inFlatDirDirs) {\n allprojectsrepositoriesflatDirdirsLastLineNumber = methodCallExpression.getLastLineNumber();\n inAllProjectsRepositoriesFlatDirDirs = true;\n }\n\n if (inPluginManagement && inRepositories) {\n pluginManagementRepositoriesLastLineNumber = methodCallExpression.getLastLineNumber();\n inPluginManagementRepositories = true;\n }\n\n if (inDependencyResolutionManagement && inRepositories) {\n dependencyResolutionManagementRepositoriesLastLineNumber =\n methodCallExpression.getLastLineNumber();\n inDependencyResolutionManagementRepositories = true;\n }\n\n if (inDependencyResolutionManagement && inRepositories && inFlatDir) {\n dependencyresolutionmanagementrepositoriesflatDirLastLineNumber =\n methodCallExpression.getLastLineNumber();\n inDependencyResolutionManagementRepositoriesFlatDir = true;\n }\n\n if (inDependencyResolutionManagement && inRepositories && inFlatDir && inFlatDirDirs) {\n dependencyresolutionmanagementrepositoriesflatDirdirsLastLineNumber =\n methodCallExpression.getLastLineNumber();\n inDependencyResolutionManagementRepositoriesFlatDirDirs = true;\n }\n\n if (inBuildScript && inDependencies) {\n buildscriptDependenciesLastLineNumber = methodCallExpression.getLastLineNumber();\n inBuildScriptDependencies = true;\n }\n\n if (inRepositories\n && !inBuildScript\n && !inAllProjects\n && !inPluginManagement\n && !inDependencyResolutionManagement\n && !inFlatDir) {\n if (methodName.equals(\"google\")) {\n repositories.add(new Repository(methodName, \"https://maven.google.com/\"));\n }\n if (methodName.equals(\"mavenLocal\")) {\n repositories.add(new Repository(methodName, \".m2/repository\"));\n }\n if (methodName.equals(\"mavenCentral\")) {\n repositories.add(new Repository(methodName, \"https://repo.maven.apache.org/maven2/\"));\n }\n if (methodName.equals(\"gradlePluginPortal\")) {\n repositories.add(new Repository(methodName, \"https://plugins.gradle.org/m2/\"));\n }\n }\n\n if (inBuildScriptRepositories && !inFlatDir) {\n\n if (methodName.equals(\"google\")) {\n buildscriptRepositories.add(new Repository(methodName, \"https://maven.google.com/\"));\n }\n if (methodName.equals(\"mavenLocal\")) {\n buildscriptRepositories.add(new Repository(methodName, \".m2/repository\"));\n }\n if (methodName.equals(\"mavenCentral\")) {\n buildscriptRepositories.add(\n new Repository(methodName, \"https://repo.maven.apache.org/maven2/\"));\n }\n if (methodName.equals(\"gradlePluginPortal\")) {\n buildscriptRepositories.add(new Repository(methodName, \"https://plugins.gradle.org/m2/\"));\n }\n }\n\n if (inAllProjectsRepositories && !inFlatDir) {\n\n if (methodName.equals(\"google\")) {\n allprojectsRepositories.add(new Repository(methodName, \"https://maven.google.com/\"));\n }\n if (methodName.equals(\"mavenLocal\")) {\n allprojectsRepositories.add(new Repository(methodName, \".m2/repository\"));\n }\n if (methodName.equals(\"mavenCentral\")) {\n allprojectsRepositories.add(\n new Repository(methodName, \"https://repo.maven.apache.org/maven2/\"));\n }\n if (methodName.equals(\"gradlePluginPortal\")) {\n allprojectsRepositories.add(new Repository(methodName, \"https://plugins.gradle.org/m2/\"));\n }\n }\n\n if (inAllProjectsRepositories\n && inAllProjectsRepositoriesFlatDirDirs\n && (blockStatementStack.isEmpty() ? false : blockStatementStack.peek())) {\n\n Expression expression = methodCallExpression.getArguments();\n\n if (expression != null && expression instanceof TupleExpression) {\n TupleExpression tupleExpression = (TupleExpression) expression;\n if (tupleExpression != null) {\n for (Expression expr : tupleExpression.getExpressions()) {\n if (expr != null && expr instanceof ConstantExpression) {\n ConstantExpression constantExpression = (ConstantExpression) expr;\n if (constantExpression != null) {\n String constantExpressionText = constantExpression.getText();\n if (constantExpressionText != null) {\n allprojectsrepositoriesflatDirDirs.add(new FlatDir(constantExpressionText));\n }\n }\n }\n }\n }\n }\n }\n\n if (inPluginManagementRepositories && !inFlatDir) {\n\n if (methodName.equals(\"google\")) {\n pluginManagementRepositories.add(new Repository(methodName, \"https://maven.google.com/\"));\n }\n if (methodName.equals(\"mavenLocal\")) {\n pluginManagementRepositories.add(new Repository(methodName, \".m2/repository\"));\n }\n if (methodName.equals(\"mavenCentral\")) {\n pluginManagementRepositories.add(\n new Repository(methodName, \"https://repo.maven.apache.org/maven2/\"));\n }\n if (methodName.equals(\"gradlePluginPortal\")) {\n pluginManagementRepositories.add(\n new Repository(methodName, \"https://plugins.gradle.org/m2/\"));\n }\n }\n\n if (inDependencyResolutionManagementRepositories && !inFlatDir) {\n if (methodName.equals(\"google\")) {\n dependencyResolutionManagementRepositories.add(\n new Repository(methodName, \"https://maven.google.com/\"));\n }\n if (methodName.equals(\"mavenLocal\")) {\n dependencyResolutionManagementRepositories.add(\n new Repository(methodName, \".m2/repository\"));\n }\n if (methodName.equals(\"mavenCentral\")) {\n dependencyResolutionManagementRepositories.add(\n new Repository(methodName, \"https://repo.maven.apache.org/maven2/\"));\n }\n if (methodName.equals(\"gradlePluginPortal\")) {\n dependencyResolutionManagementRepositories.add(\n new Repository(methodName, \"https://plugins.gradle.org/m2/\"));\n }\n }\n\n if (inDependencyResolutionManagementRepositories\n && inDependencyResolutionManagementRepositoriesFlatDirDirs\n && (blockStatementStack.isEmpty() ? false : blockStatementStack.peek())) {\n\n Expression expression = methodCallExpression.getArguments();\n\n if (expression != null && expression instanceof TupleExpression) {\n TupleExpression tupleExpression = (TupleExpression) expression;\n if (tupleExpression != null) {\n for (Expression expr : tupleExpression.getExpressions()) {\n if (expr != null && expr instanceof ConstantExpression) {\n ConstantExpression constantExpression = (ConstantExpression) expr;\n if (constantExpression != null) {\n String constantExpressionText = constantExpression.getText();\n if (constantExpressionText != null) {\n dependencyresolutionmanagementrepositoriesflatDirDirs.add(\n new FlatDir(constantExpressionText));\n }\n }\n }\n }\n }\n }\n }\n\n if (inInclude) {\n\n Expression expression = methodCallExpression.getArguments();\n\n if (expression != null && expression instanceof TupleExpression) {\n TupleExpression tupleExpression = (TupleExpression) expression;\n if (tupleExpression != null) {\n for (Expression expr : tupleExpression.getExpressions()) {\n if (expr != null && expr instanceof ConstantExpression) {\n ConstantExpression constantExpression = (ConstantExpression) expr;\n if (constantExpression != null) {\n String constantExpressionText = constantExpression.getText();\n if (constantExpressionText != null) {\n includes.add(new Include(constantExpressionText));\n }\n }\n }\n }\n }\n }\n }\n\n if (inPlugins && (blockStatementStack.isEmpty() ? false : blockStatementStack.peek())) {\n pluginsConfigurationName = methodName;\n super.visitMethodCallExpression(methodCallExpression);\n pluginsConfigurationName = null;\n\n } else if (inRepositories\n && (blockStatementStack.isEmpty() ? false : blockStatementStack.peek())) {\n repositoriesConfigurationName = methodName;\n super.visitMethodCallExpression(methodCallExpression);\n repositoriesConfigurationName = null;\n\n } else if (inBuildScriptRepositories\n && !(blockStatementStack.isEmpty() ? false : blockStatementStack.peek())) {\n\n buildscriptRepositoriesConfigurationName = methodName;\n super.visitMethodCallExpression(methodCallExpression);\n buildscriptRepositoriesConfigurationName = null;\n\n } else if (inAllProjectsRepositories\n && !(blockStatementStack.isEmpty() ? false : blockStatementStack.peek())) {\n allprojectsRepositoriesConfigurationName = methodName;\n super.visitMethodCallExpression(methodCallExpression);\n allprojectsRepositoriesConfigurationName = null;\n\n } else if (inPluginManagementRepositories\n && !(blockStatementStack.isEmpty() ? false : blockStatementStack.peek())) {\n\n pluginManagementRepositoriesConfigurationName = methodName;\n super.visitMethodCallExpression(methodCallExpression);\n pluginManagementRepositoriesConfigurationName = null;\n\n } else if (inDependencyResolutionManagementRepositories\n && !(blockStatementStack.isEmpty() ? false : blockStatementStack.peek())) {\n dependencyResolutionManagementRepositoriesConfigurationName = methodName;\n\n super.visitMethodCallExpression(methodCallExpression);\n dependencyResolutionManagementRepositoriesConfigurationName = null;\n\n } else if (inInclude) {\n includeConfigurationName = methodName;\n super.visitMethodCallExpression(methodCallExpression);\n includeConfigurationName = null;\n\n } else if (inDependencies\n && (blockStatementStack.isEmpty() ? false : blockStatementStack.peek())) {\n dependenciesConfigurationName = methodName;\n super.visitMethodCallExpression(methodCallExpression);\n dependenciesConfigurationName = null;\n\n } else if (inBuildScriptDependencies\n && !(blockStatementStack.isEmpty() ? false : blockStatementStack.peek())) {\n\n buildscriptDependenciesConfigurationName = methodName;\n super.visitMethodCallExpression(methodCallExpression);\n buildscriptDependenciesConfigurationName = null;\n\n } else {\n super.visitMethodCallExpression(methodCallExpression);\n }\n }\n}" } ]
import java.io.File; import java.io.FileNotFoundException; import java.nio.file.Files; import java.util.List; import org.codehaus.groovy.ast.ASTNode; import org.codehaus.groovy.ast.GroovyCodeVisitor; import org.codehaus.groovy.ast.builder.AstBuilder; import org.deenu.gradle.models.Dependency; import org.deenu.gradle.models.FlatDir; import org.deenu.gradle.models.Include; import org.deenu.gradle.models.Plugin; import org.deenu.gradle.models.Repository; import org.deenu.gradle.parser.exception.UnsupportedFileException; import org.deenu.gradle.script.visitors.GradleScriptVisitor;
8,176
package org.deenu.gradle.script; public class GradleScript { private File gradleFile; private AstBuilder astBuilder; private List<ASTNode> aSTNodes; private String scriptContents; private GradleScriptVisitor gradleScriptVisitor; public GradleScript(File gradleFile) throws Exception, FileNotFoundException { this.gradleFile = gradleFile; if (gradleFile == null || !gradleFile.exists()) { throw new FileNotFoundException("Failed to get '.gradle' or '.gradle.kts' file."); } else if (gradleFile != null) { String fileName = gradleFile.getName(); String[] fileExtensions = new String[] {".gradle", ".gradle.kts"}; if (fileName != null) { if (!fileName.endsWith(fileExtensions[0]) && !fileName.endsWith(fileExtensions[1])) { throw new UnsupportedFileException("Unsupported file: " + gradleFile.getAbsolutePath()); } } } this.scriptContents = new String(Files.readAllBytes(this.gradleFile.toPath())); init(scriptContents, gradleFile); } private void init(String script, File gradleFile) throws Exception { if (script == null || script.isEmpty()) { throw new Exception("Failed to get gradle script from file: " + gradleFile.getAbsolutePath()); } this.astBuilder = new AstBuilder(); this.aSTNodes = getASTNodes(); } public File getGradleFile() { return this.gradleFile; } public String getGradleFileName() { return this.gradleFile.getName(); } public boolean isGradleBuildFile() { return getGradleFileName().startsWith("build.gradle"); } public boolean isGradleSettingsFile() { return getGradleFileName().startsWith("settings.gradle"); } private List<ASTNode> getASTNodes() throws Exception { return this.astBuilder.buildFromString(scriptContents); }
package org.deenu.gradle.script; public class GradleScript { private File gradleFile; private AstBuilder astBuilder; private List<ASTNode> aSTNodes; private String scriptContents; private GradleScriptVisitor gradleScriptVisitor; public GradleScript(File gradleFile) throws Exception, FileNotFoundException { this.gradleFile = gradleFile; if (gradleFile == null || !gradleFile.exists()) { throw new FileNotFoundException("Failed to get '.gradle' or '.gradle.kts' file."); } else if (gradleFile != null) { String fileName = gradleFile.getName(); String[] fileExtensions = new String[] {".gradle", ".gradle.kts"}; if (fileName != null) { if (!fileName.endsWith(fileExtensions[0]) && !fileName.endsWith(fileExtensions[1])) { throw new UnsupportedFileException("Unsupported file: " + gradleFile.getAbsolutePath()); } } } this.scriptContents = new String(Files.readAllBytes(this.gradleFile.toPath())); init(scriptContents, gradleFile); } private void init(String script, File gradleFile) throws Exception { if (script == null || script.isEmpty()) { throw new Exception("Failed to get gradle script from file: " + gradleFile.getAbsolutePath()); } this.astBuilder = new AstBuilder(); this.aSTNodes = getASTNodes(); } public File getGradleFile() { return this.gradleFile; } public String getGradleFileName() { return this.gradleFile.getName(); } public boolean isGradleBuildFile() { return getGradleFileName().startsWith("build.gradle"); } public boolean isGradleSettingsFile() { return getGradleFileName().startsWith("settings.gradle"); } private List<ASTNode> getASTNodes() throws Exception { return this.astBuilder.buildFromString(scriptContents); }
public List<Plugin> getPlugins() {
3
2023-12-27 10:10:31+00:00
12k
Prototik/TheConfigLib
common/src/main/java/dev/tcl/gui/controllers/ColorController.java
[ { "identifier": "Option", "path": "common/src/main/java/dev/tcl/api/Option.java", "snippet": "public interface Option<T> {\n /**\n * Name of the option\n */\n @NotNull Component name();\n\n @NotNull OptionDescription description();\n\n /**\n * Widget provider for a type of option.\n *\n * @see dev.thaumcraft.tcl.gui.controllers\n */\n @NotNull Controller<T> controller();\n\n /**\n * Binding for the option.\n * Controls setting, getting and default value.\n *\n * @see Binding\n */\n @NotNull Binding<T> binding();\n\n /**\n * If the option can be configured\n */\n boolean available();\n\n /**\n * Sets if the option can be configured after being built\n *\n * @see Option#available()\n */\n void setAvailable(boolean available);\n\n /**\n * Tasks that needs to be executed upon applying changes.\n */\n @NotNull ImmutableSet<OptionFlag> flags();\n\n /**\n * Checks if the pending value is not equal to the current set value\n */\n boolean changed();\n\n /**\n * Value in the GUI, ready to set the actual bound value or be undone.\n */\n @NotNull T pendingValue();\n\n /**\n * Sets the pending value\n */\n void requestSet(@NotNull T value);\n\n /**\n * Applies the pending value to the bound value.\n * Cannot be undone.\n *\n * @return if there were changes to apply {@link Option#changed()}\n */\n boolean applyValue();\n\n /**\n * Sets the pending value to the bound value.\n */\n void forgetPendingValue();\n\n /**\n * Sets the pending value to the default bound value.\n */\n void requestSetDefault();\n\n /**\n * Checks if the current pending value is equal to its default value\n */\n boolean isPendingValueDefault();\n\n default boolean canResetToDefault() {\n return true;\n }\n\n /**\n * Adds a listener for when the pending value changes\n */\n void addListener(BiConsumer<Option<T>, T> changedListener);\n\n static <T> Builder<T> createBuilder() {\n return new OptionImpl.BuilderImpl<>();\n }\n\n interface Builder<T> {\n /**\n * Sets the name to be used by the option.\n *\n * @see Option#name()\n */\n Builder<T> name(@NotNull Component name);\n\n /**\n * Sets the description to be used by the option.\n * @see OptionDescription\n * @param description the static description.\n * @return this builder\n */\n Builder<T> description(@NotNull OptionDescription description);\n\n /**\n * Sets the function to get the description by the option's current value.\n *\n * @see OptionDescription\n * @param descriptionFunction the function to get the description by the option's current value.\n * @return this builder\n */\n Builder<T> description(@NotNull Function<T, OptionDescription> descriptionFunction);\n\n Builder<T> controller(@NotNull Function<Option<T>, ControllerBuilder<T>> controllerBuilder);\n\n /**\n * Sets the controller for the option.\n * This is how you interact and change the options.\n *\n * @see dev.thaumcraft.tcl.gui.controllers\n */\n Builder<T> customController(@NotNull Function<Option<T>, Controller<T>> control);\n\n /**\n * Sets the binding for the option.\n * Used for default, getter and setter.\n *\n * @see Binding\n */\n Builder<T> binding(@NotNull Binding<T> binding);\n\n /**\n * Sets the binding for the option.\n * Shorthand of {@link Binding#generic(Object, Supplier, Consumer)}\n *\n * @param def default value of the option, used to reset\n * @param getter should return the current value of the option\n * @param setter should set the option to the supplied value\n * @see Binding\n */\n Builder<T> binding(@NotNull T def, @NotNull Supplier<@NotNull T> getter, @NotNull Consumer<@NotNull T> setter);\n\n /**\n * Sets if the option can be configured\n *\n * @see Option#available()\n */\n Builder<T> available(boolean available);\n\n /**\n * Adds a flag to the option.\n * Upon applying changes, all flags are executed.\n * {@link Option#flags()}\n */\n Builder<T> flag(@NotNull OptionFlag... flag);\n\n /**\n * Adds a flag to the option.\n * Upon applying changes, all flags are executed.\n * {@link Option#flags()}\n */\n Builder<T> flags(@NotNull Collection<? extends OptionFlag> flags);\n\n /**\n * Instantly invokes the binder's setter when modified in the GUI.\n * Prevents the user from undoing the change\n * <p>\n * Does not support {@link Option#flags()}!\n */\n Builder<T> instant(boolean instant);\n\n /**\n * Adds a listener to the option. Invoked upon changing the pending value.\n *\n * @see Option#addListener(BiConsumer)\n */\n Builder<T> listener(@NotNull BiConsumer<Option<T>, T> listener);\n\n /**\n * Adds multiple listeners to the option. Invoked upon changing the pending value.\n *\n * @see Option#addListener(BiConsumer)\n */\n Builder<T> listeners(@NotNull Collection<BiConsumer<Option<T>, T>> listeners);\n\n Option<T> build();\n }\n}" }, { "identifier": "Dimension", "path": "common/src/main/java/dev/tcl/api/utils/Dimension.java", "snippet": "public interface Dimension<T extends Number> {\n T x();\n T y();\n\n T width();\n T height();\n\n T xLimit();\n T yLimit();\n\n T centerX();\n T centerY();\n\n boolean isPointInside(T x, T y);\n\n MutableDimension<T> copy();\n\n Dimension<T> withX(T x);\n Dimension<T> withY(T y);\n Dimension<T> withWidth(T width);\n Dimension<T> withHeight(T height);\n\n Dimension<T> moved(T x, T y);\n Dimension<T> expanded(T width, T height);\n\n static MutableDimension<Integer> ofInt(int x, int y, int width, int height) {\n return new DimensionIntegerImpl(x, y, width, height);\n }\n}" }, { "identifier": "MutableDimension", "path": "common/src/main/java/dev/tcl/api/utils/MutableDimension.java", "snippet": "public interface MutableDimension<T extends Number> extends Dimension<T> {\n MutableDimension<T> setX(T x);\n MutableDimension<T> setY(T y);\n MutableDimension<T> setWidth(T width);\n MutableDimension<T> setHeight(T height);\n\n MutableDimension<T> move(T x, T y);\n MutableDimension<T> expand(T width, T height);\n}" }, { "identifier": "IStringController", "path": "common/src/main/java/dev/tcl/gui/controllers/string/IStringController.java", "snippet": "public interface IStringController<T> extends Controller<T> {\n /**\n * Gets the option's pending value as a string.\n *\n * @see Option#pendingValue()\n */\n String getString();\n\n /**\n * Sets the option's pending value from a string.\n *\n * @see Option#requestSet(Object)\n */\n void setFromString(String value);\n\n /**\n * {@inheritDoc}\n */\n @Override\n default Component formatValue() {\n return Component.literal(getString());\n }\n\n default boolean isInputValid(String input) {\n return true;\n }\n\n @Override\n default AbstractWidget provideWidget(TCLScreen screen, Dimension<Integer> widgetDimension) {\n return new StringControllerElement(this, screen, widgetDimension, true);\n }\n}" }, { "identifier": "StringControllerElement", "path": "common/src/main/java/dev/tcl/gui/controllers/string/StringControllerElement.java", "snippet": "public class StringControllerElement extends ControllerWidget<IStringController<?>> {\n protected final boolean instantApply;\n\n protected String inputField;\n protected Dimension<Integer> inputFieldBounds;\n protected boolean inputFieldFocused;\n\n protected int caretPos;\n protected int previousCaretPos;\n protected int selectionLength;\n protected int renderOffset;\n\n protected UndoRedoHelper undoRedoHelper;\n\n protected float ticks;\n protected float caretTicks;\n\n private final Component emptyText;\n\n public StringControllerElement(IStringController<?> control, TCLScreen screen, Dimension<Integer> dim, boolean instantApply) {\n super(control, screen, dim);\n this.instantApply = instantApply;\n inputField = control.getString();\n inputFieldFocused = false;\n selectionLength = 0;\n emptyText = Component.literal(\"Click to type...\").withStyle(ChatFormatting.GRAY);\n control.option().addListener((opt, val) -> {\n inputField = control.getString();\n });\n setDimension(dim);\n }\n\n @Override\n protected void drawValueText(GuiGraphics graphics, int mouseX, int mouseY, float delta) {\n Component valueText = getValueText();\n if (!isHovered()) valueText = Component.literal(GuiUtils.shortenString(valueText.getString(), textRenderer, getMaxUnwrapLength(), \"...\")).setStyle(valueText.getStyle());\n\n int textX = getDimension().xLimit() - textRenderer.width(valueText) + renderOffset - getXPadding();\n graphics.enableScissor(inputFieldBounds.x(), inputFieldBounds.y() - 2, inputFieldBounds.xLimit() + 1, inputFieldBounds.yLimit() + 4);\n graphics.drawString(textRenderer, valueText, textX, getTextY(), getValueColor(), true);\n\n if (isHovered()) {\n ticks += delta;\n\n String text = getValueText().getString();\n\n graphics.fill(inputFieldBounds.x(), inputFieldBounds.yLimit(), inputFieldBounds.xLimit(), inputFieldBounds.yLimit() + 1, -1);\n graphics.fill(inputFieldBounds.x() + 1, inputFieldBounds.yLimit() + 1, inputFieldBounds.xLimit() + 1, inputFieldBounds.yLimit() + 2, 0xFF404040);\n\n if (inputFieldFocused || focused) {\n if (caretPos > text.length())\n caretPos = text.length();\n\n int caretX = textX + textRenderer.width(text.substring(0, caretPos));\n if (text.isEmpty())\n caretX = inputFieldBounds.x() + inputFieldBounds.width() / 2;\n\n if (selectionLength != 0) {\n int selectionX = textX + textRenderer.width(text.substring(0, caretPos + selectionLength));\n graphics.fill(caretX, inputFieldBounds.y() - 2, selectionX, inputFieldBounds.yLimit() - 1, 0x803030FF);\n }\n\n if(caretPos != previousCaretPos) {\n previousCaretPos = caretPos;\n caretTicks = 0;\n }\n\n if ((caretTicks += delta) % 20 <= 10)\n graphics.fill(caretX, inputFieldBounds.y() - 2, caretX + 1, inputFieldBounds.yLimit() - 1, -1);\n }\n }\n graphics.disableScissor();\n }\n\n @Override\n public boolean mouseClicked(double mouseX, double mouseY, int button) {\n if (isAvailable() && getDimension().isPointInside((int) mouseX, (int) mouseY)) {\n inputFieldFocused = true;\n\n if (!inputFieldBounds.isPointInside((int) mouseX, (int) mouseY)) {\n caretPos = getDefaultCaretPos();\n } else {\n // gets the appropriate caret position for where you click\n int textX = (int) mouseX - (inputFieldBounds.xLimit() - textRenderer.width(getValueText()));\n int pos = -1;\n int currentWidth = 0;\n for (char ch : inputField.toCharArray()) {\n pos++;\n int charLength = textRenderer.width(String.valueOf(ch));\n if (currentWidth + charLength / 2 > textX) { // if more than halfway past the characters select in front of that char\n caretPos = pos;\n break;\n } else if (pos == inputField.length() - 1) {\n // if we have reached the end and no matches, it must be the second half of the char so the last position\n caretPos = pos + 1;\n }\n currentWidth += charLength;\n }\n\n selectionLength = 0;\n }\n// if (undoRedoHelper == null) {\n// undoRedoHelper = new UndoRedoHelper(inputField, caretPos, selectionLength);\n// }\n\n return true;\n } else {\n unfocus();\n }\n\n return false;\n }\n\n protected int getDefaultCaretPos() {\n return inputField.length();\n }\n\n @Override\n public boolean keyPressed(int keyCode, int scanCode, int modifiers) {\n if (!inputFieldFocused)\n return false;\n\n switch (keyCode) {\n case InputConstants.KEY_ESCAPE, InputConstants.KEY_RETURN -> {\n unfocus();\n return true;\n }\n case InputConstants.KEY_LEFT -> {\n if (Screen.hasShiftDown()) {\n if (Screen.hasControlDown()) {\n int spaceChar = findSpaceIndex(true);\n selectionLength += caretPos - spaceChar;\n caretPos = spaceChar;\n } else if (caretPos > 0) {\n caretPos--;\n selectionLength += 1;\n }\n checkRenderOffset();\n } else {\n if (caretPos > 0) {\n if (Screen.hasControlDown()) {\n caretPos = findSpaceIndex(true);\n } else {\n if (selectionLength != 0) {\n caretPos += Math.min(selectionLength, 0);\n } else caretPos--;\n }\n }\n checkRenderOffset();\n selectionLength = 0;\n }\n\n return true;\n }\n case InputConstants.KEY_RIGHT -> {\n if (Screen.hasShiftDown()) {\n if (Screen.hasControlDown()) {\n int spaceChar = findSpaceIndex(false);\n selectionLength -= spaceChar - caretPos;\n caretPos = spaceChar;\n } else if (caretPos < inputField.length()) {\n caretPos++;\n selectionLength -= 1;\n }\n checkRenderOffset();\n } else {\n if (caretPos < inputField.length()) {\n if (Screen.hasControlDown()) {\n caretPos = findSpaceIndex(false);\n } else {\n if (selectionLength != 0) {\n caretPos += Math.max(selectionLength, 0);\n } else caretPos++;\n }\n checkRenderOffset();\n }\n selectionLength = 0;\n }\n\n return true;\n }\n case InputConstants.KEY_BACKSPACE -> {\n doBackspace();\n return true;\n }\n case InputConstants.KEY_DELETE -> {\n doDelete();\n return true;\n }\n case InputConstants.KEY_END -> {\n if (Screen.hasShiftDown()) {\n selectionLength -= inputField.length() - caretPos;\n } else selectionLength = 0;\n caretPos = inputField.length();\n checkRenderOffset();\n return true;\n }\n case InputConstants.KEY_HOME -> {\n if (Screen.hasShiftDown()) {\n selectionLength += caretPos;\n caretPos = 0;\n } else {\n caretPos = 0;\n selectionLength = 0;\n }\n checkRenderOffset();\n return true;\n }\n// case InputConstants.KEY_Z -> {\n// if (Screen.hasControlDown()) {\n// UndoRedoHelper.FieldState updated = Screen.hasShiftDown() ? undoRedoHelper.redo() : undoRedoHelper.undo();\n// if (updated != null) {\n// System.out.println(\"Updated: \" + updated);\n// if (modifyInput(builder -> builder.replace(0, inputField.length(), updated.text()))) {\n// caretPos = updated.cursorPos();\n// selectionLength = updated.selectionLength();\n// checkRenderOffset();\n// }\n// }\n// return true;\n// }\n// }\n }\n\n if (Screen.isPaste(keyCode)) {\n return doPaste();\n } else if (Screen.isCopy(keyCode)) {\n return doCopy();\n } else if (Screen.isCut(keyCode)) {\n return doCut();\n } else if (Screen.isSelectAll(keyCode)) {\n return doSelectAll();\n }\n\n return false;\n }\n\n protected boolean doPaste() {\n this.write(client.keyboardHandler.getClipboard());\n updateUndoHistory();\n return true;\n }\n\n protected boolean doCopy() {\n if (selectionLength != 0) {\n client.keyboardHandler.setClipboard(getSelection());\n return true;\n }\n return false;\n }\n\n protected boolean doCut() {\n if (selectionLength != 0) {\n client.keyboardHandler.setClipboard(getSelection());\n this.write(\"\");\n updateUndoHistory();\n return true;\n }\n return false;\n }\n\n protected boolean doSelectAll() {\n caretPos = inputField.length();\n checkRenderOffset();\n selectionLength = -caretPos;\n return true;\n }\n\n protected void checkRenderOffset() {\n if (textRenderer.width(inputField) < getUnshiftedLength()) {\n renderOffset = 0;\n return;\n }\n\n int textX = getDimension().xLimit() - textRenderer.width(inputField) - getXPadding();\n int caretX = textX + textRenderer.width(inputField.substring(0, caretPos));\n\n int minX = getDimension().xLimit() - getXPadding() - getUnshiftedLength();\n int maxX = minX + getUnshiftedLength();\n\n if (caretX + renderOffset < minX) {\n renderOffset = minX - caretX;\n } else if (caretX + renderOffset > maxX) {\n renderOffset = maxX - caretX;\n }\n }\n\n @Override\n public boolean charTyped(char chr, int modifiers) {\n if (!inputFieldFocused)\n return false;\n\n if (!Screen.hasControlDown()) {\n write(Character.toString(chr));\n updateUndoHistory();\n return true;\n }\n\n return false;\n }\n\n protected void doBackspace() {\n if (selectionLength != 0) {\n write(\"\");\n } else if (caretPos > 0) {\n if (modifyInput(builder -> builder.deleteCharAt(caretPos - 1))) {\n caretPos--;\n checkRenderOffset();\n }\n }\n updateUndoHistory();\n }\n\n protected void doDelete() {\n if (selectionLength != 0) {\n write(\"\");\n } else if (caretPos < inputField.length()) {\n modifyInput(builder -> builder.deleteCharAt(caretPos));\n }\n updateUndoHistory();\n }\n\n public void write(String string) {\n if (selectionLength == 0) {\n if (modifyInput(builder -> builder.insert(caretPos, string))) {\n caretPos += string.length();\n checkRenderOffset();\n }\n } else {\n int start = getSelectionStart();\n int end = getSelectionEnd();\n\n if (modifyInput(builder -> builder.replace(start, end, string))) {\n caretPos = start + string.length();\n selectionLength = 0;\n checkRenderOffset();\n }\n }\n }\n\n public boolean modifyInput(Consumer<StringBuilder> consumer) {\n StringBuilder temp = new StringBuilder(inputField);\n consumer.accept(temp);\n if (!control.isInputValid(temp.toString()))\n return false;\n inputField = temp.toString();\n if (instantApply)\n updateControl();\n return true;\n }\n\n protected void updateUndoHistory() {\n// undoRedoHelper.save(inputField, caretPos, selectionLength);\n }\n\n public int getUnshiftedLength() {\n if (optionNameString.isEmpty())\n return getDimension().width() - getXPadding() * 2;\n return getDimension().width() / 8 * 5;\n }\n\n public int getMaxUnwrapLength() {\n if (optionNameString.isEmpty())\n return getDimension().width() - getXPadding() * 2;\n return getDimension().width() / 2;\n }\n\n public int getSelectionStart() {\n return Math.min(caretPos, caretPos + selectionLength);\n }\n\n public int getSelectionEnd() {\n return Math.max(caretPos, caretPos + selectionLength);\n }\n\n protected String getSelection() {\n return inputField.substring(getSelectionStart(), getSelectionEnd());\n }\n\n protected int findSpaceIndex(boolean reverse) {\n int i;\n int fromIndex = caretPos;\n if (reverse) {\n if (caretPos > 0)\n fromIndex -= 2;\n i = this.inputField.lastIndexOf(\" \", fromIndex) + 1;\n } else {\n if (caretPos < inputField.length())\n fromIndex += 1;\n i = this.inputField.indexOf(\" \", fromIndex) + 1;\n\n if (i == 0) i = inputField.length();\n }\n\n return i;\n }\n\n @Override\n public void setFocused(boolean focused) {\n super.setFocused(focused);\n inputFieldFocused = focused;\n }\n\n @Override\n public void unfocus() {\n super.unfocus();\n inputFieldFocused = false;\n renderOffset = 0;\n if (!instantApply) updateControl();\n }\n\n @Override\n public void setDimension(Dimension<Integer> dim) {\n super.setDimension(dim);\n\n int width = Math.max(6, Math.min(textRenderer.width(getValueText()), getUnshiftedLength()));\n inputFieldBounds = Dimension.ofInt(dim.xLimit() - getXPadding() - width, dim.centerY() - textRenderer.lineHeight / 2, width, textRenderer.lineHeight);\n }\n\n @Override\n public boolean isHovered() {\n return super.isHovered() || inputFieldFocused;\n }\n\n protected void updateControl() {\n control.setFromString(inputField);\n }\n\n @Override\n protected int getUnhoveredControlWidth() {\n return !isHovered() ? Math.min(getHoveredControlWidth(), getMaxUnwrapLength()) : getHoveredControlWidth();\n }\n\n @Override\n protected int getHoveredControlWidth() {\n return Math.min(textRenderer.width(getValueText()), getUnshiftedLength());\n }\n\n @Override\n protected Component getValueText() {\n if (!inputFieldFocused && inputField.isEmpty())\n return emptyText;\n\n return instantApply || !inputFieldFocused ? control.formatValue() : Component.literal(inputField);\n }\n}" }, { "identifier": "AbstractWidget", "path": "common/src/main/java/dev/tcl/gui/AbstractWidget.java", "snippet": "@Environment(EnvType.CLIENT)\npublic abstract class AbstractWidget implements GuiEventListener, Renderable, NarratableEntry {\n private static final WidgetSprites SPRITES = new WidgetSprites(\n new ResourceLocation(\"widget/button\"), // normal\n new ResourceLocation(\"widget/button_disabled\"), // disabled & !focused\n new ResourceLocation(\"widget/button_highlighted\"), // !disabled & focused\n new ResourceLocation(\"widget/slider_highlighted\") // disabled & focused\n );\n\n protected final Minecraft client = Minecraft.getInstance();\n protected final Font textRenderer = client.font;\n protected final int inactiveColor = 0xFFA0A0A0;\n\n private dev.tcl.api.utils.Dimension<Integer> dim;\n\n public AbstractWidget(dev.tcl.api.utils.Dimension<Integer> dim) {\n this.dim = dim;\n }\n\n public boolean canReset() {\n return false;\n }\n\n @Override\n public boolean isMouseOver(double mouseX, double mouseY) {\n if (dim == null) return false;\n return this.dim.isPointInside((int) mouseX, (int) mouseY);\n }\n\n public void setDimension(dev.tcl.api.utils.Dimension<Integer> dim) {\n this.dim = dim;\n }\n\n public Dimension<Integer> getDimension() {\n return dim;\n }\n\n @Override\n public @NotNull NarrationPriority narrationPriority() {\n return NarrationPriority.NONE;\n }\n\n public void unfocus() {\n\n }\n\n public boolean matchesSearch(String query) {\n return true;\n }\n\n @Override\n public void updateNarration(NarrationElementOutput builder) {\n\n }\n\n protected void drawButtonRect(GuiGraphics graphics, int x1, int y1, int x2, int y2, boolean hovered, boolean enabled) {\n if (x1 > x2) {\n int xx1 = x1;\n x1 = x2;\n x2 = xx1;\n }\n if (y1 > y2) {\n int yy1 = y1;\n y1 = y2;\n y2 = yy1;\n }\n int width = x2 - x1;\n int height = y2 - y1;\n\n graphics.blitSprite(SPRITES.get(enabled, hovered), x1, y1, width, height);\n }\n\n protected void drawOutline(GuiGraphics graphics, int x1, int y1, int x2, int y2, int width, int color) {\n graphics.fill(x1, y1, x2, y1 + width, color);\n graphics.fill(x2, y1, x2 - width, y2, color);\n graphics.fill(x1, y2, x2, y2 - width, color);\n graphics.fill(x1, y1, x1 + width, y2, color);\n }\n\n protected int multiplyColor(int hex, float amount) {\n Color color = new Color(hex, true);\n\n return new Color(Math.max((int)(color.getRed() * amount), 0),\n Math.max((int)(color.getGreen() * amount), 0),\n Math.max((int)(color.getBlue() * amount), 0),\n color.getAlpha()).getRGB();\n }\n\n public void playDownSound() {\n Minecraft.getInstance().getSoundManager().play(SimpleSoundInstance.forUI(SoundEvents.UI_BUTTON_CLICK, 1.0F));\n }\n}" }, { "identifier": "TCLScreen", "path": "common/src/main/java/dev/tcl/gui/TCLScreen.java", "snippet": "@Environment(EnvType.CLIENT)\npublic class TCLScreen extends Screen {\n public final TheConfigLib config;\n\n private final Screen parent;\n\n public final TabManager tabManager = new TabManager(this::addRenderableWidget, this::removeWidget);\n public TabNavigationBar tabNavigationBar;\n public ScreenRectangle tabArea;\n\n public Component saveButtonMessage;\n public Tooltip saveButtonTooltipMessage;\n private int saveButtonMessageTime;\n\n private boolean pendingChanges;\n\n public TCLScreen(TheConfigLib config, Screen parent) {\n super(config.title());\n this.config = config;\n this.parent = parent;\n\n OptionUtils.forEachOptions(config, option -> {\n option.addListener((opt, val) -> onOptionsChanged());\n });\n }\n\n @Override\n protected void init() {\n int currentTab = tabNavigationBar != null\n ? tabNavigationBar.tabs.indexOf(tabManager.getCurrentTab())\n : 0;\n if (currentTab == -1)\n currentTab = 0;\n\n tabNavigationBar = new ScrollableNavigationBar(this.width, tabManager, config.categories()\n .stream()\n .map(category -> {\n if (category instanceof PlaceholderCategory placeholder)\n return new PlaceholderTab(placeholder);\n return new CategoryTab(category);\n }).toList());\n tabNavigationBar.selectTab(currentTab, false);\n tabNavigationBar.arrangeElements();\n ScreenRectangle navBarArea = tabNavigationBar.getRectangle();\n tabArea = new ScreenRectangle(0, navBarArea.height() - 1, this.width, this.height - navBarArea.height() + 1);\n tabManager.setTabArea(tabArea);\n addRenderableWidget(tabNavigationBar);\n\n config.initConsumer().accept(this);\n }\n\n @Override\n public void render(GuiGraphics graphics, int mouseX, int mouseY, float delta) {\n renderDirtBackground(graphics);\n super.render(graphics, mouseX, mouseY, delta);\n }\n\n protected void finishOrSave() {\n saveButtonMessage = null;\n\n if (pendingChanges()) {\n Set<OptionFlag> flags = new HashSet<>();\n OptionUtils.forEachOptions(config, option -> {\n if (option.applyValue()) {\n flags.addAll(option.flags());\n }\n });\n OptionUtils.forEachOptions(config, option -> {\n if (option.changed()) {\n // if still changed after applying, reset to the current value from binding\n // as something has gone wrong.\n option.forgetPendingValue();\n TheConfigLib.LOGGER.error(\"Option '{}' value mismatch after applying! Reset to binding's getter.\", option.name().getString());\n }\n });\n config.saveFunction().run();\n onOptionsChanged();\n flags.forEach(flag -> flag.accept(minecraft));\n } else onClose();\n }\n\n protected void cancelOrReset() {\n if (pendingChanges()) { // if pending changes, button acts as a cancel button\n OptionUtils.forEachOptions(config, Option::forgetPendingValue);\n onClose();\n } else { // if not, button acts as a reset button\n OptionUtils.forEachOptions(config, Option::requestSetDefault);\n }\n }\n\n protected void undo() {\n OptionUtils.forEachOptions(config, Option::forgetPendingValue);\n }\n\n @Override\n public void tick() {\n if (tabManager.getCurrentTab() instanceof TabExt tabExt) {\n tabExt.tick();\n }\n\n if (tabManager.getCurrentTab() instanceof CategoryTab categoryTab) {\n if (saveButtonMessage != null) {\n if (saveButtonMessageTime > 140) {\n saveButtonMessage = null;\n saveButtonTooltipMessage = null;\n saveButtonMessageTime = 0;\n } else {\n saveButtonMessageTime++;\n categoryTab.saveFinishedButton.setMessage(saveButtonMessage);\n if (saveButtonTooltipMessage != null) {\n categoryTab.saveFinishedButton.setTooltip(saveButtonTooltipMessage);\n }\n }\n }\n }\n }\n\n private void setSaveButtonMessage(Component message, Component tooltip) {\n saveButtonMessage = message;\n saveButtonTooltipMessage = Tooltip.create(tooltip);\n saveButtonMessageTime = 0;\n }\n\n private boolean pendingChanges() {\n return pendingChanges;\n }\n\n private void onOptionsChanged() {\n pendingChanges = false;\n\n OptionUtils.consumeOptions(config, opt -> {\n pendingChanges |= opt.changed();\n return pendingChanges;\n });\n\n if (tabManager.getCurrentTab() instanceof CategoryTab categoryTab) {\n categoryTab.updateButtons();\n }\n }\n\n @Override\n public boolean shouldCloseOnEsc() {\n if (pendingChanges()) {\n setSaveButtonMessage(Component.translatable(\"tcl.gui.save_before_exit\").withStyle(ChatFormatting.RED), Component.translatable(\"tcl.gui.save_before_exit.tooltip\"));\n return false;\n }\n return true;\n }\n\n @Override\n public void onClose() {\n minecraft.setScreen(parent);\n }\n\n public static void renderMultilineTooltip(GuiGraphics graphics, Font font, MultiLineLabel text, int centerX, int yAbove, int yBelow, int screenWidth, int screenHeight) {\n if (text.getLineCount() > 0) {\n int maxWidth = text.getWidth();\n int lineHeight = font.lineHeight + 1;\n int height = text.getLineCount() * lineHeight - 1;\n\n int belowY = yBelow + 12;\n int aboveY = yAbove - height + 12;\n int maxBelow = screenHeight - (belowY + height);\n int minAbove = aboveY - height;\n int y = aboveY;\n if (minAbove < 8)\n y = maxBelow > minAbove ? belowY : aboveY;\n\n int x = Math.max(centerX - text.getWidth() / 2 - 12, -6);\n\n int drawX = x + 12;\n int drawY = y - 12;\n\n graphics.pose().pushPose();\n Tesselator tesselator = Tesselator.getInstance();\n BufferBuilder bufferBuilder = tesselator.getBuilder();\n RenderSystem.setShader(GameRenderer::getPositionColorShader);\n bufferBuilder.begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_COLOR);\n TooltipRenderUtil.renderTooltipBackground(\n graphics,\n drawX,\n drawY,\n maxWidth,\n height,\n 400\n );\n RenderSystem.enableDepthTest();\n RenderSystem.enableBlend();\n RenderSystem.defaultBlendFunc();\n BufferUploader.drawWithShader(bufferBuilder.end());\n RenderSystem.disableBlend();\n graphics.pose().translate(0.0, 0.0, 400.0);\n\n text.renderLeftAligned(graphics, drawX, drawY, lineHeight, -1);\n\n graphics.pose().popPose();\n }\n }\n\n public class CategoryTab implements TabExt {\n private final ConfigCategory category;\n private final Tooltip tooltip;\n\n private ListHolderWidget<OptionListWidget> optionList;\n public final Button saveFinishedButton;\n private final Button cancelResetButton;\n private final Button undoButton;\n private final SearchFieldWidget searchField;\n private OptionDescriptionWidget descriptionWidget;\n\n public CategoryTab(ConfigCategory category) {\n this.category = category;\n this.tooltip = Tooltip.create(category.tooltip());\n\n int columnWidth = width / 3;\n int padding = columnWidth / 20;\n columnWidth = Math.min(columnWidth, 400);\n int paddedWidth = columnWidth - padding * 2;\n MutableDimension<Integer> actionDim = Dimension.ofInt(width / 3 * 2 + width / 6, height - padding - 20, paddedWidth, 20);\n\n saveFinishedButton = Button.builder(Component.literal(\"Done\"), btn -> finishOrSave())\n .pos(actionDim.x() - actionDim.width() / 2, actionDim.y())\n .size(actionDim.width(), actionDim.height())\n .build();\n\n actionDim.expand(-actionDim.width() / 2 - 2, 0).move(-actionDim.width() / 2 - 2, -22);\n cancelResetButton = Button.builder(Component.literal(\"Cancel\"), btn -> cancelOrReset())\n .pos(actionDim.x() - actionDim.width() / 2, actionDim.y())\n .size(actionDim.width(), actionDim.height())\n .build();\n\n actionDim.move(actionDim.width() + 4, 0);\n undoButton = Button.builder(Component.translatable(\"tcl.gui.undo\"), btn -> undo())\n .pos(actionDim.x() - actionDim.width() / 2, actionDim.y())\n .size(actionDim.width(), actionDim.height())\n .tooltip(Tooltip.create(Component.translatable(\"tcl.gui.undo.tooltip\")))\n .build();\n\n searchField = new SearchFieldWidget(\n font,\n width / 3 * 2 + width / 6 - paddedWidth / 2 + 1,\n undoButton.getY() - 22,\n paddedWidth - 2, 18,\n Component.translatable(\"gui.recipebook.search_hint\"),\n Component.translatable(\"gui.recipebook.search_hint\"),\n searchQuery -> optionList.getList().updateSearchQuery(searchQuery)\n );\n\n this.optionList = new ListHolderWidget<>(\n () -> new ScreenRectangle(tabArea.position(), tabArea.width() / 3 * 2 + 1, tabArea.height()),\n new OptionListWidget(TCLScreen.this, category, minecraft, 0, 0, width / 3 * 2 + 1, height, desc -> {\n descriptionWidget.setOptionDescription(desc);\n })\n );\n\n descriptionWidget = new OptionDescriptionWidget(\n () -> new ScreenRectangle(\n width / 3 * 2 + padding,\n tabArea.top() + padding,\n paddedWidth,\n searchField.getY() - 1 - tabArea.top() - padding * 2\n ),\n null\n );\n\n updateButtons();\n }\n\n @Override\n public @NotNull Component getTabTitle() {\n return category.name();\n }\n\n @Override\n public void visitChildren(Consumer<AbstractWidget> consumer) {\n consumer.accept(optionList);\n consumer.accept(saveFinishedButton);\n consumer.accept(cancelResetButton);\n consumer.accept(undoButton);\n consumer.accept(searchField);\n consumer.accept(descriptionWidget);\n }\n\n @Override\n public void doLayout(ScreenRectangle screenRectangle) {\n\n }\n\n @Override\n public void tick() {\n descriptionWidget.tick();\n }\n\n @Nullable\n @Override\n public Tooltip getTooltip() {\n return tooltip;\n }\n\n public void updateButtons() {\n boolean pendingChanges = pendingChanges();\n\n undoButton.active = pendingChanges;\n saveFinishedButton.setMessage(pendingChanges ? Component.translatable(\"tcl.gui.save\") : GuiUtils.translatableFallback(\"tcl.gui.done\", CommonComponents.GUI_DONE));\n saveFinishedButton.setTooltip(new TCLTooltip(pendingChanges ? Component.translatable(\"tcl.gui.save.tooltip\") : Component.translatable(\"tcl.gui.finished.tooltip\"), saveFinishedButton));\n cancelResetButton.setMessage(pendingChanges ? GuiUtils.translatableFallback(\"tcl.gui.cancel\", CommonComponents.GUI_CANCEL) : Component.translatable(\"controls.reset\"));\n cancelResetButton.setTooltip(new TCLTooltip(pendingChanges ? Component.translatable(\"tcl.gui.cancel.tooltip\") : Component.translatable(\"tcl.gui.reset.tooltip\"), cancelResetButton));\n }\n }\n\n public class PlaceholderTab implements TabExt {\n private final PlaceholderCategory category;\n private final Tooltip tooltip;\n\n public PlaceholderTab(PlaceholderCategory category) {\n this.category = category;\n this.tooltip = Tooltip.create(category.tooltip());\n }\n\n @Override\n public @NotNull Component getTabTitle() {\n return category.name();\n }\n\n @Override\n public void visitChildren(Consumer<AbstractWidget> consumer) {\n\n }\n\n @Override\n public void doLayout(ScreenRectangle screenRectangle) {\n minecraft.setScreen(category.screen().apply(minecraft, TCLScreen.this));\n }\n\n @Override\n public @Nullable Tooltip getTooltip() {\n return this.tooltip;\n }\n }\n}" } ]
import com.google.common.collect.ImmutableList; import dev.tcl.api.Option; import dev.tcl.api.utils.Dimension; import dev.tcl.api.utils.MutableDimension; import dev.tcl.gui.controllers.string.IStringController; import dev.tcl.gui.controllers.string.StringControllerElement; import dev.tcl.gui.AbstractWidget; import dev.tcl.gui.TCLScreen; import net.minecraft.ChatFormatting; import net.minecraft.client.gui.GuiGraphics; import net.minecraft.network.chat.Component; import net.minecraft.network.chat.MutableComponent; import java.awt.*; import java.util.List;
9,981
package dev.tcl.gui.controllers; /** * A color controller that uses a hex color field as input. */ public class ColorController implements IStringController<Color> { private final Option<Color> option; private final boolean allowAlpha; /** * Constructs a color controller with {@link ColorController#allowAlpha()} defaulting to false * * @param option bound option */ public ColorController(Option<Color> option) { this(option, false); } /** * Constructs a color controller * * @param option bound option * @param allowAlpha allows the color input to accept alpha values */ public ColorController(Option<Color> option, boolean allowAlpha) { this.option = option; this.allowAlpha = allowAlpha; } /** * {@inheritDoc} */ @Override public Option<Color> option() { return option; } public boolean allowAlpha() { return allowAlpha; } @Override public String getString() { return formatValue().getString(); } @Override public Component formatValue() { MutableComponent text = Component.literal("#"); text.append(Component.literal(toHex(option().pendingValue().getRed())).withStyle(ChatFormatting.RED)); text.append(Component.literal(toHex(option().pendingValue().getGreen())).withStyle(ChatFormatting.GREEN)); text.append(Component.literal(toHex(option().pendingValue().getBlue())).withStyle(ChatFormatting.BLUE)); if (allowAlpha()) text.append(toHex(option().pendingValue().getAlpha())); return text; } private String toHex(int value) { String hex = Integer.toString(value, 16).toUpperCase(); if (hex.length() == 1) hex = "0" + hex; return hex; } @Override public void setFromString(String value) { if (value.startsWith("#")) value = value.substring(1); int red = Integer.parseInt(value.substring(0, 2), 16); int green = Integer.parseInt(value.substring(2, 4), 16); int blue = Integer.parseInt(value.substring(4, 6), 16); if (allowAlpha()) { int alpha = Integer.parseInt(value.substring(6, 8), 16); option().requestSet(new Color(red, green, blue, alpha)); } else { option().requestSet(new Color(red, green, blue)); } } @Override public AbstractWidget provideWidget(TCLScreen screen, dev.tcl.api.utils.Dimension<Integer> widgetDimension) { return new ColorControllerElement(this, screen, widgetDimension); } public static class ColorControllerElement extends StringControllerElement { private final ColorController colorController;
package dev.tcl.gui.controllers; /** * A color controller that uses a hex color field as input. */ public class ColorController implements IStringController<Color> { private final Option<Color> option; private final boolean allowAlpha; /** * Constructs a color controller with {@link ColorController#allowAlpha()} defaulting to false * * @param option bound option */ public ColorController(Option<Color> option) { this(option, false); } /** * Constructs a color controller * * @param option bound option * @param allowAlpha allows the color input to accept alpha values */ public ColorController(Option<Color> option, boolean allowAlpha) { this.option = option; this.allowAlpha = allowAlpha; } /** * {@inheritDoc} */ @Override public Option<Color> option() { return option; } public boolean allowAlpha() { return allowAlpha; } @Override public String getString() { return formatValue().getString(); } @Override public Component formatValue() { MutableComponent text = Component.literal("#"); text.append(Component.literal(toHex(option().pendingValue().getRed())).withStyle(ChatFormatting.RED)); text.append(Component.literal(toHex(option().pendingValue().getGreen())).withStyle(ChatFormatting.GREEN)); text.append(Component.literal(toHex(option().pendingValue().getBlue())).withStyle(ChatFormatting.BLUE)); if (allowAlpha()) text.append(toHex(option().pendingValue().getAlpha())); return text; } private String toHex(int value) { String hex = Integer.toString(value, 16).toUpperCase(); if (hex.length() == 1) hex = "0" + hex; return hex; } @Override public void setFromString(String value) { if (value.startsWith("#")) value = value.substring(1); int red = Integer.parseInt(value.substring(0, 2), 16); int green = Integer.parseInt(value.substring(2, 4), 16); int blue = Integer.parseInt(value.substring(4, 6), 16); if (allowAlpha()) { int alpha = Integer.parseInt(value.substring(6, 8), 16); option().requestSet(new Color(red, green, blue, alpha)); } else { option().requestSet(new Color(red, green, blue)); } } @Override public AbstractWidget provideWidget(TCLScreen screen, dev.tcl.api.utils.Dimension<Integer> widgetDimension) { return new ColorControllerElement(this, screen, widgetDimension); } public static class ColorControllerElement extends StringControllerElement { private final ColorController colorController;
protected MutableDimension<Integer> colorPreviewDim;
2
2023-12-25 14:48:27+00:00
12k
Man2Dev/N-Queen
lib/jfreechart-1.0.19/source/org/jfree/chart/labels/SymbolicXYItemLabelGenerator.java
[ { "identifier": "RegularTimePeriod", "path": "lib/jfreechart-1.0.19/source/org/jfree/data/time/RegularTimePeriod.java", "snippet": "public abstract class RegularTimePeriod implements TimePeriod, Comparable,\r\n MonthConstants {\r\n\r\n /**\r\n * Creates a time period that includes the specified millisecond, assuming\r\n * the given time zone.\r\n *\r\n * @param c the time period class.\r\n * @param millisecond the time.\r\n * @param zone the time zone.\r\n *\r\n * @return The time period.\r\n */\r\n public static RegularTimePeriod createInstance(Class c, Date millisecond,\r\n TimeZone zone) {\r\n RegularTimePeriod result = null;\r\n try {\r\n Constructor constructor = c.getDeclaredConstructor(\r\n new Class[] {Date.class, TimeZone.class});\r\n result = (RegularTimePeriod) constructor.newInstance(\r\n new Object[] {millisecond, zone});\r\n }\r\n catch (Exception e) {\r\n // do nothing, so null is returned\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Returns a subclass of {@link RegularTimePeriod} that is smaller than\r\n * the specified class.\r\n *\r\n * @param c a subclass of {@link RegularTimePeriod}.\r\n *\r\n * @return A class.\r\n */\r\n public static Class downsize(Class c) {\r\n if (c.equals(Year.class)) {\r\n return Quarter.class;\r\n }\r\n else if (c.equals(Quarter.class)) {\r\n return Month.class;\r\n }\r\n else if (c.equals(Month.class)) {\r\n return Day.class;\r\n }\r\n else if (c.equals(Day.class)) {\r\n return Hour.class;\r\n }\r\n else if (c.equals(Hour.class)) {\r\n return Minute.class;\r\n }\r\n else if (c.equals(Minute.class)) {\r\n return Second.class;\r\n }\r\n else if (c.equals(Second.class)) {\r\n return Millisecond.class;\r\n }\r\n else {\r\n return Millisecond.class;\r\n }\r\n }\r\n\r\n /**\r\n * Returns the time period preceding this one, or <code>null</code> if some\r\n * lower limit has been reached.\r\n *\r\n * @return The previous time period (possibly <code>null</code>).\r\n */\r\n public abstract RegularTimePeriod previous();\r\n\r\n /**\r\n * Returns the time period following this one, or <code>null</code> if some\r\n * limit has been reached.\r\n *\r\n * @return The next time period (possibly <code>null</code>).\r\n */\r\n public abstract RegularTimePeriod next();\r\n\r\n /**\r\n * Returns a serial index number for the time unit.\r\n *\r\n * @return The serial index number.\r\n */\r\n public abstract long getSerialIndex();\r\n\r\n //////////////////////////////////////////////////////////////////////////\r\n\r\n /**\r\n * The default time zone.\r\n *\r\n * @deprecated As of 1.0.11, we discourage the use of this field - use\r\n * {@link TimeZone#getDefault()} instead.\r\n */\r\n public static final TimeZone DEFAULT_TIME_ZONE = TimeZone.getDefault();\r\n\r\n /**\r\n * A working calendar (recycle to avoid unnecessary object creation).\r\n *\r\n * @deprecated This was a bad idea, don't use it!\r\n */\r\n public static final Calendar WORKING_CALENDAR = Calendar.getInstance(\r\n DEFAULT_TIME_ZONE);\r\n\r\n /**\r\n * Recalculates the start date/time and end date/time for this time period\r\n * relative to the supplied calendar (which incorporates a time zone).\r\n *\r\n * @param calendar the calendar (<code>null</code> not permitted).\r\n *\r\n * @since 1.0.3\r\n */\r\n public abstract void peg(Calendar calendar);\r\n\r\n /**\r\n * Returns the date/time that marks the start of the time period. This\r\n * method returns a new <code>Date</code> instance every time it is called.\r\n *\r\n * @return The start date/time.\r\n *\r\n * @see #getFirstMillisecond()\r\n */\r\n @Override\r\n public Date getStart() {\r\n return new Date(getFirstMillisecond());\r\n }\r\n\r\n /**\r\n * Returns the date/time that marks the end of the time period. This\r\n * method returns a new <code>Date</code> instance every time it is called.\r\n *\r\n * @return The end date/time.\r\n *\r\n * @see #getLastMillisecond()\r\n */\r\n @Override\r\n public Date getEnd() {\r\n return new Date(getLastMillisecond());\r\n }\r\n\r\n /**\r\n * Returns the first millisecond of the time period. This will be\r\n * determined relative to the time zone specified in the constructor, or\r\n * in the calendar instance passed in the most recent call to the\r\n * {@link #peg(Calendar)} method.\r\n *\r\n * @return The first millisecond of the time period.\r\n *\r\n * @see #getLastMillisecond()\r\n */\r\n public abstract long getFirstMillisecond();\r\n\r\n /**\r\n * Returns the first millisecond of the time period, evaluated within a\r\n * specific time zone.\r\n *\r\n * @param zone the time zone (<code>null</code> not permitted).\r\n *\r\n * @return The first millisecond of the time period.\r\n *\r\n * @deprecated As of 1.0.3, you should avoid using this method (it creates\r\n * a new Calendar instance every time it is called). You are advised\r\n * to call {@link #getFirstMillisecond(Calendar)} instead.\r\n *\r\n * @see #getLastMillisecond(TimeZone)\r\n */\r\n public long getFirstMillisecond(TimeZone zone) {\r\n Calendar calendar = Calendar.getInstance(zone);\r\n return getFirstMillisecond(calendar);\r\n }\r\n\r\n /**\r\n * Returns the first millisecond of the time period, evaluated using the\r\n * supplied calendar (which incorporates a timezone).\r\n *\r\n * @param calendar the calendar (<code>null</code> not permitted).\r\n *\r\n * @return The first millisecond of the time period.\r\n *\r\n * @throws NullPointerException if {@code calendar} is {@code null}.\r\n *\r\n * @see #getLastMillisecond(Calendar)\r\n */\r\n public abstract long getFirstMillisecond(Calendar calendar);\r\n\r\n /**\r\n * Returns the last millisecond of the time period. This will be\r\n * determined relative to the time zone specified in the constructor, or\r\n * in the calendar instance passed in the most recent call to the\r\n * {@link #peg(Calendar)} method.\r\n *\r\n * @return The last millisecond of the time period.\r\n *\r\n * @see #getFirstMillisecond()\r\n */\r\n public abstract long getLastMillisecond();\r\n\r\n /**\r\n * Returns the last millisecond of the time period, evaluated within a\r\n * specific time zone.\r\n *\r\n * @param zone the time zone (<code>null</code> not permitted).\r\n *\r\n * @return The last millisecond of the time period.\r\n *\r\n * @deprecated As of 1.0.3, you should avoid using this method (it creates\r\n * a new Calendar instance every time it is called). You are advised\r\n * to call {@link #getLastMillisecond(Calendar)} instead.\r\n *\r\n * @see #getFirstMillisecond(TimeZone)\r\n */\r\n public long getLastMillisecond(TimeZone zone) {\r\n Calendar calendar = Calendar.getInstance(zone);\r\n return getLastMillisecond(calendar);\r\n }\r\n\r\n /**\r\n * Returns the last millisecond of the time period, evaluated using the\r\n * supplied calendar (which incorporates a timezone).\r\n *\r\n * @param calendar the calendar (<code>null</code> not permitted).\r\n *\r\n * @return The last millisecond of the time period.\r\n *\r\n * @see #getFirstMillisecond(Calendar)\r\n */\r\n public abstract long getLastMillisecond(Calendar calendar);\r\n\r\n /**\r\n * Returns the millisecond closest to the middle of the time period.\r\n *\r\n * @return The middle millisecond.\r\n */\r\n public long getMiddleMillisecond() {\r\n long m1 = getFirstMillisecond();\r\n long m2 = getLastMillisecond();\r\n return m1 + (m2 - m1) / 2;\r\n }\r\n\r\n /**\r\n * Returns the millisecond closest to the middle of the time period,\r\n * evaluated within a specific time zone.\r\n *\r\n * @param zone the time zone (<code>null</code> not permitted).\r\n *\r\n * @return The middle millisecond.\r\n *\r\n * @deprecated As of 1.0.3, you should avoid using this method (it creates\r\n * a new Calendar instance every time it is called). You are advised\r\n * to call {@link #getMiddleMillisecond(Calendar)} instead.\r\n */\r\n public long getMiddleMillisecond(TimeZone zone) {\r\n Calendar calendar = Calendar.getInstance(zone);\r\n long m1 = getFirstMillisecond(calendar);\r\n long m2 = getLastMillisecond(calendar);\r\n return m1 + (m2 - m1) / 2;\r\n }\r\n\r\n /**\r\n * Returns the millisecond closest to the middle of the time period,\r\n * evaluated using the supplied calendar (which incorporates a timezone).\r\n *\r\n * @param calendar the calendar.\r\n *\r\n * @return The middle millisecond.\r\n */\r\n public long getMiddleMillisecond(Calendar calendar) {\r\n long m1 = getFirstMillisecond(calendar);\r\n long m2 = getLastMillisecond(calendar);\r\n return m1 + (m2 - m1) / 2;\r\n }\r\n\r\n /**\r\n * Returns the millisecond (relative to the epoch) corresponding to the \r\n * specified <code>anchor</code> using the supplied <code>calendar</code> \r\n * (which incorporates a time zone).\r\n * \r\n * @param anchor the anchor (<code>null</code> not permitted).\r\n * @param calendar the calendar (<code>null</code> not permitted).\r\n * \r\n * @return Milliseconds since the epoch.\r\n * \r\n * @since 1.0.18\r\n */\r\n public long getMillisecond(TimePeriodAnchor anchor, Calendar calendar) {\r\n if (anchor.equals(TimePeriodAnchor.START)) {\r\n return getFirstMillisecond(calendar);\r\n } else if (anchor.equals(TimePeriodAnchor.MIDDLE)) {\r\n return getMiddleMillisecond(calendar);\r\n } else if (anchor.equals(TimePeriodAnchor.END)) {\r\n return getLastMillisecond(calendar);\r\n } else {\r\n throw new IllegalStateException(\"Unrecognised anchor: \" + anchor);\r\n }\r\n }\r\n \r\n /**\r\n * Returns a string representation of the time period.\r\n *\r\n * @return The string.\r\n */\r\n @Override\r\n public String toString() {\r\n return String.valueOf(getStart());\r\n }\r\n\r\n}\r" }, { "identifier": "TimeSeriesCollection", "path": "lib/jfreechart-1.0.19/source/org/jfree/data/time/TimeSeriesCollection.java", "snippet": "public class TimeSeriesCollection extends AbstractIntervalXYDataset\r\n implements XYDataset, IntervalXYDataset, DomainInfo, XYDomainInfo,\r\n XYRangeInfo, VetoableChangeListener, Serializable {\r\n\r\n /** For serialization. */\r\n private static final long serialVersionUID = 834149929022371137L;\r\n\r\n /** Storage for the time series. */\r\n private List data;\r\n\r\n /** A working calendar (to recycle) */\r\n private Calendar workingCalendar;\r\n\r\n /**\r\n * The point within each time period that is used for the X value when this\r\n * collection is used as an {@link org.jfree.data.xy.XYDataset}. This can\r\n * be the start, middle or end of the time period.\r\n */\r\n private TimePeriodAnchor xPosition;\r\n\r\n /**\r\n * A flag that indicates that the domain is 'points in time'. If this\r\n * flag is true, only the x-value is used to determine the range of values\r\n * in the domain, the start and end x-values are ignored.\r\n *\r\n * @deprecated No longer used (as of 1.0.1).\r\n */\r\n private boolean domainIsPointsInTime;\r\n\r\n /**\r\n * Constructs an empty dataset, tied to the default timezone.\r\n */\r\n public TimeSeriesCollection() {\r\n this(null, TimeZone.getDefault());\r\n }\r\n\r\n /**\r\n * Constructs an empty dataset, tied to a specific timezone.\r\n *\r\n * @param zone the timezone (<code>null</code> permitted, will use\r\n * <code>TimeZone.getDefault()</code> in that case).\r\n */\r\n public TimeSeriesCollection(TimeZone zone) {\r\n // FIXME: need a locale as well as a timezone\r\n this(null, zone);\r\n }\r\n\r\n /**\r\n * Constructs a dataset containing a single series (more can be added),\r\n * tied to the default timezone.\r\n *\r\n * @param series the series (<code>null</code> permitted).\r\n */\r\n public TimeSeriesCollection(TimeSeries series) {\r\n this(series, TimeZone.getDefault());\r\n }\r\n\r\n /**\r\n * Constructs a dataset containing a single series (more can be added),\r\n * tied to a specific timezone.\r\n *\r\n * @param series a series to add to the collection (<code>null</code>\r\n * permitted).\r\n * @param zone the timezone (<code>null</code> permitted, will use\r\n * <code>TimeZone.getDefault()</code> in that case).\r\n */\r\n public TimeSeriesCollection(TimeSeries series, TimeZone zone) {\r\n // FIXME: need a locale as well as a timezone\r\n if (zone == null) {\r\n zone = TimeZone.getDefault();\r\n }\r\n this.workingCalendar = Calendar.getInstance(zone);\r\n this.data = new ArrayList();\r\n if (series != null) {\r\n this.data.add(series);\r\n series.addChangeListener(this);\r\n }\r\n this.xPosition = TimePeriodAnchor.START;\r\n this.domainIsPointsInTime = true;\r\n\r\n }\r\n\r\n /**\r\n * Returns a flag that controls whether the domain is treated as 'points in\r\n * time'. This flag is used when determining the max and min values for\r\n * the domain. If <code>true</code>, then only the x-values are considered\r\n * for the max and min values. If <code>false</code>, then the start and\r\n * end x-values will also be taken into consideration.\r\n *\r\n * @return The flag.\r\n *\r\n * @deprecated This flag is no longer used (as of 1.0.1).\r\n */\r\n public boolean getDomainIsPointsInTime() {\r\n return this.domainIsPointsInTime;\r\n }\r\n\r\n /**\r\n * Sets a flag that controls whether the domain is treated as 'points in\r\n * time', or time periods.\r\n *\r\n * @param flag the flag.\r\n *\r\n * @deprecated This flag is no longer used, as of 1.0.1. The\r\n * <code>includeInterval</code> flag in methods such as\r\n * {@link #getDomainBounds(boolean)} makes this unnecessary.\r\n */\r\n public void setDomainIsPointsInTime(boolean flag) {\r\n this.domainIsPointsInTime = flag;\r\n notifyListeners(new DatasetChangeEvent(this, this));\r\n }\r\n\r\n /**\r\n * Returns the order of the domain values in this dataset.\r\n *\r\n * @return {@link DomainOrder#ASCENDING}\r\n */\r\n @Override\r\n public DomainOrder getDomainOrder() {\r\n return DomainOrder.ASCENDING;\r\n }\r\n\r\n /**\r\n * Returns the position within each time period that is used for the X\r\n * value when the collection is used as an\r\n * {@link org.jfree.data.xy.XYDataset}.\r\n *\r\n * @return The anchor position (never <code>null</code>).\r\n */\r\n public TimePeriodAnchor getXPosition() {\r\n return this.xPosition;\r\n }\r\n\r\n /**\r\n * Sets the position within each time period that is used for the X values\r\n * when the collection is used as an {@link XYDataset}, then sends a\r\n * {@link DatasetChangeEvent} is sent to all registered listeners.\r\n *\r\n * @param anchor the anchor position (<code>null</code> not permitted).\r\n */\r\n public void setXPosition(TimePeriodAnchor anchor) {\r\n ParamChecks.nullNotPermitted(anchor, \"anchor\");\r\n this.xPosition = anchor;\r\n notifyListeners(new DatasetChangeEvent(this, this));\r\n }\r\n\r\n /**\r\n * Returns a list of all the series in the collection.\r\n *\r\n * @return The list (which is unmodifiable).\r\n */\r\n public List getSeries() {\r\n return Collections.unmodifiableList(this.data);\r\n }\r\n\r\n /**\r\n * Returns the number of series in the collection.\r\n *\r\n * @return The series count.\r\n */\r\n @Override\r\n public int getSeriesCount() {\r\n return this.data.size();\r\n }\r\n\r\n /**\r\n * Returns the index of the specified series, or -1 if that series is not\r\n * present in the dataset.\r\n *\r\n * @param series the series (<code>null</code> not permitted).\r\n *\r\n * @return The series index.\r\n *\r\n * @since 1.0.6\r\n */\r\n public int indexOf(TimeSeries series) {\r\n ParamChecks.nullNotPermitted(series, \"series\");\r\n return this.data.indexOf(series);\r\n }\r\n\r\n /**\r\n * Returns a series.\r\n *\r\n * @param series the index of the series (zero-based).\r\n *\r\n * @return The series.\r\n */\r\n public TimeSeries getSeries(int series) {\r\n if ((series < 0) || (series >= getSeriesCount())) {\r\n throw new IllegalArgumentException(\r\n \"The 'series' argument is out of bounds (\" + series + \").\");\r\n }\r\n return (TimeSeries) this.data.get(series);\r\n }\r\n\r\n /**\r\n * Returns the series with the specified key, or <code>null</code> if\r\n * there is no such series.\r\n *\r\n * @param key the series key (<code>null</code> permitted).\r\n *\r\n * @return The series with the given key.\r\n */\r\n public TimeSeries getSeries(Comparable key) {\r\n TimeSeries result = null;\r\n Iterator iterator = this.data.iterator();\r\n while (iterator.hasNext()) {\r\n TimeSeries series = (TimeSeries) iterator.next();\r\n Comparable k = series.getKey();\r\n if (k != null && k.equals(key)) {\r\n result = series;\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Returns the key for a series.\r\n *\r\n * @param series the index of the series (zero-based).\r\n *\r\n * @return The key for a series.\r\n */\r\n @Override\r\n public Comparable getSeriesKey(int series) {\r\n // check arguments...delegated\r\n // fetch the series name...\r\n return getSeries(series).getKey();\r\n }\r\n\r\n /**\r\n * Returns the index of the series with the specified key, or -1 if no\r\n * series has that key.\r\n * \r\n * @param key the key (<code>null</code> not permitted).\r\n * \r\n * @return The index.\r\n * \r\n * @since 1.0.17\r\n */\r\n public int getSeriesIndex(Comparable key) {\r\n ParamChecks.nullNotPermitted(key, \"key\");\r\n int seriesCount = getSeriesCount();\r\n for (int i = 0; i < seriesCount; i++) {\r\n TimeSeries series = (TimeSeries) this.data.get(i);\r\n if (key.equals(series.getKey())) {\r\n return i;\r\n }\r\n }\r\n return -1;\r\n }\r\n\r\n /**\r\n * Adds a series to the collection and sends a {@link DatasetChangeEvent} to\r\n * all registered listeners.\r\n *\r\n * @param series the series (<code>null</code> not permitted).\r\n */\r\n public void addSeries(TimeSeries series) {\r\n ParamChecks.nullNotPermitted(series, \"series\");\r\n this.data.add(series);\r\n series.addChangeListener(this);\r\n series.addVetoableChangeListener(this);\r\n fireDatasetChanged();\r\n }\r\n\r\n /**\r\n * Removes the specified series from the collection and sends a\r\n * {@link DatasetChangeEvent} to all registered listeners.\r\n *\r\n * @param series the series (<code>null</code> not permitted).\r\n */\r\n public void removeSeries(TimeSeries series) {\r\n ParamChecks.nullNotPermitted(series, \"series\");\r\n this.data.remove(series);\r\n series.removeChangeListener(this);\r\n series.removeVetoableChangeListener(this);\r\n fireDatasetChanged();\r\n }\r\n\r\n /**\r\n * Removes a series from the collection.\r\n *\r\n * @param index the series index (zero-based).\r\n */\r\n public void removeSeries(int index) {\r\n TimeSeries series = getSeries(index);\r\n if (series != null) {\r\n removeSeries(series);\r\n }\r\n }\r\n\r\n /**\r\n * Removes all the series from the collection and sends a\r\n * {@link DatasetChangeEvent} to all registered listeners.\r\n */\r\n public void removeAllSeries() {\r\n\r\n // deregister the collection as a change listener to each series in the\r\n // collection\r\n for (int i = 0; i < this.data.size(); i++) {\r\n TimeSeries series = (TimeSeries) this.data.get(i);\r\n series.removeChangeListener(this);\r\n series.removeVetoableChangeListener(this);\r\n }\r\n\r\n // remove all the series from the collection and notify listeners.\r\n this.data.clear();\r\n fireDatasetChanged();\r\n\r\n }\r\n\r\n /**\r\n * Returns the number of items in the specified series. This method is\r\n * provided for convenience.\r\n *\r\n * @param series the series index (zero-based).\r\n *\r\n * @return The item count.\r\n */\r\n @Override\r\n public int getItemCount(int series) {\r\n return getSeries(series).getItemCount();\r\n }\r\n\r\n /**\r\n * Returns the x-value (as a double primitive) for an item within a series.\r\n *\r\n * @param series the series (zero-based index).\r\n * @param item the item (zero-based index).\r\n *\r\n * @return The x-value.\r\n */\r\n @Override\r\n public double getXValue(int series, int item) {\r\n TimeSeries s = (TimeSeries) this.data.get(series);\r\n RegularTimePeriod period = s.getTimePeriod(item);\r\n return getX(period);\r\n }\r\n\r\n /**\r\n * Returns the x-value for the specified series and item.\r\n *\r\n * @param series the series (zero-based index).\r\n * @param item the item (zero-based index).\r\n *\r\n * @return The value.\r\n */\r\n @Override\r\n public Number getX(int series, int item) {\r\n TimeSeries ts = (TimeSeries) this.data.get(series);\r\n RegularTimePeriod period = ts.getTimePeriod(item);\r\n return new Long(getX(period));\r\n }\r\n\r\n /**\r\n * Returns the x-value for a time period.\r\n *\r\n * @param period the time period (<code>null</code> not permitted).\r\n *\r\n * @return The x-value.\r\n */\r\n protected synchronized long getX(RegularTimePeriod period) {\r\n long result = 0L;\r\n if (this.xPosition == TimePeriodAnchor.START) {\r\n result = period.getFirstMillisecond(this.workingCalendar);\r\n }\r\n else if (this.xPosition == TimePeriodAnchor.MIDDLE) {\r\n result = period.getMiddleMillisecond(this.workingCalendar);\r\n }\r\n else if (this.xPosition == TimePeriodAnchor.END) {\r\n result = period.getLastMillisecond(this.workingCalendar);\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Returns the starting X value for the specified series and item.\r\n *\r\n * @param series the series (zero-based index).\r\n * @param item the item (zero-based index).\r\n *\r\n * @return The value.\r\n */\r\n @Override\r\n public synchronized Number getStartX(int series, int item) {\r\n TimeSeries ts = (TimeSeries) this.data.get(series);\r\n return new Long(ts.getTimePeriod(item).getFirstMillisecond(\r\n this.workingCalendar));\r\n }\r\n\r\n /**\r\n * Returns the ending X value for the specified series and item.\r\n *\r\n * @param series The series (zero-based index).\r\n * @param item The item (zero-based index).\r\n *\r\n * @return The value.\r\n */\r\n @Override\r\n public synchronized Number getEndX(int series, int item) {\r\n TimeSeries ts = (TimeSeries) this.data.get(series);\r\n return new Long(ts.getTimePeriod(item).getLastMillisecond(\r\n this.workingCalendar));\r\n }\r\n\r\n /**\r\n * Returns the y-value for the specified series and item.\r\n *\r\n * @param series the series (zero-based index).\r\n * @param item the item (zero-based index).\r\n *\r\n * @return The value (possibly <code>null</code>).\r\n */\r\n @Override\r\n public Number getY(int series, int item) {\r\n TimeSeries ts = (TimeSeries) this.data.get(series);\r\n return ts.getValue(item);\r\n }\r\n\r\n /**\r\n * Returns the starting Y value for the specified series and item.\r\n *\r\n * @param series the series (zero-based index).\r\n * @param item the item (zero-based index).\r\n *\r\n * @return The value (possibly <code>null</code>).\r\n */\r\n @Override\r\n public Number getStartY(int series, int item) {\r\n return getY(series, item);\r\n }\r\n\r\n /**\r\n * Returns the ending Y value for the specified series and item.\r\n *\r\n * @param series te series (zero-based index).\r\n * @param item the item (zero-based index).\r\n *\r\n * @return The value (possibly <code>null</code>).\r\n */\r\n @Override\r\n public Number getEndY(int series, int item) {\r\n return getY(series, item);\r\n }\r\n\r\n\r\n /**\r\n * Returns the indices of the two data items surrounding a particular\r\n * millisecond value.\r\n *\r\n * @param series the series index.\r\n * @param milliseconds the time.\r\n *\r\n * @return An array containing the (two) indices of the items surrounding\r\n * the time.\r\n */\r\n public int[] getSurroundingItems(int series, long milliseconds) {\r\n int[] result = new int[] {-1, -1};\r\n TimeSeries timeSeries = getSeries(series);\r\n for (int i = 0; i < timeSeries.getItemCount(); i++) {\r\n Number x = getX(series, i);\r\n long m = x.longValue();\r\n if (m <= milliseconds) {\r\n result[0] = i;\r\n }\r\n if (m >= milliseconds) {\r\n result[1] = i;\r\n break;\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Returns the minimum x-value in the dataset.\r\n *\r\n * @param includeInterval a flag that determines whether or not the\r\n * x-interval is taken into account.\r\n *\r\n * @return The minimum value.\r\n */\r\n @Override\r\n public double getDomainLowerBound(boolean includeInterval) {\r\n double result = Double.NaN;\r\n Range r = getDomainBounds(includeInterval);\r\n if (r != null) {\r\n result = r.getLowerBound();\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Returns the maximum x-value in the dataset.\r\n *\r\n * @param includeInterval a flag that determines whether or not the\r\n * x-interval is taken into account.\r\n *\r\n * @return The maximum value.\r\n */\r\n @Override\r\n public double getDomainUpperBound(boolean includeInterval) {\r\n double result = Double.NaN;\r\n Range r = getDomainBounds(includeInterval);\r\n if (r != null) {\r\n result = r.getUpperBound();\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Returns the range of the values in this dataset's domain.\r\n *\r\n * @param includeInterval a flag that determines whether or not the\r\n * x-interval is taken into account.\r\n *\r\n * @return The range.\r\n */\r\n @Override\r\n public Range getDomainBounds(boolean includeInterval) {\r\n Range result = null;\r\n Iterator iterator = this.data.iterator();\r\n while (iterator.hasNext()) {\r\n TimeSeries series = (TimeSeries) iterator.next();\r\n int count = series.getItemCount();\r\n if (count > 0) {\r\n RegularTimePeriod start = series.getTimePeriod(0);\r\n RegularTimePeriod end = series.getTimePeriod(count - 1);\r\n Range temp;\r\n if (!includeInterval) {\r\n temp = new Range(getX(start), getX(end));\r\n }\r\n else {\r\n temp = new Range(\r\n start.getFirstMillisecond(this.workingCalendar),\r\n end.getLastMillisecond(this.workingCalendar));\r\n }\r\n result = Range.combine(result, temp);\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Returns the bounds of the domain values for the specified series.\r\n *\r\n * @param visibleSeriesKeys a list of keys for the visible series.\r\n * @param includeInterval include the x-interval?\r\n *\r\n * @return A range.\r\n *\r\n * @since 1.0.13\r\n */\r\n @Override\r\n public Range getDomainBounds(List visibleSeriesKeys,\r\n boolean includeInterval) {\r\n Range result = null;\r\n Iterator iterator = visibleSeriesKeys.iterator();\r\n while (iterator.hasNext()) {\r\n Comparable seriesKey = (Comparable) iterator.next();\r\n TimeSeries series = getSeries(seriesKey);\r\n int count = series.getItemCount();\r\n if (count > 0) {\r\n RegularTimePeriod start = series.getTimePeriod(0);\r\n RegularTimePeriod end = series.getTimePeriod(count - 1);\r\n Range temp;\r\n if (!includeInterval) {\r\n temp = new Range(getX(start), getX(end));\r\n }\r\n else {\r\n temp = new Range(\r\n start.getFirstMillisecond(this.workingCalendar),\r\n end.getLastMillisecond(this.workingCalendar));\r\n }\r\n result = Range.combine(result, temp);\r\n }\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Returns the bounds for the y-values in the dataset.\r\n * \r\n * @param includeInterval ignored for this dataset.\r\n * \r\n * @return The range of value in the dataset (possibly <code>null</code>).\r\n *\r\n * @since 1.0.15\r\n */\r\n public Range getRangeBounds(boolean includeInterval) {\r\n Range result = null;\r\n Iterator iterator = this.data.iterator();\r\n while (iterator.hasNext()) {\r\n TimeSeries series = (TimeSeries) iterator.next();\r\n Range r = new Range(series.getMinY(), series.getMaxY());\r\n result = Range.combineIgnoringNaN(result, r);\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Returns the bounds for the y-values in the dataset.\r\n *\r\n * @param visibleSeriesKeys the visible series keys.\r\n * @param xRange the x-range (<code>null</code> not permitted).\r\n * @param includeInterval ignored.\r\n *\r\n * @return The bounds.\r\n *\r\n * @since 1.0.14\r\n */\r\n @Override\r\n public Range getRangeBounds(List visibleSeriesKeys, Range xRange,\r\n boolean includeInterval) {\r\n Range result = null;\r\n Iterator iterator = visibleSeriesKeys.iterator();\r\n while (iterator.hasNext()) {\r\n Comparable seriesKey = (Comparable) iterator.next();\r\n TimeSeries series = getSeries(seriesKey);\r\n Range r = series.findValueRange(xRange, this.xPosition, \r\n this.workingCalendar.getTimeZone());\r\n result = Range.combineIgnoringNaN(result, r);\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Receives notification that the key for one of the series in the \r\n * collection has changed, and vetos it if the key is already present in \r\n * the collection.\r\n * \r\n * @param e the event.\r\n * \r\n * @since 1.0.17\r\n */\r\n @Override\r\n public void vetoableChange(PropertyChangeEvent e)\r\n throws PropertyVetoException {\r\n // if it is not the series name, then we have no interest\r\n if (!\"Key\".equals(e.getPropertyName())) {\r\n return;\r\n }\r\n \r\n // to be defensive, let's check that the source series does in fact\r\n // belong to this collection\r\n Series s = (Series) e.getSource();\r\n if (getSeriesIndex(s.getKey()) == -1) {\r\n throw new IllegalStateException(\"Receiving events from a series \" +\r\n \"that does not belong to this collection.\");\r\n }\r\n // check if the new series name already exists for another series\r\n Comparable key = (Comparable) e.getNewValue();\r\n if (getSeriesIndex(key) >= 0) {\r\n throw new PropertyVetoException(\"Duplicate key2\", e);\r\n }\r\n }\r\n\r\n /**\r\n * Tests this time series collection for equality with another object.\r\n *\r\n * @param obj the other object.\r\n *\r\n * @return A boolean.\r\n */\r\n @Override\r\n public boolean equals(Object obj) {\r\n if (obj == this) {\r\n return true;\r\n }\r\n if (!(obj instanceof TimeSeriesCollection)) {\r\n return false;\r\n }\r\n TimeSeriesCollection that = (TimeSeriesCollection) obj;\r\n if (this.xPosition != that.xPosition) {\r\n return false;\r\n }\r\n if (this.domainIsPointsInTime != that.domainIsPointsInTime) {\r\n return false;\r\n }\r\n if (!ObjectUtilities.equal(this.data, that.data)) {\r\n return false;\r\n }\r\n return true;\r\n }\r\n\r\n /**\r\n * Returns a hash code value for the object.\r\n *\r\n * @return The hashcode\r\n */\r\n @Override\r\n public int hashCode() {\r\n int result;\r\n result = this.data.hashCode();\r\n result = 29 * result + (this.workingCalendar != null\r\n ? this.workingCalendar.hashCode() : 0);\r\n result = 29 * result + (this.xPosition != null\r\n ? this.xPosition.hashCode() : 0);\r\n result = 29 * result + (this.domainIsPointsInTime ? 1 : 0);\r\n return result;\r\n }\r\n\r\n /**\r\n * Returns a clone of this time series collection.\r\n *\r\n * @return A clone.\r\n *\r\n * @throws java.lang.CloneNotSupportedException if there is a problem \r\n * cloning.\r\n */\r\n @Override\r\n public Object clone() throws CloneNotSupportedException {\r\n TimeSeriesCollection clone = (TimeSeriesCollection) super.clone();\r\n clone.data = (List) ObjectUtilities.deepClone(this.data);\r\n clone.workingCalendar = (Calendar) this.workingCalendar.clone();\r\n return clone;\r\n }\r\n\r\n}\r" }, { "identifier": "XYDataset", "path": "lib/jfreechart-1.0.19/source/org/jfree/data/xy/XYDataset.java", "snippet": "public interface XYDataset extends SeriesDataset {\r\n\r\n /**\r\n * Returns the order of the domain (or X) values returned by the dataset.\r\n *\r\n * @return The order (never <code>null</code>).\r\n */\r\n public DomainOrder getDomainOrder();\r\n\r\n /**\r\n * Returns the number of items in a series.\r\n * <br><br>\r\n * It is recommended that classes that implement this method should throw\r\n * an <code>IllegalArgumentException</code> if the <code>series</code>\r\n * argument is outside the specified range.\r\n *\r\n * @param series the series index (in the range <code>0</code> to\r\n * <code>getSeriesCount() - 1</code>).\r\n *\r\n * @return The item count.\r\n */\r\n public int getItemCount(int series);\r\n\r\n /**\r\n * Returns the x-value for an item within a series. The x-values may or\r\n * may not be returned in ascending order, that is up to the class\r\n * implementing the interface.\r\n *\r\n * @param series the series index (in the range <code>0</code> to\r\n * <code>getSeriesCount() - 1</code>).\r\n * @param item the item index (in the range <code>0</code> to\r\n * <code>getItemCount(series)</code>).\r\n *\r\n * @return The x-value (never <code>null</code>).\r\n */\r\n public Number getX(int series, int item);\r\n\r\n /**\r\n * Returns the x-value for an item within a series.\r\n *\r\n * @param series the series index (in the range <code>0</code> to\r\n * <code>getSeriesCount() - 1</code>).\r\n * @param item the item index (in the range <code>0</code> to\r\n * <code>getItemCount(series)</code>).\r\n *\r\n * @return The x-value.\r\n */\r\n public double getXValue(int series, int item);\r\n\r\n /**\r\n * Returns the y-value for an item within a series.\r\n *\r\n * @param series the series index (in the range <code>0</code> to\r\n * <code>getSeriesCount() - 1</code>).\r\n * @param item the item index (in the range <code>0</code> to\r\n * <code>getItemCount(series)</code>).\r\n *\r\n * @return The y-value (possibly <code>null</code>).\r\n */\r\n public Number getY(int series, int item);\r\n\r\n /**\r\n * Returns the y-value (as a double primitive) for an item within a series.\r\n *\r\n * @param series the series index (in the range <code>0</code> to\r\n * <code>getSeriesCount() - 1</code>).\r\n * @param item the item index (in the range <code>0</code> to\r\n * <code>getItemCount(series)</code>).\r\n *\r\n * @return The y-value.\r\n */\r\n public double getYValue(int series, int item);\r\n\r\n}\r" }, { "identifier": "XisSymbolic", "path": "lib/jfreechart-1.0.19/source/org/jfree/data/xy/XisSymbolic.java", "snippet": "public interface XisSymbolic {\r\n\r\n /**\r\n * Returns the list of symbolic values.\r\n *\r\n * @return An array of symbolic values.\r\n */\r\n public String[] getXSymbolicValues();\r\n\r\n /**\r\n * Returns the symbolic value of the data set specified by\r\n * <CODE>series</CODE> and <CODE>item</CODE> parameters.\r\n *\r\n * @param series value of the serie.\r\n * @param item value of the item.\r\n *\r\n * @return The symbolic value.\r\n */\r\n public String getXSymbolicValue(int series, int item);\r\n\r\n /**\r\n * Returns the symbolic value linked with the specified\r\n * <CODE>Integer</CODE>.\r\n *\r\n * @param val value of the integer linked with the symbolic value.\r\n *\r\n * @return The symbolic value.\r\n */\r\n public String getXSymbolicValue(Integer val);\r\n\r\n}\r" }, { "identifier": "YisSymbolic", "path": "lib/jfreechart-1.0.19/source/org/jfree/data/xy/YisSymbolic.java", "snippet": "public interface YisSymbolic {\r\n\r\n /**\r\n * Returns the list of symbolic values.\r\n *\r\n * @return The symbolic values.\r\n */\r\n public String[] getYSymbolicValues();\r\n\r\n /**\r\n * Returns the symbolic value of the data set specified by\r\n * <CODE>series</CODE> and <CODE>item</CODE> parameters.\r\n *\r\n * @param series the series index (zero-based).\r\n * @param item the item index (zero-based).\r\n *\r\n * @return The symbolic value.\r\n */\r\n public String getYSymbolicValue(int series, int item);\r\n\r\n /**\r\n * Returns the symbolic value linked with the specified\r\n * <CODE>Integer</CODE>.\r\n *\r\n * @param val value of the integer linked with the symbolic value.\r\n *\r\n * @return The symbolic value.\r\n */\r\n public String getYSymbolicValue(Integer val);\r\n\r\n}\r" } ]
import java.io.Serializable; import org.jfree.data.time.RegularTimePeriod; import org.jfree.data.time.TimeSeriesCollection; import org.jfree.data.xy.XYDataset; import org.jfree.data.xy.XisSymbolic; import org.jfree.data.xy.YisSymbolic; import org.jfree.util.PublicCloneable;
10,553
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2013, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * --------------------------------- * SymbolicXYItemLabelGenerator.java * --------------------------------- * (C) Copyright 2001-2008, by Anthony Boulestreau and Contributors. * * Original Author: Anthony Boulestreau; * Contributor(s): David Gilbert (for Object Refinery Limited); * * Changes * ------- * 29-Mar-2002 : Version 1, contributed by Anthony Boulestreau (DG); * 26-Sep-2002 : Fixed errors reported by Checkstyle (DG); * 23-Mar-2003 : Implemented Serializable (DG); * 13-Aug-2003 : Implemented Cloneable (DG); * 17-Nov-2003 : Implemented PublicCloneable (DG); * 25-Feb-2004 : Renamed XYToolTipGenerator --> XYItemLabelGenerator (DG); * 19-Jan-2005 : Now accesses primitives only from dataset (DG); * 20-Apr-2005 : Renamed XYLabelGenerator --> XYItemLabelGenerator (DG); * 02-Feb-2007 : Removed author tags all over JFreeChart sources (DG); * 31-Mar-2008 : Added hashCode() method to appease FindBugs (DG); * */ package org.jfree.chart.labels; /** * A standard item label generator for plots that use data from an * {@link XYDataset}. */ public class SymbolicXYItemLabelGenerator implements XYItemLabelGenerator, XYToolTipGenerator, Cloneable, PublicCloneable, Serializable { /** For serialization. */ private static final long serialVersionUID = 3963400354475494395L; /** * Generates a tool tip text item for a particular item within a series. * * @param data the dataset. * @param series the series number (zero-based index). * @param item the item number (zero-based index). * * @return The tool tip text (possibly <code>null</code>). */ @Override public String generateToolTip(XYDataset data, int series, int item) { String xStr, yStr; if (data instanceof YisSymbolic) { yStr = ((YisSymbolic) data).getYSymbolicValue(series, item); } else { double y = data.getYValue(series, item); yStr = Double.toString(round(y, 2)); }
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2013, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. * Other names may be trademarks of their respective owners.] * * --------------------------------- * SymbolicXYItemLabelGenerator.java * --------------------------------- * (C) Copyright 2001-2008, by Anthony Boulestreau and Contributors. * * Original Author: Anthony Boulestreau; * Contributor(s): David Gilbert (for Object Refinery Limited); * * Changes * ------- * 29-Mar-2002 : Version 1, contributed by Anthony Boulestreau (DG); * 26-Sep-2002 : Fixed errors reported by Checkstyle (DG); * 23-Mar-2003 : Implemented Serializable (DG); * 13-Aug-2003 : Implemented Cloneable (DG); * 17-Nov-2003 : Implemented PublicCloneable (DG); * 25-Feb-2004 : Renamed XYToolTipGenerator --> XYItemLabelGenerator (DG); * 19-Jan-2005 : Now accesses primitives only from dataset (DG); * 20-Apr-2005 : Renamed XYLabelGenerator --> XYItemLabelGenerator (DG); * 02-Feb-2007 : Removed author tags all over JFreeChart sources (DG); * 31-Mar-2008 : Added hashCode() method to appease FindBugs (DG); * */ package org.jfree.chart.labels; /** * A standard item label generator for plots that use data from an * {@link XYDataset}. */ public class SymbolicXYItemLabelGenerator implements XYItemLabelGenerator, XYToolTipGenerator, Cloneable, PublicCloneable, Serializable { /** For serialization. */ private static final long serialVersionUID = 3963400354475494395L; /** * Generates a tool tip text item for a particular item within a series. * * @param data the dataset. * @param series the series number (zero-based index). * @param item the item number (zero-based index). * * @return The tool tip text (possibly <code>null</code>). */ @Override public String generateToolTip(XYDataset data, int series, int item) { String xStr, yStr; if (data instanceof YisSymbolic) { yStr = ((YisSymbolic) data).getYSymbolicValue(series, item); } else { double y = data.getYValue(series, item); yStr = Double.toString(round(y, 2)); }
if (data instanceof XisSymbolic) {
3
2023-12-24 12:36:47+00:00
12k
CodecNomad/MayOBees
src/main/java/com/github/may2beez/mayobees/module/impl/other/Failsafes.java
[ { "identifier": "MayOBeesConfig", "path": "src/main/java/com/github/may2beez/mayobees/config/MayOBeesConfig.java", "snippet": "public class MayOBeesConfig extends Config {\n\n //<editor-fold desc=\"COMBAT\">\n @KeyBind(\n name = \"Shortbow Aura\",\n description = \"Automatically shoots arrows at nearby enemies\",\n category = \"Combat\",\n subcategory = \"Shortbow Aura\"\n )\n public static OneKeyBind shortBowAuraKeybind = new OneKeyBind(Keyboard.KEY_O);\n\n @Text(\n name = \"Shortbow Aura Item's Name\",\n description = \"The name of the item to use for the shortbow aura\",\n category = \"Combat\",\n subcategory = \"Shortbow Aura\",\n size = 2\n )\n public static String shortBowAuraItemName = \"Shortbow\";\n\n @Switch(\n name = \"Shortbow Aura Attack Animals\",\n description = \"Whether or not to attack mobs\",\n category = \"Combat\",\n subcategory = \"Shortbow Aura\"\n )\n public static boolean shortBowAuraAttackMobs = true;\n\n @Switch(\n name = \"Shortbow Aura Attack Until Dead\",\n description = \"Whether or not to attack mobs until they are dead\",\n category = \"Combat\",\n subcategory = \"Shortbow Aura\"\n )\n public static boolean shortBowAuraAttackUntilDead = false;\n\n @DualOption(\n name = \"Shortbow Aura Rotation Type\",\n description = \"The type of rotation to use for the shortbow aura\",\n category = \"Combat\",\n subcategory = \"Shortbow Aura\",\n left = \"Silent\",\n right = \"Client\",\n size = 2\n )\n public static boolean shortBowAuraRotationType = false;\n\n @DualOption(\n name = \"Shortbow Aura Mouse Button\",\n description = \"The mouse button to use for the shortbow aura\",\n category = \"Combat\",\n subcategory = \"Shortbow Aura\",\n left = \"Left\",\n right = \"Right\",\n size = 2\n )\n public static boolean shortBowAuraMouseButton = false;\n\n @DualOption(\n name = \"Shortbow Aura Rotation Mode\",\n description = \"The mode of rotation to use for the shortbow aura\",\n category = \"Combat\",\n subcategory = \"Shortbow Aura\",\n left = \"Bow Rotation\",\n right = \"Straight Rotation\"\n )\n public static boolean shortBowAuraRotationMode = false;\n\n @Info(\n text = \"The range of the shortbow aura\",\n category = \"Combat\",\n subcategory = \"Shortbow Aura\",\n size = 2,\n type = InfoType.INFO\n )\n public static String shortBowAuraRangeInfo = \"The range of the shortbow aura\";\n\n @Slider(\n name = \"Shortbow Aura Range\",\n description = \"The range of the shortbow aura\",\n category = \"Combat\",\n subcategory = \"Shortbow Aura\",\n min = 4,\n max = 30\n )\n public static int shortBowAuraRange = 15;\n\n @Slider(\n name = \"Shortbow Aura FOV\",\n description = \"The FOV of the shortbow aura\",\n category = \"Combat\",\n subcategory = \"Shortbow Aura\",\n min = 0,\n max = 360\n )\n public static int shortBowAuraFOV = 120;\n\n @Info(\n text = \"The speed of the shortbow aura's rotation\",\n category = \"Combat\",\n subcategory = \"Shortbow Aura\",\n size = 2,\n type = InfoType.INFO\n )\n public static String shortBowAuraRotationSpeedInfo = \"The speed of the shortbow aura's rotation\";\n\n @Slider(\n name = \"Shortbow Aura Rotation Speed\",\n description = \"The speed of the shortbow aura's rotation\",\n category = \"Combat\",\n subcategory = \"Shortbow Aura\",\n min = 50,\n max = 800\n )\n public static int shortBowAuraRotationSpeed = 300;\n\n @Slider(\n name = \"Shortbow Aura Rotation Speed Randomizer\",\n description = \"The speed of the shortbow aura's rotation\",\n category = \"Combat\",\n subcategory = \"Shortbow Aura\",\n min = 0,\n max = 500\n )\n public static int shortBowAuraRotationSpeedRandomizer = 100;\n\n public static long getRandomizedRotationSpeed() {\n return (long) (shortBowAuraRotationSpeed + Math.random() * shortBowAuraRotationSpeedRandomizer);\n }\n\n @Info(\n text = \"The speed of the shortbow aura's attack\",\n category = \"Combat\",\n subcategory = \"Shortbow Aura\",\n size = 2,\n type = InfoType.INFO\n )\n public static String shortBowAuraAttackSpeedInfo = \"The speed of the shortbow aura's attack\";\n\n @Slider(\n name = \"Shortbow Aura Cooldown (ms)\",\n description = \"The cooldown of the shortbow aura\",\n category = \"Combat\",\n subcategory = \"Shortbow Aura\",\n min = 0,\n max = 1000\n )\n public static int shortBowAuraCooldown = 500;\n\n @Slider(\n name = \"Shortbow Aura Cooldown Randomizer (ms)\",\n description = \"The randomizer of the shortbow aura cooldown\",\n category = \"Combat\",\n subcategory = \"Shortbow Aura\",\n min = 0,\n max = 1000\n )\n public static int shortBowAuraCooldownRandomizer = 100;\n\n public static long getRandomizedCooldown() {\n return (long) (shortBowAuraCooldown + Math.random() * shortBowAuraCooldownRandomizer);\n }\n\n @Color(\n name = \"Shortbow Aura Target Color\",\n description = \"The color of the shortbow aura\",\n category = \"Combat\",\n subcategory = \"Shortbow Aura\"\n )\n public static OneColor shortBowAuraTargetColor = new OneColor(255, 0, 0, 100);\n\n //</editor-fold>\n\n //<editor-fold desc=\"RENDER\">\n //<editor-fold desc=\"Chest ESP\">\n @Switch(\n name = \"Chest ESP\",\n description = \"Highlights chests\",\n category = \"Render\",\n subcategory = \"Chest ESP\"\n )\n public static boolean chestESP = false;\n\n @Color(\n name = \"Chest ESP Color\",\n description = \"The color of the chest ESP\",\n category = \"Render\",\n subcategory = \"Chest ESP\"\n )\n public static OneColor chestESPColor = new OneColor(194, 91, 12, 100);\n\n @Switch(\n name = \"Chest ESP Tracers\",\n description = \"Draws lines to chests\",\n category = \"Render\",\n subcategory = \"Chest ESP\"\n )\n public static boolean chestESPTracers = false;\n //</editor-fold>\n\n //<editor-fold desc=\"Fairy Soul ESP\">\n @Switch(\n name = \"Fairy Soul ESP\",\n description = \"Highlights fairy souls\",\n category = \"Render\",\n subcategory = \"Fairy Soul ESP\"\n )\n public static boolean fairySoulESP = false;\n\n @Color(\n name = \"Fairy Soul ESP Color\",\n description = \"The color of the fairy soul ESP\",\n category = \"Render\",\n subcategory = \"Fairy Soul ESP\"\n )\n public static OneColor fairySoulESPColor = new OneColor(147, 8, 207, 100);\n\n @Switch(\n name = \"Fairy Soul ESP Tracers\",\n description = \"Draws lines to fairy souls\",\n category = \"Render\",\n subcategory = \"Fairy Soul ESP\"\n )\n public static boolean fairySoulESPTracers = false;\n\n @Switch(\n name = \"Fairy Soul ESP Show Only Closest\",\n description = \"Only shows the closest fairy soul\",\n category = \"Render\",\n subcategory = \"Fairy Soul ESP\"\n )\n public static boolean fairySoulESPShowOnlyClosest = false;\n\n @Switch(\n name = \"Fairy Soul ESP Show Distance\",\n description = \"Shows the distance to the fairy soul\",\n category = \"Render\",\n subcategory = \"Fairy Soul ESP\"\n )\n public static boolean fairySoulESPShowDistance = false;\n\n @Button(\n name = \"Fairy Soul ESP Reset\",\n text = \"Reset\",\n description = \"Resets the fairy soul ESP\",\n category = \"Render\",\n subcategory = \"Fairy Soul ESP\",\n size = 2\n )\n public static void fairySoulESPReset() {\n ESP.getInstance().resetClickedFairySouls();\n }\n\n @Button(\n name = \"Fairy Souls ESP reset only current island\",\n text = \"Reset only current island\",\n description = \"Resets the fairy soul ESP only for the current island\",\n category = \"Render\",\n subcategory = \"Fairy Soul ESP\",\n size = 2\n )\n public static void fairySoulESPResetOnlyCurrentIsland() {\n ESP.getInstance().resetClickedFairySoulsOnlyCurrentIsland();\n }\n\n @Button(\n name = \"Fairy Souls ESP Add all visible souls to clicked list\",\n text = \"Add all visible souls to clicked list\",\n description = \"Adds all visible fairy souls to the clicked list\",\n category = \"Render\",\n subcategory = \"Fairy Soul ESP\",\n size = 2\n )\n public static void fairySoulESPAddAllVisibleSoulsToClickedList() {\n ESP.getInstance().addAllVisibleFairySoulsToClickedList();\n }\n\n //</editor-fold>\n\n //<editor-fold desc=\"Gift ESP\">\n @Switch(\n name = \"Gift ESP\",\n description = \"Highlights gifts\",\n category = \"Render\",\n subcategory = \"Gift ESP\"\n )\n public static boolean giftESP = false;\n\n @Color(\n name = \"Gift ESP Color\",\n description = \"The color of the gift ESP\",\n category = \"Render\",\n subcategory = \"Gift ESP\"\n )\n public static OneColor giftESPColor = new OneColor(230, 230, 230, 100);\n\n @Switch(\n name = \"Gift ESP Tracers\",\n description = \"Draws lines to gifts\",\n category = \"Render\",\n subcategory = \"Gift ESP\"\n )\n public static boolean giftESPTracers = false;\n\n @Switch(\n name = \"Gift ESP Show Only on Jerry Workshop\",\n description = \"Only shows the gift on jerry workshop\",\n category = \"Render\",\n subcategory = \"Gift ESP\"\n )\n public static boolean giftESPShowOnlyOnJerryWorkshop = false;\n\n @Switch(\n name = \"Gift ESP Show Distance\",\n description = \"Shows the distance to the closest gift\",\n category = \"Render\",\n subcategory = \"Gift ESP\"\n )\n public static boolean giftESPShowDistance = false;\n\n @Button(\n name = \"Gift ESP Reset\",\n text = \"Reset\",\n description = \"Resets the gift ESP\",\n category = \"Render\",\n subcategory = \"Gift ESP\",\n size = 2\n )\n public static void giftESPReset() {\n ESP.getInstance().resetClickedGifts();\n }\n\n //</editor-fold>\n //</editor-fold>\n\n //<editor-fold desc=\"MISC\">\n @Info(\n text = \"Smart Toggle activates the appropriate macro depending on the situation\",\n size = 2,\n category = \"Misc\",\n type = InfoType.WARNING\n )\n public boolean infoSmartToggle1 = false;\n\n @Info(\n text = \"Gift Aura - Be at Jerry Workshop\",\n size = 2,\n category = \"Misc\",\n type = InfoType.INFO\n )\n public boolean infoSmartToggle3 = false;\n\n @Info(\n text = \"Fishing Macro - Hold Rod\",\n size = 2,\n category = \"Misc\",\n type = InfoType.INFO\n )\n public boolean infoSmartToggle4 = false;\n\n @Info(\n text = \"Shortbow Aura - Hold Your Item\",\n size = 2,\n category = \"Misc\",\n type = InfoType.INFO\n )\n public boolean infoSmartToggle5 = false;\n\n @Info(\n text = \"Foraging Macro - Hold Treecapitator or Sappling on private island\",\n size = 2,\n category = \"Misc\",\n type = InfoType.INFO\n )\n public boolean infoSmartToggle2 = false;\n\n @Info(\n text = \"Fill Chests with Sapplings Macro - Hold Abiphone and have Treecap in hotbar\",\n size = 2,\n category = \"Misc\",\n type = InfoType.INFO\n )\n public boolean infoSmartToggle6 = false;\n\n @KeyBind(\n name = \"SmartToggle keybind\",\n category = \"Misc\"\n )\n public static OneKeyBind smartToggleKeybind = new OneKeyBind(Keyboard.KEY_NONE);\n @Switch(\n name = \"Ungrab Mouse\",\n category = \"Misc\"\n )\n public static boolean mouseUngrab = false;\n //</editor-fold>\n\n //<editor-fold desc=\"Skills\">\n //<editor-fold desc=\"Alchemy Helper\">\n @Switch(\n name = \"Alchemy Helper\",\n description = \"Automatically brews potions\",\n category = \"Skills\",\n subcategory = \"Alchemy Helper\",\n size = 2\n )\n public static boolean alchemyHelper = false;\n\n @Switch(\n name = \"Auto put water bottles\",\n description = \"Automatically puts water bottles in the brewing stand\",\n category = \"Skills\",\n subcategory = \"Alchemy Helper - Options\"\n )\n public static boolean alchemyHelperAutoPutWaterBottles = false;\n\n @Switch(\n name = \"Auto put ingredients\",\n description = \"Automatically puts ingredients in the brewing stand\",\n category = \"Skills\",\n subcategory = \"Alchemy Helper - Options\"\n )\n public static boolean alchemyHelperAutoPutIngredients = false;\n\n @Dropdown(\n name = \"Max ingredient type\",\n description = \"The max ingredient type to use\",\n category = \"Skills\",\n subcategory = \"Alchemy Helper - Options\",\n options = {\"None\", \"Enchanted Sugar Cane\", \"Enchanted Blaze Rod\"},\n size = 2\n )\n public static int alchemyHelperMaxIngredientType = 0;\n\n @Switch(\n name = \"Auto pick up finish potions\",\n description = \"Automatically picks up finish potions\",\n category = \"Skills\",\n subcategory = \"Alchemy Helper - Options\"\n )\n public static boolean alchemyHelperAutoPickUpFinishPotions = false;\n\n @Switch(\n name = \"Auto close GUI after picking up potions\",\n description = \"Automatically closes the GUI after picking up potions\",\n category = \"Skills\",\n subcategory = \"Alchemy Helper - Options\"\n )\n public static boolean alchemyHelperAutoCloseGUIAfterPickingUpPotions = false;\n\n @Slider(\n name = \"Delay between potion gui actions (ms)\",\n description = \"The delay between gui actions\",\n category = \"Skills\",\n subcategory = \"Alchemy Helper - Times\",\n min = 0,\n max = 1000\n )\n public static int alchemyHelperDelayBetweenPotionGuiActions = 300;\n\n @Slider(\n name = \"Delay between gui potion actions randomizer (ms)\",\n description = \"The randomizer of the delay between gui actions\",\n category = \"Skills\",\n subcategory = \"Alchemy Helper - Times\",\n min = 0,\n max = 1000\n )\n public static int alchemyHelperDelayBetweenPotionGuiActionsRandomizer = 100;\n\n public static long getRandomizedDelayBetweenPotionGuiActions() {\n return (long) (alchemyHelperDelayBetweenPotionGuiActions + Math.random() * alchemyHelperDelayBetweenPotionGuiActionsRandomizer);\n }\n\n @Slider(\n name = \"Delay between ingredients gui actions (ms)\",\n description = \"The delay between gui actions\",\n category = \"Skills\",\n subcategory = \"Alchemy Helper - Times\",\n min = 0,\n max = 1000\n )\n public static int alchemyHelperDelayBetweenIngredientsGuiActions = 300;\n\n @Slider(\n name = \"Delay between gui ingredients actions randomizer (ms)\",\n description = \"The randomizer of the delay between gui actions\",\n category = \"Skills\",\n subcategory = \"Alchemy Helper - Times\",\n min = 0,\n max = 1000\n )\n public static int alchemyHelperDelayBetweenIngredientsGuiActionsRandomizer = 100;\n\n public static long getRandomizedDelayBetweenIngredientsGuiActions() {\n return (long) (alchemyHelperDelayBetweenIngredientsGuiActions + Math.random() * alchemyHelperDelayBetweenIngredientsGuiActionsRandomizer);\n }\n\n @Slider(\n name = \"Delay between potion sell actions (ms)\",\n description = \"The delay between potion sell actions\",\n category = \"Skills\",\n subcategory = \"Alchemy Helper - Times\",\n min = 0,\n max = 1000\n )\n public static int alchemyHelperDelayBetweenPotionSellActions = 300;\n\n @Slider(\n name = \"Delay between potion sell actions randomizer (ms)\",\n description = \"The randomizer of the delay between potion sell actions\",\n category = \"Skills\",\n subcategory = \"Alchemy Helper - Times\",\n min = 0,\n max = 1000\n )\n public static int alchemyHelperDelayBetweenPotionSellActionsRandomizer = 100;\n\n public static long getRandomizedDelayBetweenPotionSellActions() {\n return (long) (alchemyHelperDelayBetweenPotionSellActions + Math.random() * alchemyHelperDelayBetweenPotionSellActionsRandomizer);\n }\n\n @KeyBind(\n name = \"Auto sell potions to NPC\",\n description = \"Automatically sells potions to NPC\",\n category = \"Skills\",\n subcategory = \"Alchemy Helper - Additions\"\n )\n public static OneKeyBind alchemyHelperAutoSellPotionsToNPCKeybind = new OneKeyBind(Keyboard.KEY_NONE);\n\n //</editor-fold>\n \n //<editor-fold desc=\"Foraging\">\n @Switch(name = \"Use Fishing Rod\", category = \"Skills\",\n subcategory = \"Foraging\")\n public static boolean foragingUseRod = false;\n\n @Dropdown(name = \"Fill Chest With Sapling Type\", category = \"Skills\",\n subcategory = \"Foraging\", options = {\"Spruce\",\"Jungle\", \"Dark Oak\"})\n public static int fillChestSaplingType = 0;\n\n @DualOption(\n name = \"Foraging Mode\",\n description = \"The mode of foraging\",\n category = \"Skills\",\n subcategory = \"Foraging\",\n left = \"Camera rotations\",\n right = \"Skulls and moving\",\n size = 2\n )\n public static boolean foragingMode = false;\n\n @DualOption(\n name = \"Dirt Detection Mode\",\n description = \"The mode of dirt detection. Blocks Scanner won't make the proper Vec3's for now. Doesn't really matter in skull mode\",\n category = \"Skills\",\n subcategory = \"Foraging\",\n left = \"Relative Blocks\",\n right = \"Blocks Scanner\"\n )\n public static boolean dirtDetectionMode = false;\n\n @Slider(\n name = \"Foraging Macro Base Rotation Speed\",\n description = \"The base rotation speed of the foraging macro\",\n category = \"Skills\",\n subcategory = \"Foraging - Options\",\n min = 50,\n max = 800\n )\n public static int foragingMacroBaseRotationSpeed = 150;\n\n @Slider(\n name = \"Foraging Macro Rotation Speed Randomizer\",\n description = \"The randomizer of the rotation speed of the foraging macro\",\n category = \"Skills\",\n subcategory = \"Foraging - Options\",\n min = 0,\n max = 500\n )\n public static int foragingMacroRotationSpeedRandomizer = 50;\n\n public static long getRandomizedForagingMacroRotationSpeed() {\n return (long) (foragingMacroBaseRotationSpeed + Math.random() * foragingMacroRotationSpeedRandomizer);\n }\n\n @Slider(name = \"Foraging Macro Delay\", category = \"Skills\",\n subcategory = \"Foraging - Options\", max = 500, min = 0.0F, step = 10)\n public static int foragingDelay = 50;\n\n @Slider(\n name = \"Foraging Macro Extra Break Delay\",\n description = \"The extra delay between breaking blocks. Most of the time, it's your ping\",\n category = \"Skills\",\n subcategory = \"Foraging - Options\",\n min = 0,\n max = 800\n )\n public static int foragingMacroExtraBreakDelay = 100;\n\n @Slider(name = \"Stuck timeout\",\n category = \"Skills\",\n subcategory = \"Foraging - Options\",\n max = 2500, min = 0.0F, step = 100\n )\n public static int stuckTimeout = 1500;\n\n @Slider(\n name = \"Monkey level\",\n description = \"The monkey level to calculate delay\",\n category = \"Skills\",\n subcategory = \"Foraging - Options\",\n min = 0,\n max = 100\n )\n public static int monkeyLevel = 0;\n\n //</editor-fold>\n \n //<editor-fold desc=\"Fishing\">\n @Switch(\n name = \"Fishing\",\n description = \"Automatically fishes\",\n category = \"Skills\",\n subcategory = \"Fishing\"\n )\n public static boolean fishing = false;\n @Switch(\n name = \"Sneak while fishing\",\n description = \"Sneaks while fishing\",\n category = \"Skills\",\n subcategory = \"Fishing\"\n )\n public static boolean sneakWhileFishing = false;\n @Switch(\n name = \"Anti AFK\",\n description = \"Anti AFK\",\n category = \"Skills\",\n subcategory = \"Fishing\"\n )\n public static boolean antiAfkWhileFishing = false;\n //</editor-fold>\n //</editor-fold>\n\n //<editor-fold desc=\"DEV\">\n @Switch(\n name = \"Debug Mode\",\n description = \"Enables debug mode\",\n category = \"Debug\"\n )\n public static boolean debugMode = false;\n\n //<editor-fold desc=\"Tablist\">\n @DualOption(\n name = \"Save Tablist\",\n description = \"Saves the tablist to a file\",\n category = \"Debug\",\n subcategory = \"Tablist\",\n left = \"Print\",\n right = \"Save\"\n )\n public static boolean saveTablistToFile = false;\n @Switch(\n name = \"Transposed Tablist\",\n description = \"Transposes the tablist\",\n category = \"Debug\",\n subcategory = \"Tablist\"\n )\n public static boolean transposedTablist = false;\n @Button(\n name = \"Get Tablist\",\n text = \"Get Tablist\",\n description = \"Gets the tablist\",\n category = \"Debug\",\n subcategory = \"Tablist\"\n )\n public static void getTablist() {\n Dev.getInstance().getTablist();\n }\n //</editor-fold>\n\n //<editor-fold desc=\"Inventory\">\n @DualOption(\n name = \"Save Inventory\",\n description = \"Saves the inventory to a file\",\n category = \"Debug\",\n subcategory = \"Inventory\",\n left = \"Print\",\n right = \"Save\"\n )\n public static boolean saveInventoryToFile = false;\n @Button(\n name = \"Get Inventory\",\n text = \"Get Inventory\",\n description = \"Gets the inventory\",\n category = \"Debug\",\n subcategory = \"Inventory\"\n )\n public static void getInventory() {\n Dev.getInstance().getInventory();\n }\n //</editor-fold>\n\n //<editor-fold desc=\"Item Lore\">\n @DualOption(\n name = \"Save Item Lore\",\n description = \"Saves the item lore of specific slot to a file\",\n category = \"Debug\",\n subcategory = \"Item Lore\",\n left = \"Print\",\n right = \"Save\"\n )\n public static boolean saveItemLoreToFile = false;\n @Number(\n name = \"Item Lore Slot\",\n description = \"The slot to get the item lore from\",\n category = \"Debug\",\n subcategory = \"Item Lore\",\n min = 0,\n max = 44\n )\n public static int itemLoreSlot = 0;\n @Button(\n name = \"Get Item Lore\",\n text = \"Get Item Lore\",\n description = \"Gets the item lore of specific slot\",\n category = \"Debug\",\n subcategory = \"Item Lore\"\n )\n public static void getItemLore() {\n Dev.getInstance().getItemLore(itemLoreSlot);\n }\n //</editor-fold>\n //</editor-fold>\n\n //<editor-fold desc=\"OTHER\">\n //<editor-fold desc=\"Ghost Blocks\">\n @Switch(\n name = \"Enable Ghost Blocks\",\n description = \"Middle clicks turns blocks into air for a short period of time\",\n category = \"Other\",\n subcategory = \"Ghost Blocks\"\n )\n public static boolean enableGhostBlocks = false;\n\n @Switch(\n name = \"Ghost Blocks only while holding Stonk\",\n description = \"Middle clicks turns blocks into air for a short period of time\",\n category = \"Other\",\n subcategory = \"Ghost Blocks\"\n )\n public static boolean ghostBlocksOnlyWhileHoldingStonk = false;\n\n @Slider(\n name = \"Ghost Blocks Duration (ms)\",\n description = \"The duration of the ghost blocks\",\n category = \"Other\",\n subcategory = \"Ghost Blocks\",\n min = 500,\n max = 5000\n )\n public static int ghostBlocksDuration = 1000;\n\n @Dropdown(\n name = \"Failsafe sound\",\n description = \"The sound to play when the failsafe is triggered\",\n category = \"Other\",\n subcategory = \"Failsafe\",\n options = {\"Exp Orbs\", \"Anvil\"},\n size = 2\n )\n public static int failsafeSoundSelected = 0;\n\n @Switch(\n name = \"Stop active modules on rotation/teleport packet\",\n description = \"Stops all active modules when a rotation packet is received\",\n category = \"Other\",\n subcategory = \"Failsafe\"\n )\n public static boolean stopMacrosOnRotationTeleportCheck = false;\n\n @Switch(\n name = \"Stop active modules on world change\",\n description = \"Stops all active modules when a world change is detected\",\n category = \"Other\",\n subcategory = \"Failsafe\"\n )\n public static boolean stopMacrosOnWorldChange = false;\n\n //</editor-fold>\n\n //<editor-fold desc=\"Gift Aura\">\n @Switch(\n name = \"Gift Aura\",\n description = \"Automatically opens gifts\",\n category = \"Other\",\n subcategory = \"Gift Aura\"\n )\n public static boolean giftAura = false;\n @Button(\n name = \"Gift Aura Reset\",\n text = \"Reset\",\n description = \"Resets the Gift Aura\",\n category = \"Other\",\n subcategory = \"Gift Aura\",\n size = 2\n )\n public static void giftAuraReset() {\n GiftAura.getInstance().reset();\n }\n @DualOption(\n name = \"Gift Aura Rotation Type\",\n description = \"The type of rotation to use for the gift aura\",\n category = \"Other\",\n subcategory = \"Gift Aura\",\n left = \"Silent\",\n right = \"Client\",\n size = 2\n )\n public static boolean giftAuraRotationType = true;\n\n @Color(\n name = \"Gift Aura ESP Color\",\n description = \"The color of the gift aura ESP\",\n category = \"Other\",\n subcategory = \"Gift Aura\"\n )\n public static OneColor giftAuraESPColor = new OneColor(240, 93, 94, 100);\n @Switch(\n name = \"Open default gifts at Jerry's Workshop\",\n description = \"Automatically opens gifts hidden throughout Jerry's Workshop\",\n category = \"Other\",\n subcategory = \"Gift Aura\"\n )\n public static boolean giftAuraOpenDefaultGiftsAtJerryWorkshop = false;\n @Switch(\n name = \"Open player gifts\",\n description = \"Automatically opens gifts from other players\",\n category = \"Other\",\n subcategory = \"Gift Aura\"\n )\n public static boolean giftAuraOpenPlayerGifts = false;\n @Switch(\n name = \"Open gifts outside of Jerry's Workshop\",\n description = \"Automatically opens gifts outside of Jerry's Workshop\",\n category = \"Other\",\n subcategory = \"Gift Aura\"\n )\n public static boolean giftAuraOpenGiftsOutsideOfJerryWorkshop = false;\n @Switch(\n name = \"Don't check for visibility\",\n description = \"Don't check if the gift is visible before opening it\",\n category = \"Other\",\n subcategory = \"Gift Aura\"\n )\n public static boolean giftAuraDontCheckForVisibility = false;\n @Slider(\n name = \"Delay (ms)\",\n description = \"The delay between opening gifts\",\n category = \"Other\",\n subcategory = \"Gift Aura\",\n min = 150,\n max = 2000\n )\n public static int giftAuraDelay = 750;\n\n //</editor-fold>\n //</editor-fold>\n\n public MayOBeesConfig() {\n super(new Mod(\"MayOBees\", ModType.HYPIXEL), \"/mayobees/config.json\");\n initialize();\n\n registerKeyBind(smartToggleKeybind, () -> {\n ModuleManager.getInstance().smartToggle();\n });\n\n registerKeyBind(alchemyHelperAutoSellPotionsToNPCKeybind, () -> {\n LogUtils.info(\"[Alchemy Helper] Selling to NPC: \" + (!AlchemyHelper.getInstance().isSellingPotions() ? \"Enabled\" : \"Disabled\"));\n AlchemyHelper.getInstance().setSellingPotions(!AlchemyHelper.getInstance().isSellingPotions());\n });\n }\n}" }, { "identifier": "PacketEvent", "path": "src/main/java/com/github/may2beez/mayobees/event/PacketEvent.java", "snippet": "@Cancelable\npublic class PacketEvent extends Event {\n public Packet<?> packet;\n\n protected PacketEvent(Packet<?> packet) {\n this.packet = packet;\n }\n\n @Cancelable\n public static class Receive extends PacketEvent {\n public Receive(final Packet<?> packet) {\n super(packet);\n }\n }\n\n @Cancelable\n public static class Send extends PacketEvent {\n public Send(final Packet<?> packet) {\n super(packet);\n }\n }\n}" }, { "identifier": "IModuleActive", "path": "src/main/java/com/github/may2beez/mayobees/module/IModuleActive.java", "snippet": "public interface IModuleActive extends IModule {\n void onEnable();\n void onDisable();\n}" }, { "identifier": "ModuleManager", "path": "src/main/java/com/github/may2beez/mayobees/module/ModuleManager.java", "snippet": "@Getter\npublic class ModuleManager {\n private static ModuleManager instance;\n\n public static ModuleManager getInstance() {\n if (instance == null) {\n instance = new ModuleManager();\n }\n return instance;\n }\n\n private final List<IModule> modules = fillModules();\n\n public List<IModule> fillModules() {\n return Arrays.asList(\n ShortbowAura.getInstance(),\n GhostBlocks.getInstance(),\n GiftAura.getInstance(),\n ESP.getInstance(),\n AlchemyHelper.getInstance(),\n Fishing.getInstance(),\n Foraging.getInstance(),\n FillChestWithSaplingMacro.getInstance()\n );\n }\n\n public void disableAll() {\n modules.forEach(module -> {\n if (module.isRunning() && module instanceof IModuleActive)\n ((IModuleActive) module).onDisable();\n });\n }\n\n public void toggle(IModuleActive module) {\n if (module.isRunning())\n module.onDisable();\n else\n module.onEnable();\n LogUtils.info(\"[\" + module.getName() + \"] \" + (module.isRunning() ? \"Enabled\" : \"Disabled\"));\n }\n\n public void smartToggle() {\n if (GameStateHandler.getInstance().getLocation() == GameStateHandler.Location.JERRY_WORKSHOP)\n toggle(GiftAura.getInstance());\n ItemStack heldItem = Minecraft.getMinecraft().thePlayer.getHeldItem();\n if (heldItem != null && heldItem.getItem() == Items.fishing_rod)\n toggle(Fishing.getInstance());\n if (heldItem != null && !MayOBeesConfig.shortBowAuraItemName.isEmpty() && heldItem.getDisplayName().contains(MayOBeesConfig.shortBowAuraItemName))\n toggle(ShortbowAura.getInstance());\n if (heldItem != null && heldItem.getDisplayName().contains(\"Sapling\") || heldItem != null && heldItem.getDisplayName().contains(\"Treecapitator\")\n && GameStateHandler.getInstance().getLocation() == GameStateHandler.Location.PRIVATE_ISLAND)\n toggle(Foraging.getInstance());\n if (heldItem != null && heldItem.getDisplayName().contains(\"Abiphone\") && InventoryUtils.hasItemInHotbar(\"Treecapitator\") && GameStateHandler.getInstance().getLocation() == GameStateHandler.Location.PRIVATE_ISLAND) {\n toggle(FillChestWithSaplingMacro.getInstance());\n }\n }\n}" }, { "identifier": "LogUtils", "path": "src/main/java/com/github/may2beez/mayobees/util/LogUtils.java", "snippet": "public class LogUtils {\n private static final String prefix = \"§4§ka§r§e[MayOBees]§4§ka§r \";\n private static final Minecraft mc = Minecraft.getMinecraft();\n\n public static void info(String message) {\n if (mc.thePlayer == null) {\n System.out.println(prefix + \"§3\" + message);\n return;\n }\n mc.thePlayer.addChatMessage(new ChatComponentText(prefix + \"§3\" + message));\n }\n\n public static void warn(String message) {\n if (mc.thePlayer == null) {\n System.out.println(prefix + \"§c\" + message);\n return;\n }\n mc.thePlayer.addChatMessage(new ChatComponentText(prefix + \"§c\" + message));\n }\n\n public static void error(String message) {\n if (mc.thePlayer == null) {\n System.out.println(prefix + \"§4\" + message);\n return;\n }\n mc.thePlayer.addChatMessage(new ChatComponentText(prefix + \"§4\" + message));\n }\n\n public static void debug(String message) {\n if (mc.thePlayer == null || !MayOBeesConfig.debugMode) {\n System.out.println(prefix + \"§7\" + message);\n return;\n }\n mc.thePlayer.addChatMessage(new ChatComponentText(prefix + \"§7\" + message));\n }\n}" }, { "identifier": "AudioManager", "path": "src/main/java/com/github/may2beez/mayobees/util/helper/AudioManager.java", "snippet": "public class AudioManager {\n private final Minecraft mc = Minecraft.getMinecraft();\n private static AudioManager instance;\n\n public static AudioManager getInstance() {\n if (instance == null) {\n instance = new AudioManager();\n }\n return instance;\n }\n\n @Getter\n @Setter\n private boolean minecraftSoundEnabled = false;\n\n private final Clock delayBetweenPings = new Clock();\n private int numSounds = 15;\n @Setter\n private float soundBeforeChange = 0;\n\n public void resetSound() {\n if (clip != null && clip.isRunning()) {\n clip.stop();\n clip.close();\n return;\n }\n minecraftSoundEnabled = false;\n }\n\n private static Clip clip;\n\n public void playSound() {\n if (minecraftSoundEnabled) return;\n numSounds = 15;\n minecraftSoundEnabled = true;\n }\n\n public boolean isSoundPlaying() {\n return (clip != null && clip.isRunning()) || minecraftSoundEnabled;\n }\n\n @SubscribeEvent\n public void onTick(TickEvent.ClientTickEvent event) {\n if (mc.thePlayer == null || mc.theWorld == null) return;\n if (!minecraftSoundEnabled) return;\n if (delayBetweenPings.isScheduled() && !delayBetweenPings.passed()) return;\n if (numSounds <= 0) {\n minecraftSoundEnabled = false;\n return;\n }\n\n switch (MayOBeesConfig.failsafeSoundSelected) {\n case 0: {\n mc.theWorld.playSound(mc.thePlayer.posX, mc.thePlayer.posY, mc.thePlayer.posZ, \"random.orb\", 10.0F, 1.0F, false);\n break;\n }\n case 1: {\n mc.theWorld.playSound(mc.thePlayer.posX, mc.thePlayer.posY, mc.thePlayer.posZ, \"random.anvil_land\", 10.0F, 1.0F, false);\n break;\n }\n }\n delayBetweenPings.schedule(100);\n numSounds--;\n }\n}" } ]
import com.github.may2beez.mayobees.config.MayOBeesConfig; import com.github.may2beez.mayobees.event.PacketEvent; import com.github.may2beez.mayobees.module.IModuleActive; import com.github.may2beez.mayobees.module.ModuleManager; import com.github.may2beez.mayobees.util.LogUtils; import com.github.may2beez.mayobees.util.helper.AudioManager; import net.minecraft.client.Minecraft; import net.minecraft.network.play.server.S08PacketPlayerPosLook; import net.minecraftforge.event.world.WorldEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors;
9,416
package com.github.may2beez.mayobees.module.impl.other; public class Failsafes { private static Failsafes instance; public static Failsafes getInstance() { if (instance == null) { instance = new Failsafes(); } return instance; } private static final Minecraft mc = Minecraft.getMinecraft(); private static final String[] teleportItems = new String[] {"Void", "Hyperion", "Aspect"}; @SubscribeEvent public void onWorldChange(WorldEvent.Unload event) { if (!MayOBeesConfig.stopMacrosOnWorldChange) return;
package com.github.may2beez.mayobees.module.impl.other; public class Failsafes { private static Failsafes instance; public static Failsafes getInstance() { if (instance == null) { instance = new Failsafes(); } return instance; } private static final Minecraft mc = Minecraft.getMinecraft(); private static final String[] teleportItems = new String[] {"Void", "Hyperion", "Aspect"}; @SubscribeEvent public void onWorldChange(WorldEvent.Unload event) { if (!MayOBeesConfig.stopMacrosOnWorldChange) return;
List<IModuleActive> activeModules = ModuleManager.getInstance().getModules().stream().filter(mod -> mod instanceof IModuleActive && mod.isRunning()).map(mod -> (IModuleActive) mod).collect(Collectors.toList());
3
2023-12-24 15:39:11+00:00
12k
viceice/verbrauchsapp
app/src/main/java/de/anipe/verbrauchsapp/GDriveStoreActivity.java
[ { "identifier": "ConsumptionDataSource", "path": "app/src/main/java/de/anipe/verbrauchsapp/db/ConsumptionDataSource.java", "snippet": "public class ConsumptionDataSource implements Serializable {\n\n\tprivate static ConsumptionDataSource dataSouce;\n\n\tprivate static final long serialVersionUID = 368016508421825334L;\n\tprivate SQLiteDatabase database;\n\tprivate DBHelper dbHelper;\n\tprivate FileSystemAccessor accessor;\n\tprivate Context context;\n\n\tprivate ConsumptionDataSource(Context context) {\n\t\tdbHelper = new DBHelper(context);\n\t\taccessor = FileSystemAccessor.getInstance();\n\t\tthis.context = context;\n\t}\n\n\tpublic static ConsumptionDataSource getInstance(Context context) {\n\t\tif (dataSouce == null) {\n\t\t\tdataSouce = new ConsumptionDataSource(context);\n\t\t}\n\n\t\treturn dataSouce;\n\t}\n\n\tpublic void open() throws SQLException {\n\t\tdatabase = dbHelper.getWritableDatabase();\n\t}\n\n\tpublic void close() {\n\t\tdbHelper.close();\n\t}\n\n\tpublic List<Consumption> getConsumptionCycles(long carId) {\n\n\t\tList<Consumption> consumptionCyclestList = new LinkedList<>();\n\t\tCursor cursor = database.query(DBHelper.TABLE_CONSUMPTIONS, null,\n\t\t\t\tDBHelper.CONSUMPTION_CAR_ID + \"=?\",\n\t\t\t\tnew String[] { String.valueOf(carId) }, null, null,\n\t\t\t\tDBHelper.CONSUMPTION_COLUMN_DATE + \" desc\");\n\n\t\twhile (cursor.moveToNext()) {\n\t\t\tConsumption cons = cursorToConsumption(cursor);\n\t\t\tconsumptionCyclestList.add(cons);\n\t\t}\n\t\tcursor.close();\n\n\t\treturn consumptionCyclestList;\n\t}\n\n\tpublic Car getCarForId(long carId) {\n\n\t\tCursor cursor = database.query(DBHelper.TABLE_CARS, null,\n\t\t\t\tDBHelper.COLUMN_ID + \"=?\",\n\t\t\t\tnew String[] { String.valueOf(carId) }, null, null, null, \"1\");\n\n\t\tif (cursor.moveToFirst()) {\n\t\t\treturn cursorToCar(cursor);\n\t\t}\n\t\tcursor.close();\n\t\treturn null;\n\t}\n\n\tpublic int getMileageForCar(long carId) {\n\n\t\tCursor cursor = database.query(DBHelper.TABLE_CONSUMPTIONS,\n\t\t\t\tnew String[] { \"MAX(\"\n\t\t\t\t\t\t+ DBHelper.CONSUMPTION_COLUMN_REFUELMILEAGE + \")\" },\n\t\t\t\tDBHelper.CONSUMPTION_CAR_ID + \"=?\",\n\t\t\t\tnew String[] { String.valueOf(carId) }, null, null, null, \"1\");\n\n\t\tint mileage = 0;\n\n\t\tif (cursor.moveToFirst() && !cursor.isNull(0)) {\n\t\t\tmileage = cursor.getInt(0);\n\t\t\tLog.d(\"ConsumptionDataSource\", \"Found mileage: \" + mileage);\n\t\t} else {\n\t\t\tcursor.close();\n\t\t\tcursor = database.query(DBHelper.TABLE_CARS,\n\t\t\t\t\tnew String[] { DBHelper.CAR_COLUMN_STARTKM },\n\t\t\t\t\tDBHelper.COLUMN_ID + \"=?\",\n\t\t\t\t\tnew String[] { String.valueOf(carId) }, null, null, null,\n\t\t\t\t\t\"1\");\n\t\t\tif (cursor.moveToFirst()) {\n\t\t\t\tmileage = cursor.getInt(0);\n\t\t\t\tLog.d(\"ConsumptionDataSource\", \"Found start mileage: \"\n\t\t\t\t\t\t+ mileage);\n\t\t\t}\n\t\t}\n\t\tcursor.close();\n\t\treturn mileage;\n\t}\n\n\tpublic double getOverallConsumptionForCar(long carId) {\n\n\t\tdouble consumption = 0;\n\t\tint cycleCount = 0;\n\n\t\tCursor cursor = database.query(DBHelper.TABLE_CONSUMPTIONS,\n\t\t\t\tnew String[] {\n\t\t\t\t\t\t\"SUM(\" + DBHelper.CONSUMPTION_COLUMN_CONSUMPTION + \")\",\n\t\t\t\t\t\t\"COUNT(\" + DBHelper.COLUMN_ID + \")\" },\n\t\t\t\tDBHelper.CONSUMPTION_CAR_ID + \"=?\",\n\t\t\t\tnew String[] { String.valueOf(carId) }, null, null, null);\n\n\t\tif (cursor.moveToFirst() && !cursor.isNull(0)) {\n\t\t\tconsumption = cursor.getDouble(0);\n\t\t\tcycleCount = cursor.getInt(1);\n\t\t}\n\t\tcursor.close();\n\t\treturn cycleCount == 0 ? 0 : (consumption / cycleCount);\n\t}\n\n\tpublic double getOverallCostsForCar(long carId) {\n\n\t\tdouble costs = 0;\n\n\t\tCursor cursor = database.query(DBHelper.TABLE_CONSUMPTIONS,\n\t\t\t\tnew String[] { \"SUM(\"\n\t\t\t\t\t\t+ DBHelper.CONSUMPTION_COLUMN_REFUELLITERS + \"*\"\n\t\t\t\t\t\t+ DBHelper.CONSUMPTION_COLUMN_REFUELPRICE + \")\" },\n\t\t\t\tDBHelper.CONSUMPTION_CAR_ID + \"=?\",\n\t\t\t\tnew String[] { String.valueOf(carId) }, null, null, null);\n\n\t\tif (cursor.moveToFirst() && !cursor.isNull(0)) {\n\t\t\tcosts = cursor.getDouble(0);\n\t\t}\n\t\tcursor.close();\n\t\treturn costs;\n\t}\n\n\tpublic List<Car> getCarList() {\n\n\t\tList<Car> carList = new LinkedList<>();\n\n\t\tCursor cursor = database.query(DBHelper.TABLE_CARS, null, null, null,\n\t\t\t\tnull, null, DBHelper.CAR_COLUMN_TYPE);\n\n\t\twhile (cursor.moveToNext()) {\n\t\t\tCar car = cursorToCar(cursor);\n\t\t\tcarList.add(car);\n\t\t}\n\t\tcursor.close();\n\t\treturn carList;\n\t}\n\n\tpublic List<String> getCarTypesList() {\n\n\t\tList<String> carTypesList = new ArrayList<>();\n\n\t\tCursor cursor = database.query(DBHelper.TABLE_CARS,\n\t\t\t\tnew String[] { DBHelper.CAR_COLUMN_TYPE }, null, null, null,\n\t\t\t\tnull, DBHelper.CAR_COLUMN_TYPE);\n\n\t\twhile (cursor.moveToNext()) {\n\t\t\tcarTypesList.add(cursor.getString(0));\n\t\t}\n\t\tcursor.close();\n\t\treturn carTypesList;\n\t}\n\n\tpublic long addCar(Car car) {\n\n\t\tContentValues values = new ContentValues();\n\t\tvalues.put(DBHelper.CAR_COLUMN_TYPE, car.getType());\n\t\tvalues.put(DBHelper.CAR_COLUMN_BRAND, car.getBrand().value());\n\t\tvalues.put(DBHelper.CAR_COLUMN_NUMBER, car.getNumberPlate());\n\t\tvalues.put(DBHelper.CAR_COLUMN_STARTKM, car.getStartKm());\n\t\tvalues.put(DBHelper.CAR_COLUMN_FUELTPE, car.getFuelType().value());\n\t\tvalues.put(DBHelper.CAR_COLUMN_IMAGEDATA,\n\t\t\t\tgetByteArrayForBitMap(car.getImage()));\n\n\t\ttry {\n\t\t\treturn database.insertOrThrow(DBHelper.TABLE_CARS, null, values);\n\t\t} catch (android.database.SQLException sqe) {\n\t\t\tsqe.printStackTrace();\n\t\t\treturn -1;\n\t\t}\n\t}\n\n\tpublic long updateCar(Car car) {\n\t\tContentValues values = new ContentValues();\n\t\tvalues.put(DBHelper.CAR_COLUMN_TYPE, car.getType());\n\t\tvalues.put(DBHelper.CAR_COLUMN_BRAND, car.getBrand().value());\n\t\tvalues.put(DBHelper.CAR_COLUMN_NUMBER, car.getNumberPlate());\n\t\tvalues.put(DBHelper.CAR_COLUMN_STARTKM, car.getStartKm());\n\t\tvalues.put(DBHelper.CAR_COLUMN_FUELTPE, car.getFuelType().value());\n\t\tvalues.put(DBHelper.CAR_COLUMN_IMAGEDATA,\n\t\t\t\tgetByteArrayForBitMap(car.getImage()));\n\n\t\treturn database.update(DBHelper.TABLE_CARS, values, DBHelper.COLUMN_ID\n\t\t\t\t+ \"=?\", new String[] { String.valueOf(car.getCarId()) });\n\t}\n\n\tpublic int deleteCar(Car car) {\n\t\ttry {\n\t\t\treturn database.delete(DBHelper.TABLE_CARS, DBHelper.COLUMN_ID\n\t\t\t\t\t+ \"=?\", new String[] { String.valueOf(car.getCarId()) });\n\t\t} catch (android.database.SQLException sqe) {\n\t\t\tsqe.printStackTrace();\n\t\t\treturn -1;\n\t\t}\n\t}\n\n\tpublic long storeImageForCar(long carId, Bitmap bitmap) {\n\t\tContentValues values = new ContentValues();\n\t\tvalues.put(DBHelper.CAR_COLUMN_IMAGEDATA, getByteArrayForBitMap(bitmap));\n\t\treturn database.update(DBHelper.TABLE_CARS, values, DBHelper.COLUMN_ID\n\t\t\t\t+ \"=?\", new String[] { String.valueOf(carId) });\n\t}\n\n\tpublic Bitmap getImageForCarId(long carId) {\n\n\t\tCursor cursor = database.query(DBHelper.TABLE_CARS,\n\t\t\t\tnew String[] { DBHelper.CAR_COLUMN_IMAGEDATA },\n\t\t\t\tDBHelper.COLUMN_ID + \"=?\",\n\t\t\t\tnew String[] { String.valueOf(carId) }, null, null, null, \"1\");\n\n\t\tBitmap bm = null;\n\n\t\tif (cursor.moveToFirst()) {\n\t\t\tbm = getBitMapForByteArray(cursor.getBlob(0));\n\t\t}\n\t\tcursor.close();\n\t\treturn bm;\n\t}\n\n\tpublic int deleteConsumption(long consumptionId) {\n\t\ttry {\n\t\t\treturn database.delete(DBHelper.TABLE_CONSUMPTIONS,\n\t\t\t\t\tDBHelper.COLUMN_ID + \"=\" + consumptionId, null);\n\t\t} catch (android.database.SQLException sqe) {\n\t\t\tsqe.printStackTrace();\n\t\t\treturn -1;\n\t\t}\n\t}\n\n\tpublic int deleteConsumptionsForCar(long carId) {\n\t\ttry {\n\t\t\treturn database.delete(DBHelper.TABLE_CONSUMPTIONS,\n\t\t\t\t\tDBHelper.CONSUMPTION_CAR_ID + \"=\" + carId, null);\n\t\t} catch (android.database.SQLException sqe) {\n\t\t\tsqe.printStackTrace();\n\t\t\treturn -1;\n\t\t}\n\t}\n\n\tpublic void addConsumptions(List<Consumption> consumptionCyclesList) {\n\t\tfor (Consumption cycle : consumptionCyclesList) {\n\t\t\taddConsumption(cycle);\n\t\t}\n\t}\n\n\tpublic long addConsumption(Consumption cycle) {\n\n\t\tContentValues values = new ContentValues();\n\t\tvalues.put(DBHelper.CONSUMPTION_CAR_ID, cycle.getCarId());\n\t\tvalues.put(DBHelper.CONSUMPTION_COLUMN_DATE, cycle.getDate().getTime());\n\t\tvalues.put(DBHelper.CONSUMPTION_COLUMN_REFUELMILEAGE,\n\t\t\t\tcycle.getRefuelmileage());\n\t\tvalues.put(DBHelper.CONSUMPTION_COLUMN_REFUELLITERS,\n\t\t\t\tcycle.getRefuelliters());\n\t\tvalues.put(DBHelper.CONSUMPTION_COLUMN_REFUELPRICE,\n\t\t\t\tcycle.getRefuelprice());\n\t\tvalues.put(DBHelper.CONSUMPTION_COLUMN_DRIVENMILEAGE,\n\t\t\t\tcycle.getDrivenmileage());\n\t\tvalues.put(DBHelper.CONSUMPTION_COLUMN_CONSUMPTION,\n\t\t\t\tcycle.getConsumption());\n\n\t\ttry {\n\t\t\treturn database.insertOrThrow(DBHelper.TABLE_CONSUMPTIONS, null,\n\t\t\t\t\tvalues);\n\t\t} catch (android.database.SQLException sqe) {\n\t\t\treturn -1;\n\t\t}\n\t}\n\n\tprivate Car cursorToCar(Cursor cursor) {\n\t\tCar car = new Car();\n\n\t\tcar.setCarId(cursor.getLong(0));\n\t\tcar.setType(cursor.getString(1));\n\t\tcar.setBrand(Brand.fromValue(cursor.getString(2)));\n\t\tcar.setNumberPlate(cursor.getString(3));\n\t\tcar.setStartKm(cursor.getInt(4));\n\t\tcar.setFuelType(Fueltype.fromValue(cursor.getString(5)));\n\t\tcar.setImage(getBitMapForByteArray(cursor.getBlob(6)));\n\t\tcar.setIcon(accessor.getBitmapForBrand(context, car.getBrand()));\n\n\t\treturn car;\n\t}\n\n\tprivate Consumption cursorToConsumption(Cursor cursor) {\n\t\tConsumption consumption = new Consumption();\n\n\t\tconsumption.setId(cursor.getLong(0));\n\t\tconsumption.setCarId(cursor.getLong(1));\n\t\tconsumption.setDate(new Date(cursor.getLong(2)));\n\t\tconsumption.setRefuelmileage(cursor.getInt(3));\n\t\tconsumption.setRefuelliters(cursor.getDouble(4));\n\t\tconsumption.setRefuelprice(cursor.getDouble(5));\n\t\tconsumption.setDrivenmileage(cursor.getInt(6));\n\t\tconsumption.setConsumption(cursor.getDouble(7));\n\n\t\treturn consumption;\n\t}\n\n\tprivate byte[] getByteArrayForBitMap(Bitmap image) {\n\t\tif (image == null) {\n\t\t\treturn new byte[0];\n\t\t}\n\n\t\tByteArrayOutputStream bos = new ByteArrayOutputStream();\n\t\timage.compress(Bitmap.CompressFormat.PNG, 100, bos);\n\t\treturn bos.toByteArray();\n\t}\n\n\tprivate Bitmap getBitMapForByteArray(byte[] blob) {\n\t\tByteArrayInputStream imageStream = new ByteArrayInputStream(blob);\n\t\treturn BitmapFactory.decodeStream(imageStream);\n\t}\n}" }, { "identifier": "FileSystemAccessor", "path": "app/src/main/java/de/anipe/verbrauchsapp/io/FileSystemAccessor.java", "snippet": "public class FileSystemAccessor {\n\n\tprivate static FileSystemAccessor accessor;\n\n\tprivate FileSystemAccessor() {\n\t}\n\n\tpublic static FileSystemAccessor getInstance() {\n\t\tif (accessor == null) {\n\t\t\taccessor = new FileSystemAccessor();\n\t\t}\n\t\treturn accessor;\n\t}\n\n\t/* Checks if external storage is available for read and write */\n\tpublic boolean isExternalStorageWritable() {\n\t\tString state = Environment.getExternalStorageState();\n return Environment.MEDIA_MOUNTED.equals(state);\n }\n\n\t/* Checks if external storage is available to at least read */\n\tpublic boolean isExternalStorageReadable() {\n\t\tString state = Environment.getExternalStorageState();\n return Environment.MEDIA_MOUNTED.equals(state)\n || Environment.MEDIA_MOUNTED_READ_ONLY.equals(state);\n }\n\n\tpublic File createOrGetStorageDir(String folderName) {\n\t\tFile file = new File(Environment.getExternalStorageDirectory(),\n\t\t\t\tfolderName);\n\n\t\tif (file.exists() && file.isDirectory()) {\n\t\t\treturn file;\n\t\t}\n\t\tif (!file.mkdirs()) {\n\t\t\tLog.e(FileSystemAccessor.class.getCanonicalName(),\n\t\t\t\t\t\"Directory not created\");\n\t\t}\n\t\treturn file;\n\t}\n\n\tpublic File getFile() {\n\t\treturn Environment.getExternalStorageDirectory();\n\t}\n\n\tpublic File[] readFilesFromStorageDir(File folder) {\n\t\tif (isExternalStorageReadable()) {\n\t\t\tFile[] files = folder.listFiles();\n\t\t\t\n\t\t\tString[] temp = new String[files.length];\n\t\t\tfor (int i = 0; i < files.length; i++) {\n\t\t\t\ttemp[i] = files[i].getAbsolutePath();\n\t\t\t}\n\t\t\tArrays.sort(temp);\n\t\t\tFile[] out = new File[files.length];\n\t\t\tfor (int i = 0; i < files.length; i++) {\n\t\t\t\tout[i] = new File(temp[i]);\n\t\t\t}\n\t\t\treturn out;\n\t\t\t\n//\t\t\treturn folder.listFiles();\n\t\t}\n\t\treturn null;\n\t}\n\n\tpublic void writeFileToStorageDir(File file, String folderName) {\n\t\tif (isExternalStorageWritable()) {\n\t\t\ttry {\n\t\t\t\tFileOutputStream out = new FileOutputStream(new File(\n\t\t\t\t\t\tcreateOrGetStorageDir(folderName), file.getName()));\n\t\t\t\tout.flush();\n\t\t\t\tout.close();\n\t\t\t} catch (Exception e) {\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic List<String> readCSVFileFromStorage(File csvFile) {\n\t\tList<String> res = new LinkedList<>();\n\n\t\ttry {\n\t\t\tBufferedReader in = new BufferedReader(new FileReader(csvFile));\n\t\t\tString zeile = null;\n\t\t\twhile ((zeile = in.readLine()) != null) {\n\t\t\t\tres.add(zeile);\n\t\t\t}\n\n\t\t\tin.close();\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\n\t\treturn res;\n\t}\n\n\tpublic File writeXMLFileToStorage(Context context, Document doc,\n\t\t\tString folder, String name) throws Exception {\n\n\t\tXMLOutputter xmlOutput = new XMLOutputter();\n\t\txmlOutput.setFormat(Format.getPrettyFormat());\n\n\t\tSimpleDateFormat dateFormat = new SimpleDateFormat(\n\t\t\t\t\"yyyy.MM.dd-HH.mm.ss\", Locale.getDefault());\n\t\tString time = dateFormat.format(new Date());\n\n\t\tFile resultFile = new File(createOrGetStorageDir(folder),\n\t\t\t\tname.replaceAll(\" \", \"_\") + \"_\" + time + \".xml\");\n\t\tFileOutputStream stream = new FileOutputStream(resultFile);\n\n\t\txmlOutput.output(doc, stream);\n\n\t\treturn resultFile;\n\t}\n\n\tpublic Document readXMLDocumentFromFile(String folder, String name)\n\t\t\tthrows Exception {\n\t\tSAXBuilder builder = new SAXBuilder();\n\t\treturn builder.build(new File(folder, name));\n\t}\n\n\tpublic Bitmap getBitmapForBrand(Context context, Brand value) {\n\t\tAssetManager manager = context.getAssets();\n\n\t\tInputStream open = null;\n\t\ttry {\n\t\t\topen = manager.open(value.toString() + \".png\");\n\t\t\treturn BitmapFactory.decodeStream(open);\n\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t} finally {\n\t\t\tif (open != null) {\n\t\t\t\ttry {\n\t\t\t\t\topen.close();\n\t\t\t\t} catch (IOException e) {\n\t\t\t\t\te.printStackTrace();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\n\tpublic Bitmap getBitmapForValue(File file) {\n\t\tFileInputStream streamIn = null;\n\t\ttry {\n\t\t\tstreamIn = new FileInputStream(file);\n\t\t} catch (FileNotFoundException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\tBitmap bitmap = BitmapFactory.decodeStream(streamIn);\n\t\ttry {\n\t\t\tstreamIn.close();\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\treturn bitmap;\n\t}\n}" }, { "identifier": "GDriveAsyncTask", "path": "app/src/main/java/de/anipe/verbrauchsapp/io/GDriveAsyncTask.java", "snippet": "public abstract class GDriveAsyncTask<Params, Progress, Result> extends\n\t\tAsyncTask<Params, Progress, Result> {\n\n\tprivate GoogleApiClient mClient;\n\n\tpublic GDriveAsyncTask(Context context) {\n\t\tGoogleApiClient.Builder builder = new GoogleApiClient.Builder(context)\n\t\t\t\t.addApi(Drive.API).addScope(Drive.SCOPE_FILE);\n\t\tmClient = builder.build();\n\t}\n\n\t@SafeVarargs\n\t@Override\n\tprotected final Result doInBackground(Params... params) {\n\t\tLog.d(\"TAG\", \"in background\");\n\t\tfinal CountDownLatch latch = new CountDownLatch(1);\n\t\tmClient.registerConnectionCallbacks(new ConnectionCallbacks() {\n\t\t\t@Override\n\t\t\tpublic void onConnectionSuspended(int cause) {\n\t\t\t}\n\n\t\t\t@Override\n\t\t\tpublic void onConnected(Bundle arg0) {\n\t\t\t\tlatch.countDown();\n\t\t\t}\n\t\t});\n\t\tmClient.registerConnectionFailedListener(arg0 -> latch.countDown());\n\t\tmClient.connect();\n\t\ttry {\n\t\t\tlatch.await();\n\t\t} catch (InterruptedException e) {\n\t\t\treturn null;\n\t\t}\n\t\tif (!mClient.isConnected()) {\n\t\t\treturn null;\n\t\t}\n\t\ttry {\n\t\t\treturn doInBackgroundConnected(params);\n\t\t} finally {\n\t\t\tmClient.disconnect();\n\t\t}\n\t}\n\n\t/**\n\t * Override this method to perform a computation on a background thread,\n\t * while the client is connected.\n\t */\n\tprotected abstract Result doInBackgroundConnected(Params... params);\n}" }, { "identifier": "XMLHandler", "path": "app/src/main/java/de/anipe/verbrauchsapp/io/XMLHandler.java", "snippet": "public class XMLHandler {\n\n\tprivate Car car;\n\tprivate double cons;\n\tprivate List<Consumption> consumptions;\n\n\tprivate static ConsumptionDataSource dataSource;\n\n\tprivate SimpleDateFormat dateFormat = new SimpleDateFormat(\n\t\t\t\"dd.MM.yyyy-HH.mm.ss\", Locale.getDefault());\n\tprivate SimpleDateFormat shortDateFormat = new SimpleDateFormat(\n\t\t\t\"dd.MM.yyyy\", Locale.getDefault());\n\n\tprivate static final String ROOT_ELEMENT_NAME = \"ConsumptionData\";\n\tprivate static final String CAR_ELEMENT_NAME = \"Car\";\n\tprivate static final String CAR_ID_NAME = \"InAppCarID\";\n\tprivate static final String EXPORT_DATE = \"ExportDatum\";\n\tprivate static final String MANUFACTURER = \"Hersteller\";\n\tprivate static final String TYPE = \"Typ\";\n\tprivate static final String NUMBERPLATE = \"Kennzeichen\";\n\tprivate static final String START_KILOMETER = \"Startkilometer\";\n\tprivate static final String FUELTYPE = \"Kraftstoff\";\n\tprivate static final String OVERALL_CONSUMPTION = \"Durchschnittsverbrauch\";\n\n\tprivate static final String CONSUMPTIONS_ROOT_NAME = \"Consumptions\";\n\tprivate static final String CONSUMPTION_ELEMENT_NAME = \"Consumption\";\n\tprivate static final String DATE_ELEMENT_NAME = \"Datum\";\n\tprivate static final String KILOMETER_STATE_NAME = \"Kilometerstand\";\n\tprivate static final String DRIVEN_KILOMETER_NAME = \"GefahreneKilometer\";\n\tprivate static final String REFUEL_LITER_NAME = \"LiterGetankt\";\n\tprivate static final String LITER_PRICE_NAME = \"PreisJeLiter\";\n\tprivate static final String CONSUMPTION_NAME = \"Verbrauch\";\n\n\tpublic XMLHandler(Context context) {\n\t\tthis(context, null, 0, null);\n\t}\n\n\tpublic XMLHandler(Context context, Car car, double cons,\n\t\t\tList<Consumption> consumptions) {\n\t\tthis.car = car;\n\t\tthis.cons = cons;\n\t\tthis.consumptions = consumptions;\n\n\t\tif (context != null) {\n\t\t\tdataSource = ConsumptionDataSource.getInstance(context);\n\t\t\ttry {\n\t\t\t\tdataSource.open();\n\t\t\t} catch (SQLException e) {\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic long importXMLCarData(File inputFile) {\n\t\ttry {\n\t\t\tSAXBuilder builder = new SAXBuilder();\n\t\t\tDocument doc = builder.build(inputFile);\n\t\t\treturn dataSource.addCar(parseCarFromDocument(doc));\n\t\t} catch (Exception e) {\n\t\t\te.printStackTrace();\n\t\t\tLog.e(\"XMLHandler\", \"Exception while parsing XML document\");\n\t\t}\n\t\treturn -1;\n\t}\n\n public int importXMLCarDataWithConsumption(InputStream input) {\n try {\n SAXBuilder builder = new SAXBuilder();\n Document doc = builder.build(input);\n long carId = dataSource.addCar(parseCarFromDocument(doc));\n List<Consumption> conList = parseConsumptionFromDocument(doc, carId);\n if (conList.size() > 0) {\n dataSource.addConsumptions(conList);\n }\n return conList.size();\n } catch (Exception e) {\n e.printStackTrace();\n Log.e(\"XMLHandler\", \"Exception while parsing XML document\");\n }\n return -1;\n }\n\n\tpublic int importXMLConsumptionDataForCar(long carId, File inputFile) {\n\t\t// remove old entries\n\t\tdataSource.deleteConsumptionsForCar(carId);\n\n\t\ttry {\n\t\t\tSAXBuilder builder = new SAXBuilder();\n\t\t\tDocument doc = builder.build(inputFile);\n\t\t\tList<Consumption> conList = parseConsumptionFromDocument(doc, carId);\n\t\t\tif (conList.size() > 0) {\n\t\t\t\tdataSource.addConsumptions(conList);\n\t\t\t}\n\t\t\treturn conList.size();\n\t\t} catch (Exception e) {\n\t\t\te.printStackTrace();\n\t\t\tLog.e(\"XMLHandler\", \"Exception while parsing XML document\");\n\t\t}\n\t\treturn 0;\n\t}\n\n public int importXMLConsumptionDataForCar(long carId, InputStream inputFile) {\n // remove old entries\n dataSource.deleteConsumptionsForCar(carId);\n\n try {\n SAXBuilder builder = new SAXBuilder();\n Document doc = builder.build(inputFile);\n List<Consumption> conList = parseConsumptionFromDocument(doc, carId);\n if (conList.size() > 0) {\n dataSource.addConsumptions(conList);\n }\n return conList.size();\n } catch (Exception e) {\n e.printStackTrace();\n Log.e(\"XMLHandler\", \"Exception while parsing XML document\");\n }\n return 0;\n }\n\n\tpublic Car parseCarFromDocument(Document doc) {\n\n\t\tElement rootElem = doc.getRootElement();\n\t\tElement carElement = rootElem.getChild(CAR_ELEMENT_NAME);\n\n\t\tCar car = new Car();\n\t\tcar.setCarId(Long.parseLong(carElement.getAttributeValue(CAR_ID_NAME)));\n\t\tcar.setBrand(Brand.fromValue(carElement.getChildText(MANUFACTURER)));\n\t\tcar.setType(carElement.getChildText(TYPE));\n\t\tcar.setNumberPlate(carElement.getChildText(NUMBERPLATE));\n\t\tcar.setStartKm(Integer.parseInt(carElement\n\t\t\t\t.getChildText(START_KILOMETER)));\n\t\tcar.setFuelType(Fueltype.fromValue(carElement.getChildText(FUELTYPE)));\n\n\t\treturn car;\n\t}\n\n\tpublic List<Consumption> parseConsumptionFromDocument(Document doc,\n\t\t\tlong carId) {\n\t\tList<Consumption> cons = new LinkedList<>();\n\t\tList<Element> conList = doc.getRootElement()\n\t\t\t\t.getChild(CONSUMPTIONS_ROOT_NAME)\n\t\t\t\t.getChildren(CONSUMPTION_ELEMENT_NAME);\n\t\tfor (int i = 0; i < conList.size(); i++) {\n\t\t\tElement elem = conList.get(i);\n\n\t\t\tConsumption conElem = new Consumption();\n\t\t\tconElem.setCarId(carId);\n\t\t\tconElem.setDate(getDateFromString(elem\n\t\t\t\t\t.getChildText(DATE_ELEMENT_NAME)));\n\t\t\tconElem.setRefuelmileage(Integer.parseInt(elem\n\t\t\t\t\t.getChildText(KILOMETER_STATE_NAME)));\n\t\t\tconElem.setDrivenmileage(Integer.parseInt(elem\n\t\t\t\t\t.getChildText(DRIVEN_KILOMETER_NAME)));\n\t\t\tconElem.setRefuelliters(Double.parseDouble(elem\n\t\t\t\t\t.getChildText(REFUEL_LITER_NAME)));\n\t\t\tconElem.setRefuelprice(Double.parseDouble(elem\n\t\t\t\t\t.getChildText(LITER_PRICE_NAME)));\n\t\t\tconElem.setConsumption(Double.parseDouble(elem\n\t\t\t\t\t.getChildText(CONSUMPTION_NAME)));\n\n\t\t\tcons.add(conElem);\n\t\t}\n\n\t\treturn cons;\n\t}\n\n\tpublic Document createConsumptionDocument() {\n\t\tElement root = new Element(ROOT_ELEMENT_NAME);\n\t\tDocument doc = new Document(root);\n\t\tdoc.getRootElement().addContent(getCarData(doc, car));\n\t\tdoc.getRootElement().addContent(getConsumptionData(doc, consumptions));\n\n\t\treturn doc;\n\t}\n\n\tprivate Element getCarData(Document doc, Car car) {\n\t\tElement carData = new Element(CAR_ELEMENT_NAME);\n\t\tcarData.setAttribute(new Attribute(CAR_ID_NAME, String.valueOf(car\n\t\t\t\t.getCarId())));\n\n\t\tcarData.addContent(new Element(EXPORT_DATE).setText(getDateTime(\n\t\t\t\tnew Date(), false)));\n\t\tcarData.addContent(new Element(MANUFACTURER).setText(car.getBrand()\n\t\t\t\t.value()));\n\t\tcarData.addContent(new Element(TYPE).setText(car.getType()));\n\t\tcarData.addContent(new Element(NUMBERPLATE).setText(car\n\t\t\t\t.getNumberPlate()));\n\t\tcarData.addContent(new Element(START_KILOMETER).setText(String\n\t\t\t\t.valueOf(car.getStartKm())));\n\t\tcarData.addContent(new Element(FUELTYPE).setText(String.valueOf(car\n\t\t\t\t.getFuelType().value())));\n\t\tcarData.addContent(new Element(OVERALL_CONSUMPTION).setText(String\n\t\t\t\t.valueOf(cons)));\n\n\t\treturn carData;\n\t}\n\n\tprivate Element getConsumptionData(Document doc,\n\t\t\tList<Consumption> consumptions) {\n\t\tElement consumptionData = new Element(CONSUMPTIONS_ROOT_NAME);\n\t\tfor (Consumption con : consumptions) {\n\t\t\tElement consumptionNode = new Element(CONSUMPTION_ELEMENT_NAME);\n\n\t\t\tconsumptionNode.addContent(new Element(DATE_ELEMENT_NAME)\n\t\t\t\t\t.setText(getDateTime(con.getDate(), true)));\n\t\t\tconsumptionNode.addContent(new Element(KILOMETER_STATE_NAME)\n\t\t\t\t\t.setText(String.valueOf(con.getRefuelmileage())));\n\t\t\tconsumptionNode.addContent(new Element(DRIVEN_KILOMETER_NAME)\n\t\t\t\t\t.setText(String.valueOf(con.getDrivenmileage())));\n\t\t\tconsumptionNode.addContent(new Element(REFUEL_LITER_NAME)\n\t\t\t\t\t.setText(String.valueOf(con.getRefuelliters())));\n\t\t\tconsumptionNode.addContent(new Element(LITER_PRICE_NAME)\n\t\t\t\t\t.setText(String.valueOf(con.getRefuelprice())));\n\t\t\tconsumptionNode.addContent(new Element(CONSUMPTION_NAME)\n\t\t\t\t\t.setText(String.valueOf(con.getConsumption())));\n\n\t\t\tconsumptionData.addContent(consumptionNode);\n\t\t}\n\t\treturn consumptionData;\n\t}\n\n\tprivate String getDateTime(Date date, boolean shortFormat) {\n\t\tif (!shortFormat) {\n\t\t\treturn dateFormat.format(date);\n\t\t}\n\t\treturn shortDateFormat.format(date);\n\t}\n\n\tprivate Date getDateFromString(String dateString) {\n\t\ttry {\n\t\t\treturn shortDateFormat.parse(dateString);\n\t\t} catch (ParseException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\treturn null;\n\t}\n}" }, { "identifier": "Car", "path": "app/src/main/java/de/anipe/verbrauchsapp/objects/Car.java", "snippet": "public class Car implements Comparable<Car> {\n\n\tprivate long carId;\n\tprivate String type;\n\tprivate Brand brand;\n\tprivate String numberPlate;\n\tprivate Fueltype fuelType;\n\tprivate int startKm;\n\tprivate Bitmap icon;\n\tprivate Bitmap image;\n\n\tpublic Car() {\n\t}\n\n public Car(String type, Brand brand, String numberPlate, Fueltype fuelType,\n\t\t\tint startKm, Bitmap icon) {\n\t\tthis.carId = -1;\n\t\tthis.type = type;\n\t\tthis.numberPlate = numberPlate;\n\t\tthis.fuelType = fuelType;\n\t\tthis.startKm = startKm;\n\t\tthis.icon = icon;\n\t}\n\n\tpublic long getCarId() {\n\t\treturn carId;\n\t}\n\n\tpublic void setCarId(long carId) {\n\t\tthis.carId = carId;\n\t}\n\n\tpublic String getType() {\n\t\treturn type;\n\t}\n\n\tpublic void setType(String type) {\n\t\tthis.type = type;\n\t}\n\n\tpublic Brand getBrand() {\n\t\treturn brand;\n\t}\n\n\tpublic void setBrand(Brand brand) {\n\t\tthis.brand = brand;\n\t}\n\n\tpublic String getNumberPlate() {\n\t\treturn numberPlate;\n\t}\n\n\tpublic void setNumberPlate(String numberPlate) {\n\t\tthis.numberPlate = numberPlate;\n\t}\n\n\tpublic Fueltype getFuelType() {\n\t\treturn fuelType;\n\t}\n\n\tpublic void setFuelType(Fueltype fuelType) {\n\t\tthis.fuelType = fuelType;\n\t}\n\n\tpublic int getStartKm() {\n\t\treturn startKm;\n\t}\n\n\tpublic void setStartKm(int startKm) {\n\t\tthis.startKm = startKm;\n\t}\n\n\t@Override\n\tpublic int compareTo(Car another) {\n\t\treturn this.type.compareTo(another.type);\n\t}\n\n\tpublic Bitmap getIcon() {\n\t\treturn icon;\n\t}\n\n\tpublic void setIcon(Bitmap icon) {\n\t\tthis.icon = icon;\n\t}\n\n\tpublic Bitmap getImage() {\n\t\treturn image;\n\t}\n\n\tpublic void setImage(Bitmap image) {\n\t\tthis.image = image;\n\t}\n\n @Override\n public String toString() {\n return getType() + \" \" + getNumberPlate();\n }\n\n @Override\n public boolean equals(Object o) {\n return o instanceof Car && compareTo((Car) o) == 0;\n }\n\n @Override\n public int hashCode() {\n return (int)getCarId();\n }\n}" } ]
import android.content.Context; import android.content.Intent; import android.content.IntentSender.SendIntentException; import android.graphics.Color; import android.os.Bundle; import androidx.appcompat.widget.Toolbar; import android.util.Log; import android.view.MenuItem; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.GooglePlayServicesUtil; import com.google.android.gms.drive.Drive; import com.google.android.gms.drive.DriveApi.DriveContentsResult; import com.google.android.gms.drive.DriveContents; import com.google.android.gms.drive.DriveFolder; import com.google.android.gms.drive.DriveFolder.DriveFileResult; import com.google.android.gms.drive.DriveResource.MetadataResult; import com.google.android.gms.drive.Metadata; import com.google.android.gms.drive.MetadataChangeSet; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.sql.SQLException; import de.anipe.verbrauchsapp.db.ConsumptionDataSource; import de.anipe.verbrauchsapp.io.FileSystemAccessor; import de.anipe.verbrauchsapp.io.GDriveAsyncTask; import de.anipe.verbrauchsapp.io.XMLHandler; import de.anipe.verbrauchsapp.objects.Car;
8,037
package de.anipe.verbrauchsapp; public class GDriveStoreActivity extends GDriveBaseActivity { private File outputFile; private long carId; private FileSystemAccessor accessor; private ConsumptionDataSource dataSource; private static final int REQUEST_CODE_CREATOR = 1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent intent = getIntent(); Bundle bundle = intent.getExtras(); carId = bundle.getLong("carid"); setContentView(R.layout.activity_gdrive_upload); Toolbar myToolbar = findViewById(R.id.toolbar); setSupportActionBar(myToolbar); accessor = FileSystemAccessor.getInstance(); dataSource = ConsumptionDataSource.getInstance(this); try { dataSource.open(); } catch (SQLException e) { Toast.makeText(GDriveStoreActivity.this, "Fehler beim Öffnen der Datenbank!", Toast.LENGTH_LONG) .show(); } // Step 1: write to local XML file writeXMLFileToLocalFileSystem(); if (outputFile == null) { Log.e("GDriveStoreActivity", "Output file is null. Nothing to write to Google Drive. Aborting Activity."); finish(); } getSupportActionBar().setDisplayHomeAsUpEnabled(true); } // @Override // protected void onResume() { // super.onResume(); // // // Step 1: write to local XML file // writeXMLFileToLocalFileSystem(); // // // Step 2: upload to the cloud // if (outputFile != null) { // if (getGoogleApiClient() == null) { // mGoogleApiClient = new GoogleApiClient.Builder(this) // .addApi(Drive.API).addScope(Drive.SCOPE_FILE) // .addScope(Drive.SCOPE_APPFOLDER) // .addConnectionCallbacks(this) // .addOnConnectionFailedListener(this).build(); // } // mGoogleApiClient.connect(); // } else { // finish(); // } // } private void writeXMLFileToLocalFileSystem() { Car car = dataSource.getCarForId(carId);
package de.anipe.verbrauchsapp; public class GDriveStoreActivity extends GDriveBaseActivity { private File outputFile; private long carId; private FileSystemAccessor accessor; private ConsumptionDataSource dataSource; private static final int REQUEST_CODE_CREATOR = 1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent intent = getIntent(); Bundle bundle = intent.getExtras(); carId = bundle.getLong("carid"); setContentView(R.layout.activity_gdrive_upload); Toolbar myToolbar = findViewById(R.id.toolbar); setSupportActionBar(myToolbar); accessor = FileSystemAccessor.getInstance(); dataSource = ConsumptionDataSource.getInstance(this); try { dataSource.open(); } catch (SQLException e) { Toast.makeText(GDriveStoreActivity.this, "Fehler beim Öffnen der Datenbank!", Toast.LENGTH_LONG) .show(); } // Step 1: write to local XML file writeXMLFileToLocalFileSystem(); if (outputFile == null) { Log.e("GDriveStoreActivity", "Output file is null. Nothing to write to Google Drive. Aborting Activity."); finish(); } getSupportActionBar().setDisplayHomeAsUpEnabled(true); } // @Override // protected void onResume() { // super.onResume(); // // // Step 1: write to local XML file // writeXMLFileToLocalFileSystem(); // // // Step 2: upload to the cloud // if (outputFile != null) { // if (getGoogleApiClient() == null) { // mGoogleApiClient = new GoogleApiClient.Builder(this) // .addApi(Drive.API).addScope(Drive.SCOPE_FILE) // .addScope(Drive.SCOPE_APPFOLDER) // .addConnectionCallbacks(this) // .addOnConnectionFailedListener(this).build(); // } // mGoogleApiClient.connect(); // } else { // finish(); // } // } private void writeXMLFileToLocalFileSystem() { Car car = dataSource.getCarForId(carId);
XMLHandler handler = new XMLHandler(null, car,
3
2023-12-28 12:33:52+00:00
12k
strokegmd/StrokeClient
stroke/client/modules/render/PlayerESP.java
[ { "identifier": "StrokeClient", "path": "stroke/client/StrokeClient.java", "snippet": "public class StrokeClient {\r\n\tpublic static Minecraft mc;\r\n\t\r\n\tpublic static String dev_username = \"megao4ko\";\r\n\tpublic static String title = \"[stroke] client ・ v1.0.00 | Minecraft 1.12.2\";\r\n\tpublic static String name = \"[stroke] client ・ \";\r\n\tpublic static String version = \"v1.0.00\";\r\n\t\r\n\tpublic static StrokeClient instance;\r\n\tpublic static ClickGuiScreen clickGui;\r\n\t\r\n\tpublic static SettingsManager settingsManager;\r\n\t\r\n\tpublic static boolean destructed = false;\r\n\t\r\n\tpublic StrokeClient()\r\n\t{\r\n\t\tinstance = this;\r\n\t\tsettingsManager = new SettingsManager();\r\n\t\tclickGui = new ClickGuiScreen();\r\n\t}\r\n\t\r\n\tpublic static void launchClient() {\r\n\t\tmc = Minecraft.getMinecraft();\r\n\t\tsettingsManager = new SettingsManager();\r\n\t\t\r\n\t\tViaMCP.getInstance().start();\r\n\t\t\r\n\t\tSystem.out.println(\"[Stroke] Launching Stroke Client \" + version + \"!\");\r\n\t\t\r\n\t\tModuleManager.loadModules();\r\n\t\tCommandManager.loadCommands();\r\n\t\t\r\n\t\tfor(BaseModule module : ModuleManager.modules) {\r\n\t\t\tif(module.autoenable) {\r\n\t\t\t\tmodule.toggle(); module.toggle(); // bugfix lmao\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\tclickGui = new ClickGuiScreen();\r\n\t\t\r\n\t\tSystem.out.println(\"[Stroke] All done!\");\r\n\t}\r\n\t\r\n\tpublic static void onKeyPress(int key) {\r\n\t\tfor(BaseModule module : ModuleManager.modules) {\r\n\t\t\tif(module.keybind == key && !(mc.currentScreen instanceof GuiChat) && !(mc.currentScreen instanceof GuiContainer) && !(mc.currentScreen instanceof GuiEditSign)) {\r\n\t\t\t\tmodule.toggle();\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic static int getScaledWidth() {\r\n\t\tmc = Minecraft.getMinecraft();\r\n\t\tScaledResolution sr = new ScaledResolution(mc);\r\n\t\treturn sr.getScaledWidth();\r\n\t}\r\n\t\r\n\tpublic static int getScaledHeight() {\r\n\t\tmc = Minecraft.getMinecraft();\r\n\t\tScaledResolution sr = new ScaledResolution(mc);\r\n\t\treturn sr.getScaledHeight();\r\n\t}\r\n\t\r\n\tpublic static int getDisplayWidth() {\r\n\t\tmc = Minecraft.getMinecraft();\r\n\t\treturn mc.displayWidth / 2;\r\n\t}\r\n\t\r\n\tpublic static int getDisplayHeight() {\r\n\t\tmc = Minecraft.getMinecraft();\r\n\t\treturn mc.displayHeight / 2;\r\n\t}\r\n\t\r\n\tpublic static String getUsername() {\r\n\t\tmc = Minecraft.getMinecraft();\r\n\t\treturn mc.getSession().getUsername();\r\n\t}\r\n\t\r\n\tpublic static void sendChatMessage(String message) {\r\n\t\tmc = Minecraft.getMinecraft();\r\n\t\tTextComponentString component = new TextComponentString(\"[\\2479Stroke§r] \" + message);\r\n\t\tmc.ingameGUI.getChatGUI().printChatMessage(component);\r\n\t}\r\n}" }, { "identifier": "Setting", "path": "stroke/client/clickgui/Setting.java", "snippet": "public class Setting {\n\t\n\tprivate String name;\n\tprivate BaseModule parent;\n\tprivate String mode;\n\t\n\tprivate String sval;\n\tprivate ArrayList<String> options;\n\tprivate String title;\n\t\n\tprivate boolean bval;\n\t\n\tprivate double dval;\n\tprivate double min;\n\tprivate double max;\n\tprivate boolean onlyint = false;\n\t\n\tprivate String text;\n\t\n\tprivate int color;\n\t\n\tpublic Setting(String name, BaseModule parent, ArrayList<String> options, String title){\n\t\tthis.name = name;\n\t\tthis.parent = parent;\n\t\tthis.options = options;\n\t\tthis.title = title;\n\t\tthis.mode = \"Combo\";\n\t}\n\t\n\tpublic Setting(String name, BaseModule parent, boolean bval){\n\t\tthis.name = name;\n\t\tthis.parent = parent;\n\t\tthis.bval = bval;\n\t\tthis.mode = \"Check\";\n\t}\n\t\n\tpublic Setting(String name, BaseModule parent, double dval, double min, double max, boolean onlyint){\n\t\tthis.name = name;\n\t\tthis.parent = parent;\n\t\tthis.dval = dval;\n\t\tthis.min = min;\n\t\tthis.max = max;\n\t\tthis.onlyint = onlyint;\n\t\tthis.mode = \"Slider\";\n\t}\n\n\t\n\tpublic String getName(){\n\t\treturn name;\n\t}\n\t\n\tpublic BaseModule getParentMod(){\n\t\treturn parent;\n\t}\n\t\n\tpublic String getValString(){\n\t\treturn this.sval;\n\t}\n\t\n\tpublic void setValString(String in){\n\t\tthis.sval = in;\n\t}\n\t\n\tpublic ArrayList<String> getOptions(){\n\t\treturn this.options;\n\t}\n\t\n\tpublic String getTitle(){\n\t\treturn this.title;\n\t}\n\t\n\tpublic boolean getValBoolean(){\n\t\treturn this.bval;\n\t}\n\t\n\tpublic void setValBoolean(boolean in){\n\t\tthis.bval = in;\n\t}\n\t\n\tpublic double getValDouble(){\n\t\tif(this.onlyint){\n\t\t\tthis.dval = (int)dval;\n\t\t}\n\t\treturn this.dval;\n\t}\n\n\tpublic void setValDouble(double in){\n\t\tthis.dval = in;\n\t}\n\t\n\tpublic double getMin(){\n\t\treturn this.min;\n\t}\n\t\n\tpublic double getMax(){\n\t\treturn this.max;\n\t}\n\t\n\tpublic int getColor(){\n\t\treturn this.color;\n\t}\n\t\n\tpublic String getString(){\n\t\treturn this.text;\n\t}\n\t\n\tpublic boolean isCombo(){\n\t\treturn this.mode.equalsIgnoreCase(\"Combo\") ? true : false;\n\t}\n\t\n\tpublic boolean isCheck(){\n\t\treturn this.mode.equalsIgnoreCase(\"Check\") ? true : false;\n\t}\n\t\n\tpublic boolean isSlider(){\n\t\treturn this.mode.equalsIgnoreCase(\"Slider\") ? true : false;\n\t}\n\t\n\tpublic boolean isMode(){\n\t\treturn this.mode.equalsIgnoreCase(\"ModeButton\") ? true : false;\n\t}\n\t\n\tpublic boolean onlyInt(){\n\t\treturn this.onlyint;\n\t}\n}" }, { "identifier": "BaseModule", "path": "stroke/client/modules/BaseModule.java", "snippet": "public class BaseModule {\r\n\tpublic static Minecraft mc = Minecraft.getMinecraft();\r\n\t\r\n\tpublic String name;\r\n\tpublic String tooltip;\r\n\t\r\n\tpublic ModuleCategory category;\r\n\tpublic int keybind;\r\n\t\r\n\tpublic boolean autoenable;\r\n\tpublic boolean enabled;\r\n\t\r\n\tpublic Map<String, Integer> settings = new HashMap();\r\n\t\r\n\tpublic int posX;\r\n\tpublic int posY;\r\n\t\r\n\tpublic BaseModule(String name, String tooltip, int keybind, ModuleCategory category, boolean autoenable) {\r\n\t\tthis.name = name;\r\n\t\tthis.tooltip = tooltip;\r\n\t\tthis.category = category;\r\n\t\tthis.keybind = keybind;\r\n\t\tthis.autoenable = autoenable;\r\n\t\tthis.enabled = autoenable;\r\n\t\t\r\n\t\tSystem.out.println(\"[Stroke] Loaded \" + this.name + \"!\");\r\n\t}\r\n\t\r\n\tpublic void toggle() {\r\n\t\tthis.enabled = !this.enabled;\r\n\t\tif(this.enabled) {\r\n\t\t\tthis.onEnable();\r\n\t\t} else {\r\n\t\t\tthis.onDisable();\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic void setKey(int key)\r\n\t{\r\n\t\tthis.keybind = key;\r\n\t}\r\n\t\r\n\tpublic void onEnable() {}\r\n\tpublic void onUpdate() {}\r\n\tpublic void onRender() {}\r\n\tpublic void onRender3D() {}\r\n\tpublic void onDisable() {}\r\n}" }, { "identifier": "ModuleCategory", "path": "stroke/client/modules/ModuleCategory.java", "snippet": "public enum ModuleCategory {\r\n\tCombat, Movement, Player, Render, Fun, Misc\r\n}\r" }, { "identifier": "FriendsManager", "path": "stroke/client/util/FriendsManager.java", "snippet": "public class FriendsManager {\r\n\tpublic static ArrayList<String> friends = new ArrayList<String>();\r\n\t\r\n\tpublic static void addFriend(String username) {\r\n\t\tfriends.add(username);\r\n\t}\r\n\t\r\n\tpublic static void removeFriend(String username) {\r\n\t\tfriends.remove(username);\r\n\t}\r\n\t\r\n\tpublic static boolean isFriend(String username) {\r\n\t\treturn friends.contains(username);\r\n\t}\r\n}\r" }, { "identifier": "RenderUtils", "path": "stroke/client/util/RenderUtils.java", "snippet": "public class RenderUtils {\r\n\tpublic static void blockESP(BlockPos b, Color c, double length, double length2) {\r\n\t\tblockEsp(b, c, length, length2);\r\n\t}\r\n\t\r\n\tpublic static void drawRect(float paramXStart, float paramYStart, float paramXEnd, float paramYEnd, int paramColor)\r\n\t{\r\n\t\tfloat alpha = (float)(paramColor >> 24 & 0xFF) / 255F;\r\n\t\tfloat red = (float)(paramColor >> 16 & 0xFF) / 255F;\r\n\t\tfloat green = (float)(paramColor >> 8 & 0xFF) / 255F;\r\n\t\tfloat blue = (float)(paramColor & 0xFF) / 255F;\r\n\t\tGL11.glPushMatrix();\r\n\t\tGL11.glEnable(GL11.GL_BLEND);\r\n\t\tGL11.glDisable(GL11.GL_TEXTURE_2D);\r\n\t\tGL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);\r\n\t\tGL11.glEnable(GL11.GL_LINE_SMOOTH);\r\n\r\n\t\tGL11.glColor4f(red, green, blue, alpha);\r\n\t\tGL11.glBegin(GL11.GL_QUADS);\r\n\t\tGL11.glVertex2d(paramXEnd, paramYStart);\r\n\t\tGL11.glVertex2d(paramXStart, paramYStart);\r\n\t\tGL11.glVertex2d(paramXStart, paramYEnd);\r\n\t\tGL11.glVertex2d(paramXEnd, paramYEnd);\r\n\t\tGL11.glEnd();\r\n\r\n\t\tGL11.glEnable(GL11.GL_TEXTURE_2D);\r\n\t\tGL11.glDisable(GL11.GL_BLEND);\r\n\t\tGL11.glDisable(GL11.GL_LINE_SMOOTH);\r\n\t\tGL11.glPopMatrix();\r\n\t}\r\n\t\r\n\tpublic static void drawBorderedRect(double x, double y, double x2, double y2, float l1, int col1, int col2) {\r\n drawRect((float)x, (float)y, (float)x2, (float)y2, col2);\r\n\r\n float f = (float)(col1 >> 24 & 0xFF) / 255F;\r\n float f1 = (float)(col1 >> 16 & 0xFF) / 255F;\r\n float f2 = (float)(col1 >> 8 & 0xFF) / 255F;\r\n float f3 = (float)(col1 & 0xFF) / 255F;\r\n GL11.glPushMatrix();\r\n GL11.glEnable(GL11.GL_BLEND);\r\n GL11.glDisable(GL11.GL_TEXTURE_2D);\r\n GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);\r\n GL11.glEnable(GL11.GL_LINE_SMOOTH);\r\n\r\n GL11.glColor4f(f1, f2, f3, f);\r\n GL11.glLineWidth(l1);\r\n GL11.glBegin(GL11.GL_LINES);\r\n GL11.glVertex2d(x, y);\r\n GL11.glVertex2d(x, y2);\r\n GL11.glVertex2d(x2, y2);\r\n GL11.glVertex2d(x2, y);\r\n GL11.glVertex2d(x, y);\r\n GL11.glVertex2d(x2, y);\r\n GL11.glVertex2d(x, y2);\r\n GL11.glVertex2d(x2, y2);\r\n GL11.glEnd();\r\n\r\n GL11.glEnable(GL11.GL_TEXTURE_2D);\r\n GL11.glDisable(GL11.GL_BLEND);\r\n GL11.glDisable(GL11.GL_LINE_SMOOTH);\r\n GL11.glPopMatrix();\r\n\t}\r\n\r\n\t/**\r\n\t * Renders an ESP box with the size of a normal block at the specified\r\n\t * BlockPos.\r\n\t */\r\n\tpublic static void blockEsp(BlockPos blockPos, Color c, double length, double length2) {\r\n\t\tdouble x = blockPos.getX() - Minecraft.getMinecraft().getRenderManager().renderPosX;\r\n\t\tdouble y = blockPos.getY() - Minecraft.getMinecraft().getRenderManager().renderPosY;\r\n\t\tdouble z = blockPos.getZ() - Minecraft.getMinecraft().getRenderManager().renderPosZ;\r\n\t\tGL11.glPushMatrix();\r\n\t\tGL11.glBlendFunc(770, 771);\r\n\t\tGL11.glEnable(GL_BLEND);\r\n\t\tGL11.glLineWidth(2.0F);\r\n\t\tGL11.glDisable(GL11.GL_TEXTURE_2D);\r\n\t\tGL11.glDisable(GL_DEPTH_TEST);\r\n\t\tGL11.glDepthMask(false);\r\n\t\tGL11.glColor4d(c.getRed() / 255f, c.getGreen() / 255f, c.getBlue() / 255f, 0.25);\r\n\t\tdrawColorBox(new AxisAlignedBB(x, y, z, x + length2, y + 1.0, z + length), 0F, 0F, 0F, 0F);\r\n\t\tGL11.glColor4d(0, 0, 0, 0.5);\r\n\t\t//drawSelectionBoundingBox(new AxisAlignedBB(x, y, z, x + length2, y + 1.0, z + length));\r\n\t\tGL11.glLineWidth(2.0F);\r\n\t\tGL11.glEnable(GL11.GL_TEXTURE_2D);\r\n\t\tGL11.glEnable(GL_DEPTH_TEST);\r\n\t\tGL11.glDepthMask(true);\r\n\t\tGL11.glDisable(GL_BLEND);\r\n\t\tGL11.glPopMatrix();\r\n\t}\r\n\r\n\r\n\tpublic static void searchBox(BlockPos blockPos) {\r\n\t\tdouble x = blockPos.getX() - Minecraft.getMinecraft().getRenderManager().renderPosX;\r\n\t\tdouble y = blockPos.getY() - Minecraft.getMinecraft().getRenderManager().renderPosY;\r\n\t\tdouble z = blockPos.getZ() - Minecraft.getMinecraft().getRenderManager().renderPosZ;\r\n\t\tGL11.glBlendFunc(770, 771);\r\n\t\tGL11.glEnable(GL_BLEND);\r\n\t\tGL11.glLineWidth(1.0F);\r\n\t\tfloat sinus = 1F - MathHelper\r\n\t\t\t\t.abs(MathHelper.sin(Minecraft.getSystemTime() % 10000L / 10000.0F * (float) Math.PI * 4.0F) * 1F);\r\n\t\tGL11.glDisable(GL11.GL_TEXTURE_2D);\r\n\t\tGL11.glDisable(GL_DEPTH_TEST);\r\n\t\tGL11.glDepthMask(false);\r\n\t\tGL11.glColor4f(1F - sinus, sinus, 0F, 0.15F);\r\n\t\tdrawColorBox(new AxisAlignedBB(x, y, z, x + 1.0, y + 1.0, z + 1.0), 1F - sinus, sinus, 0F, 0.15F);\r\n\t\tGL11.glColor4d(0, 0, 0, 0.5);\r\n\t\tdrawSelectionBoundingBox(new AxisAlignedBB(x, y, z, x + 1.0, y + 1.0, z + 1.0));\r\n\t\tGL11.glEnable(GL11.GL_TEXTURE_2D);\r\n\t\tGL11.glEnable(GL_DEPTH_TEST);\r\n\t\tGL11.glDepthMask(true);\r\n\t\tGL11.glDisable(GL_BLEND);\r\n\t}\r\n\r\n\tpublic static void drawColorBox(AxisAlignedBB axisalignedbb, float red, float green, float blue, float alpha) {\r\n\t\tTessellator ts = Tessellator.getInstance();\r\n\t\tBufferBuilder vb = ts.getBuffer();\r\n\t\tvb.begin(7, DefaultVertexFormats.POSITION_TEX);// Starts X.\r\n\t\tvb.pos(axisalignedbb.minX, axisalignedbb.minY, axisalignedbb.minZ).color(red, green, blue, alpha).endVertex();\r\n\t\tvb.pos(axisalignedbb.minX, axisalignedbb.maxY, axisalignedbb.minZ).color(red, green, blue, alpha).endVertex();\r\n\t\tvb.pos(axisalignedbb.maxX, axisalignedbb.minY, axisalignedbb.minZ).color(red, green, blue, alpha).endVertex();\r\n\t\tvb.pos(axisalignedbb.maxX, axisalignedbb.maxY, axisalignedbb.minZ).color(red, green, blue, alpha).endVertex();\r\n\t\tvb.pos(axisalignedbb.maxX, axisalignedbb.minY, axisalignedbb.maxZ).color(red, green, blue, alpha).endVertex();\r\n\t\tvb.pos(axisalignedbb.maxX, axisalignedbb.maxY, axisalignedbb.maxZ).color(red, green, blue, alpha).endVertex();\r\n\t\tvb.pos(axisalignedbb.minX, axisalignedbb.minY, axisalignedbb.maxZ).color(red, green, blue, alpha).endVertex();\r\n\t\tvb.pos(axisalignedbb.minX, axisalignedbb.maxY, axisalignedbb.maxZ).color(red, green, blue, alpha).endVertex();\r\n\t\tts.draw();\r\n\t\tvb.begin(7, DefaultVertexFormats.POSITION_TEX);\r\n\t\tvb.pos(axisalignedbb.maxX, axisalignedbb.maxY, axisalignedbb.minZ).color(red, green, blue, alpha).endVertex();\r\n\t\tvb.pos(axisalignedbb.maxX, axisalignedbb.minY, axisalignedbb.minZ).color(red, green, blue, alpha).endVertex();\r\n\t\tvb.pos(axisalignedbb.minX, axisalignedbb.maxY, axisalignedbb.minZ).color(red, green, blue, alpha).endVertex();\r\n\t\tvb.pos(axisalignedbb.minX, axisalignedbb.minY, axisalignedbb.minZ).color(red, green, blue, alpha).endVertex();\r\n\t\tvb.pos(axisalignedbb.minX, axisalignedbb.maxY, axisalignedbb.maxZ).color(red, green, blue, alpha).endVertex();\r\n\t\tvb.pos(axisalignedbb.minX, axisalignedbb.minY, axisalignedbb.maxZ).color(red, green, blue, alpha).endVertex();\r\n\t\tvb.pos(axisalignedbb.maxX, axisalignedbb.maxY, axisalignedbb.maxZ).color(red, green, blue, alpha).endVertex();\r\n\t\tvb.pos(axisalignedbb.maxX, axisalignedbb.minY, axisalignedbb.maxZ).color(red, green, blue, alpha).endVertex();\r\n\t\tts.draw();// Ends X.\r\n\t\tvb.begin(7, DefaultVertexFormats.POSITION_TEX);// Starts Y.\r\n\t\tvb.pos(axisalignedbb.minX, axisalignedbb.maxY, axisalignedbb.minZ).color(red, green, blue, alpha).endVertex();\r\n\t\tvb.pos(axisalignedbb.maxX, axisalignedbb.maxY, axisalignedbb.minZ).color(red, green, blue, alpha).endVertex();\r\n\t\tvb.pos(axisalignedbb.maxX, axisalignedbb.maxY, axisalignedbb.maxZ).color(red, green, blue, alpha).endVertex();\r\n\t\tvb.pos(axisalignedbb.minX, axisalignedbb.maxY, axisalignedbb.maxZ).color(red, green, blue, alpha).endVertex();\r\n\t\tvb.pos(axisalignedbb.minX, axisalignedbb.maxY, axisalignedbb.minZ).color(red, green, blue, alpha).endVertex();\r\n\t\tvb.pos(axisalignedbb.minX, axisalignedbb.maxY, axisalignedbb.maxZ).color(red, green, blue, alpha).endVertex();\r\n\t\tvb.pos(axisalignedbb.maxX, axisalignedbb.maxY, axisalignedbb.maxZ).color(red, green, blue, alpha).endVertex();\r\n\t\tvb.pos(axisalignedbb.maxX, axisalignedbb.maxY, axisalignedbb.minZ).color(red, green, blue, alpha).endVertex();\r\n\t\tts.draw();\r\n\t\tvb.begin(7, DefaultVertexFormats.POSITION_TEX);\r\n\t\tvb.pos(axisalignedbb.minX, axisalignedbb.minY, axisalignedbb.minZ).color(red, green, blue, alpha).endVertex();\r\n\t\tvb.pos(axisalignedbb.maxX, axisalignedbb.minY, axisalignedbb.minZ).color(red, green, blue, alpha).endVertex();\r\n\t\tvb.pos(axisalignedbb.maxX, axisalignedbb.minY, axisalignedbb.maxZ).color(red, green, blue, alpha).endVertex();\r\n\t\tvb.pos(axisalignedbb.minX, axisalignedbb.minY, axisalignedbb.maxZ).color(red, green, blue, alpha).endVertex();\r\n\t\tvb.pos(axisalignedbb.minX, axisalignedbb.minY, axisalignedbb.minZ).color(red, green, blue, alpha).endVertex();\r\n\t\tvb.pos(axisalignedbb.minX, axisalignedbb.minY, axisalignedbb.maxZ).color(red, green, blue, alpha).endVertex();\r\n\t\tvb.pos(axisalignedbb.maxX, axisalignedbb.minY, axisalignedbb.maxZ).color(red, green, blue, alpha).endVertex();\r\n\t\tvb.pos(axisalignedbb.maxX, axisalignedbb.minY, axisalignedbb.minZ).color(red, green, blue, alpha).endVertex();\r\n\t\tts.draw();// Ends Y.\r\n\t\tvb.begin(7, DefaultVertexFormats.POSITION_TEX);// Starts Z.\r\n\t\tvb.pos(axisalignedbb.minX, axisalignedbb.minY, axisalignedbb.minZ).color(red, green, blue, alpha).endVertex();\r\n\t\tvb.pos(axisalignedbb.minX, axisalignedbb.maxY, axisalignedbb.minZ).color(red, green, blue, alpha).endVertex();\r\n\t\tvb.pos(axisalignedbb.minX, axisalignedbb.minY, axisalignedbb.maxZ).color(red, green, blue, alpha).endVertex();\r\n\t\tvb.pos(axisalignedbb.minX, axisalignedbb.maxY, axisalignedbb.maxZ).color(red, green, blue, alpha).endVertex();\r\n\t\tvb.pos(axisalignedbb.maxX, axisalignedbb.minY, axisalignedbb.maxZ).color(red, green, blue, alpha).endVertex();\r\n\t\tvb.pos(axisalignedbb.maxX, axisalignedbb.maxY, axisalignedbb.maxZ).color(red, green, blue, alpha).endVertex();\r\n\t\tvb.pos(axisalignedbb.maxX, axisalignedbb.minY, axisalignedbb.minZ).color(red, green, blue, alpha).endVertex();\r\n\t\tvb.pos(axisalignedbb.maxX, axisalignedbb.maxY, axisalignedbb.minZ).color(red, green, blue, alpha).endVertex();\r\n\t\tts.draw();\r\n\t\tvb.begin(7, DefaultVertexFormats.POSITION_TEX);\r\n\t\tvb.pos(axisalignedbb.minX, axisalignedbb.maxY, axisalignedbb.maxZ).color(red, green, blue, alpha).endVertex();\r\n\t\tvb.pos(axisalignedbb.minX, axisalignedbb.minY, axisalignedbb.maxZ).color(red, green, blue, alpha).endVertex();\r\n\t\tvb.pos(axisalignedbb.minX, axisalignedbb.maxY, axisalignedbb.minZ).color(red, green, blue, alpha).endVertex();\r\n\t\tvb.pos(axisalignedbb.minX, axisalignedbb.minY, axisalignedbb.minZ).color(red, green, blue, alpha).endVertex();\r\n\t\tvb.pos(axisalignedbb.maxX, axisalignedbb.maxY, axisalignedbb.minZ).color(red, green, blue, alpha).endVertex();\r\n\t\tvb.pos(axisalignedbb.maxX, axisalignedbb.minY, axisalignedbb.minZ).color(red, green, blue, alpha).endVertex();\r\n\t\tvb.pos(axisalignedbb.maxX, axisalignedbb.maxY, axisalignedbb.maxZ).color(red, green, blue, alpha).endVertex();\r\n\t\tvb.pos(axisalignedbb.maxX, axisalignedbb.minY, axisalignedbb.maxZ).color(red, green, blue, alpha).endVertex();\r\n\t\tts.draw();// Ends Z.\r\n\t}\r\n\t\r\n\tpublic static void drawSelectionBoundingBox(AxisAlignedBB boundingBox) {\r\n\t\tTessellator tessellator = Tessellator.getInstance();\r\n\t\tBufferBuilder vertexbuffer = tessellator.getBuffer();\r\n\t\tvertexbuffer.begin(3, DefaultVertexFormats.POSITION);\r\n\t\tvertexbuffer.pos(boundingBox.minX, boundingBox.minY, boundingBox.minZ).endVertex();\r\n\t\tvertexbuffer.pos(boundingBox.maxX, boundingBox.minY, boundingBox.minZ).endVertex();\r\n\t\tvertexbuffer.pos(boundingBox.maxX, boundingBox.minY, boundingBox.maxZ).endVertex();\r\n\t\tvertexbuffer.pos(boundingBox.minX, boundingBox.minY, boundingBox.maxZ).endVertex();\r\n\t\tvertexbuffer.pos(boundingBox.minX, boundingBox.minY, boundingBox.minZ).endVertex();\r\n\t\ttessellator.draw();\r\n\t\tvertexbuffer.begin(3, DefaultVertexFormats.POSITION);\r\n\t\tvertexbuffer.pos(boundingBox.minX, boundingBox.maxY, boundingBox.minZ).endVertex();\r\n\t\tvertexbuffer.pos(boundingBox.maxX, boundingBox.maxY, boundingBox.minZ).endVertex();\r\n\t\tvertexbuffer.pos(boundingBox.maxX, boundingBox.maxY, boundingBox.maxZ).endVertex();\r\n\t\tvertexbuffer.pos(boundingBox.minX, boundingBox.maxY, boundingBox.maxZ).endVertex();\r\n\t\tvertexbuffer.pos(boundingBox.minX, boundingBox.maxY, boundingBox.minZ).endVertex();\r\n\t\ttessellator.draw();\r\n\t\tvertexbuffer.begin(1, DefaultVertexFormats.POSITION);\r\n\t\tvertexbuffer.pos(boundingBox.minX, boundingBox.minY, boundingBox.minZ).endVertex();\r\n\t\tvertexbuffer.pos(boundingBox.minX, boundingBox.maxY, boundingBox.minZ).endVertex();\r\n\t\tvertexbuffer.pos(boundingBox.maxX, boundingBox.minY, boundingBox.minZ).endVertex();\r\n\t\tvertexbuffer.pos(boundingBox.maxX, boundingBox.maxY, boundingBox.minZ).endVertex();\r\n\t\tvertexbuffer.pos(boundingBox.maxX, boundingBox.minY, boundingBox.maxZ).endVertex();\r\n\t\tvertexbuffer.pos(boundingBox.maxX, boundingBox.maxY, boundingBox.maxZ).endVertex();\r\n\t\tvertexbuffer.pos(boundingBox.minX, boundingBox.minY, boundingBox.maxZ).endVertex();\r\n\t\tvertexbuffer.pos(boundingBox.minX, boundingBox.maxY, boundingBox.maxZ).endVertex();\r\n\t\ttessellator.draw();\r\n\t}\r\n\r\n\tpublic static void setColor(Color c) {\r\n\t\tglColor4f(c.getRed() / 255f, c.getGreen() / 255f, c.getBlue() / 255f, c.getAlpha() / 255f);\r\n\t}\r\n\t\r\n\tprivate static Minecraft mc = Minecraft.getMinecraft();\r\n\t\r\n\tpublic static void drawESP(double d, double d1, double d2, double r, double b, double g)\r\n\t{\r\n\t\tGL11.glPushMatrix();\r\n\t\tGL11.glEnable(3042);\r\n\t\tGL11.glBlendFunc(770, 771);\r\n\t\tGL11.glLineWidth(1.5F);\r\n\t\tGL11.glDisable(GL11.GL_LIGHTING);\r\n\t\tGL11.glDisable(GL11.GL_TEXTURE_2D);\r\n\t\tGL11.glLineWidth(1.0F);\r\n\t\tGL11.glEnable(GL11.GL_LINE_SMOOTH);\r\n\t\tGL11.glDisable(2929);\r\n\t\tGL11.glDepthMask(false);\r\n\t\tGL11.glColor4d(r, g, b, 0.1825F);\r\n\t\tdrawColorBox(new AxisAlignedBB(d, d1, d2, d + 1.0, d1 + 1.0, d2 + 1.0), 0F, 0F, 0F, 0F);\r\n\t\tGL11.glColor4d(0, 0, 0, 0.5);\r\n\t\tdrawSelectionBoundingBox(new AxisAlignedBB(d, d1, d2, d + 1.0, d1 + 1.0, d2 + 1.0));\r\n\t\tGL11.glLineWidth(2.0F);\r\n\t\tGL11.glDisable(GL11.GL_LINE_SMOOTH);\r\n\t\tGL11.glEnable(GL11.GL_TEXTURE_2D);\r\n\t\tGL11.glEnable(GL11.GL_LIGHTING);\r\n\t\tGL11.glEnable(2929);\r\n\t\tGL11.glDepthMask(true);\r\n\t\tGL11.glDisable(3042);\r\n\t\tGL11.glPopMatrix();\r\n\t}\r\n\r\n public static void drawNameplate(FontRenderer fontRendererIn, String str, float x, float y, float z, int verticalShift, float viewerYaw, float viewerPitch, boolean isThirdPersonFrontal)\r\n {\r\n GlStateManager.pushMatrix();\r\n GlStateManager.translate(x, y, z);\r\n GlStateManager.glNormal3f(0.0F, 1.0F, 0.0F);\r\n GlStateManager.rotate(-viewerYaw, 0.0F, 1.0F, 0.0F);\r\n GlStateManager.rotate((float)(isThirdPersonFrontal ? -1 : 1) * viewerPitch, 1.0F, 0.0F, 0.0F);\r\n GlStateManager.scale(-0.025F, -0.025F, 0.025F);\r\n GlStateManager.disableLighting();\r\n GlStateManager.depthMask(false);\r\n\r\n GlStateManager.enableBlend();\r\n GlStateManager.tryBlendFuncSeparate(GlStateManager.SourceFactor.SRC_ALPHA, GlStateManager.DestFactor.ONE_MINUS_SRC_ALPHA, GlStateManager.SourceFactor.ONE, GlStateManager.DestFactor.ZERO);\r\n int i = fontRendererIn.getStringWidth(str) / 2;\r\n GlStateManager.disableTexture2D();\r\n Tessellator tessellator = Tessellator.getInstance();\r\n BufferBuilder vertexbuffer = tessellator.getBuffer();\r\n vertexbuffer.begin(7, DefaultVertexFormats.POSITION_COLOR);\r\n vertexbuffer.pos((double)(-i - 1), (double)(-1 + verticalShift), 0.0D).color(0.0F, 0.0F, 0.0F, 0.25F).endVertex();\r\n vertexbuffer.pos((double)(-i - 1), (double)(8 + verticalShift), 0.0D).color(0.0F, 0.0F, 0.0F, 0.25F).endVertex();\r\n vertexbuffer.pos((double)(i + 1), (double)(8 + verticalShift), 0.0D).color(0.0F, 0.0F, 0.0F, 0.25F).endVertex();\r\n vertexbuffer.pos((double)(i + 1), (double)(-1 + verticalShift), 0.0D).color(0.0F, 0.0F, 0.0F, 0.25F).endVertex();\r\n tessellator.draw();\r\n GlStateManager.enableTexture2D();\r\n\r\n GlStateManager.depthMask(true);\r\n fontRendererIn.drawString(str, -fontRendererIn.getStringWidth(str) / 2, verticalShift, -1);\r\n GlStateManager.enableLighting();\r\n GlStateManager.disableBlend();\r\n GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F);\r\n GlStateManager.popMatrix();\r\n }\r\n\t\r\n\tpublic static void drawEntityESP(Entity entity, Color c) {\r\n\t\tGL11.glPushMatrix();\r\n\t\tGL11.glBlendFunc(770, 771);\r\n\t\tGL11.glEnable(GL_BLEND);\r\n\t\tGL11.glLineWidth(1.0F);\r\n\t\tGL11.glDisable(GL11.GL_TEXTURE_2D);\r\n\t\tGL11.glDisable(GL_DEPTH_TEST);\r\n\t\tGL11.glDepthMask(false);\r\n\t\tGL11.glColor4d(c.getRed() / 255f, c.getGreen() / 255f, c.getBlue() / 255f, 0.15F);\r\n\t\tRenderManager renderManager = Minecraft.getMinecraft().getRenderManager();\r\n\t\tdrawColorBox(new AxisAlignedBB(\t\t\t\tentity.boundingBox.minX - 0.05 - entity.posX + (entity.posX - renderManager.renderPosX),\r\n\t\t\t\tentity.boundingBox.minY - entity.posY + (entity.posY - renderManager.renderPosY),\r\n\t\t\t\tentity.boundingBox.minZ - 0.05 - entity.posZ + (entity.posZ - renderManager.renderPosZ),\r\n\t\t\t\tentity.boundingBox.maxX + 0.05 - entity.posX + (entity.posX - renderManager.renderPosX),\r\n\t\t\t\tentity.boundingBox.maxY + 0.1 - entity.posY + (entity.posY - renderManager.renderPosY),\r\n\t\t\t\tentity.boundingBox.maxZ + 0.05 - entity.posZ + (entity.posZ - renderManager.renderPosZ)), 0F, 0F, 0F, 0F);\r\n\t\tGL11.glColor4d(0, 0, 0, 0.5);\r\n\t\t//drawSelectionBoundingBox(new AxisAlignedBB(entity.boundingBox.minX - 0.05 - entity.posX + (entity.posX - renderManager.renderPosX),\r\n\t\t//\t\tentity.boundingBox.minY - entity.posY + (entity.posY - renderManager.renderPosY),\r\n\t\t//\t\tentity.boundingBox.minZ - 0.05 - entity.posZ + (entity.posZ - renderManager.renderPosZ),\r\n\t\t//\t\tentity.boundingBox.maxX + 0.05 - entity.posX + (entity.posX - renderManager.renderPosX),\r\n\t\t//\t\tentity.boundingBox.maxY + 0.1 - entity.posY + (entity.posY - renderManager.renderPosY),\r\n\t\t//\t\tentity.boundingBox.maxZ + 0.05 - entity.posZ + (entity.posZ - renderManager.renderPosZ)));\r\n\t\tGL11.glLineWidth(2.0F);\r\n\t\tGL11.glEnable(GL11.GL_TEXTURE_2D);\r\n\t\tGL11.glEnable(GL_DEPTH_TEST);\r\n\t\tGL11.glDepthMask(true);\r\n\t\tGL11.glDisable(GL_BLEND);\r\n\t\tGL11.glPopMatrix();\r\n\t}\r\n}" } ]
import static org.lwjgl.opengl.GL11.GL_BLEND; import static org.lwjgl.opengl.GL11.GL_DEPTH_TEST; import java.awt.Color; import java.util.ArrayList; import org.lwjgl.opengl.GL11; import net.minecraft.client.renderer.entity.RenderManager; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.math.AxisAlignedBB; import net.stroke.client.StrokeClient; import net.stroke.client.clickgui.Setting; import net.stroke.client.modules.BaseModule; import net.stroke.client.modules.ModuleCategory; import net.stroke.client.util.FriendsManager; import net.stroke.client.util.RenderUtils;
7,777
package net.stroke.client.modules.render; public class PlayerESP extends BaseModule { public PlayerESP() {
package net.stroke.client.modules.render; public class PlayerESP extends BaseModule { public PlayerESP() {
super("PlayerESP", "Reveals player location", 0x00, ModuleCategory.Render, false);
3
2023-12-31 10:56:59+00:00
12k
piovas-lu/condominio
src/main/java/app/condominio/controller/RelatorioController.java
[ { "identifier": "Cobranca", "path": "src/main/java/app/condominio/domain/Cobranca.java", "snippet": "@SuppressWarnings(\"serial\")\r\n@Entity\r\n@Table(name = \"cobrancas\")\r\npublic class Cobranca implements Serializable {\r\n\r\n\t@Id\r\n\t@GeneratedValue(strategy = GenerationType.IDENTITY)\r\n\t@Column(name = \"idcobranca\")\r\n\tprivate Long idCobranca;\r\n\r\n\t@NotNull\r\n\t@Enumerated(EnumType.STRING)\r\n\t@Column(name = \"motivoemissao\")\r\n\tprivate MotivoEmissao motivoEmissao;\r\n\r\n\t@Size(max = 10)\r\n\t@NotBlank\r\n\tprivate String numero;\r\n\r\n\t@Size(max = 3)\r\n\tprivate String parcela;\r\n\r\n\t@NotNull\r\n\t@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)\r\n\t@Column(name = \"dataemissao\")\r\n\tprivate LocalDate dataEmissao;\r\n\r\n\t@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)\r\n\t@Column(name = \"datavencimento\")\r\n\tprivate LocalDate dataVencimento;\r\n\r\n\t@NotNull\r\n\t@Min(0)\r\n\tprivate BigDecimal valor;\r\n\r\n\t@Min(0)\r\n\tprivate BigDecimal desconto;\r\n\r\n\t@Min(0)\r\n\tprivate BigDecimal abatimento;\r\n\r\n\t@Min(0)\r\n\t@Column(name = \"outrasdeducoes\")\r\n\tprivate BigDecimal outrasDeducoes;\r\n\r\n\t// Juros tem atualização no banco de dados\r\n\t@Min(0)\r\n\t@Column(name = \"jurosmora\")\r\n\tprivate BigDecimal jurosMora;\r\n\r\n\t// Multa tem atualização no banco de dados\r\n\t@Min(0)\r\n\tprivate BigDecimal multa;\r\n\r\n\t@Min(0)\r\n\t@Column(name = \"outrosacrescimos\")\r\n\tprivate BigDecimal outrosAcrescimos;\r\n\r\n\t// Total é atualizado no banco de dados quando Juros e Multa são atualizados\r\n\t@Min(0)\r\n\t@NotNull\r\n\tprivate BigDecimal total;\r\n\r\n\t@Size(max = 255)\r\n\tprivate String descricao;\r\n\r\n\t@Min(0)\r\n\t@Column(name = \"percentualjurosmes\")\r\n\tprivate Float percentualJurosMes;\r\n\r\n\t@Min(0)\r\n\t@Column(name = \"percentualmulta\")\r\n\tprivate Float percentualMulta;\r\n\r\n\t@Enumerated(EnumType.STRING)\r\n\tprivate SituacaoCobranca situacao;\r\n\r\n\t@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)\r\n\t@Column(name = \"datarecebimento\")\r\n\tprivate LocalDate dataRecebimento;\r\n\r\n\t@Enumerated(EnumType.STRING)\r\n\t@Column(name = \"motivobaixa\")\r\n\tprivate MotivoBaixa motivoBaixa;\r\n\r\n\t@NotNull\r\n\t@ManyToOne(fetch = FetchType.LAZY)\r\n\t@JoinColumn(name = \"idmoradia\")\r\n\tprivate Moradia moradia;\r\n\r\n\t@ManyToOne(fetch = FetchType.LAZY)\r\n\t@JoinColumn(name = \"idcondominio\")\r\n\tprivate Condominio condominio;\r\n\r\n\tpublic Long getIdCobranca() {\r\n\t\treturn idCobranca;\r\n\t}\r\n\r\n\tpublic void setIdCobranca(Long idCobranca) {\r\n\t\tthis.idCobranca = idCobranca;\r\n\t}\r\n\r\n\tpublic Moradia getMoradia() {\r\n\t\treturn moradia;\r\n\t}\r\n\r\n\tpublic void setMoradia(Moradia moradia) {\r\n\t\tthis.moradia = moradia;\r\n\t}\r\n\r\n\tpublic MotivoEmissao getMotivoEmissao() {\r\n\t\treturn motivoEmissao;\r\n\t}\r\n\r\n\tpublic void setMotivoEmissao(MotivoEmissao motivoEmissao) {\r\n\t\tthis.motivoEmissao = motivoEmissao;\r\n\t}\r\n\r\n\tpublic String getNumero() {\r\n\t\treturn numero;\r\n\t}\r\n\r\n\tpublic void setNumero(String numero) {\r\n\t\tthis.numero = numero;\r\n\t}\r\n\r\n\tpublic String getParcela() {\r\n\t\treturn parcela;\r\n\t}\r\n\r\n\tpublic void setParcela(String parcela) {\r\n\t\tthis.parcela = parcela;\r\n\t}\r\n\r\n\tpublic LocalDate getDataEmissao() {\r\n\t\treturn dataEmissao;\r\n\t}\r\n\r\n\tpublic void setDataEmissao(LocalDate dataEmissao) {\r\n\t\tthis.dataEmissao = dataEmissao;\r\n\t}\r\n\r\n\tpublic LocalDate getDataVencimento() {\r\n\t\treturn dataVencimento;\r\n\t}\r\n\r\n\tpublic void setDataVencimento(LocalDate dataVencimento) {\r\n\t\tthis.dataVencimento = dataVencimento;\r\n\t}\r\n\r\n\tpublic BigDecimal getValor() {\r\n\t\treturn valor;\r\n\t}\r\n\r\n\tpublic void setValor(BigDecimal valor) {\r\n\t\tthis.valor = valor;\r\n\t}\r\n\r\n\tpublic BigDecimal getDesconto() {\r\n\t\treturn desconto;\r\n\t}\r\n\r\n\tpublic void setDesconto(BigDecimal desconto) {\r\n\t\tthis.desconto = desconto;\r\n\t}\r\n\r\n\tpublic BigDecimal getAbatimento() {\r\n\t\treturn abatimento;\r\n\t}\r\n\r\n\tpublic void setAbatimento(BigDecimal abatimento) {\r\n\t\tthis.abatimento = abatimento;\r\n\t}\r\n\r\n\tpublic BigDecimal getOutrasDeducoes() {\r\n\t\treturn outrasDeducoes;\r\n\t}\r\n\r\n\tpublic void setOutrasDeducoes(BigDecimal outrasDeducoes) {\r\n\t\tthis.outrasDeducoes = outrasDeducoes;\r\n\t}\r\n\r\n\tpublic BigDecimal getJurosMora() {\r\n\t\treturn jurosMora;\r\n\t}\r\n\r\n\tpublic void setJurosMora(BigDecimal jurosMora) {\r\n\t\tthis.jurosMora = jurosMora;\r\n\t}\r\n\r\n\tpublic BigDecimal getMulta() {\r\n\t\treturn multa;\r\n\t}\r\n\r\n\tpublic void setMulta(BigDecimal multa) {\r\n\t\tthis.multa = multa;\r\n\t}\r\n\r\n\tpublic BigDecimal getOutrosAcrescimos() {\r\n\t\treturn outrosAcrescimos;\r\n\t}\r\n\r\n\tpublic void setOutrosAcrescimos(BigDecimal outrosAcrescimos) {\r\n\t\tthis.outrosAcrescimos = outrosAcrescimos;\r\n\t}\r\n\r\n\tpublic BigDecimal getTotal() {\r\n\t\treturn total;\r\n\t}\r\n\r\n\tpublic void setTotal(BigDecimal total) {\r\n\t\tthis.total = total;\r\n\t}\r\n\r\n\tpublic String getDescricao() {\r\n\t\treturn descricao;\r\n\t}\r\n\r\n\tpublic void setDescricao(String descricao) {\r\n\t\tthis.descricao = descricao;\r\n\t}\r\n\r\n\tpublic Float getPercentualJurosMes() {\r\n\t\treturn percentualJurosMes;\r\n\t}\r\n\r\n\tpublic void setPercentualJurosMes(Float percentualJurosMes) {\r\n\t\tthis.percentualJurosMes = percentualJurosMes;\r\n\t}\r\n\r\n\tpublic Float getPercentualMulta() {\r\n\t\treturn percentualMulta;\r\n\t}\r\n\r\n\tpublic void setPercentualMulta(Float percentualMulta) {\r\n\t\tthis.percentualMulta = percentualMulta;\r\n\t}\r\n\r\n\tpublic SituacaoCobranca getSituacao() {\r\n\t\treturn situacao;\r\n\t}\r\n\r\n\tpublic void setSituacao(SituacaoCobranca situacao) {\r\n\t\tthis.situacao = situacao;\r\n\t}\r\n\r\n\tpublic LocalDate getDataRecebimento() {\r\n\t\treturn dataRecebimento;\r\n\t}\r\n\r\n\tpublic void setDataRecebimento(LocalDate dataRecebimento) {\r\n\t\tthis.dataRecebimento = dataRecebimento;\r\n\t}\r\n\r\n\tpublic MotivoBaixa getMotivoBaixa() {\r\n\t\treturn motivoBaixa;\r\n\t}\r\n\r\n\tpublic void setMotivoBaixa(MotivoBaixa motivoBaixa) {\r\n\t\tthis.motivoBaixa = motivoBaixa;\r\n\t}\r\n\r\n\tpublic Condominio getCondominio() {\r\n\t\treturn condominio;\r\n\t}\r\n\r\n\tpublic void setCondominio(Condominio condominio) {\r\n\t\tthis.condominio = condominio;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic String toString() {\r\n\t\tString s = numero;\r\n\t\tif (parcela != null) {\r\n\t\t\ts += \" - \" + parcela;\r\n\t\t}\r\n\t\treturn s;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic int hashCode() {\r\n\t\tfinal int prime = 31;\r\n\t\tint result = 1;\r\n\t\tresult = prime * result + ((idCobranca == null) ? 0 : idCobranca.hashCode());\r\n\t\treturn result;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic boolean equals(Object obj) {\r\n\t\tif (this == obj) {\r\n\t\t\treturn true;\r\n\t\t}\r\n\t\tif (obj == null) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\tif (getClass() != obj.getClass()) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\tCobranca other = (Cobranca) obj;\r\n\t\tif (idCobranca == null) {\r\n\t\t\tif (other.idCobranca != null) {\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t} else if (!idCobranca.equals(other.idCobranca)) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\treturn true;\r\n\t}\r\n\r\n}\r" }, { "identifier": "Moradia", "path": "src/main/java/app/condominio/domain/Moradia.java", "snippet": "@SuppressWarnings(\"serial\")\r\n@Entity\r\n@Table(name = \"moradias\")\r\npublic class Moradia implements Serializable, Comparable<Moradia> {\r\n\r\n\t@Id\r\n\t@GeneratedValue(strategy = GenerationType.IDENTITY)\r\n\t@Column(name = \"idmoradia\")\r\n\tprivate Long idMoradia;\r\n\r\n\t@Size(min = 1, max = 10)\r\n\t@NotBlank\r\n\tprivate String sigla;\r\n\r\n\t@NotNull\r\n\t@Enumerated(EnumType.STRING)\r\n\tprivate TipoMoradia tipo;\r\n\r\n\tprivate Float area;\r\n\r\n\t@Max(100)\r\n\t@Min(0)\r\n\t@Column(name = \"fracaoideal\")\r\n\tprivate Float fracaoIdeal;\r\n\r\n\t@Size(max = 30)\r\n\tprivate String matricula;\r\n\r\n\tprivate Integer vagas;\r\n\r\n\t@NotNull\r\n\t@ManyToOne(fetch = FetchType.LAZY)\r\n\t@JoinColumn(name = \"idbloco\")\r\n\tprivate Bloco bloco;\r\n\r\n\t@OneToMany(mappedBy = \"moradia\", fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)\r\n\t@OrderBy(value = \"dataEntrada\")\r\n\t@Valid\r\n\tprivate List<Relacao> relacoes = new ArrayList<>();\r\n\r\n\t@OneToMany(mappedBy = \"moradia\", fetch = FetchType.LAZY, cascade = CascadeType.REMOVE, orphanRemoval = true)\r\n\t@OrderBy(value = \"numero, parcela\")\r\n\tprivate List<Cobranca> cobrancas = new ArrayList<>();\r\n\r\n\tpublic Long getIdMoradia() {\r\n\t\treturn idMoradia;\r\n\t}\r\n\r\n\tpublic void setIdMoradia(Long idMoradia) {\r\n\t\tthis.idMoradia = idMoradia;\r\n\t}\r\n\r\n\tpublic String getSigla() {\r\n\t\treturn sigla;\r\n\t}\r\n\r\n\tpublic void setSigla(String sigla) {\r\n\t\tthis.sigla = sigla;\r\n\t}\r\n\r\n\tpublic TipoMoradia getTipo() {\r\n\t\treturn tipo;\r\n\t}\r\n\r\n\tpublic void setTipo(TipoMoradia tipo) {\r\n\t\tthis.tipo = tipo;\r\n\t}\r\n\r\n\tpublic Float getArea() {\r\n\t\treturn area;\r\n\t}\r\n\r\n\tpublic void setArea(Float area) {\r\n\t\tthis.area = area;\r\n\t}\r\n\r\n\tpublic Float getFracaoIdeal() {\r\n\t\treturn fracaoIdeal;\r\n\t}\r\n\r\n\tpublic void setFracaoIdeal(Float fracaoIdeal) {\r\n\t\tthis.fracaoIdeal = fracaoIdeal;\r\n\t}\r\n\r\n\tpublic String getMatricula() {\r\n\t\treturn matricula;\r\n\t}\r\n\r\n\tpublic void setMatricula(String matricula) {\r\n\t\tthis.matricula = matricula;\r\n\t}\r\n\r\n\tpublic Integer getVagas() {\r\n\t\treturn vagas;\r\n\t}\r\n\r\n\tpublic void setVagas(Integer vagas) {\r\n\t\tthis.vagas = vagas;\r\n\t}\r\n\r\n\tpublic Bloco getBloco() {\r\n\t\treturn bloco;\r\n\t}\r\n\r\n\tpublic void setBloco(Bloco bloco) {\r\n\t\tthis.bloco = bloco;\r\n\t}\r\n\r\n\tpublic List<Relacao> getRelacoes() {\r\n\t\treturn relacoes;\r\n\t}\r\n\r\n\tpublic void setRelacoes(List<Relacao> relacoes) {\r\n\t\tthis.relacoes = relacoes;\r\n\t}\r\n\r\n\tpublic List<Cobranca> getCobrancas() {\r\n\t\treturn cobrancas;\r\n\t}\r\n\r\n\tpublic void setCobrancas(List<Cobranca> cobrancas) {\r\n\t\tthis.cobrancas = cobrancas;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic String toString() {\r\n\t\treturn bloco.toString() + \" - \" + sigla;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic int hashCode() {\r\n\t\tfinal int prime = 31;\r\n\t\tint result = 1;\r\n\t\tresult = prime * result + ((idMoradia == null) ? 0 : idMoradia.hashCode());\r\n\t\treturn result;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic boolean equals(Object obj) {\r\n\t\tif (this == obj) {\r\n\t\t\treturn true;\r\n\t\t}\r\n\t\tif (obj == null) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\tif (getClass() != obj.getClass()) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\tMoradia other = (Moradia) obj;\r\n\t\tif (idMoradia == null) {\r\n\t\t\tif (other.idMoradia != null) {\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t} else if (!idMoradia.equals(other.idMoradia)) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\treturn true;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic int compareTo(Moradia arg0) {\r\n\t\treturn this.toString().compareTo(arg0.toString());\r\n\t}\r\n}\r" }, { "identifier": "Movimento", "path": "src/main/java/app/condominio/domain/Movimento.java", "snippet": "@SuppressWarnings(\"serial\")\r\n@Entity\r\n@Table(name = \"movimentos\")\r\n@Inheritance(strategy = InheritanceType.JOINED)\r\npublic class Movimento implements Serializable {\r\n\r\n\t@Id\r\n\t@GeneratedValue(strategy = GenerationType.IDENTITY)\r\n\t@Column(name = \"idmovimento\")\r\n\tprivate Long idMovimento;\r\n\r\n\t@NotNull\r\n\t@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)\r\n\tprivate LocalDate data;\r\n\r\n\t@NotNull\r\n\t@Min(0)\r\n\tprivate BigDecimal valor;\r\n\r\n\t@Size(max = 20)\r\n\tprivate String documento;\r\n\r\n\t@Size(max = 255)\r\n\tprivate String descricao;\r\n\r\n\tprivate Boolean reducao;\r\n\r\n\t@NotNull\r\n\t@ManyToOne(fetch = FetchType.LAZY)\r\n\t@JoinColumn(name = \"idconta\")\r\n\tprivate Conta conta;\r\n\r\n\tpublic Long getIdMovimento() {\r\n\t\treturn idMovimento;\r\n\t}\r\n\r\n\tpublic void setIdMovimento(Long idMovimento) {\r\n\t\tthis.idMovimento = idMovimento;\r\n\t}\r\n\r\n\tpublic LocalDate getData() {\r\n\t\treturn data;\r\n\t}\r\n\r\n\tpublic void setData(LocalDate data) {\r\n\t\tthis.data = data;\r\n\t}\r\n\r\n\tpublic BigDecimal getValor() {\r\n\t\treturn valor;\r\n\t}\r\n\r\n\tpublic void setValor(BigDecimal valor) {\r\n\t\tthis.valor = valor;\r\n\t}\r\n\r\n\tpublic String getDescricao() {\r\n\t\treturn descricao;\r\n\t}\r\n\r\n\tpublic void setDescricao(String descricao) {\r\n\t\tthis.descricao = descricao;\r\n\t}\r\n\r\n\tpublic String getDocumento() {\r\n\t\treturn documento;\r\n\t}\r\n\r\n\tpublic void setDocumento(String documento) {\r\n\t\tthis.documento = documento;\r\n\t}\r\n\r\n\tpublic Boolean getReducao() {\r\n\t\treturn reducao;\r\n\t}\r\n\r\n\tpublic void setReducao(Boolean reducao) {\r\n\t\tthis.reducao = reducao;\r\n\t}\r\n\r\n\tpublic Conta getConta() {\r\n\t\treturn conta;\r\n\t}\r\n\r\n\tpublic void setConta(Conta conta) {\r\n\t\tthis.conta = conta;\r\n\t}\r\n\r\n\tpublic String detalhe() {\r\n\t\tif (reducao) {\r\n\t\t\treturn \"Saída\";\r\n\t\t} else {\r\n\t\t\treturn \"Entrada\";\r\n\t\t}\r\n\t}\r\n\r\n\t@Override\r\n\tpublic String toString() {\r\n\t\tDateTimeFormatter formato = DateTimeFormatter.ofPattern(\"dd/MM/yyyy\");\r\n\t\tString s = data.format(formato) + \" - \";\r\n\t\tif (documento != null) {\r\n\t\t\ts += documento + \" - \";\r\n\t\t}\r\n\t\ts += \"R$ \" + valor;\r\n\t\treturn s;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic int hashCode() {\r\n\t\tfinal int prime = 31;\r\n\t\tint result = 1;\r\n\t\tresult = prime * result + ((idMovimento == null) ? 0 : idMovimento.hashCode());\r\n\t\treturn result;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic boolean equals(Object obj) {\r\n\t\tif (this == obj) {\r\n\t\t\treturn true;\r\n\t\t}\r\n\t\tif (obj == null) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\tif (getClass() != obj.getClass()) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\tMovimento other = (Movimento) obj;\r\n\t\tif (idMovimento == null) {\r\n\t\t\tif (other.idMovimento != null) {\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t} else if (!idMovimento.equals(other.idMovimento)) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\treturn true;\r\n\t}\r\n\r\n}\r" }, { "identifier": "Periodo", "path": "src/main/java/app/condominio/domain/Periodo.java", "snippet": "@SuppressWarnings(\"serial\")\r\n@Entity\r\n@Table(name = \"periodos\")\r\npublic class Periodo implements Serializable, Comparable<Periodo> {\r\n\r\n\t@Id\r\n\t@GeneratedValue(strategy = GenerationType.IDENTITY)\r\n\t@Column(name = \"idperiodo\")\r\n\tprivate Long idPeriodo;\r\n\r\n\t@NotNull\r\n\t@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)\r\n\tprivate LocalDate inicio;\r\n\r\n\t@NotNull\r\n\t@DateTimeFormat(iso = DateTimeFormat.ISO.DATE)\r\n\tprivate LocalDate fim;\r\n\r\n\tprivate Boolean encerrado;\r\n\r\n\t@OneToMany(mappedBy = \"periodo\", fetch = FetchType.LAZY, cascade = CascadeType.REMOVE, orphanRemoval = true)\r\n\t@OrderBy(value = \"subcategoria\")\r\n\tprivate List<Orcamento> orcamentos = new ArrayList<>();\r\n\r\n\t@OneToMany(mappedBy = \"periodo\", fetch = FetchType.LAZY, cascade = CascadeType.REMOVE, orphanRemoval = true)\r\n\tprivate List<Lancamento> lancamentos = new ArrayList<>();\r\n\r\n\t@ManyToOne(fetch = FetchType.LAZY)\r\n\t@JoinColumn(name = \"idcondominio\")\r\n\tprivate Condominio condominio;\r\n\r\n\tpublic Long getIdPeriodo() {\r\n\t\treturn idPeriodo;\r\n\t}\r\n\r\n\tpublic void setIdPeriodo(Long idPeriodo) {\r\n\t\tthis.idPeriodo = idPeriodo;\r\n\t}\r\n\r\n\tpublic LocalDate getInicio() {\r\n\t\treturn inicio;\r\n\t}\r\n\r\n\tpublic void setInicio(LocalDate inicio) {\r\n\t\tthis.inicio = inicio;\r\n\t}\r\n\r\n\tpublic LocalDate getFim() {\r\n\t\treturn fim;\r\n\t}\r\n\r\n\tpublic void setFim(LocalDate fim) {\r\n\t\tthis.fim = fim;\r\n\t}\r\n\r\n\tpublic Boolean getEncerrado() {\r\n\t\treturn encerrado;\r\n\t}\r\n\r\n\tpublic void setEncerrado(Boolean encerrado) {\r\n\t\tthis.encerrado = encerrado;\r\n\t}\r\n\r\n\tpublic Condominio getCondominio() {\r\n\t\treturn condominio;\r\n\t}\r\n\r\n\tpublic void setCondominio(Condominio condominio) {\r\n\t\tthis.condominio = condominio;\r\n\t}\r\n\r\n\tpublic List<Orcamento> getOrcamentos() {\r\n\t\treturn orcamentos;\r\n\t}\r\n\r\n\tpublic void setOrcamentos(List<Orcamento> orcamentos) {\r\n\t\tthis.orcamentos = orcamentos;\r\n\t}\r\n\r\n\tpublic List<Lancamento> getLancamentos() {\r\n\t\treturn lancamentos;\r\n\t}\r\n\r\n\tpublic void setLancamentos(List<Lancamento> lancamentos) {\r\n\t\tthis.lancamentos = lancamentos;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic String toString() {\r\n\t\tDateTimeFormatter formato = DateTimeFormatter.ofPattern(\"dd/MM/yyyy\");\r\n\t\treturn inicio.format(formato) + \" a \" + fim.format(formato);\r\n\t}\r\n\r\n\t@Override\r\n\tpublic int hashCode() {\r\n\t\tfinal int prime = 31;\r\n\t\tint result = 1;\r\n\t\tresult = prime * result + ((idPeriodo == null) ? 0 : idPeriodo.hashCode());\r\n\t\treturn result;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic boolean equals(Object obj) {\r\n\t\tif (this == obj) {\r\n\t\t\treturn true;\r\n\t\t}\r\n\t\tif (obj == null) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\tif (getClass() != obj.getClass()) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\tPeriodo other = (Periodo) obj;\r\n\t\tif (idPeriodo == null) {\r\n\t\t\tif (other.idPeriodo != null) {\r\n\t\t\t\treturn false;\r\n\t\t\t}\r\n\t\t} else if (!idPeriodo.equals(other.idPeriodo)) {\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\treturn true;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic int compareTo(Periodo arg0) {\r\n\t\treturn this.inicio.compareTo(arg0.getInicio());\r\n\t}\r\n}\r" }, { "identifier": "TipoCategoria", "path": "src/main/java/app/condominio/domain/enums/TipoCategoria.java", "snippet": "public enum TipoCategoria {\r\n\r\n\t// @formatter:off\r\n\tR(\"Receita\",\"Entrada\"),\r\n\tD(\"Despesa\",\"Saída\");\r\n\t// @formatter:on\r\n\r\n\tprivate final String nome;\r\n\tprivate final String movimento;\r\n\r\n\tprivate TipoCategoria(String nome, String movimento) {\r\n\t\tthis.nome = nome;\r\n\t\tthis.movimento = movimento;\r\n\t}\r\n\r\n\tpublic String getNome() {\r\n\t\treturn nome;\r\n\t}\r\n\r\n\tpublic String getMovimento() {\r\n\t\treturn movimento;\r\n\t}\r\n}\r" }, { "identifier": "CategoriaService", "path": "src/main/java/app/condominio/service/CategoriaService.java", "snippet": "public interface CategoriaService extends CrudService<Categoria, Long> {\r\n\r\n\tpublic List<Categoria> listarReceitas();\r\n\r\n\tpublic List<Categoria> listarDespesas();\r\n\r\n}\r" }, { "identifier": "CondominioService", "path": "src/main/java/app/condominio/service/CondominioService.java", "snippet": "public interface CondominioService extends CrudService<Condominio, Long> {\r\n\r\n\tpublic Condominio ler();\r\n\r\n}\r" }, { "identifier": "PeriodoService", "path": "src/main/java/app/condominio/service/PeriodoService.java", "snippet": "public interface PeriodoService extends CrudService<Periodo, Long> {\r\n\r\n\tpublic boolean haPeriodo(LocalDate data);\r\n\r\n\tpublic Periodo ler(LocalDate data);\r\n\r\n}\r" }, { "identifier": "RelatorioService", "path": "src/main/java/app/condominio/service/RelatorioService.java", "snippet": "public interface RelatorioService {\r\n\r\n\t/**\r\n\t * @return Retorna um BigDecimal com a soma do saldo de todas as Contas do\r\n\t * Condomínio. Nunca retorna nulo, se não houver contas, retorna\r\n\t * BigDecimal.ZERO.\r\n\t */\r\n\tpublic BigDecimal saldoAtualTodasContas();\r\n\r\n\t/**\r\n\t * @param data\r\n\t * Um dia para pesquisa.\r\n\t * @return Retorna um BigDecimal com o saldo de todas as Contas do Condomínio no\r\n\t * início do dia passado no parâmetro. Nunca retorna nulo, se não houver\r\n\t * contas, retorna BigDecimal.ZERO.\r\n\t */\r\n\tpublic BigDecimal saldoInicialTodasContasEm(LocalDate data);\r\n\r\n\t/**\r\n\t * @param data\r\n\t * Um dia para pesquisa.\r\n\t * @return Retorna um BigDecimal com o saldo de todas as Contas do Condomínio no\r\n\t * fim do dia passado no parâmetro. Nunca retorna nulo, se não houver\r\n\t * contas, retorna BigDecimal.ZERO.\r\n\t */\r\n\tpublic BigDecimal saldoFinalTodasContasEm(LocalDate data);\r\n\r\n\t/**\r\n\t * @return Retorna um BigDecimal com o valor total da inadimplência do\r\n\t * Condomínio na data atual (considera o valor total da Cobrança, com\r\n\t * acréscimos e deduções). Nunca retorna nulo, se não houver\r\n\t * inadimplência, retorna BigDecimal.ZERO.\r\n\t */\r\n\tpublic BigDecimal inadimplenciaAtual();\r\n\r\n\t/**\r\n\t * @return Retorna um vetor de BigDecimal[] com duas posições. A posição [0] é a\r\n\t * soma dos lançamentos de receitas do mês atual, e a posição [1] é a\r\n\t * soma dos lançamentos de despesas do mês atual. Nunca retorna nulo, se\r\n\t * não houver lançamentos, retorna BigDecimal.ZERO na respectiva posição\r\n\t * do vetor.\r\n\t */\r\n\tpublic BigDecimal[] receitaDespesaMesAtual();\r\n\r\n\t/**\r\n\t * @param inicio\r\n\t * Data inicial para pesquisa\r\n\t * @param fim\r\n\t * Data final para pesquisa\r\n\t * @return Retorna um vetor de BigDecimal[] com duas posições. A posição [0] é a\r\n\t * soma dos lançamentos de receitas dentro das datas informadas no\r\n\t * parâmetro, e a posição [1] é a soma dos lançamentos de despesas\r\n\t * dentro das datas informadas no parâmetro. Nunca retorna nulo, se não\r\n\t * houver lançamentos, retorna BigDecimal.ZERO na respectiva posição do\r\n\t * vetor.\r\n\t */\r\n\tpublic BigDecimal[] receitaDespesaEntre(LocalDate inicio, LocalDate fim);\r\n\r\n\t/**\r\n\t * @return Retorna um vetor de BigDecimal[] com duas posições. A posição [0] é a\r\n\t * soma dos lançamentos de receitas realizadas do Período atual, e a\r\n\t * posição [1] é a soma dos lançamentos de despesas realizadas do\r\n\t * Período atual. Nunca retorna nulo, se não houver lançamentos, retorna\r\n\t * BigDecimal.ZERO na respectiva posição do vetor.\r\n\t */\r\n\tpublic BigDecimal[] receitaDespesaRealizadaPeriodoAtual();\r\n\r\n\t/**\r\n\t * @return Retorna um vetor de BigDecimal[] com duas posições. A posição [0] é a\r\n\t * soma dos lançamentos de receitas orçadas do Período atual, e a\r\n\t * posição [1] é a soma dos lançamentos de despesas orçadas do Período\r\n\t * atual. Nunca retorna nulo, se não houver lançamentos, retorna\r\n\t * BigDecimal.ZERO na respectiva posição do vetor.\r\n\t */\r\n\tpublic BigDecimal[] receitaDespesaOrcadaPeriodoAtual();\r\n\r\n\t/**\r\n\t * @param inicio\r\n\t * Data inicial para pesquisa\r\n\t * @param fim\r\n\t * Data final para pesquisa\r\n\t * @return Retorna uma lista do tipo List{@literal <}Movimento{@literal >} com\r\n\t * Lançamentos existentes em todas as Contas dentro das datas informadas\r\n\t * no parâmetro. Nunca retorna nulo, se não houverem Contas ou\r\n\t * Lançamentos, retorna uma lista vazia.\r\n\t */\r\n\tpublic List<Movimento> lancamentosEntre(LocalDate inicio, LocalDate fim);\r\n\r\n\t/**\r\n\t * @param movimentos\r\n\t * Uma lista do tipo List{@literal <}Movimento{@literal >}\r\n\t * @param saldoInicial\r\n\t * Um BigDecimal para ser considerado como saldo inicial\r\n\t * @return Retorna um vetor de BigDecimal[] com tamanho igual ao número de\r\n\t * elementos na lista passada no parâmetro, contendo em cada enésima\r\n\t * posição o saldo após processado o enésimo Movimento, partindo do\r\n\t * saldo inicial informado no parâmetro. Nunca retorna nulo, se a lista\r\n\t * passada no parâmetro estiver vazia, retorna um vetor com uma posição\r\n\t * com valor BigDecimal.ZERO.\r\n\t */\r\n\tpublic BigDecimal[] saldosAposMovimentos(List<Movimento> movimentos, BigDecimal saldoInicial);\r\n\r\n\t/**\r\n\t * @param inicio\r\n\t * Data inicial para pesquisa\r\n\t * @param fim\r\n\t * Data final para pesquisa\r\n\t * @param tipoCategoria\r\n\t * O tipo da Categoria pai da Subcategoria a ser buscada\r\n\t * @return Retorna um mapa do tipo Map{@literal <}Subcategoria,\r\n\t * BigDecimal{@literal >}. Cada entrada do mapa é composta por uma\r\n\t * Subcategoria como chave e um BigDecimal como valor. O valor\r\n\t * representa a soma de todos os Lançamentos existentes para a\r\n\t * respectiva Subcategoria dentro das datas informadas no parâmetro.\r\n\t * Retorna somente Subcategorias com soma diferente de zero. Nunca\r\n\t * retorna nulo, se não houverem entradas, retorna um mapa vazio.\r\n\t */\r\n\tpublic SortedMap<Subcategoria, BigDecimal> somasPorTipoEntre(LocalDate inicio, LocalDate fim,\r\n\t\t\tTipoCategoria tipoCategoria);\r\n\r\n\t/**\r\n\t * @return Retorna um mapa do tipo Map{@literal <}Moradia,List{@literal\r\n\t * <}Cobranca{@literal >>}. Cada entrada do mapa é composta por uma\r\n\t * Moradia como chave e uma lista de Cobranca como valor. Esta lista\r\n\t * contém todas as Cobranças vencidas até a data atual da respectiva\r\n\t * Moradia. Retorna somente Moradias com uma lista não vazia. Nunca\r\n\t * retorna nulo, se não houverem entradas, retorna um mapa vazio.\r\n\t */\r\n\tpublic SortedMap<Moradia, List<Cobranca>> inadimplenciaAtualDetalhada();\r\n\r\n\t/**\r\n\t * @param map\r\n\t * Um mapa do tipo Map{@literal <}Moradia,List{@literal\r\n\t * <}Cobranca{@literal >>} para ser somado\r\n\t * @return Retorna um mapa do tipo Map{@literal <}Moradia,BigDecimal{@literal >}\r\n\t * com as mesmas chaves do mapa fornecido no parâmetro. Cada valor\r\n\t * corresponde à soma das Cobranças da respectiva Moradia. Nunca retorna\r\n\t * nulo, se não houverem entradas, retorna um mapa vazio.\r\n\t */\r\n\tpublic Map<Moradia, BigDecimal> somaCobrancas(Map<Moradia, List<Cobranca>> map);\r\n\r\n\t/**\r\n\t * @param periodo\r\n\t * Um Periodo para pesquisa\r\n\t * @return Retorna um mapa do tipo\r\n\t * Map{@literal <}Subcategoria,BigDecimal[]{@literal >} tendo como chave\r\n\t * uma Subcategoria. Retorna somente Subcategorias que tiveram, no\r\n\t * Período fornecido por parâmetro, valores Orçados ou Realizados. O\r\n\t * valor é um vetor de BigDecimal[] com duas posições. A posição [0] é o\r\n\t * valor orçado da respectiva Subcategoria naquele Período, e a posição\r\n\t * [1] é a soma dos Lançamentos realizados da respectiva Subcategoria\r\n\t * naquele Período, em todas as Contas. Nunca retorna nulo, se não\r\n\t * houverem entradas, retorna um mapa vazio.\r\n\t */\r\n\tpublic Map<Subcategoria, BigDecimal[]> somaOrcadoRealizadoSubcategorias(Periodo periodo);\r\n\r\n\t/**\r\n\t * @param periodo\r\n\t * Um Periodo para pesquisa\r\n\t * @return Retorna um mapa do tipo\r\n\t * Map{@literal <}Categoria,BigDecimal[]{@literal >} tendo como chave\r\n\t * uma Categoria. Retorna somente Categorias que tiveram, no Período\r\n\t * fornecido por parâmetro, valores Orçados ou Realizados em alguma de\r\n\t * suas Subcategorias. O valor é um vetor de BigDecimal[] com duas\r\n\t * posições. A posição [0] é a soma do valor orçado das Subcategorias da\r\n\t * respectiva Categoria naquele Período, e a posição [1] é a soma dos\r\n\t * Lançamentos realizados das Subcategorias da respectiva Categoria\r\n\t * naquele Período, em todas as Contas. Nunca retorna nulo, se não\r\n\t * houverem entradas, retorna um mapa vazio.\r\n\t */\r\n\tpublic Map<Categoria, BigDecimal[]> somaOrcadoRealizadoCategorias(Periodo periodo);\r\n\r\n}\r" } ]
import java.math.BigDecimal; import java.time.LocalDate; import java.util.List; import java.util.SortedMap; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.format.annotation.DateTimeFormat; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; import app.condominio.domain.Cobranca; import app.condominio.domain.Moradia; import app.condominio.domain.Movimento; import app.condominio.domain.Periodo; import app.condominio.domain.enums.TipoCategoria; import app.condominio.service.CategoriaService; import app.condominio.service.CondominioService; import app.condominio.service.PeriodoService; import app.condominio.service.RelatorioService;
8,282
package app.condominio.controller; @Controller @RequestMapping("sindico/relatorios") public class RelatorioController { @Autowired RelatorioService relatorioService; @Autowired CondominioService condominioService; @Autowired
package app.condominio.controller; @Controller @RequestMapping("sindico/relatorios") public class RelatorioController { @Autowired RelatorioService relatorioService; @Autowired CondominioService condominioService; @Autowired
PeriodoService periodoService;
7
2023-12-29 22:19:42+00:00
12k
HuXin0817/shop_api
buyer-api/src/main/java/cn/lili/controller/order/AfterSaleBuyerController.java
[ { "identifier": "ResultUtil", "path": "framework/src/main/java/cn/lili/common/enums/ResultUtil.java", "snippet": "public class ResultUtil<T> {\n\n /**\n * 抽象类,存放结果\n */\n private final ResultMessage<T> resultMessage;\n /**\n * 正常响应\n */\n private static final Integer SUCCESS = 200;\n\n\n /**\n * 构造话方法,给响应结果默认值\n */\n public ResultUtil() {\n resultMessage = new ResultMessage<>();\n resultMessage.setSuccess(true);\n resultMessage.setMessage(\"success\");\n resultMessage.setCode(SUCCESS);\n }\n\n /**\n * 返回数据\n *\n * @param t 范型\n * @return 消息\n */\n public ResultMessage<T> setData(T t) {\n this.resultMessage.setResult(t);\n return this.resultMessage;\n }\n\n\n /**\n * 返回成功消息\n *\n * @param resultCode 返回码\n * @return 返回成功消息\n */\n public ResultMessage<T> setSuccessMsg(ResultCode resultCode) {\n this.resultMessage.setSuccess(true);\n this.resultMessage.setMessage(resultCode.message());\n this.resultMessage.setCode(resultCode.code());\n return this.resultMessage;\n\n }\n\n /**\n * 抽象静态方法,返回结果集\n * @param t 范型\n * @param <T> 范型\n * @return 消息\n */\n public static <T> ResultMessage<T> data(T t) {\n return new ResultUtil<T>().setData(t);\n }\n\n /**\n * 返回成功\n *\n * @param resultCode 返回状态码\n * @return 消息\n */\n public static <T> ResultMessage<T> success(ResultCode resultCode) {\n return new ResultUtil<T>().setSuccessMsg(resultCode);\n }\n\n /**\n * 返回成功\n * @return 消息\n */\n public static <T> ResultMessage<T> success() {\n return new ResultUtil<T>().setSuccessMsg(ResultCode.SUCCESS);\n }\n\n /**\n * 返回失败\n *\n * @param resultCode 返回状态码\n * @return 消息\n */\n public static <T> ResultMessage<T> error(ResultCode resultCode) {\n return new ResultUtil<T>().setErrorMsg(resultCode);\n }\n\n /**\n * 返回失败\n *\n * @param code 状态码\n * @param msg 返回消息\n * @return 消息\n */\n public static <T> ResultMessage<T> error(Integer code, String msg) {\n return new ResultUtil<T>().setErrorMsg(code, msg);\n }\n\n /**\n * 服务器异常 追加状态码\n * @param resultCode 返回码\n * @return 消息\n */\n public ResultMessage<T> setErrorMsg(ResultCode resultCode) {\n this.resultMessage.setSuccess(false);\n this.resultMessage.setMessage(resultCode.message());\n this.resultMessage.setCode(resultCode.code());\n return this.resultMessage;\n }\n\n /**\n * 服务器异常 追加状态码\n *\n * @param code 状态码\n * @param msg 返回消息\n * @return 消息\n */\n public ResultMessage<T> setErrorMsg(Integer code, String msg) {\n this.resultMessage.setSuccess(false);\n this.resultMessage.setMessage(msg);\n this.resultMessage.setCode(code);\n return this.resultMessage;\n }\n\n}" }, { "identifier": "OperationalJudgment", "path": "framework/src/main/java/cn/lili/common/security/OperationalJudgment.java", "snippet": "public class OperationalJudgment {\n\n /**\n * 需要判定的对象必须包含属性 memberId,storeId 代表判定的角色\n *\n * @param object 判定的对象\n * @param <T> 判定处理对象\n * @return 处理结果\n */\n public static <T> T judgment(T object) {\n return judgment(object, \"memberId\", \"storeId\");\n }\n\n /**\n * 需要判定的对象必须包含属性 memberId,storeId 代表判定的角色\n *\n * @param object 判定对象\n * @param buyerIdField 买家id\n * @param storeIdField 店铺id\n * @param <T> 范型\n * @return 返回判定本身,防止多次查询对象\n */\n public static <T> T judgment(T object, String buyerIdField, String storeIdField) {\n AuthUser tokenUser = Objects.requireNonNull(UserContext.getCurrentUser());\n switch (tokenUser.getRole()) {\n case MANAGER:\n return object;\n case MEMBER:\n if (tokenUser.getId().equals(BeanUtil.getFieldValueByName(buyerIdField, object))) {\n return object;\n } else {\n throw new ServiceException(ResultCode.USER_AUTHORITY_ERROR);\n }\n case STORE:\n if (tokenUser.getStoreId().equals(BeanUtil.getFieldValueByName(storeIdField, object))) {\n return object;\n } else {\n throw new ServiceException(ResultCode.USER_AUTHORITY_ERROR);\n }\n default:\n throw new ServiceException(ResultCode.USER_AUTHORITY_ERROR);\n }\n }\n}" }, { "identifier": "ResultMessage", "path": "framework/src/main/java/cn/lili/common/vo/ResultMessage.java", "snippet": "@Data\npublic class ResultMessage<T> implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n /**\n * 成功标志\n */\n private boolean success;\n\n /**\n * 消息\n */\n private String message;\n\n /**\n * 返回代码\n */\n private Integer code;\n\n /**\n * 时间戳\n */\n private long timestamp = System.currentTimeMillis();\n\n /**\n * 结果对象\n */\n private T result;\n}" }, { "identifier": "AfterSale", "path": "framework/src/main/java/cn/lili/modules/order/aftersale/entity/dos/AfterSale.java", "snippet": "@Data\n@TableName(\"li_after_sale\")\n@ApiModel(value = \"售后\")\npublic class AfterSale extends BaseEntity {\n\n private static final long serialVersionUID = -5339221840646353416L;\n\n //基础信息\n\n @ApiModelProperty(value = \"售后服务单号\")\n private String sn;\n\n @ApiModelProperty(value = \"订单编号\")\n private String orderSn;\n\n @ApiModelProperty(value = \"订单货物编号\")\n private String orderItemSn;\n\n @ApiModelProperty(value = \"交易编号\")\n private String tradeSn;\n\n @ApiModelProperty(value = \"会员ID\")\n private String memberId;\n\n @ApiModelProperty(value = \"会员名称\")\n @Sensitive(strategy = SensitiveStrategy.PHONE)\n private String memberName;\n\n @ApiModelProperty(value = \"商家ID\")\n private String storeId;\n\n @ApiModelProperty(value = \"商家名称\")\n private String storeName;\n\n //商品信息\n\n @ApiModelProperty(value = \"商品ID\")\n private String goodsId;\n @ApiModelProperty(value = \"货品ID\")\n private String skuId;\n @ApiModelProperty(value = \"申请数量\")\n private Integer num;\n @ApiModelProperty(value = \"商品图片\")\n private String goodsImage;\n @ApiModelProperty(value = \"商品名称\")\n private String goodsName;\n\n @ApiModelProperty(value = \"规格json\")\n private String specs;\n @ApiModelProperty(value = \"实际金额\")\n private Double flowPrice;\n\n\n //交涉信息\n\n @ApiModelProperty(value = \"申请原因\")\n private String reason;\n\n @ApiModelProperty(value = \"问题描述\")\n private String problemDesc;\n\n @ApiModelProperty(value = \"评价图片\")\n private String afterSaleImage;\n\n /**\n * @see cn.lili.modules.order.trade.entity.enums.AfterSaleTypeEnum\n */\n @ApiModelProperty(value = \"售后类型\", allowableValues = \"RETURN_GOODS,RETURN_MONEY\")\n private String serviceType;\n\n /**\n * @see cn.lili.modules.order.trade.entity.enums.AfterSaleStatusEnum\n */\n @ApiModelProperty(value = \"售后单状态\", allowableValues = \"APPLY,PASS,REFUSE,BUYER_RETURN,SELLER_RE_DELIVERY,BUYER_CONFIRM,SELLER_CONFIRM,COMPLETE\")\n private String serviceStatus;\n\n //退款信息\n\n /**\n * @see cn.lili.modules.order.trade.entity.enums.AfterSaleRefundWayEnum\n */\n @ApiModelProperty(value = \"退款方式\", allowableValues = \"ORIGINAL,OFFLINE\")\n private String refundWay;\n\n @ApiModelProperty(value = \"账号类型\", allowableValues = \"ALIPAY,WECHATPAY,BANKTRANSFER\")\n private String accountType;\n\n @ApiModelProperty(value = \"银行账户\")\n private String bankAccountNumber;\n\n @ApiModelProperty(value = \"银行开户名\")\n private String bankAccountName;\n\n @ApiModelProperty(value = \"银行开户行\")\n private String bankDepositName;\n\n @ApiModelProperty(value = \"商家备注\")\n private String auditRemark;\n\n @ApiModelProperty(value = \"订单支付方式返回的交易号\")\n private String payOrderNo;\n\n @ApiModelProperty(value = \"申请退款金额\")\n private Double applyRefundPrice;\n\n @ApiModelProperty(value = \"实际退款金额\")\n private Double actualRefundPrice;\n\n @ApiModelProperty(value = \"退还积分\")\n private Integer refundPoint;\n\n @ApiModelProperty(value = \"退款时间\")\n private Date refundTime;\n\n /**\n * 买家物流信息\n */\n @ApiModelProperty(value = \"发货单号\")\n private String mLogisticsNo;\n\n @ApiModelProperty(value = \"物流公司CODE\")\n private String mLogisticsCode;\n\n @ApiModelProperty(value = \"物流公司名称\")\n private String mLogisticsName;\n\n @JsonFormat(timezone = \"GMT+8\", pattern = \"yyyy-MM-dd\")\n @DateTimeFormat(pattern = \"yyyy-MM-dd\")\n @ApiModelProperty(value = \"买家发货时间\")\n private Date mDeliverTime;\n\n}" }, { "identifier": "AfterSaleLog", "path": "framework/src/main/java/cn/lili/modules/order/aftersale/entity/dos/AfterSaleLog.java", "snippet": "@Data\n@TableName(\"li_after_sale_log\")\n@ApiModel(value = \"售后日志\")\n@NoArgsConstructor\npublic class AfterSaleLog extends BaseIdEntity {\n\n @CreatedBy\n @TableField(fill = FieldFill.INSERT)\n @ApiModelProperty(value = \"创建者\", hidden = true)\n private String createBy;\n\n @CreatedDate\n @JsonFormat(timezone = \"GMT+8\", pattern = \"yyyy-MM-dd HH:mm:ss\")\n @DateTimeFormat(pattern = \"yyyy-MM-dd HH:mm:ss\")\n @TableField(fill = FieldFill.INSERT)\n @ApiModelProperty(value = \"创建时间\", hidden = true)\n private Date createTime;\n\n @ApiModelProperty(value = \"售后服务单号\")\n private String sn;\n\n @ApiModelProperty(value = \"操作者id(可以是卖家)\")\n private String operatorId;\n\n /**\n * @see UserEnums\n */\n @ApiModelProperty(value = \"操作者类型\")\n private String operatorType;\n\n\n @ApiModelProperty(value = \"操作者名称\")\n private String operatorName;\n\n @ApiModelProperty(value = \"日志信息\")\n private String message;\n\n public AfterSaleLog(String sn, String operatorId, String operatorType, String operatorName, String message) {\n this.sn = sn;\n this.operatorId = operatorId;\n this.operatorType = operatorType;\n this.operatorName = operatorName;\n this.message = message;\n }\n}" }, { "identifier": "AfterSaleReason", "path": "framework/src/main/java/cn/lili/modules/order/aftersale/entity/dos/AfterSaleReason.java", "snippet": "@Data\n@TableName(\"li_after_sale_reason\")\n@ApiModel(value = \"售后原因\")\npublic class AfterSaleReason extends BaseEntity {\n\n @NotNull\n @ApiModelProperty(value = \"售后原因\")\n private String reason;\n\n /**\n * @see cn.lili.modules.order.trade.entity.enums.AfterSaleTypeEnum\n */\n @ApiModelProperty(value = \"原因类型\", allowableValues = \"CANCEL,RETURN_GOODS,RETURN_MONEY,COMPLAIN\")\n @NotNull\n private String serviceType;\n\n}" }, { "identifier": "AfterSaleDTO", "path": "framework/src/main/java/cn/lili/modules/order/aftersale/entity/dto/AfterSaleDTO.java", "snippet": "@Data\npublic class AfterSaleDTO {\n\n @ApiModelProperty(value = \"订单SN\")\n private String orderItemSn;\n\n @ApiModelProperty(value = \"商品ID\")\n private String goodsId;\n\n @ApiModelProperty(value = \"货品ID\")\n private String skuId;\n\n @ApiModelProperty(value = \"申请退款金额\")\n private Double applyRefundPrice;\n\n @ApiModelProperty(value = \"申请数量\")\n private Integer num;\n\n @ApiModelProperty(value = \"申请原因\")\n private String reason;\n\n @ApiModelProperty(value = \"问题描述\")\n private String problemDesc;\n\n @ApiModelProperty(value = \"售后图片\")\n private String images;\n\n /**\n * @see cn.lili.modules.order.trade.entity.enums.AfterSaleTypeEnum\n */\n @ApiModelProperty(value = \"售后类型\", allowableValues = \"RETURN_GOODS,EXCHANGE_GOODS,RETURN_MONEY\")\n private String serviceType;\n\n /**\n * @see cn.lili.modules.order.trade.entity.enums.AfterSaleRefundWayEnum\n */\n @ApiModelProperty(value = \"退款方式\", allowableValues = \"ORIGINAL,OFFLINE\")\n private String refundWay;\n\n @ApiModelProperty(value = \"账号类型\", allowableValues = \"ALIPAY,WECHATPAY,BANKTRANSFER\")\n private String accountType;\n\n @ApiModelProperty(value = \"银行开户行\")\n private String bankDepositName;\n\n @ApiModelProperty(value = \"银行开户名\")\n private String bankAccountName;\n\n @ApiModelProperty(value = \"银行卡号\")\n private String bankAccountNumber;\n}" }, { "identifier": "AfterSaleApplyVO", "path": "framework/src/main/java/cn/lili/modules/order/aftersale/entity/vo/AfterSaleApplyVO.java", "snippet": "@Data\npublic class AfterSaleApplyVO {\n\n @ApiModelProperty(value = \"申请退款金额单价\")\n private Double applyRefundPrice;\n\n @ApiModelProperty(value = \"可申请数量\")\n private Integer num;\n\n @ApiModelProperty(value = \"订单子项编号\")\n private String orderItemSn;\n\n @ApiModelProperty(value = \"商品ID\")\n private String goodsId;\n\n @ApiModelProperty(value = \"货品ID\")\n private String skuId;\n\n @ApiModelProperty(value = \"商品名称\")\n private String goodsName;\n\n @ApiModelProperty(value = \"商品图片\")\n private String image;\n\n @ApiModelProperty(value = \"商品价格\")\n private Double goodsPrice;\n\n /**\n * @see cn.lili.modules.order.trade.entity.enums.AfterSaleRefundWayEnum\n */\n @ApiModelProperty(value = \"退款方式\", allowableValues = \"ORIGINAL,OFFLINE\")\n private String refundWay;\n\n /**\n * @see cn.lili.modules.order.trade.entity.enums\n */\n @ApiModelProperty(value = \"账号类型\", allowableValues = \"ALIPAY,WECHATPAY,MEMBERWALLET,BANKTRANSFER\")\n private String accountType;\n\n @ApiModelProperty(value = \"是否支持退货\")\n private Boolean returnGoods;\n\n @ApiModelProperty(value = \"是否支持退款\")\n private Boolean returnMoney;\n\n @ApiModelProperty(value = \"会员ID\")\n private String memberId;\n\n\n\n\n}" }, { "identifier": "AfterSaleSearchParams", "path": "framework/src/main/java/cn/lili/modules/order/aftersale/entity/vo/AfterSaleSearchParams.java", "snippet": "@EqualsAndHashCode(callSuper = true)\n@Data\npublic class AfterSaleSearchParams extends PageVO {\n\n private static final long serialVersionUID = 28604026820923515L;\n\n @ApiModelProperty(value = \"关键字\")\n private String keywords;\n\n @ApiModelProperty(value = \"售后服务单号\")\n private String sn;\n\n @ApiModelProperty(value = \"订单编号\")\n private String orderSn;\n\n @ApiModelProperty(value = \"会员名称\")\n private String memberName;\n\n @ApiModelProperty(value = \"商家名称\")\n private String storeName;\n\n @ApiModelProperty(value = \"商家ID\")\n private String storeId;\n\n @ApiModelProperty(value = \"商品名称\")\n private String goodsName;\n\n @ApiModelProperty(value = \"申请退款金额,可以为范围,如10_1000\")\n private String applyRefundPrice;\n\n @ApiModelProperty(value = \"实际退款金额,可以为范围,如10_1000\")\n private String actualRefundPrice;\n\n @ApiModelProperty(value = \"总价格,可以为范围,如10_1000\")\n private String flowPrice;\n\n /**\n * @see cn.lili.modules.order.trade.entity.enums.AfterSaleTypeEnum\n */\n @ApiModelProperty(value = \"售后类型\", allowableValues = \"CANCEL,RETURN_GOODS,EXCHANGE_GOODS,REISSUE_GOODS\")\n private String serviceType;\n\n /**\n * @see cn.lili.modules.order.trade.entity.enums.AfterSaleStatusEnum\n */\n @ApiModelProperty(value = \"售后单状态\", allowableValues = \"APPLY,PASS,REFUSE,BUYER_RETURN,SELLER_RE_DELIVERY,BUYER_CONFIRM,SELLER_CONFIRM,COMPLETE\")\n private String serviceStatus;\n\n @DateTimeFormat(pattern = \"yyyy-MM-dd HH:mm:ss\")\n @ApiModelProperty(value = \"开始时间\")\n private Date startDate;\n\n @DateTimeFormat(pattern = \"yyyy-MM-dd HH:mm:ss\")\n @ApiModelProperty(value = \"结束时间\")\n private Date endDate;\n\n public <T> QueryWrapper<T> queryWrapper() {\n QueryWrapper<T> queryWrapper = new QueryWrapper<>();\n if (CharSequenceUtil.isNotEmpty(keywords)) {\n queryWrapper.and(wrapper -> wrapper.like(\"sn\", keywords).or().like(\"order_sn\", keywords).or().like(\"goods_name\", keywords));\n }\n\n if (CharSequenceUtil.isNotEmpty(sn)) {\n queryWrapper.like(\"sn\", sn);\n }\n if (CharSequenceUtil.isNotEmpty(orderSn)) {\n queryWrapper.like(\"order_sn\", orderSn);\n }\n //按买家查询\n if (CharSequenceUtil.equals(UserContext.getCurrentUser().getRole().name(), UserEnums.MEMBER.name())) {\n queryWrapper.eq(\"member_id\", UserContext.getCurrentUser().getId());\n }\n //按卖家查询\n if (CharSequenceUtil.equals(UserContext.getCurrentUser().getRole().name(), UserEnums.STORE.name())) {\n queryWrapper.eq(\"store_id\", UserContext.getCurrentUser().getStoreId());\n }\n\n if (CharSequenceUtil.equals(UserContext.getCurrentUser().getRole().name(), UserEnums.MANAGER.name())\n && CharSequenceUtil.isNotEmpty(storeId)\n ) {\n queryWrapper.eq(\"store_id\", storeId);\n }\n if (CharSequenceUtil.isNotEmpty(memberName)) {\n queryWrapper.like(\"member_name\", memberName);\n }\n if (CharSequenceUtil.isNotEmpty(storeName)) {\n queryWrapper.like(\"store_name\", storeName);\n }\n if (CharSequenceUtil.isNotEmpty(goodsName)) {\n queryWrapper.like(\"goods_name\", goodsName);\n }\n //按时间查询\n if (startDate != null) {\n queryWrapper.ge(\"create_time\", startDate);\n }\n if (endDate != null) {\n queryWrapper.le(\"create_time\", endDate);\n }\n if (CharSequenceUtil.isNotEmpty(serviceStatus)) {\n queryWrapper.eq(\"service_status\", serviceStatus);\n }\n if (CharSequenceUtil.isNotEmpty(serviceType)) {\n queryWrapper.eq(\"service_type\", serviceType);\n }\n this.betweenWrapper(queryWrapper);\n queryWrapper.eq(\"delete_flag\", false);\n return queryWrapper;\n }\n\n private <T> void betweenWrapper(QueryWrapper<T> queryWrapper) {\n if (CharSequenceUtil.isNotEmpty(applyRefundPrice)) {\n String[] s = applyRefundPrice.split(\"_\");\n if (s.length > 1) {\n queryWrapper.between(\"apply_refund_price\", s[0], s[1]);\n } else {\n queryWrapper.ge(\"apply_refund_price\", s[0]);\n }\n }\n if (CharSequenceUtil.isNotEmpty(actualRefundPrice)) {\n String[] s = actualRefundPrice.split(\"_\");\n if (s.length > 1) {\n queryWrapper.between(\"actual_refund_price\", s[0], s[1]);\n } else {\n queryWrapper.ge(\"actual_refund_price\", s[0]);\n }\n }\n if (CharSequenceUtil.isNotEmpty(flowPrice)) {\n String[] s = flowPrice.split(\"_\");\n if (s.length > 1) {\n queryWrapper.between(\"flow_price\", s[0], s[1]);\n } else {\n queryWrapper.ge(\"flow_price\", s[0]);\n }\n }\n }\n\n\n}" }, { "identifier": "AfterSaleVO", "path": "framework/src/main/java/cn/lili/modules/order/aftersale/entity/vo/AfterSaleVO.java", "snippet": "@Data\npublic class AfterSaleVO extends AfterSale {\n /**\n * 初始化自身状态\n */\n public AfterSaleAllowOperation getAfterSaleAllowOperationVO() {\n\n //设置订单的可操作状态\n return new AfterSaleAllowOperation(this);\n }\n}" }, { "identifier": "AfterSaleLogService", "path": "framework/src/main/java/cn/lili/modules/order/aftersale/service/AfterSaleLogService.java", "snippet": "public interface AfterSaleLogService extends IService<AfterSaleLog> {\n\n /**\n * 获取售后日志\n *\n * @param sn 售后编号\n * @return 售后日志列表\n */\n List<AfterSaleLog> getAfterSaleLog(String sn);\n}" }, { "identifier": "AfterSaleReasonService", "path": "framework/src/main/java/cn/lili/modules/order/aftersale/service/AfterSaleReasonService.java", "snippet": "public interface AfterSaleReasonService extends IService<AfterSaleReason> {\n\n /**\n * 获取售后原因列表\n * @param serviceType\n * @return\n */\n List<AfterSaleReason> afterSaleReasonList(String serviceType);\n\n\n /**\n * 修改售后原因\n * @param afterSaleReason 售后原因\n * @return 售后原因\n */\n AfterSaleReason editAfterSaleReason(AfterSaleReason afterSaleReason);\n\n}" }, { "identifier": "AfterSaleService", "path": "framework/src/main/java/cn/lili/modules/order/aftersale/service/AfterSaleService.java", "snippet": "public interface AfterSaleService extends IService<AfterSale> {\n\n /**\n * 分页查询售后信息\n *\n * @param saleSearchParams 查询参数\n * @return 分页售后信息\n */\n IPage<AfterSaleVO> getAfterSalePages(AfterSaleSearchParams saleSearchParams);\n\n /**\n * 查询导出售后信息\n *\n * @param saleSearchParams 查询参数\n * @return 分页售后信息\n */\n List<AfterSale> exportAfterSaleOrder(AfterSaleSearchParams saleSearchParams);\n\n /**\n * 查询售后信息\n *\n * @param sn 售后单号\n * @return 售后信息\n */\n AfterSaleVO getAfterSale(String sn);\n\n /**\n * 获取申请售后页面信息\n *\n * @param sn 订单编号\n * @return\n */\n AfterSaleApplyVO getAfterSaleVO(String sn);\n\n /**\n * 售后申请\n *\n * @param afterSaleDTO 售后对象\n * @return 售后信息\n */\n AfterSale saveAfterSale(AfterSaleDTO afterSaleDTO);\n\n /**\n * 商家审核售后申请\n *\n * @param afterSaleSn 售后编号\n * @param serviceStatus 状态 PASS:审核通过,REFUSE:审核未通过\n * @param remark 商家备注\n * @param actualRefundPrice 退款金额\n * @return 售后\n */\n AfterSale review(String afterSaleSn, String serviceStatus, String remark, Double actualRefundPrice);\n\n /**\n * 买家退货,物流填写\n *\n * @param afterSaleSn 售后服务单号\n * @param logisticsNo 物流单号\n * @param logisticsId 物流公司ID\n * @param mDeliverTime 买家退货发货时间\n * @return 售后\n */\n AfterSale buyerDelivery(String afterSaleSn, String logisticsNo, String logisticsId, Date mDeliverTime);\n\n /**\n * 获取买家退货物流踪迹\n *\n * @param afterSaleSn 售后服务单号\n * @return 物流踪迹\n */\n Traces deliveryTraces(String afterSaleSn);\n\n /**\n * 商家收货\n *\n * @param afterSaleSn 售后编号\n * @param serviceStatus 状态 PASS:审核通过,REFUSE:审核未通过\n * @param remark 商家备注\n * @return 售后服务\n */\n AfterSale storeConfirm(String afterSaleSn, String serviceStatus, String remark);\n\n /**\n * 平台退款-线下支付\n *\n * @param afterSaleSn 售后单号\n * @param remark 备注\n * @return 售后服务\n */\n AfterSale refund(String afterSaleSn, String remark);\n\n /**\n * 买家确认解决问题\n *\n * @param afterSaleSn 售后订单sn\n * @return 售后服务\n */\n AfterSale complete(String afterSaleSn);\n\n /**\n * 买家取消售后\n *\n * @param afterSaleSn 售后订单sn\n * @return 售后服务\n */\n AfterSale cancel(String afterSaleSn);\n\n\n /**\n * 根据售后单号获取店铺退货收货地址信息\n *\n * @param sn 售后单号\n * @return 店铺退货收件地址\n */\n StoreAfterSaleAddressDTO getStoreAfterSaleAddressDTO(String sn);\n\n}" }, { "identifier": "StoreAfterSaleAddressDTO", "path": "framework/src/main/java/cn/lili/modules/store/entity/dto/StoreAfterSaleAddressDTO.java", "snippet": "@Data\npublic class StoreAfterSaleAddressDTO {\n\n @ApiModelProperty(value = \"收货人姓名\")\n private String salesConsigneeName;\n\n @ApiModelProperty(value = \"收件人手机\")\n private String salesConsigneeMobile;\n\n @ApiModelProperty(value = \"地址Id, ','分割\")\n private String salesConsigneeAddressId;\n\n @ApiModelProperty(value = \"地址名称, ','分割\")\n private String salesConsigneeAddressPath;\n\n @ApiModelProperty(value = \"详细地址\")\n private String salesConsigneeDetail;\n}" } ]
import cn.lili.common.aop.annotation.PreventDuplicateSubmissions; import cn.lili.common.enums.ResultUtil; import cn.lili.common.security.OperationalJudgment; import cn.lili.common.vo.ResultMessage; import cn.lili.modules.order.aftersale.entity.dos.AfterSale; import cn.lili.modules.order.aftersale.entity.dos.AfterSaleLog; import cn.lili.modules.order.aftersale.entity.dos.AfterSaleReason; import cn.lili.modules.order.aftersale.entity.dto.AfterSaleDTO; import cn.lili.modules.order.aftersale.entity.vo.AfterSaleApplyVO; import cn.lili.modules.order.aftersale.entity.vo.AfterSaleSearchParams; import cn.lili.modules.order.aftersale.entity.vo.AfterSaleVO; import cn.lili.modules.order.aftersale.service.AfterSaleLogService; import cn.lili.modules.order.aftersale.service.AfterSaleReasonService; import cn.lili.modules.order.aftersale.service.AfterSaleService; import cn.lili.modules.store.entity.dto.StoreAfterSaleAddressDTO; import com.baomidou.mybatisplus.core.metadata.IPage; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.format.annotation.DateTimeFormat; import org.springframework.web.bind.annotation.*; import javax.validation.constraints.NotNull; import java.util.Date; import java.util.List;
7,256
package cn.lili.controller.order; /** * 买家端,售后管理接口 * * @author Chopper * @since 2020/11/16 10:02 下午 */ @RestController @Api(tags = "买家端,售后管理接口") @RequestMapping("/buyer/order/afterSale") public class AfterSaleBuyerController { /** * 售后 */ @Autowired private AfterSaleService afterSaleService; /** * 售后原因 */ @Autowired private AfterSaleReasonService afterSaleReasonService; /** * 售后日志 */ @Autowired private AfterSaleLogService afterSaleLogService; @ApiOperation(value = "查看售后服务详情") @ApiImplicitParam(name = "sn", value = "售后单号", required = true, paramType = "path") @GetMapping(value = "/get/{sn}")
package cn.lili.controller.order; /** * 买家端,售后管理接口 * * @author Chopper * @since 2020/11/16 10:02 下午 */ @RestController @Api(tags = "买家端,售后管理接口") @RequestMapping("/buyer/order/afterSale") public class AfterSaleBuyerController { /** * 售后 */ @Autowired private AfterSaleService afterSaleService; /** * 售后原因 */ @Autowired private AfterSaleReasonService afterSaleReasonService; /** * 售后日志 */ @Autowired private AfterSaleLogService afterSaleLogService; @ApiOperation(value = "查看售后服务详情") @ApiImplicitParam(name = "sn", value = "售后单号", required = true, paramType = "path") @GetMapping(value = "/get/{sn}")
public ResultMessage<AfterSaleVO> get(@NotNull(message = "售后单号") @PathVariable("sn") String sn) {
2
2023-12-24 19:45:18+00:00
12k
bta-team-port/moon-mod
src/main/java/teamport/moonmod/MoonMod.java
[ { "identifier": "BiomeProviderMoon", "path": "src/main/java/teamport/moonmod/world/BiomeProviderMoon.java", "snippet": "public class BiomeProviderMoon extends BiomeProvider {\n\tprivate static final BiomeRangeMap brm = new BiomeRangeMap();\n\tprivate final PerlinSimplexNoise temperatureNoise;\n\tprivate final PerlinSimplexNoise humidityNoise;\n\tprivate final PerlinSimplexNoise varietyNoise;\n\tprivate final PerlinSimplexNoise fuzzinessNoise;\n\tprivate final double temperatureXScale = 0.025;\n\tprivate final double temperatureZScale = 0.025;\n\tprivate final double temperatureExponent = 0.25;\n\tprivate final double temperatureFuzzPercentage = 0.01;\n\tprivate final double humidityXScale = 0.05;\n\tprivate final double humidityZScale = 0.05;\n\tprivate final double humidityExponent = 0.3;\n\tprivate final double humidityFuzzPercentage = 0.002;\n\tprivate final double varietyXScale = 0.5;\n\tprivate final double varietyZScale = 0.5;\n\tprivate final double varietyExponent = 0.25;\n\tprivate final double varietyFuzzPercentage = 0.0;\n\tprivate final double fuzzinessXScale = 0.25;\n\tprivate final double fuzzinessZScale = 0.25;\n\tprivate final double fuzzinessExponent = 0.5;\n\tprivate final WorldType worldType;\n\n\tpublic BiomeProviderMoon(long seed, WorldTypeMoon worldType) {\n\t\tthis.worldType = worldType;\n\t\tthis.temperatureNoise = new PerlinSimplexNoise(new Random(seed * 9871L), 4);\n\t\tthis.humidityNoise = new PerlinSimplexNoise(new Random(seed * 39811L), 4);\n\t\tthis.varietyNoise = new PerlinSimplexNoise(new Random(seed), 4);\n\t\tthis.fuzzinessNoise = new PerlinSimplexNoise(new Random(seed * 543321L), 2);\n\t}\n\n\t@Override\n\tpublic Biome[] getBiomes(Biome[] biomes,\n\t\t\t\t\t\t\t double[] temperatures,\n\t\t\t\t\t\t\t double[] humidities,\n\t\t\t\t\t\t\t double[] varieties,\n\t\t\t\t\t\t\t int x,\n\t\t\t\t\t\t\t int y,\n\t\t\t\t\t\t\t int z,\n\t\t\t\t\t\t\t int xSize,\n\t\t\t\t\t\t\t int ySize,\n\t\t\t\t\t\t\t int zSize) {\n\t\tif (biomes == null || biomes.length < xSize * ySize * zSize) {\n\t\t\tbiomes = new Biome[xSize * ySize * zSize];\n\t\t}\n\n\t\tif (temperatures == null || temperatures.length < xSize * zSize) {\n\t\t\ttemperatures = this.getTemperatures(temperatures, x, z, xSize, zSize);\n\t\t}\n\n\t\tif (humidities == null || humidities.length < xSize * zSize) {\n\t\t\thumidities = this.getHumidities(humidities, x, z, xSize, zSize);\n\t\t}\n\n\t\tif (varieties == null || varieties.length < xSize * zSize) {\n\t\t\tvarieties = this.getVarieties(varieties, x, z, xSize, zSize);\n\t\t}\n\n\t\tfor (int dx = 0; dx < xSize; ++dx) {\n\t\t\tfor (int dz = 0; dz < zSize; ++dz) {\n\t\t\t\tdouble temperature = temperatures[dx * zSize + dz];\n\t\t\t\tdouble humidity = humidities[dx * zSize + dz];\n\t\t\t\tdouble variety = varieties[dx * zSize + dz];\n\n\t\t\t\tfor (int dy = 0; dy < ySize; ++dy) {\n\t\t\t\t\tdouble altitude = this.worldType.getYPercentage(y + dy << 3);\n\t\t\t\t\tbiomes[dy * xSize * zSize + dz * xSize + dx] = this.lookupBiome(temperature, humidity, altitude, variety);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn biomes;\n\t}\n\n\t@Override\n\tpublic double[] getTemperatures(double[] temperatures, int x, int z, int xSize, int zSize) {\n\t\tif (temperatures == null || temperatures.length < xSize * zSize) {\n\t\t\ttemperatures = new double[xSize * zSize];\n\t\t}\n\n\t\tdouble[] tnResult = this.temperatureNoise\n\t\t\t.getValue(null, x, z, xSize, zSize, this.temperatureXScale, this.temperatureZScale, this.temperatureExponent);\n\t\tdouble[] fnResult = this.fuzzinessNoise\n\t\t\t.getValue(null, x, z, xSize, zSize, this.fuzzinessXScale, this.fuzzinessZScale, this.fuzzinessExponent);\n\n\t\tfor(int dx = 0; dx < xSize; ++dx) {\n\t\t\tfor(int dz = 0; dz < zSize; ++dz) {\n\t\t\t\tdouble fuzziness = fnResult[dx * zSize + dz] * 1.1 + 0.5;\n\t\t\t\tdouble fuzzPctg = this.temperatureFuzzPercentage;\n\t\t\t\tdouble valPctg = 1.0 - fuzzPctg;\n\t\t\t\tdouble temperature = (tnResult[dx * zSize + dz] * 0.15 + 0.7) * valPctg + fuzziness * fuzzPctg;\n\t\t\t\ttemperature = 1.0 - (1.0 - temperature) * (1.0 - temperature);\n\t\t\t\tif (temperature < 0.0) {\n\t\t\t\t\ttemperature = 0.0;\n\t\t\t\t}\n\n\t\t\t\tif (temperature > 1.0) {\n\t\t\t\t\ttemperature = 1.0;\n\t\t\t\t}\n\n\t\t\t\ttemperatures[dx * zSize + dz] = temperature;\n\t\t\t}\n\t\t}\n\n\t\treturn temperatures;\n\t}\n\n\t@Override\n\tpublic double[] getHumidities(double[] humidities, int x, int z, int xSize, int zSize) {\n\t\tif (humidities == null || humidities.length < xSize * zSize) {\n\t\t\thumidities = new double[xSize * zSize];\n\t\t}\n\n\t\tdouble[] hnResult = this.humidityNoise\n\t\t\t.getValue(null, x, z, xSize, zSize, this.humidityXScale, this.humidityZScale, this.humidityExponent);\n\t\tdouble[] fnResult = this.fuzzinessNoise\n\t\t\t.getValue(null, x, z, xSize, zSize, this.fuzzinessXScale, this.fuzzinessZScale, this.fuzzinessExponent);\n\n\t\tfor(int dx = 0; dx < xSize; ++dx) {\n\t\t\tfor(int dz = 0; dz < zSize; ++dz) {\n\t\t\t\tdouble fuzziness = fnResult[dx * zSize + dz] * 1.1 + 0.5;\n\t\t\t\tdouble fuzzPctg = this.humidityFuzzPercentage;\n\t\t\t\tdouble valPctg = 1.0 - fuzzPctg;\n\t\t\t\tdouble humidity = (hnResult[dx * zSize + dz] * 0.15 + 0.5) * valPctg + fuzziness * fuzzPctg;\n\t\t\t\tif (humidity < 0.0) {\n\t\t\t\t\thumidity = 0.0;\n\t\t\t\t}\n\n\t\t\t\tif (humidity > 1.0) {\n\t\t\t\t\thumidity = 1.0;\n\t\t\t\t}\n\n\t\t\t\thumidities[dx * zSize + dz] = humidity;\n\t\t\t}\n\t\t}\n\n\t\treturn humidities;\n\t}\n\n\t@Override\n\tpublic double[] getVarieties(double[] varieties, int x, int z, int xSize, int zSize) {\n\t\tif (varieties == null || varieties.length < xSize * zSize) {\n\t\t\tvarieties = new double[xSize * zSize];\n\t\t}\n\n\t\tdouble[] vnResult = this.varietyNoise.getValue(null, x, z, xSize, zSize, this.varietyXScale, this.varietyZScale, this.varietyExponent);\n\t\tdouble[] fnResult = this.fuzzinessNoise\n\t\t\t.getValue(null, x, z, xSize, zSize, this.fuzzinessXScale, this.fuzzinessZScale, this.fuzzinessExponent);\n\n\t\tfor(int dx = 0; dx < xSize; ++dx) {\n\t\t\tfor(int dz = 0; dz < zSize; ++dz) {\n\t\t\t\tdouble fuzziness = fnResult[dx * zSize + dz] * 1.1 + 0.5;\n\t\t\t\tdouble fuzzPctg = this.varietyFuzzPercentage;\n\t\t\t\tdouble valPctg = 1.0 - fuzzPctg;\n\t\t\t\tdouble variety = (vnResult[dx * zSize + dz] * 0.15 + 0.5) * valPctg + fuzziness * fuzzPctg;\n\t\t\t\tif (variety < 0.0) {\n\t\t\t\t\tvariety = 0.0;\n\t\t\t\t}\n\n\t\t\t\tif (variety > 1.0) {\n\t\t\t\t\tvariety = 1.0;\n\t\t\t\t}\n\n\t\t\t\tvarieties[dx * zSize + dz] = variety;\n\t\t\t}\n\t\t}\n\n\t\treturn varieties;\n\t}\n\n\t@Override\n\tpublic double[] getBiomenesses(double[] biomenesses, int x, int y, int z, int xSize, int ySize, int zSize) {\n\t\tif (biomenesses == null || biomenesses.length < xSize * ySize * zSize) {\n\t\t\tbiomenesses = new double[xSize * ySize * zSize];\n\t\t}\n\n\t\tdouble[] temperatures = this.getTemperatures(null, x, z, xSize, zSize);\n\t\tdouble[] humidities = this.getHumidities(null, x, z, xSize, zSize);\n\t\tdouble[] varieties = this.getVarieties(null, x, z, xSize, zSize);\n\n\t\tfor(int dx = 0; dx < xSize; ++dx) {\n\t\t\tfor(int dy = 0; dy < ySize; ++dy) {\n\t\t\t\tfor(int dz = 0; dz < zSize; ++dz) {\n\t\t\t\t\tdouble temperature = MathHelper.clamp(temperatures[dx * zSize + dz], 0.0, 1.0);\n\t\t\t\t\tdouble humidity = MathHelper.clamp(humidities[dx * zSize + dz], 0.0, 1.0);\n\t\t\t\t\tdouble altitude = MathHelper.clamp(worldType.getYPercentage(y + dy << 3), 0.0, 1.0);\n\t\t\t\t\tdouble variety = MathHelper.clamp(varieties[dx * zSize + dz], 0.0, 1.0);\n\t\t\t\t\tBiome biome = this.lookupBiome(temperature, humidity, altitude, variety);\n\t\t\t\t\tSet<BiomeRange> ranges = brm.getRanges(biome);\n\t\t\t\t\thumidity *= temperature;\n\t\t\t\t\tdouble biomeness = 0.0;\n\n\t\t\t\t\tfor(BiomeRange range : ranges) {\n\t\t\t\t\t\tif (range.contains(temperature, humidity, variety, altitude)) {\n\t\t\t\t\t\t\tdouble temperatureRange = range.getMaxTemperature() - range.getMinTemperature();\n\t\t\t\t\t\t\tdouble humidityRange = range.getMaxHumidity() - range.getMinHumidity();\n\t\t\t\t\t\t\tdouble altitudeRange = range.getMaxAltitude() - range.getMinAltitude();\n\t\t\t\t\t\t\tdouble varietyRange = range.getMaxVariety() - range.getMinVariety();\n\t\t\t\t\t\t\tdouble newTemperature = (temperature - range.getMinTemperature()) / temperatureRange;\n\t\t\t\t\t\t\tdouble newHumidity = (humidity - range.getMinHumidity()) / humidityRange;\n\t\t\t\t\t\t\tdouble newAltitude = (altitude - range.getMinAltitude()) / altitudeRange;\n\t\t\t\t\t\t\tdouble newVariety = (variety - range.getMinVariety()) / varietyRange;\n\t\t\t\t\t\t\tif ((!(range.getMinTemperature() <= 0.0) || !(newTemperature <= 0.5))\n\t\t\t\t\t\t\t\t&& (!(range.getMaxTemperature() >= 1.0) || !(newTemperature >= 0.5))) {\n\t\t\t\t\t\t\t\tnewTemperature = -Math.abs(newTemperature * 2.0 - 1.0) + 1.0;\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tnewTemperature = 1.0;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif ((!(range.getMinHumidity() <= 0.0) || !(newHumidity <= 0.5)) && (!(range.getMaxHumidity() >= 1.0) || !(newHumidity >= 0.5))) {\n\t\t\t\t\t\t\t\tnewHumidity = -Math.abs(newHumidity * 2.0 - 1.0) + 1.0;\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tnewHumidity = 1.0;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif ((!(range.getMinAltitude() <= 0.0) || !(newAltitude <= 0.5)) && (!(range.getMaxAltitude() >= 1.0) || !(newAltitude >= 0.5))) {\n\t\t\t\t\t\t\t\tnewAltitude = -Math.abs(newAltitude * 2.0 - 1.0) + 1.0;\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tnewAltitude = 1.0;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tif ((!(range.getMinVariety() <= 0.0) || !(newVariety <= 0.5)) && (!(range.getMaxVariety() >= 1.0) || !(newVariety >= 0.5))) {\n\t\t\t\t\t\t\t\tnewVariety = -Math.abs(newVariety * 2.0 - 1.0) + 1.0;\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tnewVariety = 1.0;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tdouble newBiomeness = newTemperature * newHumidity * newAltitude * newVariety;\n\t\t\t\t\t\t\tif (newBiomeness > biomeness) {\n\t\t\t\t\t\t\t\tbiomeness = newBiomeness;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tbiomenesses[dy * xSize * zSize + dx * zSize + dz] = biomeness;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn biomenesses;\n\t}\n\n\t@Override\n\tpublic Biome lookupBiome(double temperature, double humidity, double variety, double altitude) {\n\t\thumidity *= temperature;\n\t\treturn brm.lookupBiome(temperature, humidity, altitude, variety);\n\t}\n\n\tpublic static void init() {\n\t\tbrm.clear();\n\t\tbrm.addRange(MoonBiomes.BIOME_MOON, new BiomeRange(0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0));\n\t\tbrm.lock();\n\t}\n}" }, { "identifier": "ModDimensions", "path": "src/main/java/teamport/moonmod/world/ModDimensions.java", "snippet": "public class ModDimensions {\n\tpublic static final Dimension dimensionMoon = new Dimension(\"moon\", Dimension.overworld, 3f, MoonModBlocks.portalMoon.id).setDefaultWorldType(MoonMod.MOON_WORLD);\n\tstatic\n\t{\n\t\tDimension.registerDimension(3, dimensionMoon);\n\t}\n\tpublic static void register() {}\n\n\tpublic static void dimensionShift(int targetDimension){\n\t\tMinecraft mc = Minecraft.getMinecraft(Minecraft.class);\n\t\tEntityPlayer player = mc.thePlayer;\n\t\tWorld world = mc.theWorld;\n\n\t\tDimension lastDim = Dimension.getDimensionList().get(player.dimension);\n\t\tDimension newDim = Dimension.getDimensionList().get(targetDimension);\n\t\tSystem.out.println(\"Switching to dimension \\\"\" + newDim.getTranslatedName() + \"\\\"!!\");\n\t\tplayer.dimension = targetDimension;\n\t\tworld.setEntityDead(player);\n\t\tplayer.removed = false;\n\t\tdouble x = player.x;\n\t\tdouble z = player.z;\n\t\tplayer.moveTo(x *= (double)Dimension.getCoordScale(lastDim, newDim), player.y, z *= (double)Dimension.getCoordScale(lastDim, newDim), player.yRot, player.xRot);\n\t\tif (player.isAlive()) {\n\t\t\tworld.updateEntityWithOptionalForce(player, false);\n\t\t}\n\t\tif (player.isAlive()) {\n\t\t\tworld.updateEntityWithOptionalForce(player, false);\n\t\t}\n\t\tworld = new World(world, newDim);\n\t\tif (newDim == lastDim.homeDim) {\n\t\t\tmc.changeWorld(world, \"Leaving \" + lastDim.getTranslatedName(), player);\n\t\t} else {\n\t\t\tmc.changeWorld(world, \"Entering \" + newDim.getTranslatedName(), player);\n\t\t}\n\t\tplayer.world = world;\n\t\tif (player.isAlive()) {\n\t\t\tplayer.moveTo(player.x, world.worldType.getMaxY()+1, player.z, player.yRot, player.xRot);\n\t\t\tworld.updateEntityWithOptionalForce(player, false);\n\t\t}\n\n\t}\n}" }, { "identifier": "WorldTypeMoon", "path": "src/main/java/teamport/moonmod/world/WorldTypeMoon.java", "snippet": "public class WorldTypeMoon extends WorldTypeOverworld {\n\n\tpublic WorldTypeMoon(String languageKey) {\n\t\tsuper(languageKey, Weather.overworldClear, new WindManagerGeneric(), SeasonConfig.builder()\n\t\t\t.withSingleSeason(Seasons.NULL)\n\t\t\t.build());\n\t}\n\n\t@Override\n\tpublic int getMinY() {\n\t\treturn 0;\n\t}\n\n\t@Override\n\tpublic int getMaxY() {\n\t\treturn 127;\n\t}\n\n\t@Override\n\tpublic int getOceanY() {\n\t\treturn 0;\n\t}\n\n\t@Override\n\tpublic BiomeProvider createBiomeProvider(World world) {\n\t\treturn new BiomeProviderMoon(world.getRandomSeed(), this);\n\t}\n\n\t@Override\n\tpublic float getCloudHeight() {\n\t\treturn -64;\n\t}\n\n\t@Override\n\tpublic ChunkGenerator createChunkGenerator(World world) {\n\t\treturn new ChunkGeneratorMoon(world);\n\t}\n\n\t@Override\n\tpublic boolean hasAurora() {\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic boolean isValidSpawn(World world, int x, int y, int z) {\n\t\treturn world.getBlockId(x, y -1, z) == MoonModBlocks.regolith.id;\n\t}\n\n\t@Override\n\tpublic boolean mayRespawn() {\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic int getDayNightCycleLengthTicks() {\n\t\treturn 24000;\n\t}\n\n\t@Override\n\tpublic float[] getSunriseColor(float timeOfDay, float partialTick) {\n\t\treturn new float[] {0.0f, 0.0f, 0.0f, 0.0f};\n\t}\n\n\t@Override\n\tpublic int getSkyDarken(World world, long tick, float partialTick) {\n\t\tint subtracted;\n\t\tfloat f1 = this.getCelestialAngle(world, tick, partialTick);\n\t\tfloat f2 = 1.0f - (MathHelper.cos(f1 * 3.141593f * 2.0f) * 2.0f + 0.5f);\n\t\tif (f2 < 0.0f) {\n\t\t\tf2 = 0.0f;\n\t\t}\n\t\tif (f2 > 1.0f) {\n\t\t\tf2 = 1.0f;\n\t\t}\n\t\tfloat weatherOffset = 0.0f;\n\t\tif (world.getCurrentWeather() != null) {\n\t\t\tweatherOffset = (float)world.getCurrentWeather().subtractLightLevel * world.weatherManager.getWeatherIntensity() * world.weatherManager.getWeatherPower();\n\t\t}\n\t\tif ((subtracted = (int)(f2 * (11.0f - weatherOffset) + weatherOffset)) > 8) {\n\t\t\tsubtracted = 12;\n\t\t}\n\t\treturn subtracted;\n\t}\n\n\t@Override\n\tpublic float getCelestialAngle(World world, long tick, float partialTick) {\n\t\treturn 0.5F;\n\t}\n\n\n\t@Override\n\tpublic Vec3d getFogColor(float timeOfDay, float partialTick) {\n\t\tint i = 0;\n\t\tfloat f2 = MathHelper.cos(timeOfDay * 3.141593F * 2.0F) * 2.0F + 0.5F;\n\t\tif(f2 < 0.0F)\n\t\t{\n\t\t\tf2 = 0.0F;\n\t\t}\n\t\tif(f2 > 1.0F)\n\t\t{\n\t\t\tf2 = 1.0F;\n\t\t}\n\t\tfloat f3 = (float)(i >> 16 & 0xff) / 255F;\n\t\tfloat f4 = (float)(i >> 8 & 0xff) / 255F;\n\t\tfloat f5 = (float)(i & 0xff) / 255F;\n\t\tf3 *= f2 * 0.94F + 0.06F;\n\t\tf4 *= f2 * 0.94F + 0.06F;\n\t\tf5 *= f2 * 0.91F + 0.09F;\n\t\treturn Vec3d.createVector(f3, f4, f5);\n\t}\n}" }, { "identifier": "MoonBiomes", "path": "src/main/java/teamport/moonmod/world/biome/MoonBiomes.java", "snippet": "public class MoonBiomes {\n\tpublic static Biome BIOME_MOON = new BiomeMoon();\n\n\tpublic void initializeBiomes() {\n\n\t\tBiomes.register(MoonMod.MOD_ID+\":moon.lunar.plains\", BIOME_MOON);\n\t}\n}" }, { "identifier": "EntityUFO", "path": "src/main/java/teamport/moonmod/entity/EntityUFO.java", "snippet": "public class EntityUFO extends EntityAnimal {\n\n\tpublic EntityUFO(World world) {\n\t\tsuper(world);\n\t\tskinName = \"ufo\";\n\t}\n\n\t@Override\n\tpublic String getLivingSound() {\n\t\treturn null;\n\t}\n\n\t@Override\n\tprotected String getHurtSound() {\n\t\treturn null;\n\t}\n\n\t@Override\n\tprotected String getDeathSound() {\n\t\treturn null;\n\t}\n}" }, { "identifier": "UFOModel", "path": "src/main/java/teamport/moonmod/entity/render/UFOModel.java", "snippet": "public class UFOModel extends BenchEntityModel {\n\n\t@Override\n\tpublic void setRotationAngles(float limbSwing, float limbYaw, float limbPitch, float headYaw, float headPitch, float scale) {\n\t\tsuper.setRotationAngles(limbSwing, limbYaw, limbPitch, headYaw, headPitch, scale);\n\n\t\tif (this.getIndexBones().containsKey(\"head\")) {\n\t\t\tthis.getIndexBones().get(\"head\")\n\t\t\t\t.setRotationAngle(0.0F, 0.0F, 0.0F);\n\n\t\t\tthis.getIndexBones().get(\"head\")\n\t\t\t\t.rotateAngleX = headPitch / (float) (90.0 / Math.PI);\n\n\t\t\tthis.getIndexBones().get(\"head\")\n\t\t\t\t.rotateAngleY = headYaw / ((float) (180.0 / Math.PI));\n\t\t}\n\n\t\tif (this.getIndexBones().containsKey(\"body\")) {\n\t\t\tthis.getIndexBones().get(\"body\")\n\t\t\t\t.setRotationAngle(0.0F, 0.0F, 0.0F);\n\t\t}\n\n\t\tif (this.getIndexBones().containsKey(\"leftArm\")) {\n\t\t\tthis.getIndexBones().get(\"leftArm\")\n\t\t\t\t.setRotationAngle(0.0F, 0.0F, 0.0F);\n\n\t\t\tthis.getIndexBones().get(\"leftArm\")\n\t\t\t\t.rotateAngleX = MathHelper.cos(limbSwing * 0.6662F) * 2.0F * limbYaw * 0.5F;\n\n\t\t\tthis.getIndexBones().get(\"leftArm\")\n\t\t\t\t.rotateAngleX -= MathHelper.sin(limbPitch * 0.067F) * 0.05F;\n\t\t}\n\n\n\t\tif (this.getIndexBones().containsKey(\"rightArm\")) {\n\t\t\tthis.getIndexBones().get(\"rightArm\")\n\t\t\t\t.setRotationAngle(0.0F, 0.0F, 0.0F);\n\n\t\t\tthis.getIndexBones().get(\"rightArm\")\n\t\t\t\t.rotateAngleX = MathHelper.cos(limbSwing * 0.6662F + 3.141593F) * 2.0F * limbYaw * 0.5F;\n\n\t\t\tthis.getIndexBones().get(\"rightArm\")\n\t\t\t\t.rotateAngleX += MathHelper.sin(limbPitch * 0.067F) * 0.05F;\n\t\t}\n\n\t\tif (this.getIndexBones().containsKey(\"leftLeg\")) {\n\t\t\tthis.getIndexBones().get(\"leftLeg\")\n\t\t\t\t.setRotationAngle(0.0F, 0.0F, 0.0F);\n\n\t\t\tthis.getIndexBones().get(\"leftLeg\")\n\t\t\t\t.rotateAngleX = MathHelper.cos(limbSwing * 0.6662F) * 1.4F * limbYaw;\n\t\t}\n\n\t\tif (this.getIndexBones().containsKey(\"rightLeg\")) {\n\t\t\tthis.getIndexBones().get(\"rightLeg\")\n\t\t\t\t.setRotationAngle(0.0F, 0.0F, 0.0F);\n\n\t\t\tthis.getIndexBones().get(\"rightLeg\")\n\t\t\t\t.rotateAngleX = MathHelper.cos(limbSwing * 0.6662F + 3.141593F) * 1.4F * limbYaw;\n\t\t}\n\t}\n}" }, { "identifier": "UFORenderer", "path": "src/main/java/teamport/moonmod/entity/render/UFORenderer.java", "snippet": "public class UFORenderer extends LivingRenderer<EntityUFO> {\n\n\tpublic UFORenderer(ModelBase model) {\n\t\tsuper(model, 0.25F);\n\n\t\tsetRenderPassModel(model);\n\t}\n}" }, { "identifier": "MoonModBlocks", "path": "src/main/java/teamport/moonmod/block/MoonModBlocks.java", "snippet": "public class MoonModBlocks {\n\tprivate static int blockID = 2000;\n\n\tpublic static final Block regolith = new BlockBuilder(MOD_ID)\n\t\t.setBlockSound(new BlockSound(\"step.gravel\", \"step.gravel\", 1.0f, 1.0f))\n\t\t.setHardness(0.5f)\n\t\t.setResistance(0.5f)\n\t\t.setTextures(\"regolith.png\")\n\t\t.setTags(BlockTags.MINEABLE_BY_SHOVEL, BlockTags.CAVES_CUT_THROUGH)\n\t\t.build(new Block(\"regolith\", blockID++, Material.dirt));\n\n\tpublic static final Block woolReinforced = new BlockBuilder(MOD_ID)\n\t\t.setBlockSound(new BlockSound(\"step.cloth\", \"step.cloth\", 1.0f, 1.0f))\n\t\t.setHardness(1.1f)\n\t\t.setResistance(6.0f)\n\t\t.setTextures(\"clothBlock.png\")\n\t\t.setTags(BlockTags.MINEABLE_BY_SHEARS, BlockTags.MINEABLE_BY_PICKAXE, BlockTags.CAVES_CUT_THROUGH)\n\t\t.build(new BlockReinforcedWool(\"wool.reinforced\", blockID++, Material.cloth));\n\n\tpublic static final Block tent = new BlockBuilder(MOD_ID)\n\t\t.setBlockSound(new BlockSound(\"step.cloth\", \"step.cloth\", 1.0f, 1.0f))\n\t\t.setHardness(1.1f)\n\t\t.setResistance(6.0f)\n\t\t.setTextures(\"tent.png\")\n\t\t.setTags(BlockTags.MINEABLE_BY_SHEARS, BlockTags.MINEABLE_BY_PICKAXE, BlockTags.CAVES_CUT_THROUGH)\n\t\t.build(new BlockTent(\"wool.reinforced.tent\", blockID++, Material.cloth));\n\n\tpublic static final Block cheese = new BlockBuilder(MOD_ID)\n\t\t.setBlockSound(new BlockSound(\"step.wood\", \"step.wood\", 1.0f, 1.0f))\n\t\t.setHardness(0.6f)\n\t\t.setResistance(0.6f)\n\t\t.setTextures(\"cheeseBlock.png\")\n\t\t.setTags(BlockTags.MINEABLE_BY_SHEARS, BlockTags.MINEABLE_BY_AXE)\n\t\t.build(new BlockCheese(\"cheese\", blockID++, Material.cloth));\n\n\tpublic static final Block portalMoon = new BlockBuilder(MOD_ID)\n\t\t.setBlockSound(new BlockSound(\"step.stone\", \"random.glass\", 1.0f, 1.0f))\n\t\t.setHardness(-1.0f)\n\t\t.setResistance(-1.0f)\n\t\t.setLuminance(15)\n\t\t.setTextures(13, 12)\n\t\t.setTags(BlockTags.BROKEN_BY_FLUIDS, BlockTags.NOT_IN_CREATIVE_MENU)\n\t\t.setBlockColor(new BlockColorWater())\n\t\t.build(new BlockPortal(\"portal.moon\", blockID++, 3, MoonModBlocks.cheese.id, fire.id));\n\n\tpublic void initializeBlocks(){}\n}" }, { "identifier": "MoonModItems", "path": "src/main/java/teamport/moonmod/item/MoonModItems.java", "snippet": "public class MoonModItems {\n\n\tpublic static final Item cheese = ItemHelper.createItem(MoonMod.MOD_ID,\n\t\tnew ItemFood(\"cheese\", 16600, 4, false),\n\t\t\"cheese\",\n\t\t\"cheeseSlice.png\");\n\n\tpublic static final Item sonicScrewdriver = ItemHelper.createItem(MoonMod.MOD_ID,\n\t\tnew ItemScrewdriver(\"Sonic Screwdriver\", 16601),\n\t\t\"screwdriver\",\n\t\t\"screwer.png\");\n\n\tpublic static final ArmorMaterial spacesuit = ArmorHelper.createArmorMaterial(\"moonSuit\", 240, 20.0f, 20.0f, 20.0f, 20.0f);\n\n\tpublic static final Item spaceHelmet = ItemHelper.createItem(MoonMod.MOD_ID,\n\t\tnew ItemArmor(\"Space Helmet\", 16602, spacesuit, 0),\n\t\t\"armor.helmet.space\",\n\t\t\"spaceHelmet.png\");\n\n\tpublic static final Item spaceSuit = ItemHelper.createItem(MoonMod.MOD_ID,\n\t\tnew ItemArmor(\"Space Suit\", 16603, spacesuit, 1),\n\t\t\"armor.chestplate.space\",\n\t\t\"spaceSuit.png\");\n\n\tpublic static final Item spacePants = ItemHelper.createItem(MoonMod.MOD_ID,\n\t\tnew ItemArmor(\"Space Pants\", 16604, spacesuit, 2),\n\t\t\"armor.leggings.space\",\n\t\t\"spacePants.png\");\n\n\tpublic static final Item spaceBoots = ItemHelper.createItem(MoonMod.MOD_ID,\n\t\tnew ItemArmor(\"Space Boots\", 16605, spacesuit, 3),\n\t\t\"armor.boots.space\",\n\t\t\"spaceBoots.png\");\n\tpublic void initializeItems(){}\n}" }, { "identifier": "MoonModBlocks", "path": "src/main/java/teamport/moonmod/block/MoonModBlocks.java", "snippet": "public class MoonModBlocks {\n\tprivate static int blockID = 2000;\n\n\tpublic static final Block regolith = new BlockBuilder(MOD_ID)\n\t\t.setBlockSound(new BlockSound(\"step.gravel\", \"step.gravel\", 1.0f, 1.0f))\n\t\t.setHardness(0.5f)\n\t\t.setResistance(0.5f)\n\t\t.setTextures(\"regolith.png\")\n\t\t.setTags(BlockTags.MINEABLE_BY_SHOVEL, BlockTags.CAVES_CUT_THROUGH)\n\t\t.build(new Block(\"regolith\", blockID++, Material.dirt));\n\n\tpublic static final Block woolReinforced = new BlockBuilder(MOD_ID)\n\t\t.setBlockSound(new BlockSound(\"step.cloth\", \"step.cloth\", 1.0f, 1.0f))\n\t\t.setHardness(1.1f)\n\t\t.setResistance(6.0f)\n\t\t.setTextures(\"clothBlock.png\")\n\t\t.setTags(BlockTags.MINEABLE_BY_SHEARS, BlockTags.MINEABLE_BY_PICKAXE, BlockTags.CAVES_CUT_THROUGH)\n\t\t.build(new BlockReinforcedWool(\"wool.reinforced\", blockID++, Material.cloth));\n\n\tpublic static final Block tent = new BlockBuilder(MOD_ID)\n\t\t.setBlockSound(new BlockSound(\"step.cloth\", \"step.cloth\", 1.0f, 1.0f))\n\t\t.setHardness(1.1f)\n\t\t.setResistance(6.0f)\n\t\t.setTextures(\"tent.png\")\n\t\t.setTags(BlockTags.MINEABLE_BY_SHEARS, BlockTags.MINEABLE_BY_PICKAXE, BlockTags.CAVES_CUT_THROUGH)\n\t\t.build(new BlockTent(\"wool.reinforced.tent\", blockID++, Material.cloth));\n\n\tpublic static final Block cheese = new BlockBuilder(MOD_ID)\n\t\t.setBlockSound(new BlockSound(\"step.wood\", \"step.wood\", 1.0f, 1.0f))\n\t\t.setHardness(0.6f)\n\t\t.setResistance(0.6f)\n\t\t.setTextures(\"cheeseBlock.png\")\n\t\t.setTags(BlockTags.MINEABLE_BY_SHEARS, BlockTags.MINEABLE_BY_AXE)\n\t\t.build(new BlockCheese(\"cheese\", blockID++, Material.cloth));\n\n\tpublic static final Block portalMoon = new BlockBuilder(MOD_ID)\n\t\t.setBlockSound(new BlockSound(\"step.stone\", \"random.glass\", 1.0f, 1.0f))\n\t\t.setHardness(-1.0f)\n\t\t.setResistance(-1.0f)\n\t\t.setLuminance(15)\n\t\t.setTextures(13, 12)\n\t\t.setTags(BlockTags.BROKEN_BY_FLUIDS, BlockTags.NOT_IN_CREATIVE_MENU)\n\t\t.setBlockColor(new BlockColorWater())\n\t\t.build(new BlockPortal(\"portal.moon\", blockID++, 3, MoonModBlocks.cheese.id, fire.id));\n\n\tpublic void initializeBlocks(){}\n}" }, { "identifier": "MoonModItems", "path": "src/main/java/teamport/moonmod/item/MoonModItems.java", "snippet": "public class MoonModItems {\n\n\tpublic static final Item cheese = ItemHelper.createItem(MoonMod.MOD_ID,\n\t\tnew ItemFood(\"cheese\", 16600, 4, false),\n\t\t\"cheese\",\n\t\t\"cheeseSlice.png\");\n\n\tpublic static final Item sonicScrewdriver = ItemHelper.createItem(MoonMod.MOD_ID,\n\t\tnew ItemScrewdriver(\"Sonic Screwdriver\", 16601),\n\t\t\"screwdriver\",\n\t\t\"screwer.png\");\n\n\tpublic static final ArmorMaterial spacesuit = ArmorHelper.createArmorMaterial(\"moonSuit\", 240, 20.0f, 20.0f, 20.0f, 20.0f);\n\n\tpublic static final Item spaceHelmet = ItemHelper.createItem(MoonMod.MOD_ID,\n\t\tnew ItemArmor(\"Space Helmet\", 16602, spacesuit, 0),\n\t\t\"armor.helmet.space\",\n\t\t\"spaceHelmet.png\");\n\n\tpublic static final Item spaceSuit = ItemHelper.createItem(MoonMod.MOD_ID,\n\t\tnew ItemArmor(\"Space Suit\", 16603, spacesuit, 1),\n\t\t\"armor.chestplate.space\",\n\t\t\"spaceSuit.png\");\n\n\tpublic static final Item spacePants = ItemHelper.createItem(MoonMod.MOD_ID,\n\t\tnew ItemArmor(\"Space Pants\", 16604, spacesuit, 2),\n\t\t\"armor.leggings.space\",\n\t\t\"spacePants.png\");\n\n\tpublic static final Item spaceBoots = ItemHelper.createItem(MoonMod.MOD_ID,\n\t\tnew ItemArmor(\"Space Boots\", 16605, spacesuit, 3),\n\t\t\"armor.boots.space\",\n\t\t\"spaceBoots.png\");\n\tpublic void initializeItems(){}\n}" } ]
import net.fabricmc.api.ModInitializer; import net.fabricmc.loader.api.entrypoint.PreLaunchEntrypoint; import net.minecraft.core.world.type.WorldType; import net.minecraft.core.world.type.WorldTypes; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import teamport.moonmod.world.BiomeProviderMoon; import teamport.moonmod.world.ModDimensions; import teamport.moonmod.world.WorldTypeMoon; import teamport.moonmod.world.biome.MoonBiomes; import teamport.moonmod.entity.EntityUFO; import teamport.moonmod.entity.render.UFOModel; import teamport.moonmod.entity.render.UFORenderer; import teamport.moonmod.block.MoonModBlocks; import teamport.moonmod.item.MoonModItems; import net.minecraft.client.sound.block.BlockSound; import net.minecraft.core.block.Block; import net.minecraft.core.block.material.Material; import net.minecraft.core.block.tag.BlockTags; import teamport.moonmod.block.MoonModBlocks; import teamport.moonmod.item.MoonModItems; import turniplabs.halplibe.helper.BlockBuilder; import turniplabs.halplibe.helper.EntityHelper; import turniplabs.halplibe.util.GameStartEntrypoint; import turniplabs.halplibe.util.RecipeEntrypoint; import useless.dragonfly.helper.ModelHelper;
8,726
package teamport.moonmod; public class MoonMod implements ModInitializer, GameStartEntrypoint, RecipeEntrypoint, PreLaunchEntrypoint { public static final String MOD_ID = "moonmod"; public static final Logger LOGGER = LoggerFactory.getLogger(MOD_ID); public static WorldType MOON_WORLD; @Override public void onInitialize() { new MoonModBlocks().initializeBlocks(); new MoonModItems().initializeItems(); EntityHelper.createEntity(EntityUFO.class,
package teamport.moonmod; public class MoonMod implements ModInitializer, GameStartEntrypoint, RecipeEntrypoint, PreLaunchEntrypoint { public static final String MOD_ID = "moonmod"; public static final Logger LOGGER = LoggerFactory.getLogger(MOD_ID); public static WorldType MOON_WORLD; @Override public void onInitialize() { new MoonModBlocks().initializeBlocks(); new MoonModItems().initializeItems(); EntityHelper.createEntity(EntityUFO.class,
new UFORenderer(ModelHelper.getOrCreateEntityModel(MOD_ID, "entity/ufo.json", UFOModel.class)),
6
2023-12-24 14:52:01+00:00
12k
LeeKyeongYong/SBookStudy
src/main/java/com/multibook/bookorder/global/initData/NotProd.java
[ { "identifier": "Book", "path": "src/main/java/com/multibook/bookorder/domain/book/book/entity/Book.java", "snippet": "@Entity\n@Builder\n@AllArgsConstructor(access = PROTECTED)\n@NoArgsConstructor(access = PROTECTED)\n@Setter\n@Getter\n@ToString(callSuper = true)\npublic class Book extends BaseTime {\n @ManyToOne\n private Member author;\n @OneToOne\n private Product product;\n private String title;\n private String body;\n private int price;\n private boolean published;\n}" }, { "identifier": "BookService", "path": "src/main/java/com/multibook/bookorder/domain/book/book/service/BookService.java", "snippet": "@Service\n@RequiredArgsConstructor\n@Transactional(readOnly = true)\npublic class BookService {\n private final BookRepository bookRepository;\n\n @Transactional\n public Book createBook(Member author, String title, String body, int price, boolean published) {\n Book book = Book.builder()\n .author(author)\n .title(title)\n .body(body)\n .price(price)\n .published(published)\n .build();\n\n bookRepository.save(book);\n\n return book;\n }\n\n public Page<Book> search(Member author, Boolean published, List<String> kwTypes, String kw, Pageable pageable) {\n return bookRepository.search(author, published, kwTypes, kw, pageable);\n }\n}" }, { "identifier": "CashLog", "path": "src/main/java/com/multibook/bookorder/domain/cash/cash/entity/CashLog.java", "snippet": "@Entity\n@Builder\n@AllArgsConstructor(access = PROTECTED)\n@NoArgsConstructor(access = PROTECTED)\n@Setter\n@Getter\n@ToString(callSuper = true)\npublic class CashLog extends BaseTime {\n @Enumerated(EnumType.STRING)\n private EvenType eventType;\n private String relTypeCode;\n private Long relId;\n @ManyToOne\n private Member member;\n private long price;\n\n public enum EvenType {\n 충전__무통장입금,\n 충전__토스페이먼츠,\n 출금__통장입금,\n 사용__토스페이먼츠_주문결제,\n 사용__예치금_주문결제,\n 환불__예치금_주문결제,\n 작가정산__예치금;\n }\n}" }, { "identifier": "WithdrawService", "path": "src/main/java/com/multibook/bookorder/domain/cash/withdraw/service/WithdrawService.java", "snippet": "@Service\n@RequiredArgsConstructor\n@Transactional(readOnly = true)\npublic class WithdrawService {\n private final WithdrawApplyRepository withdrawApplyRepository;\n private final MemberService memberService;\n\n public boolean canApply(Member actor, long cash) {\n return actor.getRestCash() >= cash;\n }\n\n @Transactional\n public void apply(Member applicant, long cash, String bankName, String bankAccountNo) {\n WithdrawApply apply = WithdrawApply.builder()\n .applicant(applicant)\n .cash(cash)\n .bankName(bankName)\n .bankAccountNo(bankAccountNo)\n .build();\n\n withdrawApplyRepository.save(apply);\n }\n\n public List<WithdrawApply> findByApplicant(Member applicant) {\n return withdrawApplyRepository.findByApplicantOrderByIdDesc(applicant);\n }\n\n public Optional<WithdrawApply> findById(long id) {\n return withdrawApplyRepository.findById(id);\n }\n\n public boolean canDelete(Member actor, WithdrawApply withdrawApply) {\n if (withdrawApply.isWithdrawDone()) return false;\n if (withdrawApply.isCancelDone()) return false;\n\n if (actor.isAdmin()) return true;\n\n if (!withdrawApply.getApplicant().equals(actor)) return false;\n\n return true;\n }\n\n @Transactional\n public void delete(WithdrawApply withdrawApply) {\n withdrawApplyRepository.delete(withdrawApply);\n }\n\n public List<WithdrawApply> findAll() {\n return withdrawApplyRepository.findAllByOrderByIdDesc();\n }\n\n public boolean canCancel(Member actor, WithdrawApply withdrawApply) {\n if (withdrawApply.isWithdrawDone()) return false;\n if (withdrawApply.isCancelDone()) return false;\n\n if (!actor.isAdmin()) return false;\n\n if (withdrawApply.getApplicant().getRestCash() >= withdrawApply.getCash()) return false;\n\n return true;\n }\n\n public boolean canWithdraw(Member actor, WithdrawApply withdrawApply) {\n if (withdrawApply.isWithdrawDone()) return false;\n if (withdrawApply.isCancelDone()) return false;\n\n if (!actor.isAdmin()) return false;\n\n if (withdrawApply.getApplicant().getRestCash() < withdrawApply.getCash()) return false;\n\n return true;\n }\n\n @Transactional\n public void withdraw(WithdrawApply withdrawApply) {\n withdrawApply.setWithdrawDone();\n\n memberService.addCash(withdrawApply.getApplicant(), withdrawApply.getCash() * -1, CashLog.EvenType.출금__통장입금, withdrawApply);\n }\n\n @Transactional\n public void cancel(WithdrawApply withdrawApply) {\n withdrawApply.setCancelDone(\"관리자에 의해 취소됨, 잔액부족\");\n }\n}" }, { "identifier": "Member", "path": "src/main/java/com/multibook/bookorder/domain/member/member/entity/Member.java", "snippet": "@Entity\n@Builder\n@AllArgsConstructor(access = PROTECTED)\n@NoArgsConstructor(access = PROTECTED)\n@Setter\n@Getter\n@ToString(callSuper = true, exclude = {\"myBooks\", \"owner\"})\npublic class Member extends BaseTime {\n private String username;\n private String password;\n private String nickname;\n private long restCash;\n\n @OneToMany(mappedBy = \"owner\", cascade = ALL, orphanRemoval = true)\n @Builder.Default\n private List<MyBook> myBooks = new ArrayList<>();\n\n public void addMyBook(Book book) {\n MyBook myBook = MyBook.builder()\n .owner(this)\n .book(book)\n .build();\n\n myBooks.add(myBook);\n }\n\n public void removeMyBook(Book book) {\n myBooks.removeIf(myBook -> myBook.getBook().equals(book));\n }\n\n public boolean hasBook(Book book) {\n return myBooks\n .stream()\n .anyMatch(myBook -> myBook.getBook().equals(book));\n }\n\n public boolean has(Product product) {\n return switch (product.getRelTypeCode()) {\n case \"book\" -> hasBook(product.getBook());\n default -> false;\n };\n }\n\n @Transient\n public Collection<? extends GrantedAuthority> getAuthorities() {\n List<GrantedAuthority> authorities = new ArrayList<>();\n\n authorities.add(new SimpleGrantedAuthority(\"ROLE_MEMBER\"));\n\n if (List.of(\"system\", \"admin\").contains(username)) {\n authorities.add(new SimpleGrantedAuthority(\"ROLE_ADMIN\"));\n }\n\n return authorities;\n }\n\n public boolean isAdmin() {\n return getAuthorities().stream()\n .anyMatch(a -> a.getAuthority().equals(\"ROLE_ADMIN\"));\n }\n}" }, { "identifier": "MemberService", "path": "src/main/java/com/multibook/bookorder/domain/member/member/service/MemberService.java", "snippet": "@Service\n@RequiredArgsConstructor\n@Transactional(readOnly = true)\npublic class MemberService {\n private final MemberRepository memberRepository;\n private final PasswordEncoder passwordEncoder;\n private final CashService cashService;\n private final GenFileService genFileService;\n\n @Transactional\n public RsData<Member> join(String username, String password, String nickname) {\n return join(username, password, nickname, \"\");\n }\n\n @Transactional\n public RsData<Member> join(String username, String password, String nickname, MultipartFile profileImg) {\n String profileImgFilePath = UtZip.file.toFile(profileImg, AppConfig.getTempDirPath());\n return join(username, password, nickname, profileImgFilePath);\n }\n\n @Transactional\n public RsData<Member> join(String username, String password, String nickname, String profileImgFilePath) {\n if (findByUsername(username).isPresent()) {\n return RsData.of(\"400-2\", \"이미 존재하는 회원입니다.\");\n }\n\n Member member = Member.builder()\n .username(username)\n .password(passwordEncoder.encode(password))\n .nickname(nickname)\n .build();\n memberRepository.save(member);\n\n if (UtZip.str.hasLength(profileImgFilePath)) {\n saveProfileImg(member, profileImgFilePath);\n }\n\n return RsData.of(\"200\", \"%s님 환영합니다. 회원가입이 완료되었습니다. 로그인 후 이용해주세요.\".formatted(member.getUsername()), member);\n }\n\n private void saveProfileImg(Member member, String profileImgFilePath) {\n genFileService.save(member.getModelName(), member.getId(), \"common\", \"profileImg\", 1, profileImgFilePath);\n }\n\n public Optional<Member> findByUsername(String username) {\n return memberRepository.findByUsername(username);\n }\n\n @Transactional\n public void addCash(Member member, long price, CashLog.EvenType eventType, BaseEntity relEntity) {\n CashLog cashLog = cashService.addCash(member, price, eventType, relEntity);\n\n long newRestCash = member.getRestCash() + cashLog.getPrice();\n member.setRestCash(newRestCash);\n }\n\n @Transactional\n public RsData<Member> whenSocialLogin(String providerTypeCode, String username, String nickname, String profileImgUrl) {\n Optional<Member> opMember = findByUsername(username);\n\n if (opMember.isPresent()) return RsData.of(\"200\", \"이미 존재합니다.\", opMember.get());\n\n String filePath = UtZip.str.hasLength(profileImgUrl) ? UtZip.file.downloadFileByHttp(profileImgUrl, AppConfig.getTempDirPath()) : \"\";\n\n return join(username, \"\", nickname, filePath);\n }\n\n public String getProfileImgUrl(Member member) {\n return Optional.ofNullable(member)\n .flatMap(this::findProfileImgUrl)\n .orElse(\"https://placehold.co/30x30?text=UU\");\n }\n\n private Optional<String> findProfileImgUrl(Member member) {\n return genFileService.findBy(\n member.getModelName(), member.getId(), \"common\", \"profileImg\", 1\n )\n .map(GenFile::getUrl);\n }\n}" }, { "identifier": "CartService", "path": "src/main/java/com/multibook/bookorder/domain/product/cart/service/CartService.java", "snippet": "@Service\n@RequiredArgsConstructor\n@Transactional(readOnly = true)\npublic class CartService {\n private final CartItemRepository cartItemRepository;\n\n @Transactional\n public CartItem addItem(Member buyer, Product product) {\n if (buyer.has(product))\n throw new GlobalException(\"400-1\", \"이미 구매한 상품입니다.\");\n\n CartItem cartItem = CartItem.builder()\n .buyer(buyer)\n .product(product)\n .build();\n\n cartItemRepository.save(cartItem);\n\n return cartItem;\n }\n\n @Transactional\n public void removeItem(Member buyer, Product product) {\n cartItemRepository.deleteByBuyerAndProduct(buyer, product);\n }\n\n public List<CartItem> findByBuyerOrderByIdDesc(Member buyer) {\n return cartItemRepository.findByBuyer(buyer);\n }\n\n public void delete(CartItem cartItem) {\n cartItemRepository.delete(cartItem);\n }\n\n public boolean canAdd(Member buyer, Product product) {\n if (buyer == null) return false;\n\n return !cartItemRepository.existsByBuyerAndProduct(buyer, product);\n }\n\n public boolean canRemove(Member buyer, Product product) {\n if (buyer == null) return false;\n\n return cartItemRepository.existsByBuyerAndProduct(buyer, product);\n }\n\n public boolean canDirectMakeOrder(Member buyer, Product product) {\n return canAdd(buyer, product);\n }\n}" }, { "identifier": "Order", "path": "src/main/java/com/multibook/bookorder/domain/product/order/entity/Order.java", "snippet": "@Entity\n@Builder\n@AllArgsConstructor(access = PROTECTED)\n@NoArgsConstructor(access = PROTECTED)\n@Setter\n@Getter\n@ToString(callSuper = true)\n@Table(name = \"order_\")\npublic class Order extends BaseTime {\n @ManyToOne\n private Member buyer;\n\n @Builder.Default\n @OneToMany(mappedBy = \"order\", cascade = ALL, orphanRemoval = true)\n @ToString.Exclude\n private List<OrderItem> orderItems = new ArrayList<>();\n\n private LocalDateTime payDate; // 결제일\n private LocalDateTime cancelDate; // 취소일\n private LocalDateTime refundDate; // 환불일\n\n public void addItem(CartItem cartItem) {\n addItem(cartItem.getProduct());\n }\n\n public void addItem(Product product) {\n if (buyer.has(product))\n throw new GlobalException(\"400-1\", \"이미 구매한 상품입니다.\");\n\n OrderItem orderItem = OrderItem.builder()\n .order(this)\n .product(product)\n .build();\n\n orderItems.add(orderItem);\n }\n\n public long calcPayPrice() {\n return orderItems.stream()\n .mapToLong(OrderItem::getPayPrice)\n .sum();\n }\n\n public void setPaymentDone() {\n payDate = LocalDateTime.now();\n\n orderItems.stream()\n .forEach(OrderItem::setPaymentDone);\n }\n\n public void setCancelDone() {\n cancelDate = LocalDateTime.now();\n\n orderItems.stream()\n .forEach(OrderItem::setCancelDone);\n }\n\n public void setRefundDone() {\n refundDate = LocalDateTime.now();\n\n orderItems.stream()\n .forEach(OrderItem::setRefundDone);\n }\n\n public String getName() {\n String name = orderItems.get(0).getProduct().getName();\n\n if (orderItems.size() > 1) {\n name += \" 외 %d건\".formatted(orderItems.size() - 1);\n }\n\n return name;\n }\n\n public String getCode() {\n // yyyy-MM-dd 형식의 DateTimeFormatter 생성\n DateTimeFormatter formatter = DateTimeFormatter.ofPattern(\"yyyy-MM-dd\");\n\n // LocalDateTime 객체를 문자열로 변환\n return getCreateDate().format(formatter) + (AppConfig.isNotProd() ? \"-test-\" + UUID.randomUUID().toString() : \"\") + \"__\" + getId();\n }\n\n public boolean isPayable() {\n if (payDate != null) return false;\n if (cancelDate != null) return false;\n\n return true;\n }\n\n public String getForPrintPayStatus() {\n if (payDate != null)\n return \"결제완료(\" + payDate.format(DateTimeFormatter.ofPattern(\"yyyy-MM-dd HH:mm:ss\")) + \")\";\n\n if (cancelDate != null) return \"-\";\n\n return \"결제대기\";\n }\n\n public String getForPrintCancelStatus() {\n if (cancelDate != null)\n return \"취소완료(\" + cancelDate.format(DateTimeFormatter.ofPattern(\"yyyy-MM-dd HH:mm:ss\")) + \")\";\n\n if (!isCancelable()) return \"취소불가능\";\n\n return \"취소가능\";\n }\n\n public String getForPrintRefundStatus() {\n if (refundDate != null)\n return \"환불완료(\" + refundDate.format(DateTimeFormatter.ofPattern(\"yyyy-MM-dd HH:mm:ss\")) + \")\";\n\n if (payDate == null) return \"-\";\n if (!isCancelable()) return \"-\";\n\n return \"환불가능\";\n }\n\n public boolean isPayDone() {\n return payDate != null;\n }\n\n public boolean isCancelable() {\n if (cancelDate != null) return false;\n\n // 결제일자로부터 1시간 지나면 취소 불가능\n if (payDate != null && payDate.plusHours(1).isBefore(LocalDateTime.now())) return false;\n\n return true;\n }\n}" }, { "identifier": "OrderService", "path": "src/main/java/com/multibook/bookorder/domain/product/order/service/OrderService.java", "snippet": "@Service\n@Transactional(readOnly = true)\n@RequiredArgsConstructor\npublic class OrderService {\n private final OrderRepository orderRepository;\n private final CartService cartService;\n private final MemberService memberService;\n\n @Transactional\n public Order createFromProduct(Member buyer, Product product) {\n Order order = Order.builder()\n .buyer(buyer)\n .build();\n\n order.addItem(product);\n\n orderRepository.save(order);\n\n return order;\n }\n\n @Transactional\n public Order createFromCart(Member buyer) {\n List<CartItem> cartItems = cartService.findByBuyerOrderByIdDesc(buyer);\n\n Order order = Order.builder()\n .buyer(buyer)\n .build();\n\n cartItems.stream()\n .forEach(order::addItem);\n\n orderRepository.save(order);\n\n cartItems.stream()\n .forEach(cartService::delete);\n\n return order;\n }\n\n @Transactional\n public void payByCashOnly(Order order) {\n Member buyer = order.getBuyer();\n long restCash = buyer.getRestCash();\n long payPrice = order.calcPayPrice();\n\n if (payPrice > restCash) {\n throw new GlobalException(\"400-1\", \"예치금이 부족합니다.\");\n }\n\n memberService.addCash(buyer, payPrice * -1, CashLog.EvenType.사용__예치금_주문결제, order);\n\n payDone(order);\n }\n\n @Transactional\n public void payByTossPayments(Order order, long pgPayPrice) {\n Member buyer = order.getBuyer();\n long restCash = buyer.getRestCash();\n long payPrice = order.calcPayPrice();\n\n long useRestCash = payPrice - pgPayPrice;\n\n memberService.addCash(buyer, pgPayPrice, CashLog.EvenType.충전__토스페이먼츠, order);\n memberService.addCash(buyer, pgPayPrice * -1, CashLog.EvenType.사용__토스페이먼츠_주문결제, order);\n\n if (useRestCash > 0) {\n if (useRestCash > restCash) {\n throw new RuntimeException(\"예치금이 부족합니다.\");\n }\n\n memberService.addCash(buyer, useRestCash * -1, CashLog.EvenType.사용__예치금_주문결제, order);\n }\n\n payDone(order);\n }\n\n private void payDone(Order order) {\n order.setPaymentDone();\n }\n\n private void refund(Order order) {\n long payPrice = order.calcPayPrice();\n\n memberService.addCash(order.getBuyer(), payPrice, CashLog.EvenType.환불__예치금_주문결제, order);\n\n order.setRefundDone();\n }\n\n public void checkCanPay(String orderCode, long pgPayPrice) {\n Order order = findByCode(orderCode).orElse(null);\n\n if (order == null)\n throw new GlobalException(\"400-1\", \"존재하지 않는 주문입니다.\");\n\n checkCanPay(order, pgPayPrice);\n }\n\n public void checkCanPay(Order order, long pgPayPrice) {\n if (!canPay(order, pgPayPrice))\n throw new GlobalException(\"400-2\", \"PG결제금액 혹은 예치금이 부족하여 결제할 수 없습니다.\");\n }\n\n public boolean canPay(Order order, long pgPayPrice) {\n if (!order.isPayable()) return false;\n\n long restCash = order.getBuyer().getRestCash();\n\n return order.calcPayPrice() <= restCash + pgPayPrice;\n }\n\n public Optional<Order> findById(long id) {\n return orderRepository.findById(id);\n }\n\n public boolean actorCanSee(Member actor, Order order) {\n return order.getBuyer().equals(actor);\n }\n\n public Optional<Order> findByCode(String code) {\n long id = Long.parseLong(code.split(\"__\", 2)[1]);\n\n return findById(id);\n }\n\n public void payDone(String code) {\n Order order = findByCode(code).orElse(null);\n\n if (order == null)\n throw new GlobalException(\"400-1\", \"존재하지 않는 주문입니다.\");\n\n payDone(order);\n }\n\n public Page<Order> search(Member buyer, Boolean payStatus, Boolean cancelStatus, Boolean refundStatus, Pageable pageable) {\n return orderRepository.search(buyer, payStatus, cancelStatus, refundStatus, pageable);\n }\n\n @Transactional\n public void cancel(Order order) {\n if (!order.isCancelable())\n throw new GlobalException(\"400-1\", \"취소할 수 없는 주문입니다.\");\n\n order.setCancelDone();\n\n if (order.isPayDone())\n refund(order);\n }\n\n public boolean canCancel(Member actor, Order order) {\n return actor.equals(order.getBuyer()) && order.isCancelable();\n }\n}" }, { "identifier": "Product", "path": "src/main/java/com/multibook/bookorder/domain/product/product/entity/Product.java", "snippet": "@Entity\n@Builder\n@AllArgsConstructor(access = PROTECTED)\n@NoArgsConstructor(access = PROTECTED)\n@Setter\n@Getter\n@ToString(callSuper = true)\npublic class Product extends BaseTime {\n @ManyToOne\n private Member maker;\n private String relTypeCode;\n private long relId;\n private String name;\n private int price;\n private boolean published;\n\n public Book getBook() {\n return AppConfig.getEntityManager().getReference(Book.class, relId);\n }\n}" }, { "identifier": "ProductService", "path": "src/main/java/com/multibook/bookorder/domain/product/product/service/ProductService.java", "snippet": "@Service\n@RequiredArgsConstructor\n@Transactional(readOnly = true)\npublic class ProductService {\n private final ProductRepository productRepository;\n private final ProductBookmarkService productBookmarkService;\n\n @Transactional\n public Product createProduct(Book book, boolean published) {\n if (book.getProduct() != null) return book.getProduct();\n\n Product product = Product.builder()\n .maker(book.getAuthor())\n .relTypeCode(book.getModelName())\n .relId(book.getId())\n .name(book.getTitle())\n .price(book.getPrice())\n .published(published)\n .build();\n\n productRepository.save(product);\n\n book.setProduct(product);\n\n return product;\n }\n\n public Optional<Product> findById(long id) {\n return productRepository.findById(id);\n }\n\n public Page<Product> search(Member maker, Boolean published, List<String> kwTypes, String kw, Pageable pageable) {\n return productRepository.search(maker, published, kwTypes, kw, pageable);\n }\n\n public boolean canBookmark(Member actor, Product product) {\n if (actor == null) return false;\n\n return productBookmarkService.canBookmark(actor, product);\n }\n\n public boolean canCancelBookmark(Member actor, Product product) {\n if (actor == null) return false;\n\n return productBookmarkService.canCancelBookmark(actor, product);\n }\n\n @Transactional\n public void bookmark(Member member, Product product) {\n productBookmarkService.bookmark(member, product);\n }\n\n @Transactional\n public void cancelBookmark(Member member, Product product) {\n productBookmarkService.cancelBookmark(member, product);\n }\n}" }, { "identifier": "Order", "path": "src/main/java/com/multibook/bookorder/domain/product/order/entity/Order.java", "snippet": "@Entity\n@Builder\n@AllArgsConstructor(access = PROTECTED)\n@NoArgsConstructor(access = PROTECTED)\n@Setter\n@Getter\n@ToString(callSuper = true)\n@Table(name = \"order_\")\npublic class Order extends BaseTime {\n @ManyToOne\n private Member buyer;\n\n @Builder.Default\n @OneToMany(mappedBy = \"order\", cascade = ALL, orphanRemoval = true)\n @ToString.Exclude\n private List<OrderItem> orderItems = new ArrayList<>();\n\n private LocalDateTime payDate; // 결제일\n private LocalDateTime cancelDate; // 취소일\n private LocalDateTime refundDate; // 환불일\n\n public void addItem(CartItem cartItem) {\n addItem(cartItem.getProduct());\n }\n\n public void addItem(Product product) {\n if (buyer.has(product))\n throw new GlobalException(\"400-1\", \"이미 구매한 상품입니다.\");\n\n OrderItem orderItem = OrderItem.builder()\n .order(this)\n .product(product)\n .build();\n\n orderItems.add(orderItem);\n }\n\n public long calcPayPrice() {\n return orderItems.stream()\n .mapToLong(OrderItem::getPayPrice)\n .sum();\n }\n\n public void setPaymentDone() {\n payDate = LocalDateTime.now();\n\n orderItems.stream()\n .forEach(OrderItem::setPaymentDone);\n }\n\n public void setCancelDone() {\n cancelDate = LocalDateTime.now();\n\n orderItems.stream()\n .forEach(OrderItem::setCancelDone);\n }\n\n public void setRefundDone() {\n refundDate = LocalDateTime.now();\n\n orderItems.stream()\n .forEach(OrderItem::setRefundDone);\n }\n\n public String getName() {\n String name = orderItems.get(0).getProduct().getName();\n\n if (orderItems.size() > 1) {\n name += \" 외 %d건\".formatted(orderItems.size() - 1);\n }\n\n return name;\n }\n\n public String getCode() {\n // yyyy-MM-dd 형식의 DateTimeFormatter 생성\n DateTimeFormatter formatter = DateTimeFormatter.ofPattern(\"yyyy-MM-dd\");\n\n // LocalDateTime 객체를 문자열로 변환\n return getCreateDate().format(formatter) + (AppConfig.isNotProd() ? \"-test-\" + UUID.randomUUID().toString() : \"\") + \"__\" + getId();\n }\n\n public boolean isPayable() {\n if (payDate != null) return false;\n if (cancelDate != null) return false;\n\n return true;\n }\n\n public String getForPrintPayStatus() {\n if (payDate != null)\n return \"결제완료(\" + payDate.format(DateTimeFormatter.ofPattern(\"yyyy-MM-dd HH:mm:ss\")) + \")\";\n\n if (cancelDate != null) return \"-\";\n\n return \"결제대기\";\n }\n\n public String getForPrintCancelStatus() {\n if (cancelDate != null)\n return \"취소완료(\" + cancelDate.format(DateTimeFormatter.ofPattern(\"yyyy-MM-dd HH:mm:ss\")) + \")\";\n\n if (!isCancelable()) return \"취소불가능\";\n\n return \"취소가능\";\n }\n\n public String getForPrintRefundStatus() {\n if (refundDate != null)\n return \"환불완료(\" + refundDate.format(DateTimeFormatter.ofPattern(\"yyyy-MM-dd HH:mm:ss\")) + \")\";\n\n if (payDate == null) return \"-\";\n if (!isCancelable()) return \"-\";\n\n return \"환불가능\";\n }\n\n public boolean isPayDone() {\n return payDate != null;\n }\n\n public boolean isCancelable() {\n if (cancelDate != null) return false;\n\n // 결제일자로부터 1시간 지나면 취소 불가능\n if (payDate != null && payDate.plusHours(1).isBefore(LocalDateTime.now())) return false;\n\n return true;\n }\n}" } ]
import com.multibook.bookorder.domain.book.book.entity.Book; import com.multibook.bookorder.domain.book.book.service.BookService; import com.multibook.bookorder.domain.cash.cash.entity.CashLog; import com.multibook.bookorder.domain.cash.withdraw.service.WithdrawService; import com.multibook.bookorder.domain.member.member.entity.Member; import com.multibook.bookorder.domain.member.member.service.MemberService; import com.multibook.bookorder.domain.product.cart.service.CartService; import com.multibook.bookorder.domain.product.order.entity.Order; import com.multibook.bookorder.domain.product.order.service.OrderService; import com.multibook.bookorder.domain.product.product.entity.Product; import com.multibook.bookorder.domain.product.product.service.ProductService; import lombok.RequiredArgsConstructor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.ApplicationRunner; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Lazy; import com.multibook.bookorder.domain.product.order.entity.Order; import org.springframework.transaction.annotation.Transactional;
7,324
package com.multibook.bookorder.global.initData; @Configuration @RequiredArgsConstructor public class NotProd { @Autowired @Lazy private NotProd self; private final MemberService memberService; private final BookService bookService; private final ProductService productService; private final CartService cartService; private final OrderService orderService; private final WithdrawService withdrawService; @Bean @org.springframework.core.annotation.Order(3) ApplicationRunner initNotProd() { return args -> { self.work1(); self.work2(); }; } @Transactional public void work1() { if (memberService.findByUsername("admin").isPresent()) return; Member memberAdmin = memberService.join("admin", "1234", "관리자").getData(); Member memberUser1 = memberService.join("user1", "1234", "유저1").getData(); Member memberUser2 = memberService.join("user2", "1234", "유저2").getData(); Member memberUser3 = memberService.join("user3", "1234", "유저3").getData(); Member memberUser4 = memberService.join("user4", "1234", "유저4").getData(); Member memberUser5 = memberService.join("user5", "1234", "유저5").getData();
package com.multibook.bookorder.global.initData; @Configuration @RequiredArgsConstructor public class NotProd { @Autowired @Lazy private NotProd self; private final MemberService memberService; private final BookService bookService; private final ProductService productService; private final CartService cartService; private final OrderService orderService; private final WithdrawService withdrawService; @Bean @org.springframework.core.annotation.Order(3) ApplicationRunner initNotProd() { return args -> { self.work1(); self.work2(); }; } @Transactional public void work1() { if (memberService.findByUsername("admin").isPresent()) return; Member memberAdmin = memberService.join("admin", "1234", "관리자").getData(); Member memberUser1 = memberService.join("user1", "1234", "유저1").getData(); Member memberUser2 = memberService.join("user2", "1234", "유저2").getData(); Member memberUser3 = memberService.join("user3", "1234", "유저3").getData(); Member memberUser4 = memberService.join("user4", "1234", "유저4").getData(); Member memberUser5 = memberService.join("user5", "1234", "유저5").getData();
Book book1 = bookService.createBook(memberUser1, "책 제목 1", "책 내용 1", 10_000, true);
0
2023-12-26 14:58:59+00:00
12k
huidongyin/kafka-2.7.2
clients/src/test/java/org/apache/kafka/common/utils/UtilsTest.java
[ { "identifier": "ConfigException", "path": "clients/src/main/java/org/apache/kafka/common/config/ConfigException.java", "snippet": "public class ConfigException extends KafkaException {\n\n private static final long serialVersionUID = 1L;\n\n public ConfigException(String message) {\n super(message);\n }\n\n public ConfigException(String name, Object value) {\n this(name, value, null);\n }\n\n public ConfigException(String name, Object value, String message) {\n super(\"Invalid value \" + value + \" for configuration \" + name + (message == null ? \"\" : \": \" + message));\n }\n\n}" }, { "identifier": "TestUtils", "path": "clients/src/test/java/org/apache/kafka/test/TestUtils.java", "snippet": "public class TestUtils {\n private static final Logger log = LoggerFactory.getLogger(TestUtils.class);\n\n public static final File IO_TMP_DIR = new File(System.getProperty(\"java.io.tmpdir\"));\n\n public static final String LETTERS = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\";\n public static final String DIGITS = \"0123456789\";\n public static final String LETTERS_AND_DIGITS = LETTERS + DIGITS;\n\n /* A consistent random number generator to make tests repeatable */\n public static final Random SEEDED_RANDOM = new Random(192348092834L);\n public static final Random RANDOM = new Random();\n public static final long DEFAULT_POLL_INTERVAL_MS = 100;\n public static final long DEFAULT_MAX_WAIT_MS = 15000;\n\n public static Cluster singletonCluster() {\n return clusterWith(1);\n }\n\n public static Cluster singletonCluster(final String topic, final int partitions) {\n return clusterWith(1, topic, partitions);\n }\n\n public static Cluster clusterWith(int nodes) {\n return clusterWith(nodes, new HashMap<>());\n }\n\n public static Cluster clusterWith(final int nodes, final Map<String, Integer> topicPartitionCounts) {\n final Node[] ns = new Node[nodes];\n for (int i = 0; i < nodes; i++)\n ns[i] = new Node(i, \"localhost\", 1969);\n final List<PartitionInfo> parts = new ArrayList<>();\n for (final Map.Entry<String, Integer> topicPartition : topicPartitionCounts.entrySet()) {\n final String topic = topicPartition.getKey();\n final int partitions = topicPartition.getValue();\n for (int i = 0; i < partitions; i++)\n parts.add(new PartitionInfo(topic, i, ns[i % ns.length], ns, ns));\n }\n return new Cluster(\"kafka-cluster\", asList(ns), parts, Collections.emptySet(), Collections.emptySet());\n }\n\n public static MetadataResponse metadataUpdateWith(final int numNodes,\n final Map<String, Integer> topicPartitionCounts) {\n return metadataUpdateWith(\"kafka-cluster\", numNodes, topicPartitionCounts);\n }\n\n public static MetadataResponse metadataUpdateWith(final int numNodes,\n final Map<String, Integer> topicPartitionCounts,\n final Function<TopicPartition, Integer> epochSupplier) {\n return metadataUpdateWith(\"kafka-cluster\", numNodes, Collections.emptyMap(),\n topicPartitionCounts, epochSupplier, MetadataResponse.PartitionMetadata::new, ApiKeys.METADATA.latestVersion());\n }\n\n public static MetadataResponse metadataUpdateWith(final String clusterId,\n final int numNodes,\n final Map<String, Integer> topicPartitionCounts) {\n return metadataUpdateWith(clusterId, numNodes, Collections.emptyMap(),\n topicPartitionCounts, tp -> null, MetadataResponse.PartitionMetadata::new, ApiKeys.METADATA.latestVersion());\n }\n\n public static MetadataResponse metadataUpdateWith(final String clusterId,\n final int numNodes,\n final Map<String, Errors> topicErrors,\n final Map<String, Integer> topicPartitionCounts) {\n return metadataUpdateWith(clusterId, numNodes, topicErrors,\n topicPartitionCounts, tp -> null, MetadataResponse.PartitionMetadata::new, ApiKeys.METADATA.latestVersion());\n }\n\n public static MetadataResponse metadataUpdateWith(final String clusterId,\n final int numNodes,\n final Map<String, Errors> topicErrors,\n final Map<String, Integer> topicPartitionCounts,\n final short responseVersion) {\n return metadataUpdateWith(clusterId, numNodes, topicErrors,\n topicPartitionCounts, tp -> null, MetadataResponse.PartitionMetadata::new, responseVersion);\n }\n\n public static MetadataResponse metadataUpdateWith(final String clusterId,\n final int numNodes,\n final Map<String, Errors> topicErrors,\n final Map<String, Integer> topicPartitionCounts,\n final Function<TopicPartition, Integer> epochSupplier) {\n return metadataUpdateWith(clusterId, numNodes, topicErrors,\n topicPartitionCounts, epochSupplier, MetadataResponse.PartitionMetadata::new, ApiKeys.METADATA.latestVersion());\n }\n\n public static MetadataResponse metadataUpdateWith(final String clusterId,\n final int numNodes,\n final Map<String, Errors> topicErrors,\n final Map<String, Integer> topicPartitionCounts,\n final Function<TopicPartition, Integer> epochSupplier,\n final PartitionMetadataSupplier partitionSupplier,\n final short responseVersion) {\n final List<Node> nodes = new ArrayList<>(numNodes);\n for (int i = 0; i < numNodes; i++)\n nodes.add(new Node(i, \"localhost\", 1969 + i));\n\n List<MetadataResponse.TopicMetadata> topicMetadata = new ArrayList<>();\n for (Map.Entry<String, Integer> topicPartitionCountEntry : topicPartitionCounts.entrySet()) {\n String topic = topicPartitionCountEntry.getKey();\n int numPartitions = topicPartitionCountEntry.getValue();\n\n List<MetadataResponse.PartitionMetadata> partitionMetadata = new ArrayList<>(numPartitions);\n for (int i = 0; i < numPartitions; i++) {\n TopicPartition tp = new TopicPartition(topic, i);\n Node leader = nodes.get(i % nodes.size());\n List<Integer> replicaIds = Collections.singletonList(leader.id());\n partitionMetadata.add(partitionSupplier.supply(\n Errors.NONE, tp, Optional.of(leader.id()), Optional.ofNullable(epochSupplier.apply(tp)),\n replicaIds, replicaIds, replicaIds));\n }\n\n topicMetadata.add(new MetadataResponse.TopicMetadata(Errors.NONE, topic,\n Topic.isInternal(topic), partitionMetadata));\n }\n\n for (Map.Entry<String, Errors> topicErrorEntry : topicErrors.entrySet()) {\n String topic = topicErrorEntry.getKey();\n topicMetadata.add(new MetadataResponse.TopicMetadata(topicErrorEntry.getValue(), topic,\n Topic.isInternal(topic), Collections.emptyList()));\n }\n\n return MetadataResponse.prepareResponse(nodes, clusterId, 0, topicMetadata, responseVersion);\n }\n\n @FunctionalInterface\n public interface PartitionMetadataSupplier {\n MetadataResponse.PartitionMetadata supply(Errors error,\n TopicPartition partition,\n Optional<Integer> leaderId,\n Optional<Integer> leaderEpoch,\n List<Integer> replicas,\n List<Integer> isr,\n List<Integer> offlineReplicas);\n }\n\n public static Cluster clusterWith(final int nodes, final String topic, final int partitions) {\n return clusterWith(nodes, Collections.singletonMap(topic, partitions));\n }\n\n /**\n * Generate an array of random bytes\n *\n * @param size The size of the array\n */\n public static byte[] randomBytes(final int size) {\n final byte[] bytes = new byte[size];\n SEEDED_RANDOM.nextBytes(bytes);\n return bytes;\n }\n\n /**\n * Generate a random string of letters and digits of the given length\n *\n * @param len The length of the string\n * @return The random string\n */\n public static String randomString(final int len) {\n final StringBuilder b = new StringBuilder();\n for (int i = 0; i < len; i++)\n b.append(LETTERS_AND_DIGITS.charAt(SEEDED_RANDOM.nextInt(LETTERS_AND_DIGITS.length())));\n return b.toString();\n }\n\n /**\n * Create an empty file in the default temporary-file directory, using `kafka` as the prefix and `tmp` as the\n * suffix to generate its name.\n */\n public static File tempFile() throws IOException {\n final File file = File.createTempFile(\"kafka\", \".tmp\");\n file.deleteOnExit();\n\n return file;\n }\n\n /**\n * Create a file with the given contents in the default temporary-file directory,\n * using `kafka` as the prefix and `tmp` as the suffix to generate its name.\n */\n public static File tempFile(final String contents) throws IOException {\n final File file = tempFile();\n final FileWriter writer = new FileWriter(file);\n writer.write(contents);\n writer.close();\n\n return file;\n }\n\n /**\n * Create a temporary relative directory in the default temporary-file directory with the given prefix.\n *\n * @param prefix The prefix of the temporary directory, if null using \"kafka-\" as default prefix\n */\n public static File tempDirectory(final String prefix) {\n return tempDirectory(null, prefix);\n }\n\n /**\n * Create a temporary relative directory in the default temporary-file directory with a\n * prefix of \"kafka-\"\n *\n * @return the temporary directory just created.\n */\n public static File tempDirectory() {\n return tempDirectory(null);\n }\n\n /**\n * Create a temporary relative directory in the specified parent directory with the given prefix.\n *\n * @param parent The parent folder path name, if null using the default temporary-file directory\n * @param prefix The prefix of the temporary directory, if null using \"kafka-\" as default prefix\n */\n public static File tempDirectory(final Path parent, String prefix) {\n final File file;\n prefix = prefix == null ? \"kafka-\" : prefix;\n try {\n file = parent == null ?\n Files.createTempDirectory(prefix).toFile() : Files.createTempDirectory(parent, prefix).toFile();\n } catch (final IOException ex) {\n throw new RuntimeException(\"Failed to create a temp dir\", ex);\n }\n file.deleteOnExit();\n\n Exit.addShutdownHook(\"delete-temp-file-shutdown-hook\", () -> {\n try {\n Utils.delete(file);\n } catch (IOException e) {\n log.error(\"Error deleting {}\", file.getAbsolutePath(), e);\n }\n });\n\n return file;\n }\n\n public static Properties producerConfig(final String bootstrapServers,\n final Class<?> keySerializer,\n final Class<?> valueSerializer,\n final Properties additional) {\n final Properties properties = new Properties();\n properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);\n properties.put(ProducerConfig.ACKS_CONFIG, \"all\");\n properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, keySerializer);\n properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, valueSerializer);\n properties.putAll(additional);\n return properties;\n }\n\n public static Properties producerConfig(final String bootstrapServers, final Class<?> keySerializer, final Class<?> valueSerializer) {\n return producerConfig(bootstrapServers, keySerializer, valueSerializer, new Properties());\n }\n\n public static Properties consumerConfig(final String bootstrapServers,\n final String groupId,\n final Class<?> keyDeserializer,\n final Class<?> valueDeserializer,\n final Properties additional) {\n\n final Properties consumerConfig = new Properties();\n consumerConfig.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);\n consumerConfig.put(ConsumerConfig.GROUP_ID_CONFIG, groupId);\n consumerConfig.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, \"earliest\");\n consumerConfig.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, keyDeserializer);\n consumerConfig.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, valueDeserializer);\n consumerConfig.putAll(additional);\n return consumerConfig;\n }\n\n public static Properties consumerConfig(final String bootstrapServers,\n final String groupId,\n final Class<?> keyDeserializer,\n final Class<?> valueDeserializer) {\n return consumerConfig(bootstrapServers,\n groupId,\n keyDeserializer,\n valueDeserializer,\n new Properties());\n }\n\n /**\n * returns consumer config with random UUID for the Group ID\n */\n public static Properties consumerConfig(final String bootstrapServers, final Class<?> keyDeserializer, final Class<?> valueDeserializer) {\n return consumerConfig(bootstrapServers,\n UUID.randomUUID().toString(),\n keyDeserializer,\n valueDeserializer,\n new Properties());\n }\n\n /**\n * uses default value of 15 seconds for timeout\n */\n public static void waitForCondition(final TestCondition testCondition, final String conditionDetails) throws InterruptedException {\n waitForCondition(testCondition, DEFAULT_MAX_WAIT_MS, () -> conditionDetails);\n }\n\n /**\n * uses default value of 15 seconds for timeout\n */\n public static void waitForCondition(final TestCondition testCondition, final Supplier<String> conditionDetailsSupplier) throws InterruptedException {\n waitForCondition(testCondition, DEFAULT_MAX_WAIT_MS, conditionDetailsSupplier);\n }\n\n /**\n * Wait for condition to be met for at most {@code maxWaitMs} and throw assertion failure otherwise.\n * This should be used instead of {@code Thread.sleep} whenever possible as it allows a longer timeout to be used\n * without unnecessarily increasing test time (as the condition is checked frequently). The longer timeout is needed to\n * avoid transient failures due to slow or overloaded machines.\n */\n public static void waitForCondition(final TestCondition testCondition, final long maxWaitMs, String conditionDetails) throws InterruptedException {\n waitForCondition(testCondition, maxWaitMs, () -> conditionDetails);\n }\n\n /**\n * Wait for condition to be met for at most {@code maxWaitMs} and throw assertion failure otherwise.\n * This should be used instead of {@code Thread.sleep} whenever possible as it allows a longer timeout to be used\n * without unnecessarily increasing test time (as the condition is checked frequently). The longer timeout is needed to\n * avoid transient failures due to slow or overloaded machines.\n */\n public static void waitForCondition(final TestCondition testCondition, final long maxWaitMs, Supplier<String> conditionDetailsSupplier) throws InterruptedException {\n retryOnExceptionWithTimeout(maxWaitMs, () -> {\n String conditionDetailsSupplied = conditionDetailsSupplier != null ? conditionDetailsSupplier.get() : null;\n String conditionDetails = conditionDetailsSupplied != null ? conditionDetailsSupplied : \"\";\n assertTrue(testCondition.conditionMet(),\n \"Condition not met within timeout \" + maxWaitMs + \". \" + conditionDetails);\n });\n }\n\n /**\n * Wait for the given runnable to complete successfully, i.e. throw now {@link Exception}s or\n * {@link AssertionError}s, or for the given timeout to expire. If the timeout expires then the\n * last exception or assertion failure will be thrown thus providing context for the failure.\n *\n * @param timeoutMs the total time in milliseconds to wait for {@code runnable} to complete successfully.\n * @param runnable the code to attempt to execute successfully.\n * @throws InterruptedException if the current thread is interrupted while waiting for {@code runnable} to complete successfully.\n */\n public static void retryOnExceptionWithTimeout(final long timeoutMs,\n final ValuelessCallable runnable) throws InterruptedException {\n retryOnExceptionWithTimeout(timeoutMs, DEFAULT_POLL_INTERVAL_MS, runnable);\n }\n\n /**\n * Wait for the given runnable to complete successfully, i.e. throw now {@link Exception}s or\n * {@link AssertionError}s, or for the default timeout to expire. If the timeout expires then the\n * last exception or assertion failure will be thrown thus providing context for the failure.\n *\n * @param runnable the code to attempt to execute successfully.\n * @throws InterruptedException if the current thread is interrupted while waiting for {@code runnable} to complete successfully.\n */\n public static void retryOnExceptionWithTimeout(final ValuelessCallable runnable) throws InterruptedException {\n retryOnExceptionWithTimeout(DEFAULT_MAX_WAIT_MS, DEFAULT_POLL_INTERVAL_MS, runnable);\n }\n\n /**\n * Wait for the given runnable to complete successfully, i.e. throw now {@link Exception}s or\n * {@link AssertionError}s, or for the given timeout to expire. If the timeout expires then the\n * last exception or assertion failure will be thrown thus providing context for the failure.\n *\n * @param timeoutMs the total time in milliseconds to wait for {@code runnable} to complete successfully.\n * @param pollIntervalMs the interval in milliseconds to wait between invoking {@code runnable}.\n * @param runnable the code to attempt to execute successfully.\n * @throws InterruptedException if the current thread is interrupted while waiting for {@code runnable} to complete successfully.\n */\n public static void retryOnExceptionWithTimeout(final long timeoutMs,\n final long pollIntervalMs,\n final ValuelessCallable runnable) throws InterruptedException {\n final long expectedEnd = System.currentTimeMillis() + timeoutMs;\n\n while (true) {\n try {\n runnable.call();\n return;\n } catch (final NoRetryException e) {\n throw e;\n } catch (final AssertionError t) {\n if (expectedEnd <= System.currentTimeMillis()) {\n throw t;\n }\n } catch (final Exception e) {\n if (expectedEnd <= System.currentTimeMillis()) {\n throw new AssertionError(e);\n }\n }\n Thread.sleep(Math.min(pollIntervalMs, timeoutMs));\n }\n }\n\n /**\n * Checks if a cluster id is valid.\n * @param clusterId\n */\n public static void isValidClusterId(String clusterId) {\n assertNotNull(clusterId);\n\n // Base 64 encoded value is 22 characters\n assertEquals(clusterId.length(), 22);\n\n Pattern clusterIdPattern = Pattern.compile(\"[a-zA-Z0-9_\\\\-]+\");\n Matcher matcher = clusterIdPattern.matcher(clusterId);\n assertTrue(matcher.matches());\n\n // Convert into normal variant and add padding at the end.\n String originalClusterId = String.format(\"%s==\", clusterId.replace(\"_\", \"/\").replace(\"-\", \"+\"));\n byte[] decodedUuid = Base64.getDecoder().decode(originalClusterId);\n\n // We expect 16 bytes, same as the input UUID.\n assertEquals(decodedUuid.length, 16);\n\n //Check if it can be converted back to a UUID.\n try {\n ByteBuffer uuidBuffer = ByteBuffer.wrap(decodedUuid);\n new UUID(uuidBuffer.getLong(), uuidBuffer.getLong()).toString();\n } catch (Exception e) {\n fail(clusterId + \" cannot be converted back to UUID.\");\n }\n }\n\n /**\n * Checks the two iterables for equality by first converting both to a list.\n */\n public static <T> void checkEquals(Iterable<T> it1, Iterable<T> it2) {\n assertEquals(toList(it1), toList(it2));\n }\n\n public static <T> void checkEquals(Iterator<T> it1, Iterator<T> it2) {\n assertEquals(Utils.toList(it1), Utils.toList(it2));\n }\n\n public static <T> void checkEquals(Set<T> c1, Set<T> c2, String firstDesc, String secondDesc) {\n if (!c1.equals(c2)) {\n Set<T> missing1 = new HashSet<>(c2);\n missing1.removeAll(c1);\n Set<T> missing2 = new HashSet<>(c1);\n missing2.removeAll(c2);\n fail(String.format(\"Sets not equal, missing %s=%s, missing %s=%s\", firstDesc, missing1, secondDesc, missing2));\n }\n }\n\n public static <T> List<T> toList(Iterable<? extends T> iterable) {\n List<T> list = new ArrayList<>();\n for (T item : iterable)\n list.add(item);\n return list;\n }\n\n public static <T> Set<T> toSet(Collection<T> collection) {\n return new HashSet<>(collection);\n }\n\n public static ByteBuffer toBuffer(Struct struct) {\n ByteBuffer buffer = ByteBuffer.allocate(struct.sizeOf());\n struct.writeTo(buffer);\n buffer.rewind();\n return buffer;\n }\n\n public static Set<TopicPartition> generateRandomTopicPartitions(int numTopic, int numPartitionPerTopic) {\n Set<TopicPartition> tps = new HashSet<>();\n for (int i = 0; i < numTopic; i++) {\n String topic = randomString(32);\n for (int j = 0; j < numPartitionPerTopic; j++) {\n tps.add(new TopicPartition(topic, j));\n }\n }\n return tps;\n }\n\n /**\n * Assert that a future raises an expected exception cause type. Return the exception cause\n * if the assertion succeeds; otherwise raise AssertionError.\n *\n * @param future The future to await\n * @param exceptionCauseClass Class of the expected exception cause\n * @param <T> Exception cause type parameter\n * @return The caught exception cause\n */\n public static <T extends Throwable> T assertFutureThrows(Future<?> future, Class<T> exceptionCauseClass) {\n ExecutionException exception = assertThrows(ExecutionException.class, future::get);\n assertTrue(exceptionCauseClass.isInstance(exception.getCause()),\n \"Unexpected exception cause \" + exception.getCause());\n return exceptionCauseClass.cast(exception.getCause());\n }\n\n public static void assertFutureError(Future<?> future, Class<? extends Throwable> exceptionClass)\n throws InterruptedException {\n try {\n future.get();\n fail(\"Expected a \" + exceptionClass.getSimpleName() + \" exception, but got success.\");\n } catch (ExecutionException ee) {\n Throwable cause = ee.getCause();\n assertEquals(exceptionClass, cause.getClass(),\n \"Expected a \" + exceptionClass.getSimpleName() + \" exception, but got \" +\n cause.getClass().getSimpleName());\n }\n }\n\n public static ApiKeys apiKeyFrom(NetworkReceive networkReceive) {\n return RequestHeader.parse(networkReceive.payload().duplicate()).apiKey();\n }\n\n public static <T> void assertOptional(Optional<T> optional, Consumer<T> assertion) {\n if (optional.isPresent()) {\n assertion.accept(optional.get());\n } else {\n fail(\"Missing value from Optional\");\n }\n }\n\n @SuppressWarnings(\"unchecked\")\n public static <T> T fieldValue(Object o, Class<?> clazz, String fieldName) {\n try {\n Field field = clazz.getDeclaredField(fieldName);\n field.setAccessible(true);\n return (T) field.get(o);\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }\n\n public static void setFieldValue(Object obj, String fieldName, Object value) throws Exception {\n Field field = obj.getClass().getDeclaredField(fieldName);\n field.setAccessible(true);\n field.set(obj, value);\n }\n}" }, { "identifier": "diff", "path": "clients/src/main/java/org/apache/kafka/common/utils/Utils.java", "snippet": "public static <E> Set<E> diff(final Supplier<Set<E>> constructor, final Set<E> left, final Set<E> right) {\n final Set<E> result = constructor.get();\n result.addAll(left);\n result.removeAll(right);\n return result;\n}" }, { "identifier": "formatAddress", "path": "clients/src/main/java/org/apache/kafka/common/utils/Utils.java", "snippet": "public static String formatAddress(String host, Integer port) {\n return host.contains(\":\")\n ? \"[\" + host + \"]:\" + port // IPv6\n : host + \":\" + port;\n}" }, { "identifier": "formatBytes", "path": "clients/src/main/java/org/apache/kafka/common/utils/Utils.java", "snippet": "public static String formatBytes(long bytes) {\n if (bytes < 0) {\n return String.valueOf(bytes);\n }\n double asDouble = (double) bytes;\n int ordinal = (int) Math.floor(Math.log(asDouble) / Math.log(1024.0));\n double scale = Math.pow(1024.0, ordinal);\n double scaled = asDouble / scale;\n String formatted = TWO_DIGIT_FORMAT.format(scaled);\n try {\n return formatted + \" \" + BYTE_SCALE_SUFFIXES[ordinal];\n } catch (IndexOutOfBoundsException e) {\n //huge number?\n return String.valueOf(asDouble);\n }\n}" }, { "identifier": "getHost", "path": "clients/src/main/java/org/apache/kafka/common/utils/Utils.java", "snippet": "public static String getHost(String address) {\n Matcher matcher = HOST_PORT_PATTERN.matcher(address);\n return matcher.matches() ? matcher.group(1) : null;\n}" }, { "identifier": "getPort", "path": "clients/src/main/java/org/apache/kafka/common/utils/Utils.java", "snippet": "public static Integer getPort(String address) {\n Matcher matcher = HOST_PORT_PATTERN.matcher(address);\n return matcher.matches() ? Integer.parseInt(matcher.group(2)) : null;\n}" }, { "identifier": "intersection", "path": "clients/src/main/java/org/apache/kafka/common/utils/Utils.java", "snippet": "@SafeVarargs\npublic static <E> Set<E> intersection(final Supplier<Set<E>> constructor, final Set<E> first, final Set<E>... set) {\n final Set<E> result = constructor.get();\n result.addAll(first);\n for (final Set<E> s : set) {\n result.retainAll(s);\n }\n return result;\n}" }, { "identifier": "mkSet", "path": "clients/src/main/java/org/apache/kafka/common/utils/Utils.java", "snippet": "@SafeVarargs\npublic static <T> Set<T> mkSet(T... elems) {\n Set<T> result = new HashSet<>((int) (elems.length / 0.75) + 1);\n for (T elem : elems)\n result.add(elem);\n return result;\n}" }, { "identifier": "murmur2", "path": "clients/src/main/java/org/apache/kafka/common/utils/Utils.java", "snippet": "@SuppressWarnings(\"fallthrough\")\npublic static int murmur2(final byte[] data) {\n int length = data.length;\n int seed = 0x9747b28c;\n // 'm' and 'r' are mixing constants generated offline.\n // They're not really 'magic', they just happen to work well.\n final int m = 0x5bd1e995;\n final int r = 24;\n\n // Initialize the hash to a random value\n int h = seed ^ length;\n int length4 = length / 4;\n\n for (int i = 0; i < length4; i++) {\n final int i4 = i * 4;\n int k = (data[i4 + 0] & 0xff) + ((data[i4 + 1] & 0xff) << 8) + ((data[i4 + 2] & 0xff) << 16) + ((data[i4 + 3] & 0xff) << 24);\n k *= m;\n k ^= k >>> r;\n k *= m;\n h *= m;\n h ^= k;\n }\n\n // Handle the last few bytes of the input array\n switch (length % 4) {\n case 3:\n h ^= (data[(length & ~3) + 2] & 0xff) << 16;\n case 2:\n h ^= (data[(length & ~3) + 1] & 0xff) << 8;\n case 1:\n h ^= data[length & ~3] & 0xff;\n h *= m;\n }\n\n h ^= h >>> 13;\n h *= m;\n h ^= h >>> 15;\n\n return h;\n}" }, { "identifier": "union", "path": "clients/src/main/java/org/apache/kafka/common/utils/Utils.java", "snippet": "@SafeVarargs\npublic static <E> Set<E> union(final Supplier<Set<E>> constructor, final Set<E>... set) {\n final Set<E> result = constructor.get();\n for (final Set<E> s : set) {\n result.addAll(s);\n }\n return result;\n}" }, { "identifier": "validHostPattern", "path": "clients/src/main/java/org/apache/kafka/common/utils/Utils.java", "snippet": "public static boolean validHostPattern(String address) {\n return VALID_HOST_CHARACTERS.matcher(address).matches();\n}" } ]
import org.apache.kafka.common.config.ConfigException; import org.apache.kafka.test.TestUtils; import org.junit.Test; import org.mockito.stubbing.OngoingStubbing; import java.io.Closeable; import java.io.DataOutputStream; import java.io.EOFException; import java.io.File; import java.io.IOException; import java.nio.BufferUnderflowException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.StandardOpenOption; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.Map; import java.util.Properties; import java.util.Random; import java.util.Set; import java.util.TreeSet; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; import static java.util.Arrays.asList; import static java.util.Collections.emptySet; import static org.apache.kafka.common.utils.Utils.diff; import static org.apache.kafka.common.utils.Utils.formatAddress; import static org.apache.kafka.common.utils.Utils.formatBytes; import static org.apache.kafka.common.utils.Utils.getHost; import static org.apache.kafka.common.utils.Utils.getPort; import static org.apache.kafka.common.utils.Utils.intersection; import static org.apache.kafka.common.utils.Utils.mkSet; import static org.apache.kafka.common.utils.Utils.murmur2; import static org.apache.kafka.common.utils.Utils.union; import static org.apache.kafka.common.utils.Utils.validHostPattern; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.Assert.assertArrayEquals; 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.assertThrows; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date;
7,344
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.kafka.common.utils; public class UtilsTest { @Test public void testMurmur2() { Map<byte[], Integer> cases = new java.util.HashMap<>(); cases.put("21".getBytes(), -973932308); cases.put("foobar".getBytes(), -790332482); cases.put("a-little-bit-long-string".getBytes(), -985981536); cases.put("a-little-bit-longer-string".getBytes(), -1486304829); cases.put("lkjh234lh9fiuh90y23oiuhsafujhadof229phr9h19h89h8".getBytes(), -58897971); cases.put(new byte[] {'a', 'b', 'c'}, 479470107); for (Map.Entry<byte[], Integer> c : cases.entrySet()) { assertEquals(c.getValue().intValue(), murmur2(c.getKey())); } } @Test public void testGetHost() {
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.kafka.common.utils; public class UtilsTest { @Test public void testMurmur2() { Map<byte[], Integer> cases = new java.util.HashMap<>(); cases.put("21".getBytes(), -973932308); cases.put("foobar".getBytes(), -790332482); cases.put("a-little-bit-long-string".getBytes(), -985981536); cases.put("a-little-bit-longer-string".getBytes(), -1486304829); cases.put("lkjh234lh9fiuh90y23oiuhsafujhadof229phr9h19h89h8".getBytes(), -58897971); cases.put(new byte[] {'a', 'b', 'c'}, 479470107); for (Map.Entry<byte[], Integer> c : cases.entrySet()) { assertEquals(c.getValue().intValue(), murmur2(c.getKey())); } } @Test public void testGetHost() {
assertEquals("127.0.0.1", getHost("127.0.0.1:8000"));
5
2023-12-23 07:12:18+00:00
12k
SDeVuyst/pingys-waddles-1.20.1
src/main/java/com/sdevuyst/pingyswaddles/entity/ModEntities.java
[ { "identifier": "PingysWaddles", "path": "src/main/java/com/sdevuyst/pingyswaddles/PingysWaddles.java", "snippet": "@Mod(PingysWaddles.MOD_ID)\npublic class PingysWaddles\n{\n // Define mod id in a common place for everything to reference\n public static final String MOD_ID = \"pingyswaddles\";\n // Directly reference a slf4j logger\n private static final Logger LOGGER = LogUtils.getLogger();\n\n public PingysWaddles()\n {\n IEventBus modEventBus = FMLJavaModLoadingContext.get().getModEventBus();\n // register Creative Tab\n ModCreativeModTabs.register(modEventBus);\n // register items\n ModItems.register(modEventBus);\n // register blocks\n ModBlocks.register(modEventBus);\n //register entities\n ModEntities.register(modEventBus);\n\n // Register the commonSetup method for modloading\n modEventBus.addListener(this::commonSetup);\n\n // Register ourselves for server and other game events we are interested in\n MinecraftForge.EVENT_BUS.register(this);\n\n // Register the item to a creative tab\n modEventBus.addListener(this::addCreative);\n\n }\n\n private void commonSetup(final FMLCommonSetupEvent event)\n {\n\n }\n\n // Add the example block item to the building blocks tab\n private void addCreative(BuildCreativeModeTabContentsEvent event)\n {\n\n }\n\n // You can use SubscribeEvent and let the Event Bus discover methods to call\n @SubscribeEvent\n public void onServerStarting(ServerStartingEvent event)\n {\n\n }\n\n // You can use EventBusSubscriber to automatically register all static methods in the class annotated with @SubscribeEvent\n @Mod.EventBusSubscriber(modid = MOD_ID, bus = Mod.EventBusSubscriber.Bus.MOD, value = Dist.CLIENT)\n public static class ClientModEvents\n {\n @SubscribeEvent\n public static void onClientSetup(FMLClientSetupEvent event)\n {\n EntityRenderers.register(ModEntities.EMPEROR_PENGUIN.get(), EmperorPenguinRenderer::new);\n EntityRenderers.register(ModEntities.SURFBOARD.get(), SurfboardRenderer::new);\n }\n }\n}" }, { "identifier": "AbstractSurfboard", "path": "src/main/java/com/sdevuyst/pingyswaddles/entity/custom/AbstractSurfboard.java", "snippet": "public abstract class AbstractSurfboard extends Entity {\n\n private static final EntityDataAccessor<Integer> DATA_ID_HURT;\n private static final EntityDataAccessor<Integer> DATA_ID_HURTDIR;\n private static final EntityDataAccessor<Float> DATA_ID_DAMAGE;\n private static final EntityDataAccessor<Integer> DATA_ID_TYPE;\n private static final EntityDataAccessor<Integer> DATA_ID_BUBBLE_TIME;\n private static final EntityDataAccessor<Boolean> DATA_ID_PADDLING;\n private float invFriction;\n private float outOfControlTicks;\n private float deltaRotation;\n private int lerpSteps;\n private double lerpX;\n private double lerpY;\n private double lerpZ;\n private double lerpYRot;\n private double lerpXRot;\n private boolean inputLeft;\n private boolean inputRight;\n private boolean inputUp;\n private boolean inputDown;\n private double waterLevel;\n private float landFriction;\n private SurfboardEntity.Status status;\n private SurfboardEntity.Status oldStatus;\n private double lastYd;\n private boolean isAboveBubbleColumn;\n private boolean bubbleColumnDirectionIsDown;\n private float bubbleMultiplier;\n private float bubbleAngle;\n private float bubbleAngleO;\n\n public AbstractSurfboard(EntityType<?> pEntityType, Level pLevel) {\n super(pEntityType, pLevel);\n this.blocksBuilding = true;\n }\n\n public AbstractSurfboard(EntityType<?> pEntityType, Level pLevel, double pX, double pY, double pZ) {\n this(pEntityType, pLevel);\n this.setPos(pX, pY, pZ);\n this.xo = pX;\n this.yo = pY;\n this.zo = pZ;\n }\n\n @Override\n protected float getEyeHeight(Pose pPose, EntityDimensions pSize) {\n return pSize.height;\n }\n\n protected Entity.MovementEmission getMovementEmission() {\n return MovementEmission.EVENTS;\n }\n\n @Override\n protected void defineSynchedData() {\n this.entityData.define(DATA_ID_HURT, 0);\n this.entityData.define(DATA_ID_HURTDIR, 1);\n this.entityData.define(DATA_ID_DAMAGE, 0.0F);\n this.entityData.define(DATA_ID_TYPE, SurfboardEntity.Type.OAK.ordinal());\n this.entityData.define(DATA_ID_BUBBLE_TIME, 0);\n this.entityData.define(DATA_ID_PADDLING, false);\n }\n\n @Override\n public boolean canCollideWith(Entity pEntity) {\n return canVehicleCollide(this, pEntity);\n }\n\n public static boolean canVehicleCollide(Entity pVehicle, Entity pEntity) {\n return (pEntity.canBeCollidedWith() || pEntity.isPushable()) && !pVehicle.isPassengerOfSameVehicle(pEntity);\n }\n\n @Override\n public boolean canBeCollidedWith() {\n return true;\n }\n\n @Override\n public boolean isPushable() {\n return true;\n }\n\n @Override\n protected Vec3 getRelativePortalPosition(Direction.Axis pAxis, BlockUtil.FoundRectangle pPortal) {\n return LivingEntity.resetForwardDirectionOfRelativePortalPosition(super.getRelativePortalPosition(pAxis, pPortal));\n }\n\n @Override\n public double getPassengersRidingOffset() {\n return -0.1;\n }\n\n @Override\n public boolean hurt(DamageSource pSource, float pAmount) {\n\n if (this.isInvulnerableTo(pSource)) {\n return false;\n } else if (!this.level().isClientSide && !this.isRemoved()) {\n this.setHurtDir(-this.getHurtDir());\n this.setHurtTime(10);\n this.setDamage(this.getDamage() + pAmount * 10.0F);\n this.markHurt();\n this.gameEvent(GameEvent.ENTITY_DAMAGE, pSource.getEntity());\n boolean flag = pSource.getEntity() instanceof Player && ((Player)pSource.getEntity()).getAbilities().instabuild;\n if (flag || this.getDamage() > 40.0F) {\n if (!flag && this.level().getGameRules().getBoolean(GameRules.RULE_DOENTITYDROPS)) {\n this.destroy(pSource);\n }\n\n this.discard();\n }\n\n return true;\n } else {\n return true;\n }\n }\n\n protected void destroy(DamageSource pDamageSource) {\n this.spawnAtLocation(this.getDropItem());\n }\n\n\n public void push(Entity pEntity) {\n if (pEntity instanceof SurfboardEntity) {\n if (pEntity.getBoundingBox().minY < this.getBoundingBox().maxY) {\n super.push(pEntity);\n }\n } else if (pEntity.getBoundingBox().minY <= this.getBoundingBox().minY) {\n super.push(pEntity);\n }\n\n }\n\n public Item getDropItem() {\n Item item;\n switch (this.getVariant()) {\n case OAK:\n item = ModItems.OAK_SURFBOARD.get();\n break;\n // FEATURE more variants\n default:\n item = Items.OAK_BOAT;\n }\n\n return item;\n }\n\n public void animateHurt(float pYaw) {\n this.setHurtDir(-this.getHurtDir());\n this.setHurtTime(10);\n this.setDamage(this.getDamage() * 11.0F);\n }\n\n public boolean isPickable() {\n return !this.isRemoved();\n }\n\n @Override\n public void lerpTo(double pX, double pY, double pZ, float pYaw, float pPitch, int pPosRotationIncrements, boolean pTeleport) {\n this.lerpX = pX;\n this.lerpY = pY;\n this.lerpZ = pZ;\n this.lerpYRot = (double)pYaw;\n this.lerpXRot = (double)pPitch;\n this.lerpSteps = 10;\n }\n\n @Override\n public @NotNull Direction getMotionDirection() {\n return this.getDirection().getClockWise();\n }\n\n @Override\n public void tick() {\n this.oldStatus = this.status;\n this.status = this.getStatus();\n\n // out of control surfboard\n if (this.status != SurfboardEntity.Status.UNDER_WATER && this.status != SurfboardEntity.Status.UNDER_FLOWING_WATER) {\n this.outOfControlTicks = 0.0F;\n } else {\n ++this.outOfControlTicks;\n }\n\n // eject passengers if out of control for more than 60 ticks (3 sec)\n if (!this.level().isClientSide && this.outOfControlTicks >= 60.0F) {\n this.ejectPassengers();\n }\n\n if (this.getHurtTime() > 0) {\n this.setHurtTime(this.getHurtTime() - 1);\n }\n\n if (this.getDamage() > 0.0F) {\n this.setDamage(this.getDamage() - 1.0F);\n }\n\n super.tick();\n this.tickLerp();\n\n // player is controlling surfboard\n if (this.isControlledByLocalInstance()) {\n\n this.floatSurfboard();\n if (this.level().isClientSide) {\n this.controlSurfboard();\n }\n\n // check inputs\n this.inputUp = Minecraft.getInstance().options.keyUp.isDown();\n this.inputDown = Minecraft.getInstance().options.keyDown.isDown();\n this.inputLeft = Minecraft.getInstance().options.keyLeft.isDown();\n this.inputRight= Minecraft.getInstance().options.keyRight.isDown();\n\n this.setPaddling(\n (this.inputRight || this.inputLeft || this.inputUp || this.inputDown)\n && this.isControlledByLocalInstance()\n );\n\n // actually move the surfboard\n this.move(MoverType.SELF, this.getDeltaMovement());\n\n } else {\n // don't move anything\n this.setDeltaMovement(Vec3.ZERO);\n }\n\n // play paddling sounds\n for(int i = 0; i <= 1; ++i) {\n if (this.isSilent() && this.isPaddling()) {\n SoundEvent soundevent = this.getPaddleSound();\n if (soundevent != null) {\n Vec3 vec3 = this.getViewVector(1.0F);\n double d0 = i == 1 ? -vec3.z : vec3.z;\n double d1 = i == 1 ? vec3.x : -vec3.x;\n this.level().playSound((Player)null, this.getX() + d0, this.getY(), this.getZ() + d1, soundevent, this.getSoundSource(), 1.0F, 0.8F + 0.4F * this.random.nextFloat());\n }\n }\n }\n\n this.checkInsideBlocks();\n\n // non-player entities start riding surfboat when getting closeby\n List<Entity> list = this.level().getEntities(this, this.getBoundingBox().inflate(0.20000000298023224, -0.009999999776482582, 0.20000000298023224), EntitySelector.pushableBy(this));\n if (!list.isEmpty()) {\n boolean flag = !this.level().isClientSide && !(this.getControllingPassenger() instanceof Player);\n\n for (int j = 0; j < list.size(); ++j) {\n Entity entity = (Entity)list.get(j);\n if (!entity.hasPassenger(this)) {\n if (flag && this.getPassengers().size() < this.getMaxPassengers() && !entity.isPassenger() && this.hasEnoughSpaceFor(entity) && entity instanceof LivingEntity && !(entity instanceof WaterAnimal) && !(entity instanceof Player)) {\n entity.startRiding(this);\n } else {\n this.push(entity);\n }\n }\n }\n }\n }\n\n @Nullable\n protected SoundEvent getPaddleSound() {\n return SoundEvents.BOAT_PADDLE_WATER;\n }\n\n private void tickLerp() {\n if (this.isControlledByLocalInstance()) {\n this.lerpSteps = 0;\n this.syncPacketPositionCodec(this.getX(), this.getY(), this.getZ());\n }\n\n if (this.lerpSteps > 0) {\n double d0 = this.getX() + (this.lerpX - this.getX()) / (double)this.lerpSteps;\n double d1 = this.getY() + (this.lerpY - this.getY()) / (double)this.lerpSteps;\n double d2 = this.getZ() + (this.lerpZ - this.getZ()) / (double)this.lerpSteps;\n double d3 = Mth.wrapDegrees(this.lerpYRot - (double)this.getYRot());\n this.setYRot(this.getYRot() + (float)d3 / (float)this.lerpSteps);\n this.setXRot(this.getXRot() + (float)(this.lerpXRot - (double)this.getXRot()) / (float)this.lerpSteps);\n --this.lerpSteps;\n this.setPos(d0, d1, d2);\n this.setRot(this.getYRot(), this.getXRot());\n }\n\n }\n\n private SurfboardEntity.Status getStatus() {\n AbstractSurfboard.Status boat$status = this.isUnderwater();\n if (boat$status != null) {\n this.waterLevel = this.getBoundingBox().maxY;\n return boat$status;\n } else if (this.checkInWater()) {\n return SurfboardEntity.Status.IN_WATER;\n } else {\n float f = this.getGroundFriction();\n if (f > 0.0F) {\n this.landFriction = f;\n return SurfboardEntity.Status.ON_LAND;\n } else {\n return SurfboardEntity.Status.IN_AIR;\n }\n }\n }\n\n public float getWaterLevelAbove() {\n AABB aabb = this.getBoundingBox();\n int i = Mth.floor(aabb.minX);\n int j = Mth.ceil(aabb.maxX);\n int k = Mth.floor(aabb.maxY);\n int l = Mth.ceil(aabb.maxY - this.lastYd);\n int i1 = Mth.floor(aabb.minZ);\n int j1 = Mth.ceil(aabb.maxZ);\n BlockPos.MutableBlockPos blockpos$mutableblockpos = new BlockPos.MutableBlockPos();\n\n label39:\n for(int k1 = k; k1 < l; ++k1) {\n float f = 0.0F;\n\n for(int l1 = i; l1 < j; ++l1) {\n for(int i2 = i1; i2 < j1; ++i2) {\n blockpos$mutableblockpos.set(l1, k1, i2);\n FluidState fluidstate = this.level().getFluidState(blockpos$mutableblockpos);\n f = Math.max(f, fluidstate.getHeight(this.level(), blockpos$mutableblockpos));\n\n if (f >= 1.0F) {\n continue label39;\n }\n }\n }\n\n if (f < 1.0F) {\n return (float)blockpos$mutableblockpos.getY() + f;\n }\n }\n\n return (float)(l + 1);\n }\n\n public float getGroundFriction() {\n AABB aabb = this.getBoundingBox();\n AABB aabb1 = new AABB(aabb.minX, aabb.minY - 0.001, aabb.minZ, aabb.maxX, aabb.minY, aabb.maxZ);\n int i = Mth.floor(aabb1.minX) - 1;\n int j = Mth.ceil(aabb1.maxX) + 1;\n int k = Mth.floor(aabb1.minY) - 1;\n int l = Mth.ceil(aabb1.maxY) + 1;\n int i1 = Mth.floor(aabb1.minZ) - 1;\n int j1 = Mth.ceil(aabb1.maxZ) + 1;\n VoxelShape voxelshape = Shapes.create(aabb1);\n float f = 0.0F;\n int k1 = 0;\n BlockPos.MutableBlockPos blockpos$mutableblockpos = new BlockPos.MutableBlockPos();\n\n for(int l1 = i; l1 < j; ++l1) {\n for(int i2 = i1; i2 < j1; ++i2) {\n int j2 = (l1 != i && l1 != j - 1 ? 0 : 1) + (i2 != i1 && i2 != j1 - 1 ? 0 : 1);\n if (j2 != 2) {\n for(int k2 = k; k2 < l; ++k2) {\n if (j2 <= 0 || k2 != k && k2 != l - 1) {\n blockpos$mutableblockpos.set(l1, k2, i2);\n BlockState blockstate = this.level().getBlockState(blockpos$mutableblockpos);\n if (!(blockstate.getBlock() instanceof WaterlilyBlock) && Shapes.joinIsNotEmpty(blockstate.getCollisionShape(this.level(), blockpos$mutableblockpos).move((double)l1, (double)k2, (double)i2), voxelshape, BooleanOp.AND)) {\n f += blockstate.getFriction(this.level(), blockpos$mutableblockpos, this);\n ++k1;\n }\n }\n }\n }\n }\n }\n\n return f / (float)k1;\n }\n\n private boolean checkInWater() {\n AABB aabb = this.getBoundingBox();\n int i = Mth.floor(aabb.minX);\n int j = Mth.ceil(aabb.maxX);\n int k = Mth.floor(aabb.minY);\n int l = Mth.ceil(aabb.minY + 0.001);\n int i1 = Mth.floor(aabb.minZ);\n int j1 = Mth.ceil(aabb.maxZ);\n boolean flag = false;\n this.waterLevel = -1.7976931348623157E308;\n BlockPos.MutableBlockPos blockpos$mutableblockpos = new BlockPos.MutableBlockPos();\n\n for(int k1 = i; k1 < j; ++k1) {\n for(int l1 = k; l1 < l; ++l1) {\n for(int i2 = i1; i2 < j1; ++i2) {\n blockpos$mutableblockpos.set(k1, l1, i2);\n FluidState fluidstate = this.level().getFluidState(blockpos$mutableblockpos);\n\n float f = (float)l1 + fluidstate.getHeight(this.level(), blockpos$mutableblockpos);\n this.waterLevel = Math.max((double)f, this.waterLevel);\n flag |= aabb.minY < (double)f;\n }\n }\n }\n\n return flag;\n }\n\n @Nullable\n private AbstractSurfboard.Status isUnderwater() {\n AABB aabb = this.getBoundingBox();\n double d0 = aabb.maxY + 0.001;\n int i = Mth.floor(aabb.minX);\n int j = Mth.ceil(aabb.maxX);\n int k = Mth.floor(aabb.maxY);\n int l = Mth.ceil(d0);\n int i1 = Mth.floor(aabb.minZ);\n int j1 = Mth.ceil(aabb.maxZ);\n boolean flag = false;\n BlockPos.MutableBlockPos blockpos$mutableblockpos = new BlockPos.MutableBlockPos();\n\n for(int k1 = i; k1 < j; ++k1) {\n for(int l1 = k; l1 < l; ++l1) {\n for(int i2 = i1; i2 < j1; ++i2) {\n blockpos$mutableblockpos.set(k1, l1, i2);\n FluidState fluidstate = this.level().getFluidState(blockpos$mutableblockpos);\n if (d0 < (double)((float)blockpos$mutableblockpos.getY() + fluidstate.getHeight(this.level(), blockpos$mutableblockpos))) {\n if (!fluidstate.isSource()) {\n return AbstractSurfboard.Status.UNDER_FLOWING_WATER;\n }\n\n flag = true;\n }\n }\n }\n }\n\n return flag ? AbstractSurfboard.Status.UNDER_WATER : null;\n }\n\n private void floatSurfboard() {\n double d0 = (double) -1/50;\n double d1 = this.isNoGravity() ? 0.0 : (double) -1/50;\n double d2 = 0.0;\n this.invFriction = 0.03F;\n\n if (this.oldStatus == AbstractSurfboard.Status.IN_AIR && this.status != AbstractSurfboard.Status.IN_AIR && this.status != AbstractSurfboard.Status.ON_LAND) {\n this.waterLevel = this.getY(1.0);\n this.setPos(this.getX(), (double)(this.getWaterLevelAbove() - this.getBbHeight() + 0.101), this.getZ());\n this.setDeltaMovement(this.getDeltaMovement().multiply(1.0, 0.0, 1.0));\n this.lastYd = 0.0;\n this.status = AbstractSurfboard.Status.IN_WATER;\n\n } else {\n if (this.status == AbstractSurfboard.Status.IN_WATER) {\n d2 = (this.waterLevel - this.getY()) / (double)this.getBbHeight();\n this.invFriction = 0.9F;\n\n } else if (this.status == AbstractSurfboard.Status.UNDER_FLOWING_WATER) {\n d1 = -7.0E-4;\n this.invFriction = 0.9F;\n\n } else if (this.status == AbstractSurfboard.Status.UNDER_WATER) {\n d2 = (this.waterLevel - this.getY()) / (double)this.getBbHeight();\n this.invFriction = 0.45F;\n\n } else if (this.status == AbstractSurfboard.Status.IN_AIR) {\n this.invFriction = 0.9F;\n\n } else if (this.status == AbstractSurfboard.Status.ON_LAND) {\n this.invFriction = this.landFriction;\n if (this.getControllingPassenger() instanceof Player) {\n this.landFriction /= 2.0F;\n }\n }\n\n Vec3 vec3 = this.getDeltaMovement();\n this.setDeltaMovement(vec3.x * (double)this.invFriction, vec3.y + d1, vec3.z * (double)this.invFriction);\n this.deltaRotation *= this.invFriction;\n if (d2 > 0.0) {\n Vec3 vec31 = this.getDeltaMovement();\n this.setDeltaMovement(vec31.x, (vec31.y + d2 * 0.06) * 0.75, vec31.z);\n }\n }\n\n }\n\n private void setBubbleTime(int pBubbleTime) {\n this.entityData.set(DATA_ID_BUBBLE_TIME, pBubbleTime);\n }\n\n private int getBubbleTime() {\n return (Integer)this.entityData.get(DATA_ID_BUBBLE_TIME);\n }\n\n public float getBubbleAngle(float pPartialTicks) {\n return Mth.lerp(pPartialTicks, this.bubbleAngleO, this.bubbleAngle);\n }\n\n private void controlSurfboard() {\n if (this.isVehicle()) {\n float f = 0.0F;\n if (this.inputLeft) {\n --this.deltaRotation;\n }\n\n if (this.inputRight) {\n ++this.deltaRotation;\n }\n\n if (this.inputRight != this.inputLeft && !this.inputUp && !this.inputDown) {\n f += 0.005F;\n }\n\n this.setYRot(this.getYRot() + this.deltaRotation);\n if (this.inputUp) {\n f += 0.04F;\n }\n\n if (this.inputDown) {\n f -= 0.005F;\n }\n\n this.setDeltaMovement(this.getDeltaMovement().add((double)(Mth.sin(-this.getYRot() * 0.017453292F) * f), 0.0, (double)(Mth.cos(this.getYRot() * 0.017453292F) * f)));\n }\n\n }\n\n protected float getSinglePassengerXOffset() {\n return 0.0F;\n }\n\n public boolean hasEnoughSpaceFor(Entity pEntity) {\n return pEntity.getBbWidth() < this.getBbWidth();\n }\n\n @Override\n protected void positionRider(Entity pPassenger, Entity.MoveFunction pCallback) {\n if (this.hasPassenger(pPassenger)) {\n float f = this.getSinglePassengerXOffset();\n float f1 = (float)((this.isRemoved() ? 0.009999999776482582 : this.getPassengersRidingOffset()) + pPassenger.getMyRidingOffset());\n if (this.getPassengers().size() > 1) {\n int i = this.getPassengers().indexOf(pPassenger);\n if (i == 0) {\n f = 0.2F;\n } else {\n f = -0.6F;\n }\n\n if (pPassenger instanceof Animal) {\n f += 0.2F;\n }\n }\n\n // TODO new postition for riding surfboard\n Vec3 vec3 = (new Vec3((double)f, 0.0, 0.0)).yRot(-this.getYRot() * 0.017453292F - 1.5707964F);\n pCallback.accept(pPassenger, this.getX() + vec3.x, this.getY() + (double)f1, this.getZ() + vec3.z);\n pPassenger.setYRot(pPassenger.getYRot() + this.deltaRotation);\n pPassenger.setYHeadRot(pPassenger.getYHeadRot() + this.deltaRotation);\n this.clampRotation(pPassenger);\n if (pPassenger instanceof Animal && this.getPassengers().size() == this.getMaxPassengers()) {\n int j = pPassenger.getId() % 2 == 0 ? 90 : 270;\n pPassenger.setYBodyRot(((Animal)pPassenger).yBodyRot + (float)j);\n pPassenger.setYHeadRot(pPassenger.getYHeadRot() + (float)j);\n }\n }\n\n }\n @Override\n public @NotNull Vec3 getDismountLocationForPassenger(LivingEntity pLivingEntity) {\n Vec3 vec3 = getCollisionHorizontalEscapeVector((double)(this.getBbWidth() * Mth.SQRT_OF_TWO), (double)pLivingEntity.getBbWidth(), pLivingEntity.getYRot());\n double d0 = this.getX() + vec3.x;\n double d1 = this.getZ() + vec3.z;\n BlockPos blockpos = BlockPos.containing(d0, this.getBoundingBox().maxY, d1);\n BlockPos blockpos1 = blockpos.below();\n if (!this.level().isWaterAt(blockpos1)) {\n List<Vec3> list = Lists.newArrayList();\n double d2 = this.level().getBlockFloorHeight(blockpos);\n if (DismountHelper.isBlockFloorValid(d2)) {\n list.add(new Vec3(d0, (double)blockpos.getY() + d2, d1));\n }\n\n double d3 = this.level().getBlockFloorHeight(blockpos1);\n if (DismountHelper.isBlockFloorValid(d3)) {\n list.add(new Vec3(d0, (double)blockpos1.getY() + d3, d1));\n }\n\n UnmodifiableIterator var14 = pLivingEntity.getDismountPoses().iterator();\n\n while (var14.hasNext()) {\n Pose pose = (Pose)var14.next();\n Iterator var16 = list.iterator();\n\n while(var16.hasNext()) {\n Vec3 vec31 = (Vec3)var16.next();\n if (DismountHelper.canDismountTo(this.level(), vec31, pLivingEntity, pose)) {\n pLivingEntity.setPose(pose);\n return vec31;\n }\n }\n }\n }\n\n return super.getDismountLocationForPassenger(pLivingEntity);\n }\n\n protected void clampRotation(Entity pEntityToUpdate) {\n pEntityToUpdate.setYBodyRot(this.getYRot());\n float f = Mth.wrapDegrees(pEntityToUpdate.getYRot() - this.getYRot());\n float f1 = Mth.clamp(f, -105.0F, 105.0F);\n pEntityToUpdate.yRotO += f1 - f;\n pEntityToUpdate.setYRot(pEntityToUpdate.getYRot() + f1 - f);\n pEntityToUpdate.setYHeadRot(pEntityToUpdate.getYRot());\n }\n\n @Override\n public void onPassengerTurned(Entity pEntityToUpdate) {\n this.clampRotation(pEntityToUpdate);\n }\n\n @Override\n protected void addAdditionalSaveData(CompoundTag pCompound) {\n pCompound.putString(\"Type\", this.getModVariant().getSerializedName());\n }\n\n @Override\n protected void readAdditionalSaveData(CompoundTag pCompound) {\n if (pCompound.contains(\"Type\", 8)) {\n this.setVariant(SurfboardEntity.Type.byName(pCompound.getString(\"Type\")));\n }\n }\n\n @Override\n public @NotNull InteractionResult interact(Player pPlayer, @NotNull InteractionHand pHand) {\n if (pPlayer.isSecondaryUseActive()) {\n return InteractionResult.PASS;\n } else if (this.outOfControlTicks < 60.0F) {\n if (!this.level().isClientSide) {\n return pPlayer.startRiding(this) ? InteractionResult.CONSUME : InteractionResult.PASS;\n } else {\n return InteractionResult.SUCCESS;\n }\n } else {\n return InteractionResult.PASS;\n }\n }\n\n @Override\n protected void checkFallDamage(double pY, boolean pOnGround, BlockState pState, BlockPos pPos) {\n this.lastYd = this.getDeltaMovement().y;\n if (!this.isPassenger()) {\n if (pOnGround) {\n if (this.fallDistance > 3.0F) {\n if (this.status != AbstractSurfboard.Status.ON_LAND) {\n this.resetFallDistance();\n return;\n }\n\n this.causeFallDamage(this.fallDistance, 1.0F, this.damageSources().fall());\n if (!this.level().isClientSide && !this.isRemoved()) {\n this.kill();\n if (this.level().getGameRules().getBoolean(GameRules.RULE_DOENTITYDROPS)) {\n int j;\n for(j = 0; j < 3; ++j) {\n this.spawnAtLocation(this.getVariant().getPlanks());\n }\n\n for(j = 0; j < 2; ++j) {\n this.spawnAtLocation(Items.STICK);\n }\n }\n }\n }\n\n this.resetFallDistance();\n } else if (pY < 0.0) {\n this.fallDistance -= (float)pY;\n }\n }\n\n }\n\n public void setDamage(float pDamageTaken) {\n this.entityData.set(DATA_ID_DAMAGE, pDamageTaken);\n }\n\n public float getDamage() {\n return (Float)this.entityData.get(DATA_ID_DAMAGE);\n }\n\n public void setHurtTime(int pHurtTime) {\n this.entityData.set(DATA_ID_HURT, pHurtTime);\n }\n\n public int getHurtTime() {\n return (Integer)this.entityData.get(DATA_ID_HURT);\n }\n\n public boolean isPaddling() {\n return (Boolean)this.entityData.get(DATA_ID_PADDLING);\n }\n\n private void setPaddling(boolean paddling) {\n this.entityData.set(DATA_ID_PADDLING, paddling);\n }\n\n public void setHurtDir(int pHurtDirection) {\n this.entityData.set(DATA_ID_HURTDIR, pHurtDirection);\n }\n\n public int getHurtDir() {\n return (Integer)this.entityData.get(DATA_ID_HURTDIR);\n }\n\n public void setVariant(SurfboardEntity.Type pVariant) {\n this.entityData.set(DATA_ID_TYPE, pVariant.ordinal());\n }\n\n public Type getVariant() {\n return SurfboardEntity.Type.byId((Integer)this.entityData.get(DATA_ID_TYPE));\n }\n\n protected boolean canAddPassenger(Entity pPassenger) {\n return this.getPassengers().size() < this.getMaxPassengers();\n }\n\n protected int getMaxPassengers() {\n return 1;\n }\n\n @Nullable\n @Override\n public LivingEntity getControllingPassenger() {\n Entity entity = this.getFirstPassenger();\n LivingEntity livingentity1;\n\n if (entity instanceof LivingEntity livingentity) {\n livingentity1 = livingentity;\n } else {\n livingentity1 = null;\n }\n\n return livingentity1;\n }\n\n @Override\n public boolean isUnderWater() {\n return this.status == AbstractSurfboard.Status.UNDER_WATER || this.status == AbstractSurfboard.Status.UNDER_FLOWING_WATER;\n }\n\n @Override\n protected void addPassenger(Entity passenger) {\n super.addPassenger(passenger);\n if (this.isControlledByLocalInstance() && this.lerpSteps > 0) {\n this.lerpSteps = 0;\n this.absMoveTo(this.lerpX, this.lerpY, this.lerpZ, (float)this.lerpYRot, (float)this.lerpXRot);\n }\n\n }\n\n @Override\n public ItemStack getPickResult() {\n return new ItemStack(this.getDropItem());\n }\n\n public SurfboardEntity.Type getModVariant() {\n return SurfboardEntity.Type.byId(this.entityData.get(DATA_ID_TYPE));\n }\n\n static {\n DATA_ID_HURT = SynchedEntityData.defineId(AbstractSurfboard.class, EntityDataSerializers.INT);\n DATA_ID_HURTDIR = SynchedEntityData.defineId(AbstractSurfboard.class, EntityDataSerializers.INT);\n DATA_ID_DAMAGE = SynchedEntityData.defineId(AbstractSurfboard.class, EntityDataSerializers.FLOAT);\n DATA_ID_TYPE = SynchedEntityData.defineId(AbstractSurfboard.class, EntityDataSerializers.INT);\n DATA_ID_BUBBLE_TIME = SynchedEntityData.defineId(AbstractSurfboard.class, EntityDataSerializers.INT);\n DATA_ID_PADDLING = SynchedEntityData.defineId(AbstractSurfboard.class, EntityDataSerializers.BOOLEAN);\n }\n\n\n public static enum Type implements StringRepresentable {\n OAK(Blocks.OAK_PLANKS, \"oak\");\n\n private final String name;\n private final Block planks;\n public static final StringRepresentable.EnumCodec<SurfboardEntity.Type> CODEC = StringRepresentable.fromEnum(SurfboardEntity.Type::values);\n private static final IntFunction<Type> BY_ID = ByIdMap.continuous(Enum::ordinal, values(), ByIdMap.OutOfBoundsStrategy.ZERO);\n\n private Type(Block pPlanks, String pName) {\n this.name = pName;\n this.planks = pPlanks;\n }\n\n public String getSerializedName() {\n return this.name;\n }\n\n public String getName() {\n return this.name;\n }\n\n public Block getPlanks() {\n return this.planks;\n }\n\n public String toString() {\n return this.name;\n }\n\n /**\n * Get a surfboard type by its enum ordinal\n */\n public static SurfboardEntity.Type byId(int pId) {\n return BY_ID.apply(pId);\n }\n\n public static SurfboardEntity.Type byName(String pName) {\n return CODEC.byName(pName, OAK);\n }\n }\n\n\n public static enum Status {\n IN_WATER,\n UNDER_WATER,\n UNDER_FLOWING_WATER,\n ON_LAND,\n IN_AIR;\n\n private Status() {\n }\n }\n\n}" }, { "identifier": "EmperorPenguinEntity", "path": "src/main/java/com/sdevuyst/pingyswaddles/entity/custom/EmperorPenguinEntity.java", "snippet": "public class EmperorPenguinEntity extends AbstractPenguin {\n\n public EmperorPenguinEntity(EntityType<? extends Animal> pEntityType, Level pLevel) {\n super(pEntityType, pLevel);\n }\n\n @Nullable\n @Override\n public AgeableMob getBreedOffspring(ServerLevel serverLevel, AgeableMob ageableMob) {\n return ModEntities.EMPEROR_PENGUIN.get().create(serverLevel);\n }\n\n static {\n NORMAL_DIMENSIONS = EntityDimensions.fixed(1.0F, 1.9F);\n BABY_DIMENSIONS = EntityDimensions.fixed(0.5F, 0.9F);\n }\n}" }, { "identifier": "SurfboardEntity", "path": "src/main/java/com/sdevuyst/pingyswaddles/entity/custom/SurfboardEntity.java", "snippet": "public class SurfboardEntity extends AbstractSurfboard {\n\n public SurfboardEntity(EntityType<?> entityEntityType, Level level) {\n super(entityEntityType, level);\n }\n\n public SurfboardEntity(Level pLevel, double pX, double pY, double pZ) {\n super(ModEntities.SURFBOARD.get(), pLevel, pX, pY, pZ);\n }\n\n}" } ]
import com.sdevuyst.pingyswaddles.PingysWaddles; import com.sdevuyst.pingyswaddles.entity.custom.AbstractSurfboard; import com.sdevuyst.pingyswaddles.entity.custom.EmperorPenguinEntity; import com.sdevuyst.pingyswaddles.entity.custom.SurfboardEntity; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.EntityType; import net.minecraft.world.entity.MobCategory; import net.minecraftforge.eventbus.api.IEventBus; import net.minecraftforge.registries.DeferredRegister; import net.minecraftforge.registries.ForgeRegistries; import net.minecraftforge.registries.RegistryObject;
9,275
package com.sdevuyst.pingyswaddles.entity; public class ModEntities { public static final DeferredRegister<EntityType<?>> ENTITY_TYPES = DeferredRegister.create(ForgeRegistries.ENTITY_TYPES, PingysWaddles.MOD_ID);
package com.sdevuyst.pingyswaddles.entity; public class ModEntities { public static final DeferredRegister<EntityType<?>> ENTITY_TYPES = DeferredRegister.create(ForgeRegistries.ENTITY_TYPES, PingysWaddles.MOD_ID);
public static final RegistryObject<EntityType<EmperorPenguinEntity>> EMPEROR_PENGUIN =
2
2023-12-31 09:54:03+00:00
12k
quarkiverse/quarkus-langchain4j
openai/openai-vanilla/runtime/src/main/java/io/quarkiverse/langchain4j/openai/runtime/OpenAiRecorder.java
[ { "identifier": "firstOrDefault", "path": "core/runtime/src/main/java/io/quarkiverse/langchain4j/runtime/OptionalUtil.java", "snippet": "@SafeVarargs\npublic static <T> T firstOrDefault(T defaultValue, Optional<T>... values) {\n for (Optional<T> o : values) {\n if (o != null && o.isPresent()) {\n return o.get();\n }\n }\n return defaultValue;\n}" }, { "identifier": "QuarkusOpenAiClient", "path": "openai/openai-common/runtime/src/main/java/io/quarkiverse/langchain4j/openai/QuarkusOpenAiClient.java", "snippet": "public class QuarkusOpenAiClient extends OpenAiClient {\n\n private final String apiKey;\n private final String apiVersion;\n private final String organizationId;\n\n private final OpenAiRestApi restApi;\n\n private static final Map<Builder, OpenAiRestApi> cache = new ConcurrentHashMap<>();\n\n public QuarkusOpenAiClient(String apiKey) {\n this(new Builder().openAiApiKey(apiKey));\n }\n\n public static Builder builder() {\n return new Builder();\n }\n\n public static void clearCache() {\n cache.clear();\n }\n\n private QuarkusOpenAiClient(Builder builder) {\n this.apiKey = determineApiKey(builder);\n this.apiVersion = builder.apiVersion;\n this.organizationId = builder.organizationId;\n // cache the client the builder could be called with the same parameters from multiple models\n this.restApi = cache.compute(builder, new BiFunction<Builder, OpenAiRestApi, OpenAiRestApi>() {\n @Override\n public OpenAiRestApi apply(Builder builder, OpenAiRestApi openAiRestApi) {\n try {\n QuarkusRestClientBuilder restApiBuilder = QuarkusRestClientBuilder.newBuilder()\n .baseUri(new URI(builder.baseUrl))\n .connectTimeout(builder.connectTimeout.toSeconds(), TimeUnit.SECONDS)\n .readTimeout(builder.readTimeout.toSeconds(), TimeUnit.SECONDS);\n if (builder.logRequests || builder.logResponses) {\n restApiBuilder.loggingScope(LoggingScope.REQUEST_RESPONSE);\n restApiBuilder.clientLogger(new OpenAiRestApi.OpenAiClientLogger(builder.logRequests,\n builder.logResponses));\n }\n if (builder.proxy != null) {\n if (builder.proxy.type() != Proxy.Type.HTTP) {\n throw new IllegalArgumentException(\"Only HTTP type proxy is supported\");\n }\n if (!(builder.proxy.address() instanceof InetSocketAddress)) {\n throw new IllegalArgumentException(\"Unsupported proxy type\");\n }\n InetSocketAddress socketAddress = (InetSocketAddress) builder.proxy.address();\n restApiBuilder.proxyAddress(socketAddress.getHostName(), socketAddress.getPort());\n }\n\n return restApiBuilder.build(OpenAiRestApi.class);\n } catch (URISyntaxException e) {\n throw new RuntimeException(e);\n }\n }\n });\n\n }\n\n private static String determineApiKey(Builder builder) {\n var result = builder.openAiApiKey;\n if (result != null) {\n return result;\n }\n result = builder.azureApiKey;\n return result;\n }\n\n @Override\n public SyncOrAsyncOrStreaming<CompletionResponse> completion(CompletionRequest request) {\n return new SyncOrAsyncOrStreaming<>() {\n @Override\n public CompletionResponse execute() {\n return restApi.blockingCompletion(\n CompletionRequest.builder().from(request).stream(null).build(),\n OpenAiRestApi.ApiMetadata.builder()\n .apiKey(apiKey)\n .apiVersion(apiVersion)\n .organizationId(organizationId)\n .build());\n }\n\n @Override\n public AsyncResponseHandling onResponse(Consumer<CompletionResponse> responseHandler) {\n return new AsyncResponseHandlingImpl<>(\n new Supplier<>() {\n @Override\n public Uni<CompletionResponse> get() {\n return restApi.completion(request,\n OpenAiRestApi.ApiMetadata.builder()\n .apiKey(apiKey)\n .apiVersion(apiVersion)\n .organizationId(organizationId)\n .build());\n }\n },\n responseHandler);\n }\n\n @Override\n public StreamingResponseHandling onPartialResponse(\n Consumer<CompletionResponse> partialResponseHandler) {\n return new StreamingResponseHandlingImpl<>(\n new Supplier<>() {\n @Override\n public Multi<CompletionResponse> get() {\n return restApi.streamingCompletion(request,\n OpenAiRestApi.ApiMetadata.builder()\n .apiKey(apiKey)\n .apiVersion(apiVersion)\n .organizationId(organizationId)\n .build());\n }\n }, partialResponseHandler);\n }\n };\n }\n\n @Override\n public SyncOrAsyncOrStreaming<String> completion(String prompt) {\n throw new NotImplementedYet();\n }\n\n @Override\n public SyncOrAsyncOrStreaming<ChatCompletionResponse> chatCompletion(ChatCompletionRequest request) {\n return new SyncOrAsyncOrStreaming<>() {\n @Override\n public ChatCompletionResponse execute() {\n return restApi.blockingChatCompletion(\n ChatCompletionRequest.builder().from(request).stream(null).build(),\n OpenAiRestApi.ApiMetadata.builder()\n .apiKey(apiKey)\n .apiVersion(apiVersion)\n .organizationId(organizationId)\n .build());\n }\n\n @Override\n public AsyncResponseHandling onResponse(Consumer<ChatCompletionResponse> responseHandler) {\n return new AsyncResponseHandlingImpl<>(\n new Supplier<>() {\n @Override\n public Uni<ChatCompletionResponse> get() {\n return restApi.createChatCompletion(request,\n OpenAiRestApi.ApiMetadata.builder()\n .apiKey(apiKey)\n .apiVersion(apiVersion)\n .organizationId(organizationId)\n .build());\n }\n },\n responseHandler);\n }\n\n @Override\n public StreamingResponseHandling onPartialResponse(\n Consumer<ChatCompletionResponse> partialResponseHandler) {\n return new StreamingResponseHandlingImpl<>(\n new Supplier<>() {\n @Override\n public Multi<ChatCompletionResponse> get() {\n return restApi.streamingChatCompletion(request,\n OpenAiRestApi.ApiMetadata.builder()\n .apiKey(apiKey)\n .apiVersion(apiVersion)\n .organizationId(organizationId)\n .build());\n }\n }, partialResponseHandler);\n }\n };\n }\n\n @Override\n public SyncOrAsyncOrStreaming<String> chatCompletion(String userMessage) {\n ChatCompletionRequest request = ChatCompletionRequest.builder()\n .addUserMessage(userMessage)\n .build();\n\n return new SyncOrAsyncOrStreaming<>() {\n @Override\n public String execute() {\n return restApi\n .blockingChatCompletion(request,\n OpenAiRestApi.ApiMetadata.builder()\n .apiKey(apiKey)\n .apiVersion(apiVersion)\n .organizationId(organizationId)\n .build())\n .content();\n }\n\n @Override\n public AsyncResponseHandling onResponse(Consumer<String> responseHandler) {\n return new AsyncResponseHandlingImpl<>(\n new Supplier<>() {\n @Override\n public Uni<String> get() {\n return restApi\n .createChatCompletion(\n ChatCompletionRequest.builder().from(request).stream(null).build(),\n OpenAiRestApi.ApiMetadata.builder()\n .apiKey(apiKey)\n .apiVersion(apiVersion)\n .organizationId(organizationId)\n .build())\n .map(ChatCompletionResponse::content);\n }\n },\n responseHandler);\n }\n\n @Override\n public StreamingResponseHandling onPartialResponse(\n Consumer<String> partialResponseHandler) {\n return new StreamingResponseHandlingImpl<>(\n new Supplier<>() {\n @Override\n public Multi<String> get() {\n return restApi\n .streamingChatCompletion(\n ChatCompletionRequest.builder().from(request).stream(true).build(),\n OpenAiRestApi.ApiMetadata.builder()\n .apiKey(apiKey)\n .apiVersion(apiVersion)\n .organizationId(organizationId)\n .build())\n .filter(r -> {\n if (r.choices() != null) {\n if (r.choices().size() == 1) {\n Delta delta = r.choices().get(0).delta();\n if (delta != null) {\n return delta.content() != null;\n }\n }\n }\n return false;\n })\n .map(r -> r.choices().get(0).delta().content())\n .filter(Objects::nonNull);\n }\n }, partialResponseHandler);\n }\n };\n }\n\n @Override\n public SyncOrAsync<EmbeddingResponse> embedding(EmbeddingRequest request) {\n return new SyncOrAsync<>() {\n @Override\n public EmbeddingResponse execute() {\n return restApi.blockingEmbedding(request,\n OpenAiRestApi.ApiMetadata.builder()\n .apiKey(apiKey)\n .apiVersion(apiVersion)\n .organizationId(organizationId)\n .build());\n }\n\n @Override\n public AsyncResponseHandling onResponse(Consumer<EmbeddingResponse> responseHandler) {\n return new AsyncResponseHandlingImpl<>(\n new Supplier<>() {\n @Override\n public Uni<EmbeddingResponse> get() {\n return restApi.embedding(request,\n OpenAiRestApi.ApiMetadata.builder()\n .apiKey(apiKey)\n .apiVersion(apiVersion)\n .organizationId(organizationId)\n .build());\n }\n },\n responseHandler);\n }\n };\n }\n\n @Override\n public SyncOrAsync<List<Float>> embedding(String input) {\n EmbeddingRequest request = EmbeddingRequest.builder()\n .input(input)\n .build();\n return new SyncOrAsync<>() {\n @Override\n public List<Float> execute() {\n return restApi.blockingEmbedding(request,\n OpenAiRestApi.ApiMetadata.builder()\n .apiKey(apiKey)\n .apiVersion(apiVersion)\n .organizationId(organizationId)\n .build())\n .embedding();\n }\n\n @Override\n public AsyncResponseHandling onResponse(Consumer<List<Float>> responseHandler) {\n return new AsyncResponseHandlingImpl<>(\n new Supplier<>() {\n @Override\n public Uni<List<Float>> get() {\n return restApi.embedding(request,\n OpenAiRestApi.ApiMetadata.builder()\n .apiKey(apiKey)\n .apiVersion(apiVersion)\n .organizationId(organizationId)\n .build())\n .map(EmbeddingResponse::embedding);\n }\n },\n responseHandler);\n }\n };\n }\n\n @Override\n public SyncOrAsync<ModerationResponse> moderation(ModerationRequest request) {\n return new SyncOrAsync<>() {\n @Override\n public ModerationResponse execute() {\n return restApi.blockingModeration(request,\n OpenAiRestApi.ApiMetadata.builder()\n .apiKey(apiKey)\n .apiVersion(apiVersion)\n .organizationId(organizationId)\n .build());\n }\n\n @Override\n public AsyncResponseHandling onResponse(Consumer<ModerationResponse> responseHandler) {\n return new AsyncResponseHandlingImpl<>(\n new Supplier<>() {\n @Override\n public Uni<ModerationResponse> get() {\n return restApi.moderation(request,\n OpenAiRestApi.ApiMetadata.builder()\n .apiKey(apiKey)\n .apiVersion(apiVersion)\n .organizationId(organizationId)\n .build());\n }\n },\n responseHandler);\n }\n };\n }\n\n @Override\n public SyncOrAsync<ModerationResult> moderation(String input) {\n ModerationRequest request = ModerationRequest.builder()\n .input(input)\n .build();\n\n return new SyncOrAsync<>() {\n @Override\n public ModerationResult execute() {\n return restApi.blockingModeration(request,\n OpenAiRestApi.ApiMetadata.builder()\n .apiKey(apiKey)\n .apiVersion(apiVersion)\n .organizationId(organizationId)\n .build())\n .results().get(0);\n }\n\n @Override\n public AsyncResponseHandling onResponse(Consumer<ModerationResult> responseHandler) {\n return new AsyncResponseHandlingImpl<>(\n new Supplier<>() {\n @Override\n public Uni<ModerationResult> get() {\n return restApi.moderation(request,\n OpenAiRestApi.ApiMetadata.builder()\n .apiKey(apiKey)\n .apiVersion(apiVersion)\n .organizationId(organizationId)\n .build())\n .map(r -> r.results().get(0));\n }\n },\n responseHandler);\n }\n };\n }\n\n @Override\n public SyncOrAsync<GenerateImagesResponse> imagesGeneration(GenerateImagesRequest generateImagesRequest) {\n return new SyncOrAsync<GenerateImagesResponse>() {\n @Override\n public GenerateImagesResponse execute() {\n return restApi.blockingImagesGenerations(generateImagesRequest,\n OpenAiRestApi.ApiMetadata.builder()\n .apiKey(apiKey)\n .apiVersion(apiVersion)\n .organizationId(organizationId)\n .build());\n }\n\n @Override\n public AsyncResponseHandling onResponse(Consumer<GenerateImagesResponse> responseHandler) {\n return new AsyncResponseHandlingImpl<>(\n new Supplier<>() {\n @Override\n public Uni<GenerateImagesResponse> get() {\n return restApi.imagesGenerations(generateImagesRequest,\n OpenAiRestApi.ApiMetadata.builder()\n .apiKey(apiKey)\n .apiVersion(apiVersion)\n .organizationId(organizationId)\n .build());\n }\n },\n responseHandler);\n }\n };\n }\n\n @Override\n public void shutdown() {\n\n }\n\n public static class QuarkusOpenAiClientBuilderFactory implements OpenAiClientBuilderFactory {\n\n @Override\n public Builder get() {\n return new Builder();\n }\n }\n\n public static class Builder extends OpenAiClient.Builder<QuarkusOpenAiClient, Builder> {\n\n @Override\n public QuarkusOpenAiClient build() {\n return new QuarkusOpenAiClient(this);\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) {\n return true;\n }\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n Builder builder = (Builder) o;\n return logRequests == builder.logRequests && logResponses == builder.logResponses\n && logStreamingResponses == builder.logStreamingResponses && Objects.equals(baseUrl, builder.baseUrl)\n && Objects.equals(apiVersion, builder.apiVersion) && Objects.equals(openAiApiKey,\n builder.openAiApiKey)\n && Objects.equals(azureApiKey, builder.azureApiKey)\n && Objects.equals(organizationId, builder.organizationId)\n && Objects.equals(callTimeout, builder.callTimeout)\n && Objects.equals(connectTimeout, builder.connectTimeout)\n && Objects.equals(readTimeout, builder.readTimeout) && Objects.equals(writeTimeout,\n builder.writeTimeout)\n && Objects.equals(proxy, builder.proxy);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(baseUrl, apiVersion, openAiApiKey, azureApiKey, organizationId, callTimeout, connectTimeout,\n readTimeout,\n writeTimeout, proxy, logRequests, logResponses, logStreamingResponses);\n }\n }\n\n private static class AsyncResponseHandlingImpl<RESPONSE> implements AsyncResponseHandling {\n private final AtomicReference<Consumer<Throwable>> errorHandlerRef = new AtomicReference<>(NoopErrorHandler.INSTANCE);\n\n private final SingleResultHandling<RESPONSE> resultHandling;\n\n public AsyncResponseHandlingImpl(Supplier<Uni<RESPONSE>> uniSupplier, Consumer<RESPONSE> responseHandler) {\n resultHandling = new SingleResultHandling<>(uniSupplier, responseHandler, errorHandlerRef);\n }\n\n @Override\n public ErrorHandling onError(Consumer<Throwable> errorHandler) {\n errorHandlerRef.set(errorHandler);\n return resultHandling;\n }\n\n @Override\n public ErrorHandling ignoreErrors() {\n errorHandlerRef.set(NoopErrorHandler.INSTANCE);\n return resultHandling;\n }\n\n private static class SingleResultHandling<RESPONSE> implements ErrorHandling {\n\n private final Supplier<Uni<RESPONSE>> uniSupplier;\n private final Consumer<RESPONSE> responseHandler;\n private final AtomicReference<Consumer<Throwable>> errorHandlerRef;\n\n public SingleResultHandling(Supplier<Uni<RESPONSE>> uniSupplier, Consumer<RESPONSE> responseHandler,\n AtomicReference<Consumer<Throwable>> errorHandlerRef) {\n this.uniSupplier = uniSupplier;\n this.responseHandler = responseHandler;\n this.errorHandlerRef = errorHandlerRef;\n }\n\n @Override\n public ResponseHandle execute() {\n var cancellable = uniSupplier.get()\n .subscribe().with(responseHandler, errorHandlerRef.get());\n return new ResponseHandleImpl(cancellable);\n }\n }\n }\n\n private static class StreamingResponseHandlingImpl<RESPONSE>\n implements StreamingResponseHandling, StreamingCompletionHandling {\n\n private final AtomicReference<Runnable> completeHandlerRef = new AtomicReference<>(NoopCompleteHandler.INSTANCE);\n private final AtomicReference<Consumer<Throwable>> errorHandlerRef = new AtomicReference<>(NoopErrorHandler.INSTANCE);\n\n private final StreamingResultErrorHandling<RESPONSE> resultHandling;\n\n public StreamingResponseHandlingImpl(Supplier<Multi<RESPONSE>> multiSupplier,\n Consumer<RESPONSE> partialResponseHandler) {\n resultHandling = new StreamingResultErrorHandling<>(multiSupplier, partialResponseHandler, completeHandlerRef,\n errorHandlerRef);\n }\n\n @Override\n public StreamingCompletionHandling onComplete(Runnable streamingCompletionCallback) {\n completeHandlerRef.set(streamingCompletionCallback);\n return this;\n }\n\n @Override\n public ErrorHandling onError(Consumer<Throwable> errorHandler) {\n errorHandlerRef.set(errorHandler);\n return resultHandling;\n }\n\n @Override\n public ErrorHandling ignoreErrors() {\n errorHandlerRef.set(NoopErrorHandler.INSTANCE);\n return resultHandling;\n }\n\n private static class StreamingResultErrorHandling<RESPONSE> implements ErrorHandling {\n\n private final Supplier<Multi<RESPONSE>> multiSupplier;\n private final Consumer<RESPONSE> partialResponseHandler;\n private final AtomicReference<Runnable> completeHandlerRef;\n private final AtomicReference<Consumer<Throwable>> errorHandlerRef;\n\n public StreamingResultErrorHandling(Supplier<Multi<RESPONSE>> multiSupplier,\n Consumer<RESPONSE> partialResponseHandler, AtomicReference<Runnable> completeHandlerRef,\n AtomicReference<Consumer<Throwable>> errorHandlerRef) {\n this.multiSupplier = multiSupplier;\n this.partialResponseHandler = partialResponseHandler;\n this.completeHandlerRef = completeHandlerRef;\n this.errorHandlerRef = errorHandlerRef;\n }\n\n @Override\n public ResponseHandle execute() {\n var cancellable = multiSupplier.get()\n .subscribe()\n .with(partialResponseHandler, errorHandlerRef.get(), completeHandlerRef.get());\n return new ResponseHandleImpl(cancellable);\n }\n }\n }\n\n private static class NoopErrorHandler implements Consumer<Throwable> {\n\n private static final NoopErrorHandler INSTANCE = new NoopErrorHandler();\n\n private NoopErrorHandler() {\n }\n\n @Override\n public void accept(Throwable throwable) {\n\n }\n }\n\n private static class NoopCompleteHandler implements Runnable {\n\n private static final NoopCompleteHandler INSTANCE = new NoopCompleteHandler();\n\n private NoopCompleteHandler() {\n }\n\n @Override\n public void run() {\n\n }\n }\n\n private static class ResponseHandleImpl extends ResponseHandle {\n private final Cancellable cancellable;\n\n public ResponseHandleImpl(Cancellable cancellable) {\n this.cancellable = cancellable;\n }\n\n @Override\n public void cancel() {\n cancellable.cancel();\n }\n }\n\n}" }, { "identifier": "QuarkusOpenAiImageModel", "path": "openai/openai-vanilla/runtime/src/main/java/io/quarkiverse/langchain4j/openai/QuarkusOpenAiImageModel.java", "snippet": "@SuppressWarnings(\"OptionalUsedAsFieldOrParameterType\")\npublic class QuarkusOpenAiImageModel implements ImageModel {\n private final String modelName;\n private final String size;\n private final String quality;\n private final String style;\n private final Optional<String> user;\n private final String responseFormat;\n private final Integer maxRetries;\n private final Optional<Path> persistDirectory;\n\n private final QuarkusOpenAiClient client;\n\n public QuarkusOpenAiImageModel(String baseUrl, String apiKey, String organizationId, String modelName, String size,\n String quality, String style, Optional<String> user, String responseFormat, Duration timeout,\n Integer maxRetries, Boolean logRequests, Boolean logResponses,\n Optional<Path> persistDirectory) {\n this.modelName = modelName;\n this.size = size;\n this.quality = quality;\n this.style = style;\n this.user = user;\n this.responseFormat = responseFormat;\n this.maxRetries = maxRetries;\n this.persistDirectory = persistDirectory;\n\n this.client = QuarkusOpenAiClient.builder()\n .baseUrl(baseUrl)\n .openAiApiKey(apiKey)\n .organizationId(organizationId)\n .callTimeout(timeout)\n .connectTimeout(timeout)\n .readTimeout(timeout)\n .writeTimeout(timeout)\n .logRequests(logRequests)\n .logResponses(logResponses)\n .build();\n }\n\n @Override\n public Response<Image> generate(String prompt) {\n GenerateImagesRequest request = requestBuilder(prompt).build();\n\n GenerateImagesResponse response = withRetry(() -> client.imagesGeneration(request), maxRetries).execute();\n persistIfNecessary(response);\n\n return Response.from(fromImageData(response.data().get(0)));\n }\n\n @Override\n public Response<List<Image>> generate(String prompt, int n) {\n GenerateImagesRequest request = requestBuilder(prompt).n(n).build();\n\n GenerateImagesResponse response = withRetry(() -> client.imagesGeneration(request), maxRetries).execute();\n persistIfNecessary(response);\n\n return Response.from(\n response.data().stream().map(QuarkusOpenAiImageModel::fromImageData).collect(Collectors.toList()));\n }\n\n private void persistIfNecessary(GenerateImagesResponse response) {\n if (persistDirectory.isEmpty()) {\n return;\n }\n Path persistTo = persistDirectory.get();\n try {\n Files.createDirectories(persistTo);\n } catch (IOException e) {\n throw new UncheckedIOException(e);\n }\n for (GenerateImagesResponse.ImageData data : response.data()) {\n try {\n data.url(\n data.url() != null\n ? FilePersistor.persistFromUri(data.url(), persistTo).toUri()\n : FilePersistor.persistFromBase64String(data.b64Json(), persistTo).toUri());\n } catch (IOException e) {\n throw new UncheckedIOException(e);\n }\n }\n }\n\n private static Image fromImageData(GenerateImagesResponse.ImageData data) {\n return Image.builder().url(data.url()).base64Data(data.b64Json()).revisedPrompt(data.revisedPrompt()).build();\n }\n\n private GenerateImagesRequest.Builder requestBuilder(String prompt) {\n var builder = GenerateImagesRequest\n .builder()\n .prompt(prompt)\n .size(size)\n .quality(quality)\n .style(style)\n .responseFormat(responseFormat);\n\n if (DALL_E_2.equals(modelName)) {\n builder.model(dev.ai4j.openai4j.image.ImageModel.DALL_E_2);\n }\n if (user.isPresent()) {\n builder.user(user.get());\n }\n\n return builder;\n }\n\n public static Builder builder() {\n return new Builder();\n }\n\n public static class Builder {\n private String baseUrl;\n private String apiKey;\n private String organizationId;\n private String modelName;\n private String size;\n private String quality;\n private String style;\n private Optional<String> user;\n private String responseFormat;\n private Duration timeout;\n private Integer maxRetries;\n private Boolean logRequests;\n private Boolean logResponses;\n private Optional<Path> persistDirectory;\n\n public Builder baseUrl(String baseUrl) {\n this.baseUrl = baseUrl;\n return this;\n }\n\n public Builder apiKey(String apiKey) {\n this.apiKey = apiKey;\n return this;\n }\n\n public Builder organizationId(String organizationId) {\n this.organizationId = organizationId;\n return this;\n }\n\n public Builder timeout(Duration timeout) {\n this.timeout = timeout;\n return this;\n }\n\n public Builder maxRetries(Integer maxRetries) {\n this.maxRetries = maxRetries;\n return this;\n }\n\n public Builder logRequests(Boolean logRequests) {\n this.logRequests = logRequests;\n return this;\n }\n\n public Builder logResponses(Boolean logResponses) {\n this.logResponses = logResponses;\n return this;\n }\n\n public Builder modelName(String modelName) {\n this.modelName = modelName;\n return this;\n }\n\n public Builder size(String size) {\n this.size = size;\n return this;\n }\n\n public Builder quality(String quality) {\n this.quality = quality;\n return this;\n }\n\n public Builder style(String style) {\n this.style = style;\n return this;\n }\n\n public Builder user(Optional<String> user) {\n this.user = user;\n return this;\n }\n\n public Builder responseFormat(String responseFormat) {\n this.responseFormat = responseFormat;\n return this;\n }\n\n public Builder persistDirectory(Optional<Path> persistDirectory) {\n this.persistDirectory = persistDirectory;\n return this;\n }\n\n public QuarkusOpenAiImageModel build() {\n return new QuarkusOpenAiImageModel(baseUrl, apiKey, organizationId, modelName, size, quality, style, user,\n responseFormat, timeout, maxRetries, logRequests, logResponses,\n persistDirectory);\n }\n }\n\n /**\n * Copied from {@code dev.ai4j.openai4j.FilePersistor}\n */\n private static class FilePersistor {\n\n static Path persistFromUri(URI uri, Path destinationFolder) {\n try {\n Path fileName = Paths.get(uri.getPath()).getFileName();\n Path destinationFilePath = destinationFolder.resolve(fileName);\n try (InputStream inputStream = uri.toURL().openStream()) {\n java.nio.file.Files.copy(inputStream, destinationFilePath, StandardCopyOption.REPLACE_EXISTING);\n }\n\n return destinationFilePath;\n } catch (IOException e) {\n throw new RuntimeException(\"Error persisting file from URI: \" + uri, e);\n }\n }\n\n public static Path persistFromBase64String(String base64EncodedString, Path destinationFolder) throws IOException {\n byte[] decodedBytes = Base64.getDecoder().decode(base64EncodedString);\n Path destinationFile = destinationFolder.resolve(randomFileName());\n\n Files.write(destinationFile, decodedBytes, StandardOpenOption.CREATE);\n\n return destinationFile;\n }\n\n private static String randomFileName() {\n return UUID.randomUUID().toString().replaceAll(\"-\", \"\").substring(0, 20);\n }\n }\n}" }, { "identifier": "ChatModelConfig", "path": "openai/openai-vanilla/runtime/src/main/java/io/quarkiverse/langchain4j/openai/runtime/config/ChatModelConfig.java", "snippet": "@ConfigGroup\npublic interface ChatModelConfig {\n\n /**\n * Model name to use\n */\n @WithDefault(\"gpt-3.5-turbo\")\n String modelName();\n\n /**\n * What sampling temperature to use, with values between 0 and 2.\n * Higher values means the model will take more risks.\n * A value of 0.9 is good for more creative applications, while 0 (argmax sampling) is good for ones with a well-defined\n * answer.\n * It is recommended to alter this or topP, but not both.\n */\n @WithDefault(\"1.0\")\n Double temperature();\n\n /**\n * An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens\n * with topP probability mass.\n * 0.1 means only the tokens comprising the top 10% probability mass are considered.\n * It is recommended to alter this or topP, but not both.\n */\n @WithDefault(\"1.0\")\n Double topP();\n\n /**\n * The maximum number of tokens to generate in the completion. The token count of your prompt plus max_tokens can't exceed\n * the model's context length.\n * Most models have a context length of 2048 tokens (except for the newest models, which support 4096).\n */\n Optional<Integer> maxTokens();\n\n /**\n * Number between -2.0 and 2.0.\n * Positive values penalize new tokens based on whether they appear in the text so far, increasing the model's likelihood to\n * talk about new topics.\n */\n @WithDefault(\"0\")\n Double presencePenalty();\n\n /**\n * Number between -2.0 and 2.0.\n * Positive values penalize new tokens based on their existing frequency in the text so far, decreasing the model's\n * likelihood to repeat the same line verbatim.\n */\n @WithDefault(\"0\")\n Double frequencyPenalty();\n\n /**\n * Whether chat model requests should be logged\n */\n @ConfigDocDefault(\"false\")\n Optional<Boolean> logRequests();\n\n /**\n * Whether chat model responses should be logged\n */\n @ConfigDocDefault(\"false\")\n Optional<Boolean> logResponses();\n}" }, { "identifier": "EmbeddingModelConfig", "path": "openai/openai-vanilla/runtime/src/main/java/io/quarkiverse/langchain4j/openai/runtime/config/EmbeddingModelConfig.java", "snippet": "@ConfigGroup\npublic interface EmbeddingModelConfig {\n\n /**\n * Model name to use\n */\n @WithDefault(\"text-embedding-ada-002\")\n String modelName();\n\n /**\n * Whether embedding model requests should be logged\n */\n @ConfigDocDefault(\"false\")\n Optional<Boolean> logRequests();\n\n /**\n * Whether embedding model responses should be logged\n */\n @ConfigDocDefault(\"false\")\n Optional<Boolean> logResponses();\n\n /**\n * A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse.\n */\n Optional<String> user();\n}" }, { "identifier": "ImageModelConfig", "path": "openai/openai-vanilla/runtime/src/main/java/io/quarkiverse/langchain4j/openai/runtime/config/ImageModelConfig.java", "snippet": "@ConfigGroup\npublic interface ImageModelConfig {\n\n /**\n * Model name to use\n */\n @WithDefault(\"dall-e-3\")\n String modelName();\n\n /**\n * Configure whether the generated images will be saved to disk.\n * By default, persisting is disabled, but it is implicitly enabled when\n * {@code quarkus.langchain4j.openai.image-mode.directory} is set and this property is not to {@code false}\n */\n @ConfigDocDefault(\"false\")\n Optional<Boolean> persist();\n\n /**\n * The path where the generated images will be persisted to disk.\n * This only applies of {@code quarkus.langchain4j.openai.image-mode.persist} is not set to {@code false}.\n */\n @ConfigDocDefault(\"${java.io.tmpdir}/dall-e-images\")\n Optional<Path> persistDirectory();\n\n /**\n * The format in which the generated images are returned.\n * <p>\n * Must be one of {@code url} or {@code b64_json}\n */\n @WithDefault(\"url\")\n String responseFormat();\n\n /**\n * The size of the generated images.\n * <p>\n * Must be one of {@code 1024x1024}, {@code 1792x1024}, or {@code 1024x1792} when the model is {@code dall-e-3}.\n * <p>\n * Must be one of {@code 256x256}, {@code 512x512}, or {@code 1024x1024} when the model is {@code dall-e-2}.\n */\n @WithDefault(\"1024x1024\")\n String size();\n\n /**\n * The quality of the image that will be generated.\n * <p>\n * {@code hd} creates images with finer details and greater consistency across the image.\n * <p>\n * This param is only supported for when the model is {@code dall-e-3}.\n */\n @WithDefault(\"standard\")\n String quality();\n\n /**\n * The number of images to generate.\n * <p>\n * Must be between 1 and 10.\n * <p>\n * When the model is dall-e-3, only n=1 is supported.\n */\n @WithDefault(\"1\")\n int number();\n\n /**\n * The style of the generated images.\n * <p>\n * Must be one of {@code vivid} or {@code natural}. Vivid causes the model to lean towards generating hyper-real and\n * dramatic images. Natural causes the model to produce more natural, less hyper-real looking images.\n * <p>\n * This param is only supported for when the model is {@code dall-e-3}.\n */\n @WithDefault(\"vivid\")\n String style();\n\n /**\n * A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse.\n */\n Optional<String> user();\n\n /**\n * Whether image model requests should be logged\n */\n @ConfigDocDefault(\"false\")\n Optional<Boolean> logRequests();\n\n /**\n * Whether image model responses should be logged\n */\n @ConfigDocDefault(\"false\")\n Optional<Boolean> logResponses();\n}" }, { "identifier": "Langchain4jOpenAiConfig", "path": "openai/openai-vanilla/runtime/src/main/java/io/quarkiverse/langchain4j/openai/runtime/config/Langchain4jOpenAiConfig.java", "snippet": "@ConfigRoot(phase = RUN_TIME)\n@ConfigMapping(prefix = \"quarkus.langchain4j.openai\")\npublic interface Langchain4jOpenAiConfig {\n\n /**\n * Base URL of OpenAI API\n */\n @WithDefault(\"https://api.openai.com/v1/\")\n String baseUrl();\n\n /**\n * OpenAI API key\n */\n Optional<String> apiKey();\n\n /**\n * OpenAI Organization ID (https://platform.openai.com/docs/api-reference/organization-optional)\n */\n Optional<String> organizationId();\n\n /**\n * Timeout for OpenAI calls\n */\n @WithDefault(\"10s\")\n Duration timeout();\n\n /**\n * The maximum number of times to retry\n */\n @WithDefault(\"3\")\n Integer maxRetries();\n\n /**\n * Whether the OpenAI client should log requests\n */\n @ConfigDocDefault(\"false\")\n Optional<Boolean> logRequests();\n\n /**\n * Whether the OpenAI client should log responses\n */\n @ConfigDocDefault(\"false\")\n Optional<Boolean> logResponses();\n\n /**\n * Chat model related settings\n */\n ChatModelConfig chatModel();\n\n /**\n * Embedding model related settings\n */\n EmbeddingModelConfig embeddingModel();\n\n /**\n * Moderation model related settings\n */\n ModerationModelConfig moderationModel();\n\n /**\n * Image model related settings\n */\n ImageModelConfig imageModel();\n}" }, { "identifier": "ModerationModelConfig", "path": "openai/openai-vanilla/runtime/src/main/java/io/quarkiverse/langchain4j/openai/runtime/config/ModerationModelConfig.java", "snippet": "@ConfigGroup\npublic interface ModerationModelConfig {\n\n /**\n * Model name to use\n */\n @WithDefault(\"text-moderation-latest\")\n String modelName();\n\n /**\n * Whether moderation model requests should be logged\n */\n @ConfigDocDefault(\"false\")\n Optional<Boolean> logRequests();\n\n /**\n * Whether moderation model responses should be logged\n */\n @ConfigDocDefault(\"false\")\n Optional<Boolean> logResponses();\n}" } ]
import static io.quarkiverse.langchain4j.runtime.OptionalUtil.firstOrDefault; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Optional; import java.util.function.Supplier; import dev.langchain4j.model.openai.OpenAiChatModel; import dev.langchain4j.model.openai.OpenAiEmbeddingModel; import dev.langchain4j.model.openai.OpenAiModerationModel; import dev.langchain4j.model.openai.OpenAiStreamingChatModel; import io.quarkiverse.langchain4j.openai.QuarkusOpenAiClient; import io.quarkiverse.langchain4j.openai.QuarkusOpenAiImageModel; import io.quarkiverse.langchain4j.openai.runtime.config.ChatModelConfig; import io.quarkiverse.langchain4j.openai.runtime.config.EmbeddingModelConfig; import io.quarkiverse.langchain4j.openai.runtime.config.ImageModelConfig; import io.quarkiverse.langchain4j.openai.runtime.config.Langchain4jOpenAiConfig; import io.quarkiverse.langchain4j.openai.runtime.config.ModerationModelConfig; import io.quarkus.runtime.ShutdownContext; import io.quarkus.runtime.annotations.Recorder; import io.smallrye.config.ConfigValidationException;
9,113
package io.quarkiverse.langchain4j.openai.runtime; @Recorder public class OpenAiRecorder { public Supplier<?> chatModel(Langchain4jOpenAiConfig runtimeConfig) { Optional<String> apiKeyOpt = runtimeConfig.apiKey(); if (apiKeyOpt.isEmpty()) { throw new ConfigValidationException(createApiKeyConfigProblems()); } ChatModelConfig chatModelConfig = runtimeConfig.chatModel(); var builder = OpenAiChatModel.builder() .baseUrl(runtimeConfig.baseUrl()) .apiKey(apiKeyOpt.get()) .timeout(runtimeConfig.timeout()) .maxRetries(runtimeConfig.maxRetries())
package io.quarkiverse.langchain4j.openai.runtime; @Recorder public class OpenAiRecorder { public Supplier<?> chatModel(Langchain4jOpenAiConfig runtimeConfig) { Optional<String> apiKeyOpt = runtimeConfig.apiKey(); if (apiKeyOpt.isEmpty()) { throw new ConfigValidationException(createApiKeyConfigProblems()); } ChatModelConfig chatModelConfig = runtimeConfig.chatModel(); var builder = OpenAiChatModel.builder() .baseUrl(runtimeConfig.baseUrl()) .apiKey(apiKeyOpt.get()) .timeout(runtimeConfig.timeout()) .maxRetries(runtimeConfig.maxRetries())
.logRequests(firstOrDefault(false, chatModelConfig.logRequests(), runtimeConfig.logRequests()))
0
2023-11-13 09:10:27+00:00
12k
qiusunshine/xiu
clinglibrary/src/main/java/org/fourthline/cling/android/AndroidUpnpServiceImpl.java
[ { "identifier": "UpnpService", "path": "clinglibrary/src/main/java/org/fourthline/cling/UpnpService.java", "snippet": "public interface UpnpService {\n\n public UpnpServiceConfiguration getConfiguration();\n\n public ControlPoint getControlPoint();\n\n public ProtocolFactory getProtocolFactory();\n\n public Registry getRegistry();\n\n public Router getRouter();\n\n /**\n * Stopping the UPnP stack.\n * <p>\n * Clients are required to stop the UPnP stack properly. Notifications for\n * disappearing devices will be multicast'ed, existing event subscriptions cancelled.\n * </p>\n */\n public void shutdown();\n\n static public class Start {\n\n }\n\n static public class Shutdown {\n\n }\n\n}" }, { "identifier": "UpnpServiceConfiguration", "path": "clinglibrary/src/main/java/org/fourthline/cling/UpnpServiceConfiguration.java", "snippet": "public interface UpnpServiceConfiguration {\n\n /**\n * @return A new instance of the {@link org.fourthline.cling.transport.spi.NetworkAddressFactory} interface.\n */\n public NetworkAddressFactory createNetworkAddressFactory();\n\n /**\n * @return The shared implementation of {@link org.fourthline.cling.transport.spi.DatagramProcessor}.\n */\n public DatagramProcessor getDatagramProcessor();\n\n /**\n * @return The shared implementation of {@link org.fourthline.cling.transport.spi.SOAPActionProcessor}.\n */\n public SOAPActionProcessor getSoapActionProcessor();\n\n /**\n * @return The shared implementation of {@link org.fourthline.cling.transport.spi.GENAEventProcessor}.\n */\n public GENAEventProcessor getGenaEventProcessor();\n\n /**\n * @return A new instance of the {@link org.fourthline.cling.transport.spi.StreamClient} interface.\n */\n public StreamClient createStreamClient();\n\n /**\n * @param networkAddressFactory The configured {@link org.fourthline.cling.transport.spi.NetworkAddressFactory}.\n * @return A new instance of the {@link org.fourthline.cling.transport.spi.MulticastReceiver} interface.\n */\n public MulticastReceiver createMulticastReceiver(NetworkAddressFactory networkAddressFactory);\n\n /**\n * @param networkAddressFactory The configured {@link org.fourthline.cling.transport.spi.NetworkAddressFactory}.\n * @return A new instance of the {@link org.fourthline.cling.transport.spi.DatagramIO} interface.\n */\n public DatagramIO createDatagramIO(NetworkAddressFactory networkAddressFactory);\n\n /**\n * @param networkAddressFactory The configured {@link org.fourthline.cling.transport.spi.NetworkAddressFactory}.\n * @return A new instance of the {@link org.fourthline.cling.transport.spi.StreamServer} interface.\n */\n public StreamServer createStreamServer(NetworkAddressFactory networkAddressFactory);\n\n /**\n * @return The executor which runs the listening background threads for multicast datagrams.\n */\n public Executor getMulticastReceiverExecutor();\n\n /**\n * @return The executor which runs the listening background threads for unicast datagrams.\n */\n public Executor getDatagramIOExecutor();\n\n /**\n * @return The executor which runs the listening background threads for HTTP requests.\n */\n public ExecutorService getStreamServerExecutorService();\n\n /**\n * @return The shared implementation of {@link org.fourthline.cling.binding.xml.DeviceDescriptorBinder} for the UPnP 1.0 Device Architecture..\n */\n public DeviceDescriptorBinder getDeviceDescriptorBinderUDA10();\n\n /**\n * @return The shared implementation of {@link org.fourthline.cling.binding.xml.ServiceDescriptorBinder} for the UPnP 1.0 Device Architecture..\n */\n public ServiceDescriptorBinder getServiceDescriptorBinderUDA10();\n\n /**\n * Returns service types that can be handled by this UPnP stack, all others will be ignored.\n * <p>\n * Return <code>null</code> to completely disable remote device and service discovery.\n * All incoming notifications and search responses will then be dropped immediately.\n * This is mostly useful in applications that only provide services with no (remote)\n * control point functionality.\n * </p>\n * <p>\n * Note that a discovered service type with version 2 or 3 will match an exclusive\n * service type with version 1. UPnP services are required to be backwards\n * compatible, version 2 is a superset of version 1, and version 3 is a superset\n * of version 2, etc.\n * </p>\n *\n * @return An array of service types that are exclusively discovered, no other service will\n * be discovered. A <code>null</code> return value will disable discovery!\n * An empty array means all services will be discovered.\n */\n public ServiceType[] getExclusiveServiceTypes();\n\n /**\n * @return The time in milliseconds to wait between each registry maintenance operation.\n */\n public int getRegistryMaintenanceIntervalMillis();\n \n /**\n * Optional setting for flooding alive NOTIFY messages for local devices.\n * <p>\n * Use this to advertise local devices at the specified interval, independent of its\n * {@link org.fourthline.cling.model.meta.DeviceIdentity#maxAgeSeconds} value. Note\n * that this will increase network traffic.\n * </p>\n * <p>\n * Some control points (XBMC and other Platinum UPnP SDK based devices, OPPO-93) seem\n * to not properly receive SSDP M-SEARCH replies sent by Cling, but will handle NOTIFY\n * alive messages just fine.\n * </p>\n *\n * @return The time in milliseconds for ALIVE message intervals, set to <code>0</code> to disable\n */\n public int getAliveIntervalMillis();\n\n /**\n * Ignore the received event subscription timeout from remote control points.\n * <p>\n * Some control points have trouble renewing subscriptions properly; enabling this option\n * in conjunction with a high value for\n * {@link org.fourthline.cling.model.UserConstants#DEFAULT_SUBSCRIPTION_DURATION_SECONDS}\n * ensures that your devices will not disappear on such control points.\n * </p>\n *\n * @return <code>true</code> if the timeout in incoming event subscriptions should be ignored\n * and the default value ({@link org.fourthline.cling.model.UserConstants#DEFAULT_SUBSCRIPTION_DURATION_SECONDS})\n * should be used instead.\n *\n */\n public boolean isReceivedSubscriptionTimeoutIgnored();\n\n /**\n * Returns the time in seconds a remote device will be registered until it is expired.\n * <p>\n * This setting is useful on systems which do not support multicast networking\n * (Android on HTC phones, for hiker). On such a system you will not receive messages when a\n * remote device disappears from the network and you will not receive its periodic heartbeat\n * alive messages. Only an initial search response (UDP unicast) has been received from the\n * remote device, with its proposed maximum age. To avoid (early) expiration of the remote\n * device, you can override its maximum age with this configuration setting, ignoring the\n * initial maximum age sent by the device. You most likely want to return\n * <code>0</code> in this case, so that the remote device is never expired unless you\n * manually remove it from the {@link org.fourthline.cling.registry.Registry}. You typically remove\n * the device when an action or GENA subscription request to the remote device failed.\n * </p>\n *\n * @return <code>null</code> (the default) to accept the remote device's proposed maximum age, or\n * <code>0</code> for unlimited age, or a value in seconds.\n */\n public Integer getRemoteDeviceMaxAgeSeconds();\n\n /**\n * Optional extra headers for device descriptor retrieval HTTP requests.\n * <p>\n * Some devices might require extra headers to recognize your control point, use this\n * method to set these headers. They will be used for every descriptor (XML) retrieval\n * HTTP request by Cling. See {@link org.fourthline.cling.model.profile.ClientInfo} for\n * action request messages.\n * </p>\n *\n * @param identity The (so far) discovered identity of the remote device.\n * @return <code>null</code> or extra HTTP headers.\n */\n public UpnpHeaders getDescriptorRetrievalHeaders(RemoteDeviceIdentity identity);\n\n /**\n * Optional extra headers for event subscription (almost HTTP) messages.\n * <p>\n * Some devices might require extra headers to recognize your control point, use this\n * method to set these headers for GENA subscriptions. Note that the headers will\n * not be applied to actual event messages, only subscribe, unsubscribe, and renewal.\n * </p>\n *\n * @return <code>null</code> or extra HTTP headers.\n */\n public UpnpHeaders getEventSubscriptionHeaders(RemoteService service);\n\n /**\n * @return The executor which runs the processing of asynchronous aspects of the UPnP stack (discovery).\n */\n public Executor getAsyncProtocolExecutor();\n\n /**\n * @return The executor service which runs the processing of synchronous aspects of the UPnP stack (description, control, GENA).\n */\n public ExecutorService getSyncProtocolExecutorService();\n\n /**\n * @return An instance of {@link org.fourthline.cling.model.Namespace} for this UPnP stack.\n */\n public Namespace getNamespace();\n\n /**\n * @return The executor which runs the background thread for maintaining the registry.\n */\n public Executor getRegistryMaintainerExecutor();\n\n /**\n * @return The executor which runs the notification threads of registry listeners.\n */\n public Executor getRegistryListenerExecutor();\n\n /**\n * Called by the {@link org.fourthline.cling.UpnpService} on shutdown, useful to e.g. shutdown thread pools.\n */\n public void shutdown();\n\n}" }, { "identifier": "UpnpServiceImpl", "path": "clinglibrary/src/main/java/org/fourthline/cling/UpnpServiceImpl.java", "snippet": "@Alternative\npublic class UpnpServiceImpl implements UpnpService {\n\n private static Logger log = Logger.getLogger(UpnpServiceImpl.class.getName());\n\n protected final UpnpServiceConfiguration configuration;\n protected final ControlPoint controlPoint;\n protected final ProtocolFactory protocolFactory;\n protected final Registry registry;\n protected final Router router;\n\n public UpnpServiceImpl() {\n this(new DefaultUpnpServiceConfiguration());\n }\n\n public UpnpServiceImpl(RegistryListener... registryListeners) {\n this(new DefaultUpnpServiceConfiguration(), registryListeners);\n }\n\n public UpnpServiceImpl(UpnpServiceConfiguration configuration, RegistryListener... registryListeners) {\n this.configuration = configuration;\n\n log.info(\">>> Starting UPnP service...\");\n\n log.info(\"Using configuration: \" + getConfiguration().getClass().getName());\n\n // Instantiation order is important: Router needs to start its network services after registry is ready\n\n this.protocolFactory = createProtocolFactory();\n\n this.registry = createRegistry(protocolFactory);\n for (RegistryListener registryListener : registryListeners) {\n this.registry.addListener(registryListener);\n }\n\n this.router = createRouter(protocolFactory, registry);\n\n try {\n this.router.enable();\n } catch (RouterException ex) {\n throw new RuntimeException(\"Enabling network router failed: \" + ex, ex);\n }\n\n this.controlPoint = createControlPoint(protocolFactory, registry);\n\n log.info(\"<<< UPnP service started successfully\");\n }\n\n protected ProtocolFactory createProtocolFactory() {\n return new ProtocolFactoryImpl(this);\n }\n\n protected Registry createRegistry(ProtocolFactory protocolFactory) {\n return new RegistryImpl(this);\n }\n\n protected Router createRouter(ProtocolFactory protocolFactory, Registry registry) {\n return new RouterImpl(getConfiguration(), protocolFactory);\n }\n\n protected ControlPoint createControlPoint(ProtocolFactory protocolFactory, Registry registry) {\n return new ControlPointImpl(getConfiguration(), protocolFactory, registry);\n }\n\n public UpnpServiceConfiguration getConfiguration() {\n return configuration;\n }\n\n public ControlPoint getControlPoint() {\n return controlPoint;\n }\n\n public ProtocolFactory getProtocolFactory() {\n return protocolFactory;\n }\n\n public Registry getRegistry() {\n return registry;\n }\n\n public Router getRouter() {\n return router;\n }\n\n synchronized public void shutdown() {\n shutdown(false);\n }\n\n protected void shutdown(boolean separateThread) {\n Runnable shutdown = new Runnable() {\n @Override\n public void run() {\n log.info(\">>> Shutting down UPnP service...\");\n shutdownRegistry();\n shutdownRouter();\n shutdownConfiguration();\n log.info(\"<<< UPnP service shutdown completed\");\n }\n };\n if (separateThread) {\n // This is not a daemon thread, it has to complete!\n new Thread(shutdown).start();\n } else {\n shutdown.run();\n }\n }\n\n protected void shutdownRegistry() {\n getRegistry().shutdown();\n }\n\n protected void shutdownRouter() {\n try {\n getRouter().shutdown();\n } catch (RouterException ex) {\n Throwable cause = Exceptions.unwrap(ex);\n if (cause instanceof InterruptedException) {\n log.log(Level.INFO, \"Router shutdown was interrupted: \" + ex, cause);\n } else {\n log.log(Level.SEVERE, \"Router error on shutdown: \" + ex, cause);\n }\n }\n }\n\n protected void shutdownConfiguration() {\n getConfiguration().shutdown();\n }\n\n}" }, { "identifier": "ControlPoint", "path": "clinglibrary/src/main/java/org/fourthline/cling/controlpoint/ControlPoint.java", "snippet": "public interface ControlPoint {\n\n public UpnpServiceConfiguration getConfiguration();\n public ProtocolFactory getProtocolFactory();\n public Registry getRegistry();\n\n public void search();\n public void search(UpnpHeader searchType);\n public void search(int mxSeconds);\n public void search(UpnpHeader searchType, int mxSeconds);\n public Future execute(ActionCallback callback);\n public void execute(SubscriptionCallback callback);\n\n}" }, { "identifier": "ProtocolFactory", "path": "clinglibrary/src/main/java/org/fourthline/cling/protocol/ProtocolFactory.java", "snippet": "public interface ProtocolFactory {\n\n public UpnpService getUpnpService();\n\n /**\n * Creates a {@link org.fourthline.cling.protocol.async.ReceivingNotification},\n * {@link org.fourthline.cling.protocol.async.ReceivingSearch},\n * or {@link org.fourthline.cling.protocol.async.ReceivingSearchResponse} protocol.\n *\n * @param message The incoming message, either {@link org.fourthline.cling.model.message.UpnpRequest} or\n * {@link org.fourthline.cling.model.message.UpnpResponse}.\n * @return The appropriate protocol that handles the messages or <code>null</code> if the message should be dropped.\n * @throws ProtocolCreationException If no protocol could be found for the message.\n */\n public ReceivingAsync createReceivingAsync(IncomingDatagramMessage message) throws ProtocolCreationException;\n\n /**\n * Creates a {@link org.fourthline.cling.protocol.sync.ReceivingRetrieval},\n * {@link org.fourthline.cling.protocol.sync.ReceivingAction},\n * {@link org.fourthline.cling.protocol.sync.ReceivingSubscribe},\n * {@link org.fourthline.cling.protocol.sync.ReceivingUnsubscribe}, or\n * {@link org.fourthline.cling.protocol.sync.ReceivingEvent} protocol.\n *\n * @param requestMessage The incoming message, examime {@link org.fourthline.cling.model.message.UpnpRequest.Method}\n * to determine the protocol.\n * @return The appropriate protocol that handles the messages.\n * @throws ProtocolCreationException If no protocol could be found for the message.\n */\n public ReceivingSync createReceivingSync(StreamRequestMessage requestMessage) throws ProtocolCreationException;\n\n /**\n * Called by the {@link org.fourthline.cling.registry.Registry}, creates a protocol for announcing local devices.\n */\n public SendingNotificationAlive createSendingNotificationAlive(LocalDevice localDevice);\n\n /**\n * Called by the {@link org.fourthline.cling.registry.Registry}, creates a protocol for announcing local devices.\n */\n public SendingNotificationByebye createSendingNotificationByebye(LocalDevice localDevice);\n\n /**\n * Called by the {@link org.fourthline.cling.controlpoint.ControlPoint}, creates a protocol for a multicast search.\n */\n public SendingSearch createSendingSearch(UpnpHeader searchTarget, int mxSeconds);\n\n /**\n * Called by the {@link org.fourthline.cling.controlpoint.ControlPoint}, creates a protocol for executing an action.\n */\n public SendingAction createSendingAction(ActionInvocation actionInvocation, URL controlURL);\n\n /**\n * Called by the {@link org.fourthline.cling.controlpoint.ControlPoint}, creates a protocol for GENA subscription.\n */\n public SendingSubscribe createSendingSubscribe(RemoteGENASubscription subscription) throws ProtocolCreationException;\n\n /**\n * Called by the {@link org.fourthline.cling.controlpoint.ControlPoint}, creates a protocol for GENA renewal.\n */\n public SendingRenewal createSendingRenewal(RemoteGENASubscription subscription);\n\n /**\n * Called by the {@link org.fourthline.cling.controlpoint.ControlPoint}, creates a protocol for GENA unsubscription.\n */\n public SendingUnsubscribe createSendingUnsubscribe(RemoteGENASubscription subscription);\n\n /**\n * Called by the {@link org.fourthline.cling.model.gena.GENASubscription}, creates a protocol for sending GENA events.\n */\n public SendingEvent createSendingEvent(LocalGENASubscription subscription);\n}" }, { "identifier": "Registry", "path": "clinglibrary/src/main/java/org/fourthline/cling/registry/Registry.java", "snippet": "public interface Registry {\n\n public UpnpService getUpnpService();\n public UpnpServiceConfiguration getConfiguration();\n public ProtocolFactory getProtocolFactory();\n\n // #################################################################################################\n\n /**\n * Typically called internally when the UPnP stack is stopping.\n * <p>\n * Unsubscribe all local devices and GENA subscriptions.\n * </p>\n */\n public void shutdown();\n\n /**\n * Stops background maintenance (thread) of registered items.\n * <p>\n * When paused, the registry will no longer remove expired remote devices if their\n * discovery announcements stop for some reason (device was turned off). Your local\n * control point will now see potentially unavailable remote devices. Outbound\n * GENA subscriptions from your local control point to remote services will not\n * be renewed automatically anymore, a remote service might drop your subscriptions\n * if you don't resume maintenance within the subscription's expiration timeout.\n * </p>\n * <p>\n * Local devices and services will not be announced periodically anymore to remote\n * control points, only when they are manually added are removed from the registry.\n * The registry will also no longer remove expired inbound GENA subscriptions to\n * local service from remote control points, if that control point for some reason\n * stops sending subscription renewal messages.\n * </p>\n */\n public void pause();\n\n /**\n * Resumes background maintenance (thread) of registered items.\n * <p>\n * A local control point has to handle the following situations when resuming\n * registry maintenance:\n * <p>\n * A remote device registration might have expired. This is the case when the remote\n * device stopped sending announcements while the registry was paused (maybe because\n * the device was switched off) and the registry was paused longer than the device\n * advertisement's maximum age. The registry will not know if the device is still\n * available when it resumes maintenance. However, it will simply assume that the\n * remote device is still available and restart its expiration check cycle. That means\n * a device will finally be removed from the registry, if no further announcements\n * from the device are received, when the maximum age of the device has elapsed\n * after the registry resumed operation.\n * </p>\n * <p>\n * Secondly, a remote device registration might not have expired but some of your\n * outbound GENA subscriptions to its services have not been renewed within the expected renewal\n * period. Therefore your outbound subscriptions might be invalid, because the remote\n * service can drop subscriptions when you don't renew them. On resume, the registry\n * will attempt to send renewals for all outbound GENA subscriptions that require\n * renewal, on devices that still haven't expired. If renewal fails, your subscription will\n * end with {@link org.fourthline.cling.model.gena.CancelReason#RENEWAL_FAILED}. Although\n * you then might conclude that the remote device is no longer available, a GENA renewal\n * can also fail for other reasons. The remote device will be kept and maintained in the\n * registry until it announces itself or it expires, even after a failed GENA renewal.\n * </p>\n * <p>\n * If you are providing local devices and services, resuming registry maintenance has\n * the following effects:\n * </p>\n * <p>\n * Local devices and their services are announced again immediately if the registry\n * has been paused for longer than half of the device's maximum age. Remote control\n * points will either see this as a new device advertisement (if they have dropped\n * your device while you paused maintenance) or as a regular update if you didn't\n * pause longer than the device's maximum age/expiration timeout.\n * </p>\n * <p>\n * Inbound GENA subscriptions to your local services are active, even in\n * paused state - remote control points should continue renewing the subscription.\n * If a remote control point stopped renewing a subscription without unsubscribing\n * (hard power off), an outdated inbound subscription will be detected when you\n * resume maintenance. This subscription will be cleaned up immediately on resume.\n * </p>\n */\n public void resume();\n\n /**\n * @return <code>true</code> if the registry has currently no running background\n * maintenance (thread).\n */\n public boolean isPaused();\n\n // #################################################################################################\n\n public void addListener(RegistryListener listener);\n\n public void removeListener(RegistryListener listener);\n\n public Collection<RegistryListener> getListeners();\n\n /**\n * Called internally by the UPnP stack when the discovery protocol starts.\n * <p>\n * The registry will notify all registered listeners of this event, unless the\n * given device was already in the registry.\n * </p>\n *\n * @param device The half-hydrated (without services) metadata of the discovered device.\n * @return <code>false</code> if the device was already registered.\n */\n public boolean notifyDiscoveryStart(RemoteDevice device);\n\n /**\n * Called internally by the UPnP stack when the discovery protocol stopped abnormally.\n * <p>\n * The registry will notify all registered listeners of this event.\n * </p>\n *\n * @param device The half-hydrated (without services) metadata of the discovered device.\n * @param ex The cause for the interruption of the discovery protocol.\n */\n public void notifyDiscoveryFailure(RemoteDevice device, Exception ex);\n\n // #################################################################################################\n\n /**\n * Call this method to add your local device metadata.\n *\n * @param localDevice The device to add and maintain.\n * @throws RegistrationException If a conflict with an already registered device was detected.\n */\n public void addDevice(LocalDevice localDevice) throws RegistrationException;\n\n /**\n * Call this method to add your local device metadata.\n *\n * @param localDevice The device to add and maintain.\n * @param options Immediately effective when this device is registered.\n * @throws RegistrationException If a conflict with an already registered device was detected.\n */\n public void addDevice(LocalDevice localDevice, DiscoveryOptions options) throws RegistrationException;\n\n /**\n * Change the active {@link DiscoveryOptions} for the given (local device) UDN.\n *\n * @param options Set to <code>null</code> to disable any options.\n */\n public void setDiscoveryOptions(UDN udn, DiscoveryOptions options);\n\n /**\n * Get the currently active {@link DiscoveryOptions} for the given (local device) UDN.\n *\n * @return <code>null</code> if there are no active discovery options for the given UDN.\n */\n public DiscoveryOptions getDiscoveryOptions(UDN udn);\n\n /**\n * Called internally by the UPnP discovery protocol.\n *\n * @throws RegistrationException If a conflict with an already registered device was detected.\n */\n public void addDevice(RemoteDevice remoteDevice) throws RegistrationException;\n\n /**\n * Called internally by the UPnP discovery protocol.\n */\n public boolean update(RemoteDeviceIdentity rdIdentity);\n\n /**\n * Call this to remove your local device metadata.\n *\n * @return <code>true</code> if the device was registered and has been removed.\n */\n public boolean removeDevice(LocalDevice localDevice);\n\n /**\n * Called internally by the UPnP discovery protocol.\n */\n public boolean removeDevice(RemoteDevice remoteDevice);\n\n /**\n * Call this to remove any device metadata with the given UDN.\n *\n * @return <code>true</code> if the device was registered and has been removed.\n */\n public boolean removeDevice(UDN udn);\n\n /**\n * Clear the registry of all locally registered device metadata.\n */\n public void removeAllLocalDevices();\n\n /**\n * Clear the registry of all discovered remote device metadata.\n */\n public void removeAllRemoteDevices();\n\n /**\n * @param udn The device name to lookup.\n * @param rootOnly If <code>true</code>, only matches of root devices are returned.\n * @return The registered root or embedded device metadata, or <code>null</code>.\n */\n public Device getDevice(UDN udn, boolean rootOnly);\n\n /**\n * @param udn The device name to lookup.\n * @param rootOnly If <code>true</code>, only matches of root devices are returned.\n * @return The registered root or embedded device metadata, or <code>null</code>.\n */\n public LocalDevice getLocalDevice(UDN udn, boolean rootOnly);\n\n /**\n * @param udn The device name to lookup.\n * @param rootOnly If <code>true</code>, only matches of root devices are returned.\n * @return The registered root or embedded device metadata, or <code>null</code>.\n */\n public RemoteDevice getRemoteDevice(UDN udn, boolean rootOnly);\n\n /**\n * @return All locally registered device metadata, in no particular order, or an empty collection.\n */\n public Collection<LocalDevice> getLocalDevices();\n\n /**\n * @return All discovered remote device metadata, in no particular order, or an empty collection.\n */\n public Collection<RemoteDevice> getRemoteDevices();\n\n /**\n * @return All device metadata, in no particular order, or an empty collection.\n */\n public Collection<Device> getDevices();\n\n /**\n * @return All device metadata of devices which implement the given type, in no particular order,\n * or an empty collection.\n */\n public Collection<Device> getDevices(DeviceType deviceType);\n\n /**\n * @return All device metadata of devices which have a service that implements the given type,\n * in no particular order, or an empty collection.\n */\n public Collection<Device> getDevices(ServiceType serviceType);\n\n /**\n * @return Complete service metadata for a service reference or <code>null</code> if no service\n * for the given reference has been registered.\n */\n public Service getService(ServiceReference serviceReference);\n\n // #################################################################################################\n\n /**\n * Stores an arbitrary resource in the registry.\n *\n * @param resource The resource to maintain indefinitely (until it is manually removed).\n */\n public void addResource(Resource resource);\n\n /**\n * Stores an arbitrary resource in the registry.\n * <p>\n * Call this method repeatedly to refresh and prevent expiration of the resource.\n * </p>\n *\n * @param resource The resource to maintain.\n * @param maxAgeSeconds The time after which the registry will automatically remove the resource.\n */\n public void addResource(Resource resource, int maxAgeSeconds);\n\n /**\n * Removes a resource from the registry.\n *\n * @param resource The resource to remove.\n * @return <code>true</code> if the resource was registered and has been removed.\n */\n public boolean removeResource(Resource resource);\n\n /**\n * @param pathQuery The path and optional query string of the resource's\n * registration URI (e.g. <code>/dev/somefile.xml?param=value</code>)\n * @return Any registered resource that matches the given URI path.\n * @throws IllegalArgumentException If the given URI was absolute, only path and query are allowed.\n */\n public Resource getResource(URI pathQuery) throws IllegalArgumentException;\n\n /**\n * @param <T> The required subtype of the {@link org.fourthline.cling.model.resource.Resource}.\n * @param pathQuery The path and optional query string of the resource's\n * registration URI (e.g. <code>/dev/somefile.xml?param=value</code>)\n * @param resourceType The required subtype of the {@link org.fourthline.cling.model.resource.Resource}.\n * @return Any registered resource that matches the given URI path and subtype.\n * @throws IllegalArgumentException If the given URI was absolute, only path and query are allowed.\n */\n public <T extends Resource> T getResource(Class<T> resourceType, URI pathQuery) throws IllegalArgumentException;\n\n /**\n * @return All registered resources, in no particular order, or an empty collection.\n */\n public Collection<Resource> getResources();\n\n /**\n * @param <T> The required subtype of the {@link org.fourthline.cling.model.resource.Resource}.\n * @param resourceType The required subtype of the {@link org.fourthline.cling.model.resource.Resource}.\n * @return Any registered resource that matches the given subtype.\n */\n public <T extends Resource> Collection<T> getResources(Class<T> resourceType);\n\n // #################################################################################################\n\n /**\n * Called internally by the UPnP stack, during GENA protocol execution.\n */\n public void addLocalSubscription(LocalGENASubscription subscription);\n\n /**\n * Called internally by the UPnP stack, during GENA protocol execution.\n */\n public LocalGENASubscription getLocalSubscription(String subscriptionId);\n\n /**\n * Called internally by the UPnP stack, during GENA protocol execution.\n */\n public boolean updateLocalSubscription(LocalGENASubscription subscription);\n\n /**\n * Called internally by the UPnP stack, during GENA protocol execution.\n */\n public boolean removeLocalSubscription(LocalGENASubscription subscription);\n\n /**\n * Called internally by the UPnP stack, during GENA protocol execution.\n */\n public void addRemoteSubscription(RemoteGENASubscription subscription);\n\n /**\n * Called internally by the UPnP stack, during GENA protocol execution.\n */\n public RemoteGENASubscription getRemoteSubscription(String subscriptionId);\n\n /**\n * Called internally by the UPnP stack, during GENA protocol execution.\n */\n public void updateRemoteSubscription(RemoteGENASubscription subscription);\n\n /**\n * Called internally by the UPnP stack, during GENA protocol execution.\n */\n public void removeRemoteSubscription(RemoteGENASubscription subscription);\n\n /**\n * Called internally by the UPnP stack, during GENA protocol execution.\n * <p>\n * When subscribing with a remote host, the remote host might send the\n * initial event message faster than the response for the subscription\n * request. This method register that the subscription procedure is\n * executing.\n * </p>\n */\n public void registerPendingRemoteSubscription(RemoteGENASubscription subscription);\n\n /**\n * Called internally by the UPnP stack, during GENA protocol execution.\n * <p>\n * Notify that the subscription procedure has terminated.\n * </p>\n */\n public void unregisterPendingRemoteSubscription(RemoteGENASubscription subscription);\n\n /**\n * Called internally by the UPnP stack, during GENA protocol execution.\n * <p>\n * Get a remote subscription from its subscriptionId. If the subscription can't be found,\n * wait for one of the pending remote subscription procedures from the registry background\n * maintainer to terminate, until the subscription has been found or until there are no\n * more pending subscription procedures.\n * </p>\n */\n public RemoteGENASubscription getWaitRemoteSubscription(String subscriptionId);\n\n // #################################################################################################\n\n /**\n * Manually trigger advertisement messages for all local devices.\n * <p>\n * No messages will be send for devices with disabled advertisements, see\n * {@link DiscoveryOptions}!\n * </p>\n */\n public void advertiseLocalDevices();\n\n}" }, { "identifier": "Router", "path": "clinglibrary/src/main/java/org/fourthline/cling/transport/Router.java", "snippet": "public interface Router {\n\n /**\n * @return The configuration used by this router.\n */\n public UpnpServiceConfiguration getConfiguration();\n\n /**\n * @return The protocol factory used by this router.\n */\n public ProtocolFactory getProtocolFactory();\n\n /**\n * Starts all sockets and listening threads for datagrams and streams.\n *\n * @return <code>true</code> if the router was enabled. <code>false</code> if it's already running.\n */\n boolean enable() throws RouterException;\n\n /**\n * Unbinds all sockets and stops all listening threads for datagrams and streams.\n *\n * @return <code>true</code> if the router was disabled. <code>false</code> if it wasn't running.\n */\n boolean disable() throws RouterException;\n\n /**\n * Disables the router and releases all other resources.\n */\n void shutdown() throws RouterException ;\n\n /**\n *\n * @return <code>true</code> if the router is currently enabled.\n */\n boolean isEnabled() throws RouterException;\n\n /**\n * Called by the {@link #enable()} method before it returns.\n *\n * @param ex The cause of the failure.\n * @throws InitializationException if the exception was not recoverable.\n */\n void handleStartFailure(InitializationException ex) throws InitializationException;\n\n /**\n * @param preferredAddress A preferred stream server bound address or <code>null</code>.\n * @return An empty list if no stream server is currently active, otherwise a single network\n * address if the preferred address is active, or a list of all active bound\n * stream servers.\n */\n public List<NetworkAddress> getActiveStreamServers(InetAddress preferredAddress) throws RouterException;\n\n /**\n * <p>\n * This method is called internally by the transport layer when a datagram, either unicast or\n * multicast, has been received. An implementation of this interface has to handle the received\n * message, e.g. selecting and executing a UPnP protocol. This method should not block until\n * the execution completes, the calling thread should be free to handle the next reception as\n * soon as possible.\n * </p>\n * @param msg The received datagram message.\n */\n public void received(IncomingDatagramMessage msg);\n\n /**\n * <p>\n * This method is called internally by the transport layer when a TCP stream connection has\n * been made and a response has to be returned to the sender. An implementation of this interface\n * has to handle the received stream connection and return a response, e.g. selecting and executing\n * a UPnP protocol. This method should not block until the execution completes, the calling thread\n * should be free to process the next reception as soon as possible. Typically this means starting\n * a new thread of execution in this method.\n * </p>\n * @param stream\n */\n public void received(UpnpStream stream);\n\n /**\n * <p>\n * Call this method to send a UDP datagram message.\n * </p>\n * @param msg The UDP datagram message to send.\n * @throws RouterException if a recoverable error, such as thread interruption, occurs.\n */\n public void send(OutgoingDatagramMessage msg) throws RouterException;\n\n /**\n * <p>\n * Call this method to send a TCP (HTTP) stream message.\n * </p>\n * @param msg The TCP (HTTP) stream message to send.\n * @return The response received from the server.\n * @throws RouterException if a recoverable error, such as thread interruption, occurs.\n */\n public StreamResponseMessage send(StreamRequestMessage msg) throws RouterException;\n\n /**\n * <p>\n * Call this method to broadcast a UDP message to all hosts on the network.\n * </p>\n * @param bytes The byte payload of the UDP datagram.\n * @throws RouterException if a recoverable error, such as thread interruption, occurs.\n */\n public void broadcast(byte[] bytes) throws RouterException;\n\n}" } ]
import android.app.Service; import android.content.Context; import android.content.Intent; import android.os.IBinder; import org.fourthline.cling.UpnpService; import org.fourthline.cling.UpnpServiceConfiguration; import org.fourthline.cling.UpnpServiceImpl; import org.fourthline.cling.controlpoint.ControlPoint; import org.fourthline.cling.protocol.ProtocolFactory; import org.fourthline.cling.registry.Registry; import org.fourthline.cling.transport.Router;
9,506
/* * Copyright (C) 2013 4th Line GmbH, Switzerland * * The contents of this file are subject to the terms of either the GNU * Lesser General Public License Version 2 or later ("LGPL") or the * Common Development and Distribution License Version 1 or later * ("CDDL") (collectively, the "License"). You may not use this file * except in compliance with the License. See LICENSE.txt for more * information. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. */ package org.fourthline.cling.android; /** * Provides a UPnP stack with Android configuration as an application service component. * <p> * Sends a search for all UPnP devices on instantiation. See the * {@link org.fourthline.cling.android.AndroidUpnpService} interface for a usage hiker. * </p> * <p/> * Override the {@link #createRouter(org.fourthline.cling.UpnpServiceConfiguration, org.fourthline.cling.protocol.ProtocolFactory, android.content.Context)} * and {@link #createConfiguration()} methods to customize the service. * * @author Christian Bauer */ public class AndroidUpnpServiceImpl extends Service { protected UpnpService upnpService; protected Binder binder = new Binder(); /** * Starts the UPnP service. */ @Override public void onCreate() { super.onCreate(); upnpService = new UpnpServiceImpl(createConfiguration()) { @Override
/* * Copyright (C) 2013 4th Line GmbH, Switzerland * * The contents of this file are subject to the terms of either the GNU * Lesser General Public License Version 2 or later ("LGPL") or the * Common Development and Distribution License Version 1 or later * ("CDDL") (collectively, the "License"). You may not use this file * except in compliance with the License. See LICENSE.txt for more * information. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. */ package org.fourthline.cling.android; /** * Provides a UPnP stack with Android configuration as an application service component. * <p> * Sends a search for all UPnP devices on instantiation. See the * {@link org.fourthline.cling.android.AndroidUpnpService} interface for a usage hiker. * </p> * <p/> * Override the {@link #createRouter(org.fourthline.cling.UpnpServiceConfiguration, org.fourthline.cling.protocol.ProtocolFactory, android.content.Context)} * and {@link #createConfiguration()} methods to customize the service. * * @author Christian Bauer */ public class AndroidUpnpServiceImpl extends Service { protected UpnpService upnpService; protected Binder binder = new Binder(); /** * Starts the UPnP service. */ @Override public void onCreate() { super.onCreate(); upnpService = new UpnpServiceImpl(createConfiguration()) { @Override
protected Router createRouter(ProtocolFactory protocolFactory, Registry registry) {
5
2023-11-10 14:28:40+00:00
12k
noear/folkmq
folkmq-server/src/main/java/org/noear/folkmq/server/pro/mq/FolkmqLifecycleBean.java
[ { "identifier": "FolkMQ", "path": "folkmq/src/main/java/org/noear/folkmq/FolkMQ.java", "snippet": "public class FolkMQ {\n /**\n * 获取版本\n */\n public static String version() {\n return \"1.0.27\";\n }\n\n /**\n * 创建服务端\n */\n public static MqServer createServer() {\n return new MqServerDefault();\n }\n\n /**\n * 创建客户端\n */\n public static MqClient createClient(String... serverUrls) {\n return new MqClientDefault(serverUrls);\n }\n}" }, { "identifier": "MqConstants", "path": "folkmq/src/main/java/org/noear/folkmq/common/MqConstants.java", "snippet": "public interface MqConstants {\n /**\n * 元信息:消息事务Id\n */\n String MQ_META_TID = \"mq.tid\";\n /**\n * 元信息:消息主题\n */\n String MQ_META_TOPIC = \"mq.topic\";\n /**\n * 元信息:消息调度时间\n */\n String MQ_META_SCHEDULED = \"mq.scheduled\";\n /**\n * 元信息:消息质量等级\n */\n String MQ_META_QOS = \"mq.qos\";\n /**\n * 元信息:消费者组\n */\n String MQ_META_CONSUMER_GROUP = \"mq.consumer\"; //此处不改动,算历史痕迹。保持向下兼容\n /**\n * 元信息:派发次数\n */\n String MQ_META_TIMES = \"mq.times\";\n /**\n * 元信息:消费回执\n */\n String MQ_META_ACK = \"mq.ack\";\n /**\n * 元信息:执行确认\n */\n String MQ_META_CONFIRM = \"mq.confirm\";\n /**\n * 元信息:批量处理\n */\n String MQ_META_BATCH = \"mq.batch\";\n\n /**\n * 事件:订阅\n */\n String MQ_EVENT_SUBSCRIBE = \"mq.event.subscribe\";\n /**\n * 事件:取消订阅\n */\n String MQ_EVENT_UNSUBSCRIBE = \"mq.event.unsubscribe\";\n /**\n * 事件:发布\n */\n String MQ_EVENT_PUBLISH = \"mq.event.publish\";\n /**\n * 事件:取消发布\n */\n String MQ_EVENT_UNPUBLISH = \"mq.event.unpublish\";\n /**\n * 事件:派发\n */\n String MQ_EVENT_DISTRIBUTE = \"mq.event.distribute\";\n /**\n * 事件:保存快照\n */\n String MQ_EVENT_SAVE = \"mq.event.save\";\n\n /**\n * 事件:加入集群\n * */\n String MQ_EVENT_JOIN = \"mq.event.join\";\n\n /**\n * 管理视图-队列\n */\n String ADMIN_VIEW_QUEUE = \"admin.view.queue\";\n\n /**\n * 连接参数:ak\n */\n String PARAM_ACCESS_KEY = \"ak\";\n /**\n * 连接参数: sk\n */\n String PARAM_ACCESS_SECRET_KEY = \"sk\";\n\n /**\n * 主题与消息者间隔符\n */\n String SEPARATOR_TOPIC_CONSUMER_GROUP = \"#\";\n\n /**\n * 经理人服务\n */\n String BROKER_AT_SERVER = \"folkmq-server\";\n\n /**\n * 经理人所有服务\n */\n String BROKER_AT_SERVER_ALL = \"folkmq-server*\";\n\n /**\n * 最大分片大小(1m)\n */\n int MAX_FRAGMENT_SIZE = 1024 * 1024;\n}" }, { "identifier": "MqServer", "path": "folkmq/src/main/java/org/noear/folkmq/server/MqServer.java", "snippet": "public interface MqServer {\n /**\n * 服务端配置\n */\n MqServer config(ServerConfigHandler configHandler);\n\n /**\n * 配置观察者\n */\n MqServer watcher(MqWatcher watcher);\n\n /**\n * 配置访问账号\n *\n * @param ak 访问者身份\n * @param sk 访问者密钥\n */\n MqServer addAccess(String ak, String sk);\n\n /**\n * 配置访问账号\n *\n * @param accessMap 访问账号集合\n */\n MqServer addAccessAll(Map<String, String> accessMap);\n\n /**\n * 启动\n */\n MqServer start(int port) throws Exception;\n\n /**\n * 停止\n */\n void stop();\n\n\n /**\n * 获取内部服务\n */\n MqServiceInternal getServerInternal();\n}" }, { "identifier": "MqServiceInternal", "path": "folkmq/src/main/java/org/noear/folkmq/server/MqServiceInternal.java", "snippet": "public interface MqServiceInternal {\n /**\n * 获取订阅关系(topic=>[queueName]) //queueName='topic#consumer'\n */\n Map<String, Set<String>> getSubscribeMap();\n\n /**\n * 获取队列字典(queueName=>Queue)\n */\n Map<String, MqQueue> getQueueMap();\n\n /**\n * 执行订阅\n *\n * @param topic 主题\n * @param consumerGroup 消费者组\n * @param session 会话(即消费者)\n */\n void subscribeDo(String topic, String consumerGroup, Session session);\n\n /**\n * 执行取消订阅\n *\n * @param topic 主题\n * @param consumerGroup 消费者组\n * @param session 会话(即消费者)\n */\n void unsubscribeDo(String topic, String consumerGroup, Session session);\n\n /**\n * 执行路由\n *\n * @param message 消息\n */\n void routingDo(Message message);\n\n /**\n * 执行路由\n *\n * @param queueName 队列名\n * @param message 消息\n * @param tid 事务Id\n * @param qos 质量等级\n * @param times 派发次数\n * @param scheduled 计划时间\n */\n void routingDo(String queueName, Message message, String tid, int qos, int times, long scheduled);\n\n /**\n * 保存\n */\n void save();\n}" }, { "identifier": "MqServiceListener", "path": "folkmq/src/main/java/org/noear/folkmq/server/MqServiceListener.java", "snippet": "public class MqServiceListener extends EventListener implements MqServiceInternal {\n private static final Logger log = LoggerFactory.getLogger(MqServerDefault.class);\n\n private Object SUBSCRIBE_LOCK = new Object();\n\n //服务端访问账号\n private Map<String, String> serverAccessMap = new ConcurrentHashMap<>();\n //观察者\n private MqWatcher watcher;\n\n //订阅关系(topic=>[queueName]) //queueName='topic#consumer'\n private Map<String, Set<String>> subscribeMap = new ConcurrentHashMap<>();\n //队列字典(queueName=>Queue)\n private Map<String, MqQueue> queueMap = new ConcurrentHashMap<>();\n\n //派发线程\n private Thread distributeThread;\n\n private boolean brokerMode;\n\n\n public MqServiceListener(boolean brokerMode) {\n //::初始化 Watcher 接口\n this.brokerMode = brokerMode;\n\n this.distributeThread = new Thread(this::distributeDo, \"distributeThread\");\n\n this.watcher = new MqWatcherDefault();\n this.watcher.init(this);\n\n //::初始化 BuilderListener(self) 的路由监听\n\n //接收订阅指令\n doOn(MqConstants.MQ_EVENT_SUBSCRIBE, (s, m) -> {\n String is_batch = m.meta(MqConstants.MQ_META_BATCH);\n\n if(\"1\".equals(is_batch)){\n ONode oNode = ONode.loadStr(m.dataAsString());\n Map<String, Collection<String>> subscribeData = oNode.toObject();\n if(subscribeData != null){\n for(Map.Entry<String, Collection<String>> kv : subscribeData.entrySet()){\n for(String queueName : kv.getValue()){\n String consumerGroup = queueName.split(MqConstants.SEPARATOR_TOPIC_CONSUMER_GROUP)[1];\n\n //观察者::订阅时(适配时,可选择同步或异步。同步可靠性高,异步性能好)\n watcher.onSubscribe(kv.getKey(), consumerGroup, s);\n\n //执行订阅\n subscribeDo(kv.getKey(), consumerGroup, s);\n }\n }\n }\n }else {\n String topic = m.meta(MqConstants.MQ_META_TOPIC);\n String consumerGroup = m.meta(MqConstants.MQ_META_CONSUMER_GROUP);\n\n //观察者::订阅时(适配时,可选择同步或异步。同步可靠性高,异步性能好)\n watcher.onSubscribe(topic, consumerGroup, s);\n\n //执行订阅\n subscribeDo(topic, consumerGroup, s);\n }\n\n //答复(以支持同步的原子性需求。同步或异步,由用户按需控制)\n if (m.isRequest() || m.isSubscribe()) {\n //发送“确认”,表示服务端收到了\n if (s.isValid()) {\n //如果会话仍有效,则答复(有可能会半路关掉)\n s.replyEnd(m, new StringEntity(\"\").metaPut(MqConstants.MQ_META_CONFIRM, \"1\"));\n }\n }\n });\n\n //接收取消订阅指令\n doOn(MqConstants.MQ_EVENT_UNSUBSCRIBE, (s, m) -> {\n String topic = m.meta(MqConstants.MQ_META_TOPIC);\n String consumerGroup = m.meta(MqConstants.MQ_META_CONSUMER_GROUP);\n\n //观察者::取消订阅时(适配时,可选择同步或异步。同步可靠性高,异步性能好)\n watcher.onUnSubscribe(topic, consumerGroup, s);\n\n //执行取消订阅\n unsubscribeDo(topic, consumerGroup, s);\n\n //答复(以支持同步的原子性需求。同步或异步,由用户按需控制)\n if (m.isRequest() || m.isSubscribe()) {\n //发送“确认”,表示服务端收到了\n if (s.isValid()) {\n //如果会话仍有效,则答复(有可能会半路关掉)\n s.replyEnd(m, new StringEntity(\"\").metaPut(MqConstants.MQ_META_CONFIRM, \"1\"));\n }\n }\n });\n\n //接收发布指令\n doOn(MqConstants.MQ_EVENT_PUBLISH, (s, m) -> {\n //观察者::发布时(适配时,可选择同步或异步。同步可靠性高,异步性能好)\n watcher.onPublish(m);\n\n //执行交换\n routingDo(m);\n\n //再答复(以支持同步的原子性需求。同步或异步,由用户按需控制)\n if (m.isRequest() || m.isSubscribe()) { //此判断兼容 Qos0, Qos1\n //发送“确认”,表示服务端收到了\n if (s.isValid()) {\n //如果会话仍有效,则答复(有可能会半路关掉)\n s.replyEnd(m, new StringEntity(\"\").metaPut(MqConstants.MQ_META_CONFIRM, \"1\"));\n }\n }\n });\n\n //接收取消发布指令\n doOn(MqConstants.MQ_EVENT_UNPUBLISH, (s,m)->{\n //观察者::取消发布时(适配时,可选择同步或异步。同步可靠性高,异步性能好)\n watcher.onUnPublish(m);\n\n //执行交换\n unRoutingDo(m);\n\n //再答复(以支持同步的原子性需求。同步或异步,由用户按需控制)\n if (m.isRequest() || m.isSubscribe()) { //此判断兼容 Qos0, Qos1\n //发送“确认”,表示服务端收到了\n if (s.isValid()) {\n //如果会话仍有效,则答复(有可能会半路关掉)\n s.replyEnd(m, new StringEntity(\"\").metaPut(MqConstants.MQ_META_CONFIRM, \"1\"));\n }\n }\n });\n\n //接收保存指令\n doOn(MqConstants.MQ_EVENT_SAVE, (s, m) -> {\n save();\n\n if (m.isRequest() || m.isSubscribe()) { //此判断兼容 Qos0, Qos1\n //发送“确认”,表示服务端收到了\n if (s.isValid()) {\n //如果会话仍有效,则答复(有可能会半路关掉)\n s.replyEnd(m, new StringEntity(\"\").metaPut(MqConstants.MQ_META_CONFIRM, \"1\"));\n }\n }\n });\n }\n\n public MqServiceListener watcher(MqWatcher watcher) {\n if (watcher != null) {\n this.watcher = watcher;\n this.watcher.init(this);\n }\n\n return this;\n }\n\n /**\n * 配置访问账号\n *\n * @param accessKey 访问者身份\n * @param accessSecretKey 访问者密钥\n */\n public MqServiceListener addAccess(String accessKey, String accessSecretKey) {\n serverAccessMap.put(accessKey, accessSecretKey);\n return this;\n }\n\n /**\n * 配置访问账号\n *\n * @param accessMap 访问账号集合\n */\n public MqServiceListener addAccessAll(Map<String, String> accessMap) {\n if (accessMap != null) {\n serverAccessMap.putAll(accessMap);\n }\n return this;\n }\n\n /**\n * 启动\n */\n public void start(OnStart onStart) throws Exception {\n\n //观察者::服务启动之前\n watcher.onStartBefore();\n\n //启动\n if (onStart != null) {\n onStart.run();\n }\n distributeThread.start();\n\n //观察者::服务启动之后\n watcher.onStartAfter();\n }\n\n /**\n * 保存\n */\n @Override\n public void save() {\n //观察者::保存时\n watcher.onSave();\n }\n\n /**\n * 停止\n */\n public void stop(Runnable onStop) {\n //观察者::服务停止之前\n watcher.onStopBefore();\n\n //停止\n if (onStop != null) {\n onStop.run();\n }\n distributeThread.interrupt();\n\n //观察者::服务停止之后\n watcher.onStopAfter();\n\n //关闭队列\n List<MqQueue> queueList = new ArrayList<>(queueMap.values());\n for (MqQueue queue : queueList) {\n queue.close();\n }\n }\n\n /**\n * 会话打开时\n */\n @Override\n public void onOpen(Session session) throws IOException {\n super.onOpen(session);\n\n if (brokerMode) {\n //申请加入\n session.send(MqConstants.MQ_EVENT_JOIN, new StringEntity(\"\"));\n\n log.info(\"Broker channel opened, sessionId={}\", session.sessionId());\n } else {\n if (serverAccessMap.size() > 0) {\n //如果有 ak/sk 配置,则进行鉴权\n String accessKey = session.param(MqConstants.PARAM_ACCESS_KEY);\n String accessSecretKey = session.param(MqConstants.PARAM_ACCESS_SECRET_KEY);\n\n if (accessKey == null || accessSecretKey == null) {\n session.close();\n return;\n }\n\n if (accessSecretKey.equals(serverAccessMap.get(accessKey)) == false) {\n session.close();\n return;\n }\n }\n\n log.info(\"Client channel opened, sessionId={}\", session.sessionId());\n }\n }\n\n /**\n * 会话关闭时\n */\n @Override\n public void onClose(Session session) {\n super.onClose(session);\n\n log.info(\"Server channel closed, sessionId={}\", session.sessionId());\n\n //遍历会话绑定的队列 //线程安全处理\n List<String> queueNameList = new ArrayList<>(session.attrMap().keySet());\n for (String queueName : queueNameList) {\n MqQueue queue = queueMap.get(queueName);\n\n //如果找到对应的队列\n if (queue != null) {\n queue.removeSession(session);\n }\n }\n }\n\n /**\n * 会话出错时\n */\n @Override\n public void onError(Session session, Throwable error) {\n super.onError(session, error);\n\n if (log.isWarnEnabled()) {\n if (error instanceof SocketdAlarmException) {\n SocketdAlarmException alarmException = (SocketdAlarmException) error;\n log.warn(\"Server channel error, sessionId={}, from={}\", session.sessionId(), alarmException.getAlarm(), error);\n } else {\n log.warn(\"Server channel error, sessionId={}\", session.sessionId(), error);\n }\n }\n }\n\n @Override\n public Map<String, Set<String>> getSubscribeMap() {\n return Collections.unmodifiableMap(subscribeMap);\n }\n\n @Override\n public Map<String, MqQueue> getQueueMap() {\n return Collections.unmodifiableMap(queueMap);\n }\n\n /**\n * 执行订阅\n */\n @Override\n public void subscribeDo(String topic, String consumerGroup, Session session) {\n String queueName = topic + MqConstants.SEPARATOR_TOPIC_CONSUMER_GROUP + consumerGroup;\n\n synchronized (SUBSCRIBE_LOCK) {\n //::1.构建订阅关系\n\n //建立订阅关系(topic=>[queueName]) //queueName='topic#consumer'\n Set<String> queueNameSet = subscribeMap.computeIfAbsent(topic, n -> Collections.newSetFromMap(new ConcurrentHashMap<>()));\n queueNameSet.add(queueName);\n\n //队列映射关系(queueName=>Queue)\n MqQueue queue = queueMap.get(queueName);\n if (queue == null) {\n queue = new MqQueueDefault(watcher, topic, consumerGroup, queueName);\n queueMap.put(queueName, queue);\n }\n\n //::2.标识会话身份(从持久层恢复时,会话可能为 null)\n\n if (session != null) {\n log.info(\"Server channel subscribe topic={}, consumerGroup={}, sessionId={}\", topic, consumerGroup, session.sessionId());\n\n //会话绑定队列(可以绑定多个队列)\n session.attrPut(queueName, \"1\");\n\n //加入队列会话\n queue.addSession(session);\n }\n }\n }\n\n /**\n * 执行取消订阅\n */\n @Override\n public void unsubscribeDo(String topic, String consumerGroup, Session session) {\n if (session == null) {\n return;\n }\n\n log.info(\"Server channel unsubscribe topic={}, consumerGroup={}, sessionId={}\", topic, consumerGroup, session.sessionId());\n\n String queueName = topic + MqConstants.SEPARATOR_TOPIC_CONSUMER_GROUP + consumerGroup;\n\n //1.获取相关队列\n MqQueue queue = queueMap.get(queueName);\n\n //2.移除队列绑定\n session.attrMap().remove(queueName);\n\n //3.退出队列会话\n if (queue != null) {\n queue.removeSession(session);\n }\n }\n\n /**\n * 执行路由\n */\n @Override\n public void routingDo(Message message) {\n String tid = message.meta(MqConstants.MQ_META_TID);\n //可能是非法消息\n if (StrUtils.isEmpty(tid)) {\n log.warn(\"The tid cannot be null, sid={}\", message.sid());\n return;\n }\n\n //复用解析\n String topic = message.meta(MqConstants.MQ_META_TOPIC);\n int qos = \"0\".equals(message.meta(MqConstants.MQ_META_QOS)) ? 0 : 1;\n int times = Integer.parseInt(message.metaOrDefault(MqConstants.MQ_META_TIMES, \"0\"));\n long scheduled = 0;\n\n String scheduledStr = message.meta(MqConstants.MQ_META_SCHEDULED);\n if (StrUtils.isNotEmpty(scheduledStr)) {\n scheduled = Long.parseLong(scheduledStr);\n }\n\n if(scheduled == 0){\n //默认为当前ms(相对于后面者,有个排序作用)\n scheduled = System.currentTimeMillis();\n }\n\n\n //取出所有订阅的主题消费者\n Set<String> topicConsumerSet = subscribeMap.get(topic);\n\n if (topicConsumerSet != null) {\n //避免遍历 Set 时,出现 add or remove 而异常\n List<String> topicConsumerList = new ArrayList<>(topicConsumerSet);\n\n for (String topicConsumer : topicConsumerList) {\n routingDo(topicConsumer, message, tid, qos, times, scheduled);\n }\n }\n }\n\n /**\n * 执行路由\n */\n public void routingDo(String queueName, Message message, String tid, int qos, int times, long scheduled) {\n MqQueue queue = queueMap.get(queueName);\n\n if (queue != null) {\n MqMessageHolder messageHolder = new MqMessageHolder(queueName, queue.getConsumerGroup(), message, tid, qos, times, scheduled);\n queue.add(messageHolder);\n }\n }\n\n /**\n * 执行取消路由\n */\n public void unRoutingDo(Message message) {\n String tid = message.meta(MqConstants.MQ_META_TID);\n //可能是非法消息\n if (StrUtils.isEmpty(tid)) {\n log.warn(\"The tid cannot be null, sid={}\", message.sid());\n return;\n }\n\n //复用解析\n String topic = message.meta(MqConstants.MQ_META_TOPIC);\n\n //取出所有订阅的主题消费者\n Set<String> topicConsumerSet = subscribeMap.get(topic);\n\n if (topicConsumerSet != null) {\n //避免遍历 Set 时,出现 add or remove 而异常\n List<String> topicConsumerList = new ArrayList<>(topicConsumerSet);\n\n for (String topicConsumer : topicConsumerList) {\n MqQueue queue = queueMap.get(topicConsumer);\n queue.removeAt(tid);\n }\n }\n }\n\n private void distributeDo() {\n while (!distributeThread.isInterrupted()) {\n try {\n int count = 0;\n\n List<MqQueue> queueList = new ArrayList<>(queueMap.values());\n for (MqQueue queue : queueList) {\n try {\n if (queue.distribute()) {\n count++;\n }\n } catch (Throwable e) {\n if (log.isWarnEnabled()) {\n log.warn(\"MqQueue take error, queue={}\", queue.getQueueName(), e);\n }\n }\n }\n\n if (count == 0) {\n //一点消息都没有,就修复下\n Thread.sleep(100);\n }\n } catch (Throwable e) {\n if (e instanceof InterruptedException == false) {\n if (log.isWarnEnabled()) {\n log.warn(\"MqQueue distribute error\", e);\n }\n }\n }\n }\n\n if (log.isWarnEnabled()) {\n log.warn(\"MqQueue take stoped!\");\n }\n }\n}" }, { "identifier": "MqWatcherSnapshotPlus", "path": "folkmq-pro/src/main/java/org/noear/folkmq/server/pro/MqWatcherSnapshotPlus.java", "snippet": "public class MqWatcherSnapshotPlus extends MqWatcherSnapshot {\n private final LongAdder save900Count;\n private final LongAdder save300Count;\n private final LongAdder save100Count;\n\n private final ScheduledFuture<?> save900Future;\n private final ScheduledFuture<?> save300Future;\n private final ScheduledFuture<?> save100Future;\n\n protected long save900Condition = 1L;\n protected long save300Condition = 10L;\n protected long save100Condition = 10000L;\n\n public MqWatcherSnapshotPlus() {\n this(null);\n }\n\n public MqWatcherSnapshotPlus(String dataPath) {\n super(dataPath);\n\n this.save900Count = new LongAdder();\n this.save300Count = new LongAdder();\n this.save100Count = new LongAdder();\n\n int fixedDelay900 = 1000 * 900; //900秒\n this.save900Future = RunUtils.scheduleWithFixedDelay(this::onSave900, fixedDelay900, fixedDelay900);\n\n int fixedDelay300 = 1000 * 300; //300秒\n this.save300Future = RunUtils.scheduleWithFixedDelay(this::onSave300, fixedDelay300, fixedDelay300);\n\n int fixedDelay100 = 1000 * 100; //100秒\n this.save100Future = RunUtils.scheduleWithFixedDelay(this::onSave100, fixedDelay100, fixedDelay100);\n }\n\n public MqWatcherSnapshotPlus save900Condition(long save900Condition) {\n if (save900Condition >= 1L) {\n this.save900Condition = save900Condition;\n }\n return this;\n }\n\n public MqWatcherSnapshotPlus save300Condition(long save300Condition) {\n if (save300Condition >= 1L) {\n this.save300Condition = save300Condition;\n }\n\n return this;\n }\n\n public MqWatcherSnapshotPlus save100Condition(long save100Condition) {\n if (save100Condition >= 1L) {\n this.save100Condition = save100Condition;\n }\n\n return this;\n }\n\n public long getSave900Count() {\n return save900Count.longValue();\n }\n\n public long getSave300Count() {\n return save300Count.longValue();\n }\n\n public long getSave100Count() {\n return save100Count.longValue();\n }\n\n private void onSave900() {\n long count = save900Count.sumThenReset();\n\n if (count >= save900Condition) {\n onSave();\n } else {\n if (log.isDebugEnabled()) {\n log.debug(\"No trigger save900 condition!\");\n }\n }\n }\n\n private void onSave300() {\n long count = save300Count.sumThenReset();\n\n if (count >= save300Condition) {\n onSave();\n } else {\n if (log.isDebugEnabled()) {\n log.debug(\"No trigger save300 condition!\");\n }\n }\n }\n\n private void onSave100() {\n long count = save100Count.sumThenReset();\n\n if (count >= save100Condition) {\n onSave();\n } else {\n if (log.isDebugEnabled()) {\n log.debug(\"No trigger save100 condition!\");\n }\n }\n }\n\n @Override\n public void onStopBefore() {\n if (save900Future != null) {\n save900Future.cancel(false);\n }\n\n if (save300Future != null) {\n save300Future.cancel(false);\n }\n\n if (save100Future != null) {\n save100Future.cancel(false);\n }\n }\n\n @Override\n public void onSubscribe(String topic, String consumerGroup, Session session) {\n super.onSubscribe(topic, consumerGroup, session);\n onChange();\n }\n\n @Override\n public void onUnSubscribe(String topic, String consumerGroup, Session session) {\n super.onUnSubscribe(topic, consumerGroup, session);\n onChange();\n }\n\n @Override\n public void onPublish(Message message) {\n super.onPublish(message);\n onChange();\n }\n\n @Override\n public void onAcknowledge(String topic, String consumerGroup, MqMessageHolder messageHolder, boolean isOk) {\n super.onAcknowledge(topic, consumerGroup, messageHolder, isOk);\n onChange();\n }\n\n private void onChange() {\n //记数\n save900Count.increment();\n save300Count.increment();\n save100Count.increment();\n }\n}" }, { "identifier": "ViewUtils", "path": "folkmq-server/src/main/java/org/noear/folkmq/server/pro/admin/dso/ViewUtils.java", "snippet": "public class ViewUtils {\n public static List<QueueVo> queueView(MqServiceInternal server) {\n List<MqQueue> queueList = new ArrayList<>(server.getQueueMap().values());\n\n //先排序,可以直接取前99 (旧方案是,全构建完成,再取99)\n queueList.sort(Comparator.comparing(MqQueue::getQueueName));\n\n List<QueueVo> list = new ArrayList<>();\n\n for (MqQueue tmp : queueList) {\n MqQueueDefault queue = (MqQueueDefault) tmp;\n\n QueueVo queueVo = new QueueVo();\n queueVo.queue = queue.getQueueName();\n\n queueVo.sessionCount = (queue.sessionCount());\n queueVo.messageCount = (queue.messageTotal());\n\n queueVo.messageDelayedCount1 = queue.messageCount(1);\n queueVo.messageDelayedCount2 = queue.messageCount(2);\n queueVo.messageDelayedCount3 = queue.messageCount(3);\n queueVo.messageDelayedCount4 = queue.messageCount(4);\n queueVo.messageDelayedCount5 = queue.messageCount(5);\n queueVo.messageDelayedCount6 = queue.messageCount(6);\n queueVo.messageDelayedCount7 = queue.messageCount(7);\n queueVo.messageDelayedCount8 = queue.messageCount(8);\n\n\n list.add(queueVo);\n\n //不超过99\n if (list.size() == 99) {\n break;\n }\n }\n\n return list;\n }\n}" }, { "identifier": "ConfigNames", "path": "folkmq-server/src/main/java/org/noear/folkmq/server/pro/common/ConfigNames.java", "snippet": "public interface ConfigNames {\n //管理密码\n String folkmq_admin = \"folkmq.admin\";\n\n //经纪人地址\n String folkmq_broker = \"folkmq.broker\";\n\n //快照相关\n String folkmq_snapshot_enable = \"folkmq.snapshot.enable\";\n String folkmq_snapshot_save900 = \"folkmq.snapshot.save900\";\n String folkmq_snapshot_save300 = \"folkmq.snapshot.save300\";\n String folkmq_snapshot_save100 = \"folkmq.snapshot.save100\";\n\n //访问账号(ak:sk) //弃用(改为单账号,用户好接受)\n String folkmq_access_x = \"folkmq.access.\";\n //访问账号(ak:sk)\n String folkmq_access_ak = \"folkmq.access.ak\";\n String folkmq_access_sk = \"folkmq.access.sk\";\n}" } ]
import org.noear.folkmq.FolkMQ; import org.noear.folkmq.common.MqConstants; import org.noear.folkmq.server.MqServer; import org.noear.folkmq.server.MqServiceInternal; import org.noear.folkmq.server.MqServiceListener; import org.noear.folkmq.server.pro.MqWatcherSnapshotPlus; import org.noear.folkmq.server.pro.admin.dso.ViewUtils; import org.noear.folkmq.server.pro.common.ConfigNames; import org.noear.snack.ONode; import org.noear.socketd.SocketD; import org.noear.socketd.transport.client.ClientSession; import org.noear.socketd.transport.core.entity.StringEntity; import org.noear.socketd.utils.StrUtils; import org.noear.solon.Solon; import org.noear.solon.Utils; import org.noear.solon.annotation.Component; import org.noear.solon.annotation.Inject; import org.noear.solon.core.AppContext; import org.noear.solon.core.bean.LifecycleBean; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.List; import java.util.Map;
8,469
package org.noear.folkmq.server.pro.mq; /** * @author noear * @since 1.0 */ @Component public class FolkmqLifecycleBean implements LifecycleBean { private static final Logger log = LoggerFactory.getLogger(FolkmqLifecycleBean.class); @Inject private AppContext appContext; private MqServer localServer; private MqServiceListener brokerServiceListener; private ClientSession brokerSession; private MqWatcherSnapshotPlus snapshotPlus; private boolean saveEnable; @Override public void start() throws Throwable { String brokerServer = Solon.cfg().get(ConfigNames.folkmq_broker); saveEnable = Solon.cfg().getBool(ConfigNames.folkmq_snapshot_enable, true); long save900 = Solon.cfg().getLong(ConfigNames.folkmq_snapshot_save900, 0); long save300 = Solon.cfg().getLong(ConfigNames.folkmq_snapshot_save300, 0); long save100 = Solon.cfg().getLong(ConfigNames.folkmq_snapshot_save100, 0); //初始化快照持久化 snapshotPlus = new MqWatcherSnapshotPlus(); snapshotPlus.save900Condition(save900); snapshotPlus.save300Condition(save300); snapshotPlus.save100Condition(save100); appContext.wrapAndPut(MqWatcherSnapshotPlus.class, snapshotPlus); if (Utils.isEmpty(brokerServer)) { startLocalServerMode(snapshotPlus); } else { startBrokerSession(brokerServer, snapshotPlus); } log.info("Server:main: folkmq-server: Started (SOCKET.D/{}-{}, folkmq/{})", SocketD.protocolVersion(), SocketD.version(),
package org.noear.folkmq.server.pro.mq; /** * @author noear * @since 1.0 */ @Component public class FolkmqLifecycleBean implements LifecycleBean { private static final Logger log = LoggerFactory.getLogger(FolkmqLifecycleBean.class); @Inject private AppContext appContext; private MqServer localServer; private MqServiceListener brokerServiceListener; private ClientSession brokerSession; private MqWatcherSnapshotPlus snapshotPlus; private boolean saveEnable; @Override public void start() throws Throwable { String brokerServer = Solon.cfg().get(ConfigNames.folkmq_broker); saveEnable = Solon.cfg().getBool(ConfigNames.folkmq_snapshot_enable, true); long save900 = Solon.cfg().getLong(ConfigNames.folkmq_snapshot_save900, 0); long save300 = Solon.cfg().getLong(ConfigNames.folkmq_snapshot_save300, 0); long save100 = Solon.cfg().getLong(ConfigNames.folkmq_snapshot_save100, 0); //初始化快照持久化 snapshotPlus = new MqWatcherSnapshotPlus(); snapshotPlus.save900Condition(save900); snapshotPlus.save300Condition(save300); snapshotPlus.save100Condition(save100); appContext.wrapAndPut(MqWatcherSnapshotPlus.class, snapshotPlus); if (Utils.isEmpty(brokerServer)) { startLocalServerMode(snapshotPlus); } else { startBrokerSession(brokerServer, snapshotPlus); } log.info("Server:main: folkmq-server: Started (SOCKET.D/{}-{}, folkmq/{})", SocketD.protocolVersion(), SocketD.version(),
FolkMQ.version());
0
2023-11-18 19:09:28+00:00
12k
BlyznytsiaOrg/bring
web/src/main/java/io/github/blyznytsiaorg/bring/web/servlet/DispatcherServlet.java
[ { "identifier": "MissingApplicationMappingException", "path": "web/src/main/java/io/github/blyznytsiaorg/bring/web/servlet/exception/MissingApplicationMappingException.java", "snippet": "@ResponseStatus(value = HttpStatus.NOT_FOUND)\npublic class MissingApplicationMappingException extends RuntimeException {\n\n public MissingApplicationMappingException(String message) {\n super(message);\n }\n\n public MissingApplicationMappingException(String message,\n Throwable cause,\n boolean enableSuppression,\n boolean writableStackTrace) {\n super(message, cause, enableSuppression, writableStackTrace);\n }\n}" }, { "identifier": "MissingRequestParamException", "path": "web/src/main/java/io/github/blyznytsiaorg/bring/web/servlet/exception/MissingRequestParamException.java", "snippet": "public class MissingRequestParamException extends RuntimeException {\n public MissingRequestParamException(String message) {\n super(message);\n }\n}" }, { "identifier": "HttpHeaders", "path": "web/src/main/java/io/github/blyznytsiaorg/bring/web/servlet/http/HttpHeaders.java", "snippet": "public class HttpHeaders {\n\n /**\n * Map to store header name-value pairs.\n */\n private final Map<String, String> headers;\n\n /**\n * List containing all header names as strings.\n */\n private final List<String> headersNameList;\n\n /**\n * Constructs a new HttpHeaders object with an empty header map and initializes the list of header names.\n */\n public HttpHeaders() {\n this.headers = new HashMap<>();\n this.headersNameList = getAllHeadersNames();\n }\n\n /**\n * Retrieves the header name-value pairs.\n *\n * @return A map containing header name-value pairs.\n */\n public Map<String, String> getHeaders() {\n return headers;\n }\n\n /**\n * Retrieves a list of all header names.\n *\n * @return A list containing all header names.\n */\n public List<String> getHeadersNameList() {\n return headersNameList;\n }\n\n\n /**\n * Sets a single header with a specific value.\n *\n * @param headerName The name of the header to set.\n * @param headerValue The value of the header.\n */\n public void set(String headerName, String headerValue) {\n headers.put(headerName, headerValue);\n }\n\n /**\n * Sets a single header with multiple values, comma-separated.\n *\n * @param headerName The name of the header to set.\n * @param headerValues A list of values for the header.\n */\n public void set(String headerName, List<String> headerValues) {\n headers.put(headerName, toCommaDelimitedString(headerValues));\n }\n\n /**\n * Retrieves the value of a specific header.\n *\n * @param headerName The name of the header to retrieve.\n * @return The value of the specified header.\n */\n public String get(String headerName) {\n return headers.get(headerName);\n }\n\n /**\n * Retrieves a list of all available header names.\n *\n * @return A list containing all available header names.\n */\n private List<String> getAllHeadersNames() {\n return Arrays.stream(Name.values())\n .map(Name::getName)\n .toList();\n }\n\n /**\n * Converts a list of header values to a comma-separated string.\n *\n * @param headerValues A list of header values.\n * @return A comma-separated string containing all header values.\n */\n private String toCommaDelimitedString(List<String> headerValues) {\n return headerValues.stream()\n .filter(Objects::nonNull)\n .collect(Collectors.joining(\", \"));\n }\n\n /**\n * Enumeration containing common HTTP header names.\n */\n public enum Name {\n ACCEPT(\"Accept\"),\n ACCEPT_ENCODING(\"Accept-Encoding\"),\n AUTHORIZATION(\"Authorization\"),\n CACHE_CONTROL(\"Cache-Control\"),\n CONNECTION(\"Connection\"),\n CONTENT_ENCODING(\"Content-Encoding\"),\n CONTENT_LANGUAGE(\"Content-Language\"),\n CONTENT_LENGTH(\"Content-Length\"),\n CONTENT_TYPE(\"Content-Type\"),\n COOKIE(\"Cookie\"),\n ETAG(\"ETag\"),\n HOST(\"Host\"),\n LAST_MODIFIED(\"Last-Modified\"),\n LOCATION(\"Location\"),\n SET_COOKIE(\"Set-Cookie\");\n\n private final String name;\n\n Name(String name) {\n this.name = name;\n }\n\n /**\n * Retrieves the header name as a string.\n *\n * @return The name of the header.\n */\n public String getName() {\n return name;\n }\n }\n}" }, { "identifier": "HttpStatus", "path": "web/src/main/java/io/github/blyznytsiaorg/bring/web/servlet/http/HttpStatus.java", "snippet": "public enum HttpStatus {\n\n // 1xx Informational\n\n /**\n * {@code 100 Continue}.\n * @see <a href=\"https://tools.ietf.org/html/rfc7231#section-6.2.1\">HTTP/1.1: Semantics and Content, section 6.2.1</a>\n */\n CONTINUE(100, Series.INFORMATIONAL, \"Continue\"),\n /**\n * {@code 101 Switching Protocols}.\n * @see <a href=\"https://tools.ietf.org/html/rfc7231#section-6.2.2\">HTTP/1.1: Semantics and Content, section 6.2.2</a>\n */\n SWITCHING_PROTOCOLS(101, Series.INFORMATIONAL, \"Switching Protocols\"),\n /**\n * {@code 102 Processing}.\n * @see <a href=\"https://tools.ietf.org/html/rfc2518#section-10.1\">WebDAV</a>\n */\n PROCESSING(102, Series.INFORMATIONAL, \"Processing\"),\n /**\n * {@code 103 Early Hints}.\n * @see <a href=\"https://tools.ietf.org/html/rfc8297\">An HTTP Status Code for Indicating Hints</a>\n */\n EARLY_HINTS(103, Series.INFORMATIONAL, \"Early Hints\"),\n\n // 2xx Success\n\n /**\n * {@code 200 OK}.\n * @see <a href=\"https://tools.ietf.org/html/rfc7231#section-6.3.1\">HTTP/1.1: Semantics and Content, section 6.3.1</a>\n */\n OK(200, Series.SUCCESSFUL, \"OK\"),\n /**\n * {@code 201 Created}.\n * @see <a href=\"https://tools.ietf.org/html/rfc7231#section-6.3.2\">HTTP/1.1: Semantics and Content, section 6.3.2</a>\n */\n CREATED(201, Series.SUCCESSFUL, \"Created\"),\n /**\n * {@code 202 Accepted}.\n * @see <a href=\"https://tools.ietf.org/html/rfc7231#section-6.3.3\">HTTP/1.1: Semantics and Content, section 6.3.3</a>\n */\n ACCEPTED(202, Series.SUCCESSFUL, \"Accepted\"),\n /**\n * {@code 203 Non-Authoritative Information}.\n * @see <a href=\"https://tools.ietf.org/html/rfc7231#section-6.3.4\">HTTP/1.1: Semantics and Content, section 6.3.4</a>\n */\n NON_AUTHORITATIVE_INFORMATION(203, Series.SUCCESSFUL, \"Non-Authoritative Information\"),\n /**\n * {@code 204 No Content}.\n * @see <a href=\"https://tools.ietf.org/html/rfc7231#section-6.3.5\">HTTP/1.1: Semantics and Content, section 6.3.5</a>\n */\n NO_CONTENT(204, Series.SUCCESSFUL, \"No Content\"),\n /**\n * {@code 205 Reset Content}.\n * @see <a href=\"https://tools.ietf.org/html/rfc7231#section-6.3.6\">HTTP/1.1: Semantics and Content, section 6.3.6</a>\n */\n RESET_CONTENT(205, Series.SUCCESSFUL, \"Reset Content\"),\n /**\n * {@code 206 Partial Content}.\n * @see <a href=\"https://tools.ietf.org/html/rfc7233#section-4.1\">HTTP/1.1: Range Requests, section 4.1</a>\n */\n PARTIAL_CONTENT(206, Series.SUCCESSFUL, \"Partial Content\"),\n /**\n * {@code 207 Multi-Status}.\n * @see <a href=\"https://tools.ietf.org/html/rfc4918#section-13\">WebDAV</a>\n */\n MULTI_STATUS(207, Series.SUCCESSFUL, \"Multi-Status\"),\n /**\n * {@code 208 Already Reported}.\n * @see <a href=\"https://tools.ietf.org/html/rfc5842#section-7.1\">WebDAV Binding Extensions</a>\n */\n ALREADY_REPORTED(208, Series.SUCCESSFUL, \"Already Reported\"),\n /**\n * {@code 226 IM Used}.\n * @see <a href=\"https://tools.ietf.org/html/rfc3229#section-10.4.1\">Delta encoding in HTTP</a>\n */\n IM_USED(226, Series.SUCCESSFUL, \"IM Used\"),\n\n // 3xx Redirection\n\n /**\n * {@code 300 Multiple Choices}.\n * @see <a href=\"https://tools.ietf.org/html/rfc7231#section-6.4.1\">HTTP/1.1: Semantics and Content, section 6.4.1</a>\n */\n MULTIPLE_CHOICES(300, Series.REDIRECTION, \"Multiple Choices\"),\n /**\n * {@code 301 Moved Permanently}.\n * @see <a href=\"https://tools.ietf.org/html/rfc7231#section-6.4.2\">HTTP/1.1: Semantics and Content, section 6.4.2</a>\n */\n MOVED_PERMANENTLY(301, Series.REDIRECTION, \"Moved Permanently\"),\n /**\n * {@code 302 Found}.\n * @see <a href=\"https://tools.ietf.org/html/rfc7231#section-6.4.3\">HTTP/1.1: Semantics and Content, section 6.4.3</a>\n */\n FOUND(302, Series.REDIRECTION, \"Found\"),\n /**\n * {@code 303 See Other}.\n * @see <a href=\"https://tools.ietf.org/html/rfc7231#section-6.4.4\">HTTP/1.1: Semantics and Content, section 6.4.4</a>\n */\n SEE_OTHER(303, Series.REDIRECTION, \"See Other\"),\n /**\n * {@code 304 Not Modified}.\n * @see <a href=\"https://tools.ietf.org/html/rfc7232#section-4.1\">HTTP/1.1: Conditional Requests, section 4.1</a>\n */\n NOT_MODIFIED(304, Series.REDIRECTION, \"Not Modified\"),\n /**\n * {@code 307 Temporary Redirect}.\n * @see <a href=\"https://tools.ietf.org/html/rfc7231#section-6.4.7\">HTTP/1.1: Semantics and Content, section 6.4.7</a>\n */\n TEMPORARY_REDIRECT(307, Series.REDIRECTION, \"Temporary Redirect\"),\n /**\n * {@code 308 Permanent Redirect}.\n * @see <a href=\"https://tools.ietf.org/html/rfc7238\">RFC 7238</a>\n */\n PERMANENT_REDIRECT(308, Series.REDIRECTION, \"Permanent Redirect\"),\n\n // --- 4xx Client Error ---\n\n /**\n * {@code 400 Bad Request}.\n * @see <a href=\"https://tools.ietf.org/html/rfc7231#section-6.5.1\">HTTP/1.1: Semantics and Content, section 6.5.1</a>\n */\n BAD_REQUEST(400, Series.CLIENT_ERROR, \"Bad Request\"),\n /**\n * {@code 401 Unauthorized}.\n * @see <a href=\"https://tools.ietf.org/html/rfc7235#section-3.1\">HTTP/1.1: Authentication, section 3.1</a>\n */\n UNAUTHORIZED(401, Series.CLIENT_ERROR, \"Unauthorized\"),\n /**\n * {@code 402 Payment Required}.\n * @see <a href=\"https://tools.ietf.org/html/rfc7231#section-6.5.2\">HTTP/1.1: Semantics and Content, section 6.5.2</a>\n */\n PAYMENT_REQUIRED(402, Series.CLIENT_ERROR, \"Payment Required\"),\n /**\n * {@code 403 Forbidden}.\n * @see <a href=\"https://tools.ietf.org/html/rfc7231#section-6.5.3\">HTTP/1.1: Semantics and Content, section 6.5.3</a>\n */\n FORBIDDEN(403, Series.CLIENT_ERROR, \"Forbidden\"),\n /**\n * {@code 404 Not Found}.\n * @see <a href=\"https://tools.ietf.org/html/rfc7231#section-6.5.4\">HTTP/1.1: Semantics and Content, section 6.5.4</a>\n */\n NOT_FOUND(404, Series.CLIENT_ERROR, \"Not Found\"),\n /**\n * {@code 405 Method Not Allowed}.\n * @see <a href=\"https://tools.ietf.org/html/rfc7231#section-6.5.5\">HTTP/1.1: Semantics and Content, section 6.5.5</a>\n */\n METHOD_NOT_ALLOWED(405, Series.CLIENT_ERROR, \"Method Not Allowed\"),\n /**\n * {@code 406 Not Acceptable}.\n * @see <a href=\"https://tools.ietf.org/html/rfc7231#section-6.5.6\">HTTP/1.1: Semantics and Content, section 6.5.6</a>\n */\n NOT_ACCEPTABLE(406, Series.CLIENT_ERROR, \"Not Acceptable\"),\n /**\n * {@code 407 Proxy Authentication Required}.\n * @see <a href=\"https://tools.ietf.org/html/rfc7235#section-3.2\">HTTP/1.1: Authentication, section 3.2</a>\n */\n PROXY_AUTHENTICATION_REQUIRED(407, Series.CLIENT_ERROR, \"Proxy Authentication Required\"),\n /**\n * {@code 408 Request Timeout}.\n * @see <a href=\"https://tools.ietf.org/html/rfc7231#section-6.5.7\">HTTP/1.1: Semantics and Content, section 6.5.7</a>\n */\n REQUEST_TIMEOUT(408, Series.CLIENT_ERROR, \"Request Timeout\"),\n /**\n * {@code 409 Conflict}.\n * @see <a href=\"https://tools.ietf.org/html/rfc7231#section-6.5.8\">HTTP/1.1: Semantics and Content, section 6.5.8</a>\n */\n CONFLICT(409, Series.CLIENT_ERROR, \"Conflict\"),\n /**\n * {@code 410 Gone}.\n * @see <a href=\"https://tools.ietf.org/html/rfc7231#section-6.5.9\">\n * HTTP/1.1: Semantics and Content, section 6.5.9</a>\n */\n GONE(410, Series.CLIENT_ERROR, \"Gone\"),\n /**\n * {@code 411 Length Required}.\n * @see <a href=\"https://tools.ietf.org/html/rfc7231#section-6.5.10\">\n * HTTP/1.1: Semantics and Content, section 6.5.10</a>\n */\n LENGTH_REQUIRED(411, Series.CLIENT_ERROR, \"Length Required\"),\n /**\n * {@code 412 Precondition failed}.\n * @see <a href=\"https://tools.ietf.org/html/rfc7232#section-4.2\">\n * HTTP/1.1: Conditional Requests, section 4.2</a>\n */\n PRECONDITION_FAILED(412, Series.CLIENT_ERROR, \"Precondition Failed\"),\n /**\n * {@code 413 Payload Too Large}.\n * @see <a href=\"https://tools.ietf.org/html/rfc7231#section-6.5.11\">\n * HTTP/1.1: Semantics and Content, section 6.5.11</a>\n */\n PAYLOAD_TOO_LARGE(413, Series.CLIENT_ERROR, \"Payload Too Large\"),\n /**\n * {@code 414 URI Too Long}.\n * @see <a href=\"https://tools.ietf.org/html/rfc7231#section-6.5.12\">\n * HTTP/1.1: Semantics and Content, section 6.5.12</a>\n */\n URI_TOO_LONG(414, Series.CLIENT_ERROR, \"URI Too Long\"),\n /**\n * {@code 415 Unsupported Media Type}.\n * @see <a href=\"https://tools.ietf.org/html/rfc7231#section-6.5.13\">\n * HTTP/1.1: Semantics and Content, section 6.5.13</a>\n */\n UNSUPPORTED_MEDIA_TYPE(415, Series.CLIENT_ERROR, \"Unsupported Media Type\"),\n /**\n * {@code 416 Requested Range Not Satisfiable}.\n * @see <a href=\"https://tools.ietf.org/html/rfc7233#section-4.4\">HTTP/1.1: Range Requests, section 4.4</a>\n */\n REQUESTED_RANGE_NOT_SATISFIABLE(416, Series.CLIENT_ERROR, \"Requested range not satisfiable\"),\n /**\n * {@code 417 Expectation Failed}.\n * @see <a href=\"https://tools.ietf.org/html/rfc7231#section-6.5.14\">\n * HTTP/1.1: Semantics and Content, section 6.5.14</a>\n */\n EXPECTATION_FAILED(417, Series.CLIENT_ERROR, \"Expectation Failed\"),\n /**\n * {@code 418 I'm a teapot}.\n * @see <a href=\"https://tools.ietf.org/html/rfc2324#section-2.3.2\">HTCPCP/1.0</a>\n */\n I_AM_A_TEAPOT(418, Series.CLIENT_ERROR, \"I'm a teapot\"),\n /**\n * {@code 422 Unprocessable Entity}.\n * @see <a href=\"https://tools.ietf.org/html/rfc4918#section-11.2\">WebDAV</a>\n */\n UNPROCESSABLE_ENTITY(422, Series.CLIENT_ERROR, \"Unprocessable Entity\"),\n /**\n * {@code 423 Locked}.\n * @see <a href=\"https://tools.ietf.org/html/rfc4918#section-11.3\">WebDAV</a>\n */\n LOCKED(423, Series.CLIENT_ERROR, \"Locked\"),\n /**\n * {@code 424 Failed Dependency}.\n * @see <a href=\"https://tools.ietf.org/html/rfc4918#section-11.4\">WebDAV</a>\n */\n FAILED_DEPENDENCY(424, Series.CLIENT_ERROR, \"Failed Dependency\"),\n /**\n * {@code 425 Too Early}.\n * @see <a href=\"https://tools.ietf.org/html/rfc8470\">RFC 8470</a>\n */\n TOO_EARLY(425, Series.CLIENT_ERROR, \"Too Early\"),\n /**\n * {@code 426 Upgrade Required}.\n * @see <a href=\"https://tools.ietf.org/html/rfc2817#section-6\">Upgrading to TLS Within HTTP/1.1</a>\n */\n UPGRADE_REQUIRED(426, Series.CLIENT_ERROR, \"Upgrade Required\"),\n /**\n * {@code 428 Precondition Required}.\n * @see <a href=\"https://tools.ietf.org/html/rfc6585#section-3\">Additional HTTP Status Codes</a>\n */\n PRECONDITION_REQUIRED(428, Series.CLIENT_ERROR, \"Precondition Required\"),\n /**\n * {@code 429 Too Many Requests}.\n * @see <a href=\"https://tools.ietf.org/html/rfc6585#section-4\">Additional HTTP Status Codes</a>\n */\n TOO_MANY_REQUESTS(429, Series.CLIENT_ERROR, \"Too Many Requests\"),\n /**\n * {@code 431 Request Header Fields Too Large}.\n * @see <a href=\"https://tools.ietf.org/html/rfc6585#section-5\">Additional HTTP Status Codes</a>\n */\n REQUEST_HEADER_FIELDS_TOO_LARGE(431, Series.CLIENT_ERROR, \"Request Header Fields Too Large\"),\n /**\n * {@code 451 Unavailable For Legal Reasons}.\n * @see <a href=\"https://tools.ietf.org/html/draft-ietf-httpbis-legally-restricted-status-04\">\n * An HTTP Status Code to Report Legal Obstacles</a>\n */\n UNAVAILABLE_FOR_LEGAL_REASONS(451, Series.CLIENT_ERROR, \"Unavailable For Legal Reasons\"),\n\n // --- 5xx Server Error ---\n\n /**\n * {@code 500 Internal Server Error}.\n * @see <a href=\"https://tools.ietf.org/html/rfc7231#section-6.6.1\">HTTP/1.1: Semantics and Content, section 6.6.1</a>\n */\n INTERNAL_SERVER_ERROR(500, Series.SERVER_ERROR, \"Internal Server Error\"),\n /**\n * {@code 501 Not Implemented}.\n * @see <a href=\"https://tools.ietf.org/html/rfc7231#section-6.6.2\">HTTP/1.1: Semantics and Content, section 6.6.2</a>\n */\n NOT_IMPLEMENTED(501, Series.SERVER_ERROR, \"Not Implemented\"),\n /**\n * {@code 502 Bad Gateway}.\n * @see <a href=\"https://tools.ietf.org/html/rfc7231#section-6.6.3\">HTTP/1.1: Semantics and Content, section 6.6.3</a>\n */\n BAD_GATEWAY(502, Series.SERVER_ERROR, \"Bad Gateway\"),\n /**\n * {@code 503 Service Unavailable}.\n * @see <a href=\"https://tools.ietf.org/html/rfc7231#section-6.6.4\">HTTP/1.1: Semantics and Content, section 6.6.4</a>\n */\n SERVICE_UNAVAILABLE(503, Series.SERVER_ERROR, \"Service Unavailable\"),\n /**\n * {@code 504 Gateway Timeout}.\n * @see <a href=\"https://tools.ietf.org/html/rfc7231#section-6.6.5\">HTTP/1.1: Semantics and Content, section 6.6.5</a>\n */\n GATEWAY_TIMEOUT(504, Series.SERVER_ERROR, \"Gateway Timeout\"),\n /**\n * {@code 505 HTTP Version Not Supported}.\n * @see <a href=\"https://tools.ietf.org/html/rfc7231#section-6.6.6\">HTTP/1.1: Semantics and Content, section 6.6.6</a>\n */\n HTTP_VERSION_NOT_SUPPORTED(505, Series.SERVER_ERROR, \"HTTP Version not supported\"),\n /**\n * {@code 506 Variant Also Negotiates}\n * @see <a href=\"https://tools.ietf.org/html/rfc2295#section-8.1\">Transparent Content Negotiation</a>\n */\n VARIANT_ALSO_NEGOTIATES(506, Series.SERVER_ERROR, \"Variant Also Negotiates\"),\n /**\n * {@code 507 Insufficient Storage}\n * @see <a href=\"https://tools.ietf.org/html/rfc4918#section-11.5\">WebDAV</a>\n */\n INSUFFICIENT_STORAGE(507, Series.SERVER_ERROR, \"Insufficient Storage\"),\n /**\n * {@code 508 Loop Detected}\n * @see <a href=\"https://tools.ietf.org/html/rfc5842#section-7.2\">WebDAV Binding Extensions</a>\n */\n LOOP_DETECTED(508, Series.SERVER_ERROR, \"Loop Detected\"),\n /**\n * {@code 509 Bandwidth Limit Exceeded}\n */\n BANDWIDTH_LIMIT_EXCEEDED(509, Series.SERVER_ERROR, \"Bandwidth Limit Exceeded\"),\n /**\n * {@code 510 Not Extended}\n * @see <a href=\"https://tools.ietf.org/html/rfc2774#section-7\">HTTP Extension Framework</a>\n */\n NOT_EXTENDED(510, Series.SERVER_ERROR, \"Not Extended\"),\n /**\n * {@code 511 Network Authentication Required}.\n * @see <a href=\"https://tools.ietf.org/html/rfc6585#section-6\">Additional HTTP Status Codes</a>\n */\n NETWORK_AUTHENTICATION_REQUIRED(511, Series.SERVER_ERROR, \"Network Authentication Required\");\n\n private final int value;\n\n private final Series series;\n\n private final String reasonPhrase;\n\n HttpStatus(int value, Series series, String reasonPhrase) {\n this.value = value;\n this.series = series;\n this.reasonPhrase = reasonPhrase;\n }\n\n public int getValue() {\n return value;\n }\n\n public Series getSeries() {\n return series;\n }\n\n public String getReasonPhrase() {\n return reasonPhrase;\n }\n\n public enum Series {\n\n INFORMATIONAL(1),\n SUCCESSFUL(2),\n REDIRECTION(3),\n CLIENT_ERROR(4),\n SERVER_ERROR(5);\n\n Series(int value) {\n this.value = value;\n }\n\n private final int value;\n\n public int getValue() {\n return value;\n }\n }\n}" }, { "identifier": "ResponseEntity", "path": "web/src/main/java/io/github/blyznytsiaorg/bring/web/servlet/http/ResponseEntity.java", "snippet": "public class ResponseEntity<T> {\n\n private final HttpHeaders headers;\n private final T body;\n private final HttpStatus httpStatus;\n\n /**\n * Constructs a new ResponseEntity with the given body, headers, and HTTP status.\n *\n * @param body The response body.\n * @param headers The headers to be included in the response.\n * @param httpStatus The HTTP status of the response.\n */\n public ResponseEntity(T body, HttpHeaders headers, HttpStatus httpStatus) {\n this.body = body;\n this.headers = headers;\n this.httpStatus = httpStatus;\n }\n\n\n /**\n * Constructs a new ResponseEntity with the given body and HTTP status.\n *\n * @param body The response body.\n * @param httpStatus The HTTP status of the response.\n */\n public ResponseEntity(T body, HttpStatus httpStatus) {\n this(body, null, httpStatus);\n }\n\n /**\n * Constructs a new ResponseEntity with the given headers and HTTP status.\n *\n * @param headers The headers to be included in the response.\n * @param httpStatus The HTTP status of the response.\n */\n public ResponseEntity(HttpHeaders headers, HttpStatus httpStatus) {\n this(null, headers, httpStatus);\n }\n\n /**\n * Gets the headers included in the response.\n *\n * @return The headers of the response.\n */\n public HttpHeaders getHeaders() {\n return headers;\n }\n\n /**\n * Gets the body of the response.\n *\n * @return The response body.\n */\n public T getBody() {\n return body;\n }\n\n /**\n * Gets the HTTP status of the response.\n *\n * @return The HTTP status.\n */\n public HttpStatus getHttpStatus() {\n return httpStatus;\n }\n}" }, { "identifier": "ReflectionUtils", "path": "web/src/main/java/io/github/blyznytsiaorg/bring/web/utils/ReflectionUtils.java", "snippet": "@UtilityClass\npublic final class ReflectionUtils {\n\n /**\n * An instance of Paranamer for parameter name lookup.\n */\n private final Paranamer info = new CachingParanamer(new AnnotationParanamer(new BytecodeReadingParanamer()));\n\n /**\n * Retrieves the parameter names of the specified accessible method or constructor.\n *\n * @param method The accessible method or constructor.\n * @return A list of parameter names in the order they appear in the method signature.\n */\n public List<String> getParameterNames(AccessibleObject method) {\n return Arrays.stream(info.lookupParameterNames(method)).toList();\n }\n}" }, { "identifier": "getRequestPath", "path": "web/src/main/java/io/github/blyznytsiaorg/bring/web/utils/HttpServletRequestUtils.java", "snippet": "public static String getRequestPath(HttpServletRequest req) {\n String contextPath = req.getContextPath();\n String requestURI = req.getRequestURI();\n if (requestURI.startsWith(contextPath)) {\n requestURI = requestURI.replace(contextPath, EMPTY);\n }\n return requestURI.equals(\"/\") ? \"\" : requestURI;\n}" }, { "identifier": "getShortenedPath", "path": "web/src/main/java/io/github/blyznytsiaorg/bring/web/utils/HttpServletRequestUtils.java", "snippet": "public static String getShortenedPath(String requestPath) {\n String requestPathShortened;\n int index = requestPath.lastIndexOf(\"/\");\n requestPathShortened = requestPath.substring(0, index + 1);\n return requestPathShortened;\n}" }, { "identifier": "parseToParameterType", "path": "web/src/main/java/io/github/blyznytsiaorg/bring/web/utils/ParameterTypeUtils.java", "snippet": "public static Object parseToParameterType(String pathVariable, Class<?> type) {\n Object obj;\n try {\n if (type.equals(String.class)) {\n obj = pathVariable;\n } else if (type.equals(Long.class) || type.equals(long.class)) {\n obj = Long.parseLong(pathVariable);\n } else if (type.equals(Double.class) || type.equals(double.class)) {\n obj = Double.parseDouble(pathVariable);\n } else if (type.equals(Float.class) || type.equals(float.class)) {\n obj = Float.parseFloat(pathVariable);\n } else if (type.equals(Integer.class) || type.equals(int.class)) {\n obj = Integer.parseInt(pathVariable);\n } else if (type.equals(Byte.class) || type.equals(byte.class)) {\n obj = Byte.parseByte(pathVariable);\n } else if (type.equals(Short.class) || type.equals(short.class)) {\n obj = Short.parseShort(pathVariable);\n } else if (type.equals(Character.class) || type.equals(char.class)) {\n obj = pathVariable.charAt(0);\n } else if (type.equals(Boolean.class) || type.equals(boolean.class)) {\n if (pathVariable.equals(TRUE)) {\n obj = Boolean.TRUE;\n } else if (pathVariable.equals(FALSE)) {\n obj = Boolean.FALSE;\n } else {\n throw new MethodArgumentTypeMismatchException(\n String.format(\"Failed to convert value of type 'java.lang.String' \"\n + \"to required type '%s'; Invalid value [%s]\", type.getName(), pathVariable));\n }\n } else {\n throw new TypeArgumentUnsupportedException(\n String.format(\"The type parameter: '%s' is not supported\", type.getName()));\n }\n return obj;\n } catch (NumberFormatException exception) {\n throw new MethodArgumentTypeMismatchException(\n String.format(\"Failed to convert value of type 'java.lang.String' \"\n + \"to required type '%s'; Invalid value [%s]\", type.getName(), pathVariable));\n }\n}" } ]
import io.github.blyznytsiaorg.bring.core.annotation.Component; import io.github.blyznytsiaorg.bring.web.servlet.annotation.PathVariable; import io.github.blyznytsiaorg.bring.web.servlet.annotation.RequestBody; import io.github.blyznytsiaorg.bring.web.servlet.annotation.RequestHeader; import io.github.blyznytsiaorg.bring.web.servlet.annotation.RequestParam; import io.github.blyznytsiaorg.bring.web.servlet.annotation.ResponseStatus; import io.github.blyznytsiaorg.bring.web.servlet.exception.MissingApplicationMappingException; import io.github.blyznytsiaorg.bring.web.servlet.exception.MissingRequestParamException; import io.github.blyznytsiaorg.bring.web.servlet.http.HttpHeaders; import io.github.blyznytsiaorg.bring.web.servlet.http.HttpStatus; import io.github.blyznytsiaorg.bring.web.servlet.http.ResponseEntity; import io.github.blyznytsiaorg.bring.web.servlet.mapping.RestControllerParams; import io.github.blyznytsiaorg.bring.web.servlet.mapping.RestControllerProcessResult; import io.github.blyznytsiaorg.bring.web.utils.ReflectionUtils; import com.fasterxml.jackson.databind.ObjectMapper; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; import java.io.BufferedReader; import java.io.IOException; import java.io.PrintWriter; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Parameter; import java.util.*; import java.util.regex.Pattern; import java.util.stream.Collectors; import static io.github.blyznytsiaorg.bring.web.utils.HttpServletRequestUtils.getRequestPath; import static io.github.blyznytsiaorg.bring.web.utils.HttpServletRequestUtils.getShortenedPath; import static io.github.blyznytsiaorg.bring.web.utils.ParameterTypeUtils.parseToParameterType;
9,554
package io.github.blyznytsiaorg.bring.web.servlet; /** * The {@code DispatcherServlet} class extends {@code FrameworkServlet} and serves as the central * dispatcher for handling HTTP requests in a RESTful web application. * It processes incoming requests, resolves appropriate controllers and manages response generation. * * <p> * The class supports the annotation-based mapping of controllers and provides a flexible mechanism * for handling various types of parameters in controller methods. * </p> * * <p> * Key Constants: * - {@code REST_CONTROLLER_PARAMS}: Key for storing REST controller parameters in the servlet context. * - {@code REGEX_STATIC_URL}: Regular expression for matching static URLs. * </p> * * <p> * Key Components: * - {@code objectMapper}: Object mapper for converting between JSON and Java objects. * </p> * * @see RestControllerContext * @since 1.0 */ @Component @Slf4j public class DispatcherServlet extends FrameworkServlet { private static final String MISSING_APPLICATION_MAPPING_MESSAGE = "This application has no explicit mapping for '%s'"; public static final String REST_CONTROLLER_PARAMS = "REST_CONTROLLER_PARAMS"; public static final String REGEX_STATIC_URL = "^/static/.*$"; public static final int HTTP_STATUS_OK = 200; private final ObjectMapper objectMapper; public DispatcherServlet(ObjectMapper objectMapper) { this.objectMapper = objectMapper; } /** * Overrides the {@code processRequest} method of {@code FrameworkServlet}. * Processes incoming HTTP requests by obtaining REST controller parameters and * delegating the processing to {@code processRestControllerRequest}. * * @param req HttpServletRequest object representing the HTTP request. * @param resp HttpServletResponse object representing the HTTP response. */ @Override public void processRequest(HttpServletRequest req, HttpServletResponse resp) { log.info("Got a {} request by path: {}", req.getMethod(), req.getRequestURI()); RestControllerParams restControllerParams = getRestControllerParams(req); processRestControllerRequest(restControllerParams, req, resp); } /** * Retrieves the {@code RestControllerParams} for the given {@code HttpServletRequest}. * The method uses the request's method and path to find the corresponding controller parameters * stored in the servlet context. It filters the parameters based on the path and path variables, * then returns the first match. If no match is found, it throws a {@code MissingApplicationMappingException}. * * @param req HttpServletRequest object representing the HTTP request. * @return The matched {@code RestControllerParams} for the request. * @throws MissingApplicationMappingException If no explicit mapping is found for the request. */ @SuppressWarnings("unchecked") private RestControllerParams getRestControllerParams(HttpServletRequest req) { String requestPath = getRequestPath(req); String methodName = req.getMethod(); var restControllerParams = (Map<String, List<RestControllerParams>>) req.getServletContext() .getAttribute(REST_CONTROLLER_PARAMS); return restControllerParams.getOrDefault(methodName, Collections.emptyList()) .stream() .filter(params -> checkParams(requestPath, params)) .findFirst() .orElseThrow(() -> { log.warn(String.format(MISSING_APPLICATION_MAPPING_MESSAGE, getRequestPath(req))); return new MissingApplicationMappingException( String.format(MISSING_APPLICATION_MAPPING_MESSAGE, getRequestPath(req)), null, true, false); }); } /** * Checks if the given {@code RestControllerParams} match the provided request path. * If the controller method has path variables, it shortens the request path accordingly. * The method returns true if the paths match, considering path variables and static URLs. * * @param requestPath The path of the HTTP request. * @param params The {@code RestControllerParams} to check against. * @return True if the paths match; false otherwise. */ private boolean checkParams(String requestPath, RestControllerParams params) { Method method = params.method(); Parameter[] parameters = method.getParameters(); if (checkIfPathVariableAnnotationIsPresent(parameters)) { String requestPathShortened = getShortenedPath(requestPath); return requestPathShortened.equals(params.path()); } return requestPath.equals(params.path()) || checkIfUrlIsStatic(requestPath, params.path()); } /** * Processes the HTTP request for a specific {@code RestControllerParams}. * Invokes the corresponding controller method with the provided arguments and handles the resulting response. * * @param params The {@code RestControllerParams} representing the controller method to invoke. * @param req HttpServletRequest object representing the HTTP request. * @param resp HttpServletResponse object representing the HTTP response. */ @SneakyThrows private void processRestControllerRequest(RestControllerParams params, HttpServletRequest req, HttpServletResponse resp) { String requestPath = getRequestPath(req); Object instance = params.instance(); Method method = params.method(); Object[] args = (method.getParameterCount() == 0) ? new Object[0] : prepareArgs(req, resp, requestPath, method); getRestControllerProcessResult(instance, method, resp, args); } /** * Invokes the controller method with the provided arguments and handles the resulting response. * If the method returns a non-null result, it is passed to the {@code performResponse} method * along with method metadata (e.g., annotations). The response is then written to the provided {@code HttpServletResponse}. * * @param instance The instance of the controller. * @param method The controller method to invoke. * @param resp The {@code HttpServletResponse} object representing the HTTP response. * @param args The arguments to be passed to the controller method. * @throws IllegalAccessException If the method is inaccessible. * @throws InvocationTargetException If the invoked method throws an exception. */ private void getRestControllerProcessResult( Object instance, Method method, HttpServletResponse resp, Object... args) throws IllegalAccessException, InvocationTargetException { log.trace("Invoking {} method {}", instance.getClass().getSimpleName(), method.getName()); Optional.ofNullable(method.invoke(instance, args)) .ifPresent(result -> performResponse(new RestControllerProcessResult(method, result), resp)); } /** * Handles the response generated by a controller method. * Checks if the response is an instance of {@code ResponseEntity}. * If it is, processes the response entity, including HTTP status and headers. * Writes the final response (including possible modifications) to the provided {@code HttpServletResponse}. * * @param processResult The result of the controller method execution, including metadata. * @param resp The {@code HttpServletResponse} object representing the HTTP response. */ @SneakyThrows private void performResponse(RestControllerProcessResult processResult, HttpServletResponse resp) { Object response = processResult.result(); Object body; if (response instanceof ResponseEntity<?> entity) { body = processResponseEntity(resp, entity); } else { body = response; } processResponseStatusAnnotation(processResult, resp); try (PrintWriter writer = resp.getWriter()) { if (!checkIfBodyIsSimple(body)) { body = objectMapper.writeValueAsString(body); } writer.print(body); writer.flush(); } } /** * Processes the {@code ResponseStatus} annotation, if present, for a controller method. * Sets the HTTP status code of the provided {@code HttpServletResponse} based on the annotation value. * * @param processResult The result of the controller method execution, including metadata. * @param resp The {@code HttpServletResponse} object representing the HTTP response. */ private void processResponseStatusAnnotation(RestControllerProcessResult processResult, HttpServletResponse resp) { Method method = processResult.method(); if (method.isAnnotationPresent(ResponseStatus.class)) { ResponseStatus annotation = method.getAnnotation(ResponseStatus.class); int statusValue = annotation.value().getValue(); if (statusValue != HTTP_STATUS_OK) { resp.setStatus(statusValue); } } } /** * Processes a {@code ResponseEntity} object, setting the HTTP status code and headers * in the provided {@code HttpServletResponse}. Retrieves and returns the response body. * * @param resp The {@code HttpServletResponse} object representing the HTTP response. * @param entity The {@code ResponseEntity} object containing response information. * @return The response body extracted from the {@code ResponseEntity}. */ private Object processResponseEntity(HttpServletResponse resp, ResponseEntity<?> entity) {
package io.github.blyznytsiaorg.bring.web.servlet; /** * The {@code DispatcherServlet} class extends {@code FrameworkServlet} and serves as the central * dispatcher for handling HTTP requests in a RESTful web application. * It processes incoming requests, resolves appropriate controllers and manages response generation. * * <p> * The class supports the annotation-based mapping of controllers and provides a flexible mechanism * for handling various types of parameters in controller methods. * </p> * * <p> * Key Constants: * - {@code REST_CONTROLLER_PARAMS}: Key for storing REST controller parameters in the servlet context. * - {@code REGEX_STATIC_URL}: Regular expression for matching static URLs. * </p> * * <p> * Key Components: * - {@code objectMapper}: Object mapper for converting between JSON and Java objects. * </p> * * @see RestControllerContext * @since 1.0 */ @Component @Slf4j public class DispatcherServlet extends FrameworkServlet { private static final String MISSING_APPLICATION_MAPPING_MESSAGE = "This application has no explicit mapping for '%s'"; public static final String REST_CONTROLLER_PARAMS = "REST_CONTROLLER_PARAMS"; public static final String REGEX_STATIC_URL = "^/static/.*$"; public static final int HTTP_STATUS_OK = 200; private final ObjectMapper objectMapper; public DispatcherServlet(ObjectMapper objectMapper) { this.objectMapper = objectMapper; } /** * Overrides the {@code processRequest} method of {@code FrameworkServlet}. * Processes incoming HTTP requests by obtaining REST controller parameters and * delegating the processing to {@code processRestControllerRequest}. * * @param req HttpServletRequest object representing the HTTP request. * @param resp HttpServletResponse object representing the HTTP response. */ @Override public void processRequest(HttpServletRequest req, HttpServletResponse resp) { log.info("Got a {} request by path: {}", req.getMethod(), req.getRequestURI()); RestControllerParams restControllerParams = getRestControllerParams(req); processRestControllerRequest(restControllerParams, req, resp); } /** * Retrieves the {@code RestControllerParams} for the given {@code HttpServletRequest}. * The method uses the request's method and path to find the corresponding controller parameters * stored in the servlet context. It filters the parameters based on the path and path variables, * then returns the first match. If no match is found, it throws a {@code MissingApplicationMappingException}. * * @param req HttpServletRequest object representing the HTTP request. * @return The matched {@code RestControllerParams} for the request. * @throws MissingApplicationMappingException If no explicit mapping is found for the request. */ @SuppressWarnings("unchecked") private RestControllerParams getRestControllerParams(HttpServletRequest req) { String requestPath = getRequestPath(req); String methodName = req.getMethod(); var restControllerParams = (Map<String, List<RestControllerParams>>) req.getServletContext() .getAttribute(REST_CONTROLLER_PARAMS); return restControllerParams.getOrDefault(methodName, Collections.emptyList()) .stream() .filter(params -> checkParams(requestPath, params)) .findFirst() .orElseThrow(() -> { log.warn(String.format(MISSING_APPLICATION_MAPPING_MESSAGE, getRequestPath(req))); return new MissingApplicationMappingException( String.format(MISSING_APPLICATION_MAPPING_MESSAGE, getRequestPath(req)), null, true, false); }); } /** * Checks if the given {@code RestControllerParams} match the provided request path. * If the controller method has path variables, it shortens the request path accordingly. * The method returns true if the paths match, considering path variables and static URLs. * * @param requestPath The path of the HTTP request. * @param params The {@code RestControllerParams} to check against. * @return True if the paths match; false otherwise. */ private boolean checkParams(String requestPath, RestControllerParams params) { Method method = params.method(); Parameter[] parameters = method.getParameters(); if (checkIfPathVariableAnnotationIsPresent(parameters)) { String requestPathShortened = getShortenedPath(requestPath); return requestPathShortened.equals(params.path()); } return requestPath.equals(params.path()) || checkIfUrlIsStatic(requestPath, params.path()); } /** * Processes the HTTP request for a specific {@code RestControllerParams}. * Invokes the corresponding controller method with the provided arguments and handles the resulting response. * * @param params The {@code RestControllerParams} representing the controller method to invoke. * @param req HttpServletRequest object representing the HTTP request. * @param resp HttpServletResponse object representing the HTTP response. */ @SneakyThrows private void processRestControllerRequest(RestControllerParams params, HttpServletRequest req, HttpServletResponse resp) { String requestPath = getRequestPath(req); Object instance = params.instance(); Method method = params.method(); Object[] args = (method.getParameterCount() == 0) ? new Object[0] : prepareArgs(req, resp, requestPath, method); getRestControllerProcessResult(instance, method, resp, args); } /** * Invokes the controller method with the provided arguments and handles the resulting response. * If the method returns a non-null result, it is passed to the {@code performResponse} method * along with method metadata (e.g., annotations). The response is then written to the provided {@code HttpServletResponse}. * * @param instance The instance of the controller. * @param method The controller method to invoke. * @param resp The {@code HttpServletResponse} object representing the HTTP response. * @param args The arguments to be passed to the controller method. * @throws IllegalAccessException If the method is inaccessible. * @throws InvocationTargetException If the invoked method throws an exception. */ private void getRestControllerProcessResult( Object instance, Method method, HttpServletResponse resp, Object... args) throws IllegalAccessException, InvocationTargetException { log.trace("Invoking {} method {}", instance.getClass().getSimpleName(), method.getName()); Optional.ofNullable(method.invoke(instance, args)) .ifPresent(result -> performResponse(new RestControllerProcessResult(method, result), resp)); } /** * Handles the response generated by a controller method. * Checks if the response is an instance of {@code ResponseEntity}. * If it is, processes the response entity, including HTTP status and headers. * Writes the final response (including possible modifications) to the provided {@code HttpServletResponse}. * * @param processResult The result of the controller method execution, including metadata. * @param resp The {@code HttpServletResponse} object representing the HTTP response. */ @SneakyThrows private void performResponse(RestControllerProcessResult processResult, HttpServletResponse resp) { Object response = processResult.result(); Object body; if (response instanceof ResponseEntity<?> entity) { body = processResponseEntity(resp, entity); } else { body = response; } processResponseStatusAnnotation(processResult, resp); try (PrintWriter writer = resp.getWriter()) { if (!checkIfBodyIsSimple(body)) { body = objectMapper.writeValueAsString(body); } writer.print(body); writer.flush(); } } /** * Processes the {@code ResponseStatus} annotation, if present, for a controller method. * Sets the HTTP status code of the provided {@code HttpServletResponse} based on the annotation value. * * @param processResult The result of the controller method execution, including metadata. * @param resp The {@code HttpServletResponse} object representing the HTTP response. */ private void processResponseStatusAnnotation(RestControllerProcessResult processResult, HttpServletResponse resp) { Method method = processResult.method(); if (method.isAnnotationPresent(ResponseStatus.class)) { ResponseStatus annotation = method.getAnnotation(ResponseStatus.class); int statusValue = annotation.value().getValue(); if (statusValue != HTTP_STATUS_OK) { resp.setStatus(statusValue); } } } /** * Processes a {@code ResponseEntity} object, setting the HTTP status code and headers * in the provided {@code HttpServletResponse}. Retrieves and returns the response body. * * @param resp The {@code HttpServletResponse} object representing the HTTP response. * @param entity The {@code ResponseEntity} object containing response information. * @return The response body extracted from the {@code ResponseEntity}. */ private Object processResponseEntity(HttpServletResponse resp, ResponseEntity<?> entity) {
HttpStatus httpStatus = entity.getHttpStatus();
3
2023-11-10 13:42:05+00:00
12k
johndeweyzxc/AWPS-Command
app/src/main/java/com/johndeweydev/awps/view/manualarmafragment/ManualArmaFragment.java
[ { "identifier": "BAUD_RATE", "path": "app/src/main/java/com/johndeweydev/awps/AppConstants.java", "snippet": "public static final int BAUD_RATE = 19200;" }, { "identifier": "DATA_BITS", "path": "app/src/main/java/com/johndeweydev/awps/AppConstants.java", "snippet": "public static final int DATA_BITS = 8;" }, { "identifier": "PARITY_NONE", "path": "app/src/main/java/com/johndeweydev/awps/AppConstants.java", "snippet": "public static final String PARITY_NONE = \"PARITY_NONE\";" }, { "identifier": "STOP_BITS", "path": "app/src/main/java/com/johndeweydev/awps/AppConstants.java", "snippet": "public static final int STOP_BITS = 1;" }, { "identifier": "HashInfoEntity", "path": "app/src/main/java/com/johndeweydev/awps/model/data/HashInfoEntity.java", "snippet": "@Entity(tableName = \"hash_information\")\npublic class HashInfoEntity {\n\n @PrimaryKey(autoGenerate = true)\n public int uid;\n @ColumnInfo(name = \"ssid\")\n public String ssid;\n @ColumnInfo(name = \"bssid\")\n public String bssid;\n @ColumnInfo(name = \"client_mac_address\")\n public String clientMacAddress;\n\n // The key type can be either \"PMKID\" in the case of PMKID based attack or \"MIC\" in the case\n // of MIC based attack\n @ColumnInfo(name = \"key_type\")\n public String keyType;\n\n // The anonce or access point nonce from the first eapol message, this is initialized in the\n // case of MIC based attack otherwise its value is \"None\" in the case of PMKID based attack\n @ColumnInfo(name = \"a_nonce\")\n public String aNonce;\n\n // The hash data is where the actual PMKID or MIC is stored\n @ColumnInfo(name = \"hash_data\")\n public String hashData;\n\n // The key data is where the second eapol authentication message is stored in the case of\n // MIC based attack otherwise its value is \"None\"\n @ColumnInfo(name = \"key_data\")\n public String keyData;\n @ColumnInfo(name = \"date_captured\")\n public String dateCaptured;\n\n @ColumnInfo(name = \"latitude\")\n public String latitude;\n @ColumnInfo(name = \"longitude\")\n public String longitude;\n @ColumnInfo(name = \"address\")\n public String address;\n\n public HashInfoEntity(\n @Nullable String ssid,\n @Nullable String bssid,\n @Nullable String clientMacAddress,\n @Nullable String keyType,\n @Nullable String aNonce,\n @Nullable String hashData,\n @Nullable String keyData,\n @Nullable String dateCaptured,\n @Nullable String latitude,\n @Nullable String longitude,\n @Nullable String address\n ) {\n this.ssid = ssid;\n this.bssid = bssid;\n this.clientMacAddress = clientMacAddress;\n this.keyType = keyType;\n this.aNonce = aNonce;\n this.hashData = hashData;\n this.keyData = keyData;\n this.dateCaptured = dateCaptured;\n this.latitude = latitude;\n this.longitude = longitude;\n this.address = address;\n }\n}" }, { "identifier": "SessionRepoSerial", "path": "app/src/main/java/com/johndeweydev/awps/model/repo/serial/sessionreposerial/SessionRepoSerial.java", "snippet": "public class SessionRepoSerial extends RepositoryIOControl implements Launcher.UsbSerialIOEvent {\n\n public interface RepositoryEvent extends RepositoryIOEvent, InitializationPhase,\n TargetLockingPhase, ExecutionPhase, PostExecutionPhase {}\n\n private SessionRepoSerial.RepositoryEvent repositoryEvent;\n private final StringBuilder queueData = new StringBuilder();\n @Override\n public void onUsbSerialOutput(String data) {\n char[] dataChar = data.toCharArray();\n for (char c : dataChar) {\n if (c == '\\n') {\n processFormattedOutput();\n queueData.setLength(0);\n } else {\n queueData.append(c);\n }\n }\n }\n\n @Override\n public void onUsbSerialOutputError(String error) {\n repositoryEvent.onRepoOutputError(error);\n }\n\n @Override\n public void onUsbSerialInputError(String input) {\n repositoryEvent.onRepoInputError(input);\n }\n\n public void setEventHandler(SessionRepoSerial.RepositoryEvent repositoryEvent) {\n this.repositoryEvent = repositoryEvent;\n Log.d(\"dev-log\", \"SessionRepository.setEventHandler: Session repository event \" +\n \"callback set\");\n }\n\n public void setLauncherEventHandler() {\n LauncherSingleton.getInstance().getLauncher().setLauncherEventHandler(\n this);\n Log.d(\"dev-log\", \"SessionRepository.setLauncherEventHandler: Launcher event \" +\n \"callback set in the context of session repository\");\n }\n\n private void processFormattedOutput() {\n String data = queueData.toString();\n String time = createStringTime();\n\n LauncherOutputData launcherOutputData = new LauncherOutputData(time, data);\n\n char firstChar = data.charAt(0);\n char lastChar = data.charAt(data.length() - 2);\n if (firstChar == '{' && lastChar == '}') {\n repositoryEvent.onRepoOutputFormatted(launcherOutputData);\n data = data.replace(\"{\", \"\").replace(\"}\", \"\");\n String[] splitStrData = data.split(\",\");\n\n ArrayList<String> strDataList = new ArrayList<>(Arrays.asList(splitStrData));\n processContentOfFormattedOutput(strDataList);\n }\n }\n\n private String createStringTime() {\n Calendar calendar = Calendar.getInstance();\n SimpleDateFormat dateFormat = new SimpleDateFormat(\"HH:mm:ss\", Locale.getDefault());\n return dateFormat.format(calendar.getTime());\n }\n\n private void processContentOfFormattedOutput(ArrayList<String> strDataList) {\n StringBuilder dataArguments = new StringBuilder();\n for (int i = 0; i < strDataList.size(); i++) {\n dataArguments.append(strDataList.get(i));\n dataArguments.append(\"-\");\n }\n\n switch (strDataList.get(0)) {\n case \"ESP_STARTED\" -> repositoryEvent.onRepoStarted();\n case \"CMD_PARSER\" -> cmdParserContext(strDataList);\n case \"ARMAMENT\" -> armamentContext(strDataList);\n case \"PMKID\" -> pmkidContext(strDataList);\n case \"MIC\" -> micContext(strDataList);\n case \"DEAUTH\" -> deauthContext(strDataList);\n case \"RECONNAISSANCE\" -> reconnaissanceContext(strDataList);\n }\n }\n\n private void cmdParserContext(ArrayList<String> strDataList) {\n String currentArmament = strDataList.get(2);\n String currentBssidTarget = strDataList.get(3);\n\n String namedArmament = switch (currentArmament) {\n case \"01\" -> \"Reconnaissance\";\n case \"02\" -> \"PMKID\";\n case \"03\" -> \"MIC\";\n case \"04\" -> \"Deauth\";\n default -> \"\";\n };\n\n String formattedBssid = currentBssidTarget.substring(0, 2) + \":\" +\n currentBssidTarget.substring(2, 4) + \":\" +\n currentBssidTarget.substring(4, 6) + \":\" +\n currentBssidTarget.substring(6, 8) + \":\" +\n currentBssidTarget.substring(8, 10) + \":\" +\n currentBssidTarget.substring(10, 12);\n\n switch (strDataList.get(1)) {\n case \"CURRENT_ARMA\" -> repositoryEvent.onRepoArmamentStatus(\n namedArmament, formattedBssid);\n case \"TARGET_ARMA_SET\" -> repositoryEvent.onRepoInstructionIssued(\n namedArmament, formattedBssid);\n }\n }\n\n private void armamentContext(ArrayList<String> strDataList) {\n if (Objects.equals(strDataList.get(1), \"ACTIVATE\")) {\n repositoryEvent.onRepoArmamentActivation();\n } else if (Objects.equals(strDataList.get(1), \"DEACTIVATE\")) {\n repositoryEvent.onRepoArmamentDeactivation();\n }\n }\n\n private void pmkidContext(ArrayList<String> strDataList) {\n switch (strDataList.get(1)) {\n case \"AP_NOT_FOUND\" -> repositoryEvent.onRepoTargetAccessPointNotFound();\n case \"LAUNCHING_SEQUENCE\" -> repositoryEvent.onRepoLaunchingSequence();\n case \"SNIFF_STARTED\" -> repositoryEvent.onRepoMainTaskCreated();\n case \"WRONG_KEY_TYPE\" -> {\n String keyType = strDataList.get(3);\n repositoryEvent.onRepoPmkidWrongKeyType(keyType);\n }\n case \"WRONG_OUI\" -> repositoryEvent.onRepoPmkidWrongOui(strDataList.get(2));\n case \"WRONG_KDE\" -> repositoryEvent.onRepoPmkidWrongKde(strDataList.get(2));\n case \"SNIFF_STATUS\" -> {\n int status = Integer.parseInt(strDataList.get(2));\n repositoryEvent.onRepoMainTaskCurrentStatus(\"PMKID\", status);\n }\n case \"MSG_1\" -> handlePmkidMessage1(strDataList);\n case \"FINISHING_SEQUENCE\" -> repositoryEvent.onRepoFinishingSequence();\n case \"SUCCESS\" -> repositoryEvent.onRepoSuccess();\n case \"FAILURE\" -> repositoryEvent.onRepoFailure(strDataList.get(2));\n }\n }\n\n private void handlePmkidMessage1(ArrayList<String> dataList) {\n String bssid = dataList.get(2);\n String client = dataList.get(3);\n String pmkid = dataList.get(4);\n PmkidFirstMessageData pmkidFirstMessageData = new PmkidFirstMessageData(bssid, client, pmkid);\n repositoryEvent.onRepoReceivedEapolMessage(\n \"PMKID\", 1, pmkidFirstMessageData,\n null, null);\n }\n\n private void micContext(ArrayList<String> strDataList) {\n switch (strDataList.get(1)) {\n case \"AP_NOT_FOUND\" -> repositoryEvent.onRepoTargetAccessPointNotFound();\n case \"LAUNCHING_SEQUENCE\" -> repositoryEvent.onRepoLaunchingSequence();\n case \"DEAUTH_STARTED\" -> repositoryEvent.onRepoMainTaskCreated();\n case \"INJECTED_DEAUTH\" -> {\n int status = Integer.parseInt(strDataList.get(2));\n repositoryEvent.onRepoMainTaskCurrentStatus(\"MIC\", status);\n }\n case \"MSG_1\" -> handleMicMessage1(strDataList);\n case \"MSG_2\" -> handleMicMessage2(strDataList);\n case \"FINISHING SEQUENCE\" -> repositoryEvent.onRepoFinishingSequence();\n case \"SUCCESS\" -> repositoryEvent.onRepoSuccess();\n case \"FAILURE\" -> repositoryEvent.onRepoFailure(strDataList.get(2));\n }\n }\n\n private void handleMicMessage1(ArrayList<String> dataList) {\n String bssid = dataList.get(2);\n String client = dataList.get(3);\n String anonce = dataList.get(4);\n MicFirstMessageData micFirstMessageData = new MicFirstMessageData(bssid, client, anonce);\n repositoryEvent.onRepoReceivedEapolMessage(\n \"MIC\", 1, null,\n micFirstMessageData, null);\n }\n\n private void handleMicMessage2(ArrayList<String> dataList) {\n String version = dataList.get(4);\n String type = dataList.get(5);\n String length = dataList.get(6);\n String keyDescriptionType = dataList.get(7);\n String keyInformation = dataList.get(8);\n String keyLength = dataList.get(9);\n\n String replayCounter = dataList.get(10);\n String snonce = dataList.get(11);\n String keyIv = dataList.get(12);\n String keyRsc = dataList.get(13);\n String keyId = dataList.get(14);\n String mic = dataList.get(15);\n\n String keyDataLength = dataList.get(16);\n String keyData = dataList.get(17);\n\n MicSecondMessageData micSecondMessageData = new MicSecondMessageData(\n version, type, length, keyDescriptionType, keyInformation, keyLength,\n replayCounter, snonce, keyIv, keyRsc, keyId, mic, keyDataLength, keyData);\n\n repositoryEvent.onRepoReceivedEapolMessage(\"MIC\", 2,\n null, null, micSecondMessageData);\n }\n\n private void reconnaissanceContext(ArrayList<String> strDataList) {\n\n switch (strDataList.get(1)) {\n case \"FOUND_APS\" -> {\n String numberOfAps = strDataList.get(2);\n repositoryEvent.onRepoNumberOfFoundAccessPoints(numberOfAps);\n }\n case \"SCAN\" -> processScannedAccessPointsAndNotifyViewModel(strDataList);\n case \"FINISH_SCAN\" -> repositoryEvent.onRepoFinishScan();\n }\n }\n\n private void deauthContext(ArrayList<String> strDataList) {\n switch (strDataList.get(1)) {\n case \"AP_NOT_FOUND\" -> repositoryEvent.onRepoTargetAccessPointNotFound();\n case \"FINISH_SCAN\" -> repositoryEvent.onRepoFinishScan();\n case \"LAUNCHING_SEQUENCE\" -> repositoryEvent.onRepoLaunchingSequence();\n case \"DEAUTH_STARTED\" -> repositoryEvent.onRepoMainTaskCreated();\n case \"INJECTED_DEAUTH\" -> {\n int numberOfInjectedDeauthentications = Integer.parseInt(strDataList.get(2));\n repositoryEvent.onRepoMainTaskCurrentStatus(\"DEAUTH\",\n numberOfInjectedDeauthentications);\n }\n case \"STOPPED\" ->\n repositoryEvent.onRepoMainTaskInDeautherStopped(strDataList.get(2));\n }\n }\n\n private void processScannedAccessPointsAndNotifyViewModel(\n ArrayList<String> strDataList\n ) {\n String macAddress = strDataList.get(2);\n String ssid = strDataList.get(3);\n StringBuilder asciiSsid = new StringBuilder();\n\n // Decodes the SSID from hexadecimal string to ascii characters\n for (int i = 0; i < ssid.length(); i += 2) {\n String hex = ssid.substring(i, i + 2);\n int decimal = Integer.parseInt(hex, 16);\n asciiSsid.append((char) decimal);\n }\n\n String rssi = strDataList.get(4);\n String channel = strDataList.get(5);\n AccessPointData accessPointData = new AccessPointData(\n macAddress, asciiSsid.toString(), Integer.parseInt(rssi), Integer.parseInt(channel)\n );\n repositoryEvent.onRepoFoundAccessPoint(accessPointData);\n }\n\n}" }, { "identifier": "SessionViewModel", "path": "app/src/main/java/com/johndeweydev/awps/viewmodel/serial/sessionviewmodel/SessionViewModel.java", "snippet": "public class SessionViewModel extends ViewModel implements ViewModelIOControl,\n SessionRepoSerial.RepositoryEvent {\n\n public boolean automaticAttack = false;\n public String selectedArmament;\n public SessionRepoSerial sessionRepoSerial;\n\n /**\n * Serial Listeners\n * The variables and live data below this comment is use for logging and setting up listeners\n * when an error occurred\n * */\n public MutableLiveData<String> currentAttackLog = new MutableLiveData<>();\n public MutableLiveData<String> currentSerialInputError = new MutableLiveData<>();\n public MutableLiveData<String> currentSerialOutputError = new MutableLiveData<>();\n public int attackLogNumber = 0;\n\n /**\n * INITIALIZATION PHASE\n * Variables and live data below this comment is use for setting up the target and activating\n * the armament\n * */\n public MutableLiveData<String> launcherStarted = new MutableLiveData<>();\n public MutableLiveData<String> launcherActivateConfirmation = new MutableLiveData<>();\n public String targetAccessPointSsid;\n\n /**\n * TARGET LOCKING PHASE\n * Variables and live data below this comment is use for scanning access points and checking if\n * the target is found on the scanned access points\n * */\n public boolean userWantsToScanForAccessPoint = false;\n public ArrayList<AccessPointData> accessPointDataList = new ArrayList<>();\n public MutableLiveData<ArrayList<AccessPointData>> launcherFinishScanning =\n new MutableLiveData<>();\n public MutableLiveData<String> launcherAccessPointNotFound = new MutableLiveData<>();\n\n /**\n * EXECUTION PHASE\n * Variables and live data below this comment is use when the attack is ongoing\n * */\n public MutableLiveData<String> launcherMainTaskCreated = new MutableLiveData<>();\n public boolean attackOnGoing = false;\n\n /**\n * POST EXECUTION PHASE\n * Variables and live data below this comment is use when the attack has finished, an attack can\n * either be successfully or a failure\n * */\n public HashInfoEntity launcherExecutionResultData;\n public MutableLiveData<String> launcherExecutionResult = new MutableLiveData<>();\n public MutableLiveData<String> launcherDeauthStopped = new MutableLiveData<>();\n\n public SessionViewModel(SessionRepoSerial sessionRepoSerial) {\n Log.d(\"dev-log\", \"SessionViewModel: Created new instance of SessionViewModel\");\n this.sessionRepoSerial = sessionRepoSerial;\n sessionRepoSerial.setEventHandler(this);\n }\n\n public void writeControlCodeActivationToLauncher() {\n sessionRepoSerial.writeDataToDevice(\"06\");\n }\n\n public void writeControlCodeDeactivationToLauncher() {\n sessionRepoSerial.writeDataToDevice(\"07\");\n }\n\n public void writeControlCodeRestartLauncher() {\n attackLogNumber = 0;\n sessionRepoSerial.writeDataToDevice(\"08\");\n }\n\n public void writeInstructionCodeForScanningDevicesToLauncher() {\n sessionRepoSerial.writeDataToDevice(\"01\");\n }\n\n public void writeInstructionCodeToLauncher(String targetMacAddress) {\n String instructionCode = \"\";\n switch (selectedArmament) {\n case \"PMKID Based Attack\" -> instructionCode += \"02\";\n case \"MIC Based Attack\" -> instructionCode += \"03\";\n case \"Deauther\" -> instructionCode += \"04\";\n }\n instructionCode += targetMacAddress;\n sessionRepoSerial.writeDataToDevice(instructionCode);\n }\n\n @Override\n public void setLauncherEventHandler() {\n sessionRepoSerial.setLauncherEventHandler();\n }\n\n @Override\n public String connectToDevice(DeviceConnectionParamData deviceConnectionParamData) {\n return sessionRepoSerial.connectToDevice(deviceConnectionParamData);\n }\n\n @Override\n public void disconnectFromDevice() {\n sessionRepoSerial.disconnectFromDevice();\n }\n\n @Override\n public void startEventDrivenReadFromDevice() {\n sessionRepoSerial.startEventDrivenReadFromDevice();\n }\n\n @Override\n public void stopEventDrivenReadFromDevice() {\n sessionRepoSerial.stopEventDrivenReadFromDevice();\n }\n\n @Override\n public void onRepoOutputError(String error) {\n Log.d(\"dev-log\", \"SessionViewModel.onLauncherOutputError: Serial -> \" + error);\n currentSerialOutputError.postValue(error);\n }\n\n @Override\n public void onRepoInputError(String input) {\n Log.d(\"dev-log\", \"SessionViewModel.onLauncherInputError: Serial -> \" + input);\n currentSerialInputError.postValue(input);\n }\n\n @Override\n public void onRepoStarted() {\n launcherStarted.postValue(\"Launcher module started\");\n currentAttackLog.postValue(\"(\" + attackLogNumber + \") \" + \"Module started\");\n attackLogNumber++;\n }\n\n @Override\n public void onRepoArmamentStatus(String armament, String targetBssid) {\n currentAttackLog.postValue(\"(\" + attackLogNumber + \") \" + \"Using \" + armament + \"\" +\n \", targeting \" + targetBssid);\n attackLogNumber++;\n }\n\n @Override\n public void onRepoInstructionIssued(String armament, String targetBssid) {\n if (userWantsToScanForAccessPoint) {\n currentAttackLog.postValue(\"(\" + attackLogNumber + \") \" + \"Using \" + armament);\n launcherActivateConfirmation.postValue(\"Proceed to scan for nearby access points?\");\n } else {\n currentAttackLog.postValue(\"(\" + attackLogNumber + \") \" + \"Using \" + armament +\n \", target set \" + targetBssid);\n launcherActivateConfirmation.postValue(\"Do you wish to activate the attack targeting \"\n + targetAccessPointSsid + \" using \" + selectedArmament + \"?\");\n }\n attackLogNumber++;\n }\n\n @Override\n public void onRepoArmamentActivation() {\n currentAttackLog.postValue(\"(\" + attackLogNumber + \") \" + \"Armament activate!\");\n attackLogNumber++;\n }\n\n @Override\n public void onRepoArmamentDeactivation() {\n currentAttackLog.postValue(\"(\" + attackLogNumber + \") \" + \"Armament deactivate!\");\n attackLogNumber++;\n }\n\n @Override\n public void onRepoNumberOfFoundAccessPoints(String numberOfAps) {\n currentAttackLog.postValue(\"(\" + attackLogNumber + \") \" + \"Found \" + numberOfAps +\n \" access points\");\n accessPointDataList.clear();\n attackLogNumber++;\n }\n\n @Override\n public void onRepoFoundAccessPoint(AccessPointData accessPointData) {\n if (userWantsToScanForAccessPoint) {\n accessPointDataList.add(accessPointData);\n }\n String ssid = accessPointData.ssid();\n int channel = accessPointData.channel();\n currentAttackLog.postValue(\"(\" + attackLogNumber + \") \" + ssid + \" at channel \" + channel);\n attackLogNumber++;\n }\n\n @Override\n public void onRepoFinishScan() {\n if (userWantsToScanForAccessPoint) {\n launcherFinishScanning.postValue(accessPointDataList);\n }\n currentAttackLog.postValue(\"(\" + attackLogNumber + \") \" + \"Done scanning access point\");\n attackLogNumber++;\n }\n\n @Override\n public void onRepoTargetAccessPointNotFound() {\n currentAttackLog.postValue(\"(\" + attackLogNumber + \") \" + \"The target \" +\n targetAccessPointSsid + \" is not found\");\n attackLogNumber++;\n launcherAccessPointNotFound.postValue(targetAccessPointSsid);\n }\n\n @Override\n public void onRepoLaunchingSequence() {\n currentAttackLog.postValue(\"(\" + attackLogNumber + \") \" + selectedArmament +\n \" launching sequence\");\n attackLogNumber++;\n }\n\n @Override\n public void onRepoMainTaskCreated() {\n currentAttackLog.postValue(\"(\" + attackLogNumber + \") \" + \"Main task created\");\n attackLogNumber++;\n launcherMainTaskCreated.postValue(selectedArmament + \" main task created\");\n attackOnGoing = true;\n }\n\n @Override\n public void onRepoPmkidWrongKeyType(String keyType) {\n currentAttackLog.postValue(\"(\" + attackLogNumber + \") \" + \"Got wrong PMKID key type, \"\n + keyType);\n attackLogNumber++;\n }\n\n @Override\n public void onRepoPmkidWrongOui(String oui) {\n currentAttackLog.postValue(\"(\" + attackLogNumber + \") \" + \"Got wrong PMKID key data OUI, \"\n + oui);\n attackLogNumber++;\n }\n\n @Override\n public void onRepoPmkidWrongKde(String kde) {\n currentAttackLog.postValue(\"(\" + attackLogNumber + \") \" + \"Got wrong PMKID KDE, \" +\n kde);\n attackLogNumber++;\n }\n\n @Override\n public void onRepoMainTaskCurrentStatus(String attackType, int attackStatus) {\n currentAttackLog.postValue(\"(\" + attackLogNumber + \") \" + attackType + \", status is \" +\n attackStatus);\n attackLogNumber++;\n }\n\n @Override\n public void onRepoReceivedEapolMessage(\n String attackType,\n int messageNumber,\n @Nullable PmkidFirstMessageData pmkidFirstMessageData,\n @Nullable MicFirstMessageData micFirstMessageData,\n @Nullable MicSecondMessageData micSecondMessageData\n ) {\n if (attackType.equals(\"PMKID\") && messageNumber == 1) {\n handlePmkidEapolMessageEvent(pmkidFirstMessageData);\n } else if (attackType.equals(\"MIC\")) {\n handleMicEapolMessageEvent(micFirstMessageData, micSecondMessageData, messageNumber);\n }\n }\n\n private void handlePmkidEapolMessageEvent(PmkidFirstMessageData pmkidFirstMessageData) {\n if (pmkidFirstMessageData == null) {\n Log.d(\"dev-log\", \"SessionViewModel.handlePmkidEapolMessageEvent: \" +\n \"PMKID data is null\");\n return;\n }\n\n String result = \"PMKID is \" + pmkidFirstMessageData.pmkid();\n\n String ssid = targetAccessPointSsid;\n String bssid = pmkidFirstMessageData.bssid();\n String clientMacAddress = pmkidFirstMessageData.client();\n String keyType = \"PMKID\";\n String aNonce = \"None\";\n String hashData = pmkidFirstMessageData.pmkid();\n String keyData = \"None\";\n String dateCaptured = createStringDateTime();\n\n // Set the default value for location, fragment will populate this data before saving it in\n // the local database\n String latitude = \"0.0\";\n String longitude = \"0.0\";\n String address = \"None\";\n\n launcherExecutionResultData = new HashInfoEntity(\n ssid, bssid, clientMacAddress, keyType, aNonce, hashData, keyData, dateCaptured,\n latitude, longitude, address);\n\n currentAttackLog.postValue(\"(\" + attackLogNumber + \") \" + result);\n attackLogNumber++;\n }\n\n private void handleMicEapolMessageEvent(\n @Nullable MicFirstMessageData micFirstMessageData,\n @Nullable MicSecondMessageData micSecondMessageData,\n int messageNumber\n ) {\n if (messageNumber == 1) {\n if (micFirstMessageData == null) {\n Log.d(\"dev-log\", \"SessionViewModel.onLauncherReceivedEapolMessage: \" +\n \"MIC first message is null\");\n return;\n }\n\n String result = \"Anonce is \" + micFirstMessageData.anonce();\n\n String ssid = targetAccessPointSsid;\n String bssid = micFirstMessageData.bssid();\n String clientMacAddress = micFirstMessageData.clientMacAddress();\n String keyType = \"MIC\";\n String aNonce = micFirstMessageData.anonce();\n String hashData = \"None\";\n String keyData = \"None\";\n String dateCaptured = createStringDateTime();\n\n // Set default value for the location, fragment will populate this data before saving it in\n // the local database\n String latitude = \"0.0\";\n String longitude = \"0.0\";\n String address = \"None\";\n\n launcherExecutionResultData = new HashInfoEntity(\n ssid, bssid, clientMacAddress, keyType, aNonce, hashData, keyData, dateCaptured,\n latitude, longitude, address);\n\n currentAttackLog.postValue(\"(\" + attackLogNumber + \") \" +\n \"Got anonce from first EAPOL message. \" + result);\n attackLogNumber++;\n } else if (messageNumber == 2) {\n if (micSecondMessageData == null) {\n Log.d(\"dev-log\", \"SessionViewModel.onLauncherReceivedEapolMessage: \" +\n \"MIC first message is null\");\n return;\n }\n\n String result = \"MIC is \" + micSecondMessageData.getMic();\n\n launcherExecutionResultData.hashData = micSecondMessageData.getMic();\n launcherExecutionResultData.keyData = micSecondMessageData.getAllData();\n\n currentAttackLog.postValue(\"(\" + attackLogNumber + \") \" +\n \"Got EAPOL data from second message. \" + result);\n attackLogNumber++;\n }\n }\n\n private String createStringDateTime() {\n LocalDateTime dateTime = LocalDateTime.now();\n DateTimeFormatter formatter = DateTimeFormatter.ofPattern(\"HH:mm:ss yyyy-MM-dd\");\n return dateTime.format(formatter);\n }\n\n @Override\n public void onRepoFinishingSequence() {\n currentAttackLog.postValue(\"(\" + attackLogNumber + \") \" + selectedArmament +\n \" finishing sequence\");\n attackLogNumber++;\n }\n\n @Override\n public void onRepoSuccess() {\n currentAttackLog.postValue(\"(\" + attackLogNumber + \") \" + selectedArmament +\n \" successfully executed\");\n attackLogNumber++;\n launcherExecutionResult.postValue(\"Success\");\n attackOnGoing = false;\n\n }\n\n @Override\n public void onRepoFailure(String targetBssid) {\n currentAttackLog.postValue(\"(\" + attackLogNumber + \") \" + selectedArmament + \" failed\");\n attackLogNumber++;\n launcherExecutionResult.postValue(\"Failed\");\n attackOnGoing = false;\n\n }\n\n @Override\n public void onRepoMainTaskInDeautherStopped(String targetBssid) {\n currentAttackLog.postValue(\"(\" + attackLogNumber + \") \" + \"In \" + selectedArmament +\n \" deauthentication task stopped\");\n attackLogNumber++;\n launcherDeauthStopped.postValue(\"Stopped\");\n attackOnGoing = false;\n }\n}" }, { "identifier": "SessionViewModelFactory", "path": "app/src/main/java/com/johndeweydev/awps/viewmodel/serial/sessionviewmodel/SessionViewModelFactory.java", "snippet": "public class SessionViewModelFactory implements ViewModelProvider.Factory {\n\n private final SessionRepoSerial sessionRepoSerial;\n\n public SessionViewModelFactory(SessionRepoSerial sessionRepoSerial) {\n this.sessionRepoSerial = sessionRepoSerial;\n }\n\n @NonNull\n @Override\n @SuppressWarnings(\"unchecked\")\n public <T extends ViewModel> T create(@NonNull Class<T> modelClass) {\n return (T) new SessionViewModel(sessionRepoSerial);\n }\n}" } ]
import static com.johndeweydev.awps.AppConstants.BAUD_RATE; import static com.johndeweydev.awps.AppConstants.DATA_BITS; import static com.johndeweydev.awps.AppConstants.PARITY_NONE; import static com.johndeweydev.awps.AppConstants.STOP_BITS; import android.content.Context; import android.content.IntentSender; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.InputMethodManager; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.core.content.ContextCompat; import androidx.fragment.app.Fragment; import androidx.lifecycle.Observer; import androidx.lifecycle.ViewModelProvider; import androidx.navigation.Navigation; import androidx.recyclerview.widget.LinearLayoutManager; import com.google.android.gms.common.api.ResolvableApiException; import com.google.android.gms.location.LocationRequest; import com.google.android.gms.location.LocationServices; import com.google.android.gms.location.LocationSettingsRequest; import com.google.android.gms.location.LocationSettingsResponse; import com.google.android.gms.location.LocationSettingsStatusCodes; import com.google.android.gms.location.Priority; import com.google.android.gms.location.SettingsClient; import com.google.android.gms.tasks.Task; import com.google.android.material.dialog.MaterialAlertDialogBuilder; import com.google.android.material.textfield.TextInputEditText; import com.johndeweydev.awps.R; import com.johndeweydev.awps.databinding.FragmentManualArmaBinding; import com.johndeweydev.awps.model.data.AccessPointData; import com.johndeweydev.awps.model.data.DeviceConnectionParamData; import com.johndeweydev.awps.model.data.HashInfoEntity; import com.johndeweydev.awps.model.repo.serial.sessionreposerial.SessionRepoSerial; import com.johndeweydev.awps.viewmodel.hashinfoviewmodel.HashInfoViewModel; import com.johndeweydev.awps.viewmodel.serial.sessionviewmodel.SessionViewModel; import com.johndeweydev.awps.viewmodel.serial.sessionviewmodel.SessionViewModelFactory; import java.util.ArrayList; import java.util.Objects;
7,611
package com.johndeweydev.awps.view.manualarmafragment; public class ManualArmaFragment extends Fragment { private FragmentManualArmaBinding binding; private ManualArmaArgs manualArmaArgs = null; private SessionViewModel sessionViewModel; private HashInfoViewModel hashInfoViewModel; @Override public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { SessionRepoSerial sessionRepoSerial = new SessionRepoSerial();
package com.johndeweydev.awps.view.manualarmafragment; public class ManualArmaFragment extends Fragment { private FragmentManualArmaBinding binding; private ManualArmaArgs manualArmaArgs = null; private SessionViewModel sessionViewModel; private HashInfoViewModel hashInfoViewModel; @Override public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { SessionRepoSerial sessionRepoSerial = new SessionRepoSerial();
SessionViewModelFactory sessionViewModelFactory = new SessionViewModelFactory(
7
2023-11-15 15:54:39+00:00
12k
Charles7c/continew-starter
continew-starter-extension/continew-starter-extension-crud/src/main/java/top/charles7c/continew/starter/extension/crud/base/BaseServiceImpl.java
[ { "identifier": "ExceptionUtils", "path": "continew-starter-core/src/main/java/top/charles7c/continew/starter/core/util/ExceptionUtils.java", "snippet": "@Slf4j\n@NoArgsConstructor(access = AccessLevel.PRIVATE)\npublic class ExceptionUtils {\n\n /**\n * 打印线程异常信息\n *\n * @param runnable 线程执行内容\n * @param throwable 异常\n */\n public static void printException(Runnable runnable, Throwable throwable) {\n if (null == throwable && runnable instanceof Future<?> future) {\n try {\n if (future.isDone()) {\n future.get();\n }\n } catch (CancellationException e) {\n throwable = e;\n } catch (ExecutionException e) {\n throwable = e.getCause();\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n }\n }\n if (null != throwable) {\n log.error(throwable.getMessage(), throwable);\n }\n }\n\n /**\n * 如果有异常,返回 null\n *\n * @param exSupplier 可能会出现异常的方法执行\n * @param <T> /\n * @return /\n */\n public static <T> T exToNull(ExSupplier<T> exSupplier) {\n return exToDefault(exSupplier, null);\n }\n\n /**\n * 如果有异常,执行异常处理\n *\n * @param supplier 可能会出现异常的方法执行\n * @param exConsumer 异常处理\n * @param <T> /\n * @return /\n */\n public static <T> T exToNull(ExSupplier<T> supplier, Consumer<Exception> exConsumer) {\n return exToDefault(supplier, null, exConsumer);\n }\n\n /**\n * 如果有异常,返回空字符串\n *\n * @param exSupplier 可能会出现异常的方法执行\n * @return /\n */\n public static String exToBlank(ExSupplier<String> exSupplier) {\n return exToDefault(exSupplier, StringConstants.EMPTY);\n }\n\n /**\n * 如果有异常,返回默认值\n *\n * @param exSupplier 可能会出现异常的方法执行\n * @param defaultValue 默认值\n * @param <T> /\n * @return /\n */\n public static <T> T exToDefault(ExSupplier<T> exSupplier, T defaultValue) {\n return exToDefault(exSupplier, defaultValue, null);\n }\n\n /**\n * 如果有异常,执行异常处理,返回默认值\n *\n * @param exSupplier 可能会出现异常的方法执行\n * @param defaultValue 默认值\n * @param exConsumer 异常处理\n * @param <T> /\n * @return /\n */\n public static <T> T exToDefault(ExSupplier<T> exSupplier, T defaultValue, Consumer<Exception> exConsumer) {\n try {\n return exSupplier.get();\n } catch (Exception e) {\n if (null != exConsumer) {\n exConsumer.accept(e);\n }\n return defaultValue;\n }\n }\n\n /**\n * 异常提供者\n *\n * @param <T> /\n */\n public interface ExSupplier<T> {\n /**\n * 获取返回值\n *\n * @return /\n * @throws Exception /\n */\n T get() throws Exception;\n }\n}" }, { "identifier": "ReflectUtils", "path": "continew-starter-core/src/main/java/top/charles7c/continew/starter/core/util/ReflectUtils.java", "snippet": "@NoArgsConstructor(access = AccessLevel.PRIVATE)\npublic class ReflectUtils {\n\n /**\n * 获得一个类中所有非静态字段名列表,包括其父类中的字段<br>\n * 如果子类与父类中存在同名字段,则这两个字段同时存在,子类字段在前,父类字段在后。\n *\n * @param beanClass 类\n * @return 非静态字段名列表\n * @throws SecurityException 安全检查异常\n */\n public static List<String> getNonStaticFieldsName(Class<?> beanClass) throws SecurityException {\n List<Field> nonStaticFields = getNonStaticFields(beanClass);\n return nonStaticFields.stream().map(Field::getName).collect(Collectors.toList());\n }\n\n /**\n * 获得一个类中所有非静态字段列表,包括其父类中的字段<br>\n * 如果子类与父类中存在同名字段,则这两个字段同时存在,子类字段在前,父类字段在后。\n *\n * @param beanClass 类\n * @return 非静态字段列表\n * @throws SecurityException 安全检查异常\n */\n public static List<Field> getNonStaticFields(Class<?> beanClass) throws SecurityException {\n Field[] fields = ReflectUtil.getFields(beanClass);\n return Arrays.stream(fields).filter(f -> !Modifier.isStatic(f.getModifiers())).collect(Collectors.toList());\n }\n}" }, { "identifier": "CheckUtils", "path": "continew-starter-core/src/main/java/top/charles7c/continew/starter/core/util/validate/CheckUtils.java", "snippet": "@Slf4j\n@NoArgsConstructor(access = AccessLevel.PRIVATE)\npublic class CheckUtils extends Validator {\n\n private static final Class<BusinessException> EXCEPTION_TYPE = BusinessException.class;\n\n /**\n * 如果不存在,抛出异常\n *\n * @param obj 被检测的对象\n * @param entityName 实体名\n * @param fieldName 字段名\n * @param fieldValue 字段值\n */\n public static void throwIfNotExists(Object obj, String entityName, String fieldName, Object fieldValue) {\n String message = String.format(\"%s 为 [%s] 的 %s 记录已不存在\", fieldName, fieldValue,\n StrUtil.replace(entityName, \"DO\", StringConstants.EMPTY));\n throwIfNull(obj, message, EXCEPTION_TYPE);\n }\n\n /**\n * 如果为空,抛出异常\n *\n * @param obj 被检测的对象\n * @param template 异常信息模板,被替换的部分用 {} 表示,如果模板为 null,返回 \"null\"\n * @param params 参数值\n */\n public static void throwIfNull(Object obj, String template, Object... params) {\n throwIfNull(obj, StrUtil.format(template, params), EXCEPTION_TYPE);\n }\n\n /**\n * 如果不为空,抛出异常\n *\n * @param obj 被检测的对象\n * @param template 异常信息模板,被替换的部分用 {} 表示,如果模板为 null,返回 \"null\"\n * @param params 参数值\n */\n public static void throwIfNotNull(Object obj, String template, Object... params) {\n throwIfNotNull(obj, StrUtil.format(template, params), EXCEPTION_TYPE);\n }\n\n /**\n * 如果存在,抛出异常\n *\n * @param obj 被检测的对象\n * @param entityName 实体名\n * @param fieldName 字段名\n * @param fieldValue 字段值\n */\n public static void throwIfExists(Object obj, String entityName, String fieldName, Object fieldValue) {\n String message = String.format(\"%s 为 [%s] 的 %s 记录已存在\", fieldName, fieldValue, entityName);\n throwIfNotNull(obj, message, EXCEPTION_TYPE);\n }\n\n /**\n * 如果为空,抛出异常\n *\n * @param obj 被检测的对象\n * @param template 异常信息模板,被替换的部分用 {} 表示,如果模板为 null,返回 \"null\"\n * @param params 参数值\n */\n public static void throwIfEmpty(Object obj, String template, Object... params) {\n throwIfEmpty(obj, StrUtil.format(template, params), EXCEPTION_TYPE);\n }\n\n /**\n * 如果不为空,抛出异常\n *\n * @param obj 被检测的对象\n * @param template 异常信息模板,被替换的部分用 {} 表示,如果模板为 null,返回 \"null\"\n * @param params 参数值\n */\n public static void throwIfNotEmpty(Object obj, String template, Object... params) {\n throwIfNotEmpty(obj, StrUtil.format(template, params), EXCEPTION_TYPE);\n }\n\n /**\n * 如果为空,抛出异常\n *\n * @param str 被检测的字符串\n * @param template 异常信息模板,被替换的部分用 {} 表示,如果模板为 null,返回 \"null\"\n * @param params 参数值\n */\n public static void throwIfBlank(CharSequence str, String template, Object... params) {\n throwIfBlank(str, StrUtil.format(template, params), EXCEPTION_TYPE);\n }\n\n /**\n * 如果不为空,抛出异常\n *\n * @param str 被检测的字符串\n * @param template 异常信息模板,被替换的部分用 {} 表示,如果模板为 null,返回 \"null\"\n * @param params 参数值\n */\n public static void throwIfNotBlank(CharSequence str, String template, Object... params) {\n throwIfNotBlank(str, StrUtil.format(template, params), EXCEPTION_TYPE);\n }\n\n /**\n * 如果相同,抛出异常\n *\n * @param obj1 要比较的对象1\n * @param obj2 要比较的对象2\n * @param template 异常信息模板,被替换的部分用 {} 表示,如果模板为 null,返回 \"null\"\n * @param params 参数值\n */\n public static void throwIfEqual(Object obj1, Object obj2, String template, Object... params) {\n throwIfEqual(obj1, obj2, StrUtil.format(template, params), EXCEPTION_TYPE);\n }\n\n /**\n * 如果不相同,抛出异常\n *\n * @param obj1 要比较的对象1\n * @param obj2 要比较的对象2\n * @param template 异常信息模板,被替换的部分用 {} 表示,如果模板为 null,返回 \"null\"\n * @param params 参数值\n */\n public static void throwIfNotEqual(Object obj1, Object obj2, String template, Object... params) {\n throwIfNotEqual(obj1, obj2, StrUtil.format(template, params), EXCEPTION_TYPE);\n }\n\n /**\n * 如果相同,抛出异常(不区分大小写)\n *\n * @param str1 要比较的字符串1\n * @param str2 要比较的字符串2\n * @param template 异常信息模板,被替换的部分用 {} 表示,如果模板为 null,返回 \"null\"\n * @param params 参数值\n */\n public static void throwIfEqualIgnoreCase(CharSequence str1, CharSequence str2, String template, Object... params) {\n throwIfEqualIgnoreCase(str1, str2, StrUtil.format(template, params), EXCEPTION_TYPE);\n }\n\n /**\n * 如果不相同,抛出异常(不区分大小写)\n *\n * @param str1 要比较的字符串1\n * @param str2 要比较的字符串2\n * @param template 异常信息模板,被替换的部分用 {} 表示,如果模板为 null,返回 \"null\"\n * @param params 参数值\n */\n public static void throwIfNotEqualIgnoreCase(CharSequence str1, CharSequence str2, String template,\n Object... params) {\n throwIfNotEqualIgnoreCase(str1, str2, StrUtil.format(template, params), EXCEPTION_TYPE);\n }\n\n /**\n * 如果条件成立,抛出异常\n *\n * @param condition 条件\n * @param template 异常信息模板,被替换的部分用 {} 表示,如果模板为 null,返回 \"null\"\n * @param params 参数值\n */\n public static void throwIf(boolean condition, String template, Object... params) {\n throwIf(condition, StrUtil.format(template, params), EXCEPTION_TYPE);\n }\n\n /**\n * 如果条件成立,抛出异常\n *\n * @param conditionSupplier 条件\n * @param template 异常信息模板,被替换的部分用 {} 表示,如果模板为 null,返回 \"null\"\n * @param params 参数值\n */\n public static void throwIf(BooleanSupplier conditionSupplier, String template, Object... params) {\n throwIf(conditionSupplier, StrUtil.format(template, params), EXCEPTION_TYPE);\n }\n}" }, { "identifier": "BaseMapper", "path": "continew-starter-data/continew-starter-data-mybatis-plus/src/main/java/top/charles7c/continew/starter/data/mybatis/plus/base/BaseMapper.java", "snippet": "public interface BaseMapper<T> extends com.baomidou.mybatisplus.core.mapper.BaseMapper<T> {\n\n /**\n * 批量插入记录\n *\n * @param entityList 实体列表\n * @return 是否成功\n */\n default boolean insertBatch(Collection<T> entityList) {\n return Db.saveBatch(entityList);\n }\n\n /**\n * 批量更新记录\n *\n * @param entityList 实体列表\n * @return 是否成功\n */\n default boolean updateBatchById(Collection<T> entityList) {\n return Db.updateBatchById(entityList);\n }\n\n /**\n * 链式查询\n *\n * @return QueryWrapper 的包装类\n */\n default QueryChainWrapper<T> query() {\n return ChainWrappers.queryChain(this);\n }\n\n /**\n * 链式查询(lambda 式)\n *\n * @return LambdaQueryWrapper 的包装类\n */\n default LambdaQueryChainWrapper<T> lambdaQuery() {\n return ChainWrappers.lambdaQueryChain(this, this.currentEntityClass());\n }\n\n /**\n * 链式查询(lambda 式)\n *\n * @param entity 实体对象\n * @return LambdaQueryWrapper 的包装类\n */\n default LambdaQueryChainWrapper<T> lambdaQuery(T entity) {\n return ChainWrappers.lambdaQueryChain(this, entity);\n }\n\n /**\n * 链式更改\n *\n * @return UpdateWrapper 的包装类\n */\n default UpdateChainWrapper<T> update() {\n return ChainWrappers.updateChain(this);\n }\n\n /**\n * 链式更改(lambda 式)\n *\n * @return LambdaUpdateWrapper 的包装类\n */\n default LambdaUpdateChainWrapper<T> lambdaUpdate() {\n return ChainWrappers.lambdaUpdateChain(this);\n }\n\n /**\n * 获取实体类 Class 对象\n *\n * @return 实体类 Class 对象\n */\n default Class<T> currentEntityClass() {\n return (Class<T>) ClassUtil.getTypeArgument(this.getClass(), 0);\n }\n}" }, { "identifier": "QueryHelper", "path": "continew-starter-data/continew-starter-data-mybatis-plus/src/main/java/top/charles7c/continew/starter/data/mybatis/plus/query/QueryHelper.java", "snippet": "@Slf4j\n@NoArgsConstructor(access = AccessLevel.PRIVATE)\npublic class QueryHelper {\n\n /**\n * 根据查询条件构建 MyBatis Plus 查询条件封装对象\n *\n * @param query 查询条件\n * @param <Q> 查询条件数据类型\n * @param <R> 查询数据类型\n * @return MyBatis Plus 查询条件封装对象\n */\n public static <Q, R> QueryWrapper<R> build(Q query) {\n QueryWrapper<R> queryWrapper = new QueryWrapper<>();\n // 没有查询条件,直接返回\n if (null == query) {\n return queryWrapper;\n }\n // 获取查询条件中所有的字段\n List<Field> fieldList = ReflectUtils.getNonStaticFields(query.getClass());\n fieldList.forEach(field -> buildQuery(query, field, queryWrapper));\n return queryWrapper;\n }\n\n /**\n * 构建 MyBatis Plus 查询条件封装对象\n *\n * @param query 查询条件\n * @param field 字段\n * @param queryWrapper MyBatis Plus 查询条件封装对象\n * @param <Q> 查询条件数据类型\n * @param <R> 查询数据类型\n */\n private static <Q, R> void buildQuery(Q query, Field field, QueryWrapper<R> queryWrapper) {\n boolean accessible = field.canAccess(query);\n try {\n field.setAccessible(true);\n // 没有 @Query,直接返回\n Query queryAnnotation = field.getAnnotation(Query.class);\n if (null == queryAnnotation) {\n return;\n }\n\n // 如果字段值为空,直接返回\n Object fieldValue = field.get(query);\n if (ObjectUtil.isEmpty(fieldValue)) {\n return;\n }\n\n // 解析查询条件\n parse(queryAnnotation, field.getName(), fieldValue, queryWrapper);\n } catch (BadRequestException e) {\n log.error(\"Build query occurred an validation error: {}. Query: {}, Field: {}.\", e.getMessage(), query,\n field, e);\n throw e;\n } catch (Exception e) {\n log.error(\"Build query occurred an error: {}. Query: {}, Field: {}.\", e.getMessage(), query, field, e);\n } finally {\n field.setAccessible(accessible);\n }\n }\n\n /**\n * 解析查询条件\n *\n * @param queryAnnotation 查询注解\n * @param fieldName 字段名\n * @param fieldValue 字段值\n * @param queryWrapper MyBatis Plus 查询条件封装对象\n * @param <R> 查询数据类型\n */\n private static <R> void parse(Query queryAnnotation, String fieldName, Object fieldValue,\n QueryWrapper<R> queryWrapper) {\n // 解析多属性模糊查询\n // 如果设置了多属性模糊查询,分割属性进行条件拼接\n String[] blurryPropertyArr = queryAnnotation.blurry();\n if (ArrayUtil.isNotEmpty(blurryPropertyArr)) {\n queryWrapper.and(wrapper -> {\n for (String blurryProperty : blurryPropertyArr) {\n wrapper.or().like(StrUtil.toUnderlineCase(blurryProperty), fieldValue);\n }\n });\n return;\n }\n\n // 解析单个属性查询\n // 如果没有单独指定属性名,就和使用该注解的属性的名称一致\n // 注意:数据库规范中列采用下划线连接法命名,程序规范中变量采用驼峰法命名\n String property = queryAnnotation.property();\n String columnName = StrUtil.toUnderlineCase(StrUtil.blankToDefault(property, fieldName));\n QueryType queryType = queryAnnotation.type();\n switch (queryType) {\n case EQUAL -> queryWrapper.eq(columnName, fieldValue);\n case NOT_EQUAL -> queryWrapper.ne(columnName, fieldValue);\n case GREATER_THAN -> queryWrapper.gt(columnName, fieldValue);\n case LESS_THAN -> queryWrapper.lt(columnName, fieldValue);\n case GREATER_THAN_OR_EQUAL -> queryWrapper.ge(columnName, fieldValue);\n case LESS_THAN_OR_EQUAL -> queryWrapper.le(columnName, fieldValue);\n case BETWEEN -> {\n List<Object> between = new ArrayList<>((List<Object>) fieldValue);\n ValidationUtils.throwIf(between.size() != 2, \"[{}] 必须是一个范围\", fieldName);\n queryWrapper.between(columnName, between.get(0), between.get(1));\n }\n case LEFT_LIKE -> queryWrapper.likeLeft(columnName, fieldValue);\n case INNER_LIKE -> queryWrapper.like(columnName, fieldValue);\n case RIGHT_LIKE -> queryWrapper.likeRight(columnName, fieldValue);\n case IN -> {\n ValidationUtils.throwIfEmpty(fieldValue, \"[{}] 不能为空\", fieldName);\n queryWrapper.in(columnName, (List<Object>) fieldValue);\n }\n case NOT_IN -> {\n ValidationUtils.throwIfEmpty(fieldValue, \"[{}] 不能为空\", fieldName);\n queryWrapper.notIn(columnName, (List<Object>) fieldValue);\n }\n case IS_NULL -> queryWrapper.isNull(columnName);\n case IS_NOT_NULL -> queryWrapper.isNotNull(columnName);\n default -> throw new IllegalArgumentException(String.format(\"暂不支持 [%s] 查询类型\", queryType));\n }\n }\n}" }, { "identifier": "PageQuery", "path": "continew-starter-extension/continew-starter-extension-crud/src/main/java/top/charles7c/continew/starter/extension/crud/model/query/PageQuery.java", "snippet": "@Data\n@ParameterObject\n@NoArgsConstructor\n@Schema(description = \"分页查询条件\")\npublic class PageQuery extends SortQuery {\n\n @Serial\n private static final long serialVersionUID = 1L;\n /**\n * 默认页码:1\n */\n private static final int DEFAULT_PAGE = 1;\n /**\n * 默认每页条数:10\n */\n private static final int DEFAULT_SIZE = 10;\n\n /**\n * 页码\n */\n @Schema(description = \"页码\", example = \"1\")\n @Min(value = 1, message = \"页码最小值为 {value}\")\n private Integer page = DEFAULT_PAGE;\n\n /**\n * 每页条数\n */\n @Schema(description = \"每页条数\", example = \"10\")\n @Range(min = 1, max = 1000, message = \"每页条数(取值范围 {min}-{max})\")\n private Integer size = DEFAULT_SIZE;\n\n /**\n * 基于分页查询条件转换为 MyBatis Plus 分页条件\n *\n * @param <T> 列表数据类型\n * @return MyBatis Plus 分页条件\n */\n public <T> IPage<T> toPage() {\n Page<T> mybatisPage = new Page<>(this.getPage(), this.getSize());\n Sort pageSort = this.getSort();\n if (CollUtil.isNotEmpty(pageSort)) {\n for (Sort.Order order : pageSort) {\n OrderItem orderItem = new OrderItem();\n orderItem.setAsc(order.isAscending());\n orderItem.setColumn(StrUtil.toUnderlineCase(order.getProperty()));\n mybatisPage.addOrder(orderItem);\n }\n }\n return mybatisPage;\n }\n}" }, { "identifier": "SortQuery", "path": "continew-starter-extension/continew-starter-extension-crud/src/main/java/top/charles7c/continew/starter/extension/crud/model/query/SortQuery.java", "snippet": "@Data\n@Schema(description = \"排序查询条件\")\npublic class SortQuery implements Serializable {\n\n @Serial\n private static final long serialVersionUID = 1L;\n\n /**\n * 排序条件\n */\n @Schema(description = \"排序条件\", example = \"createTime,desc\")\n private String[] sort;\n\n /**\n * 解析排序条件为 Spring 分页排序实体\n *\n * @return Spring 分页排序实体\n */\n public Sort getSort() {\n if (ArrayUtil.isEmpty(sort)) {\n return Sort.unsorted();\n }\n\n List<Sort.Order> orders = new ArrayList<>(sort.length);\n if (StrUtil.contains(sort[0], StringConstants.COMMA)) {\n // e.g \"sort=createTime,desc&sort=name,asc\"\n for (String s : sort) {\n List<String> sortList = StrUtil.splitTrim(s, StringConstants.COMMA);\n Sort.Order order =\n new Sort.Order(Sort.Direction.valueOf(sortList.get(1).toUpperCase()), sortList.get(0));\n orders.add(order);\n }\n } else {\n // e.g \"sort=createTime,desc\"\n Sort.Order order = new Sort.Order(Sort.Direction.valueOf(sort[1].toUpperCase()), sort[0]);\n orders.add(order);\n }\n return Sort.by(orders);\n }\n}" }, { "identifier": "PageDataResp", "path": "continew-starter-extension/continew-starter-extension-crud/src/main/java/top/charles7c/continew/starter/extension/crud/model/resp/PageDataResp.java", "snippet": "@Data\n@Schema(description = \"分页信息\")\npublic class PageDataResp<L> implements Serializable {\n\n @Serial\n private static final long serialVersionUID = 1L;\n\n /**\n * 列表数据\n */\n @Schema(description = \"列表数据\")\n private List<L> list;\n\n /**\n * 总记录数\n */\n @Schema(description = \"总记录数\", example = \"10\")\n private long total;\n\n /**\n * 基于 MyBatis Plus 分页数据构建分页信息,并将源数据转换为指定类型数据\n *\n * @param page MyBatis Plus 分页数据\n * @param targetClass 目标类型 Class 对象\n * @param <T> 源列表数据类型\n * @param <L> 目标列表数据类型\n * @return 分页信息\n */\n public static <T, L> PageDataResp<L> build(IPage<T> page, Class<L> targetClass) {\n if (null == page) {\n return empty();\n }\n PageDataResp<L> pageDataResp = new PageDataResp<>();\n pageDataResp.setList(BeanUtil.copyToList(page.getRecords(), targetClass));\n pageDataResp.setTotal(page.getTotal());\n return pageDataResp;\n }\n\n /**\n * 基于 MyBatis Plus 分页数据构建分页信息\n *\n * @param page MyBatis Plus 分页数据\n * @param <L> 列表数据类型\n * @return 分页信息\n */\n public static <L> PageDataResp<L> build(IPage<L> page) {\n if (null == page) {\n return empty();\n }\n PageDataResp<L> pageDataResp = new PageDataResp<>();\n pageDataResp.setList(page.getRecords());\n pageDataResp.setTotal(page.getTotal());\n return pageDataResp;\n }\n\n /**\n * 基于列表数据构建分页信息\n *\n * @param page 页码\n * @param size 每页条数\n * @param list 列表数据\n * @param <L> 列表数据类型\n * @return 分页信息\n */\n public static <L> PageDataResp<L> build(int page, int size, List<L> list) {\n if (CollUtil.isEmpty(list)) {\n return empty();\n }\n PageDataResp<L> pageDataResp = new PageDataResp<>();\n pageDataResp.setTotal(list.size());\n // 对列表数据进行分页\n int fromIndex = (page - 1) * size;\n int toIndex = page * size + size;\n if (fromIndex > list.size()) {\n pageDataResp.setList(new ArrayList<>(0));\n } else if (toIndex >= list.size()) {\n pageDataResp.setList(list.subList(fromIndex, list.size()));\n } else {\n pageDataResp.setList(list.subList(fromIndex, toIndex));\n }\n return pageDataResp;\n }\n\n /**\n * 空分页信息\n *\n * @param <L> 列表数据类型\n * @return 分页信息\n */\n private static <L> PageDataResp<L> empty() {\n PageDataResp<L> pageDataResp = new PageDataResp<>();\n pageDataResp.setList(new ArrayList<>(0));\n return pageDataResp;\n }\n}" }, { "identifier": "TreeUtils", "path": "continew-starter-extension/continew-starter-extension-crud/src/main/java/top/charles7c/continew/starter/extension/crud/util/TreeUtils.java", "snippet": "@NoArgsConstructor(access = AccessLevel.PRIVATE)\npublic class TreeUtils {\n\n /**\n * 默认字段配置对象(根据前端树结构灵活调整名称)\n */\n public static final TreeNodeConfig DEFAULT_CONFIG =\n TreeNodeConfig.DEFAULT_CONFIG.setNameKey(\"title\").setIdKey(\"key\").setWeightKey(\"sort\");\n\n /**\n * 树构建\n *\n * @param <T> 转换的实体 为数据源里的对象类型\n * @param <E> ID类型\n * @param list 源数据集合\n * @param nodeParser 转换器\n * @return List 树列表\n */\n public static <T, E> List<Tree<E>> build(List<T> list, NodeParser<T, E> nodeParser) {\n return build(list, DEFAULT_CONFIG, nodeParser);\n }\n\n /**\n * 树构建\n *\n * @param <T> 转换的实体 为数据源里的对象类型\n * @param <E> ID类型\n * @param list 源数据集合\n * @param treeNodeConfig 配置\n * @param nodeParser 转换器\n * @return List 树列表\n */\n public static <T, E> List<Tree<E>> build(List<T> list, TreeNodeConfig treeNodeConfig, NodeParser<T, E> nodeParser) {\n if (CollUtil.isEmpty(list)) {\n return new ArrayList<>(0);\n }\n E parentId = (E) ReflectUtil.getFieldValue(list.get(0), treeNodeConfig.getParentIdKey());\n return TreeUtil.build(list, parentId, treeNodeConfig, nodeParser);\n }\n\n /**\n * 根据 @TreeField 配置生成树结构配置\n *\n * @param treeField 树结构字段注解\n * @return 树结构配置\n */\n public static TreeNodeConfig genTreeNodeConfig(TreeField treeField) {\n CheckUtils.throwIfNull(treeField, \"请添加并配置 @TreeField 树结构信息\");\n return new TreeNodeConfig().setIdKey(treeField.value()).setParentIdKey(treeField.parentIdKey())\n .setNameKey(treeField.nameKey()).setWeightKey(treeField.weightKey()).setChildrenKey(treeField.childrenKey())\n .setDeep(treeField.deep() < 0 ? null : treeField.deep());\n }\n}" }, { "identifier": "ExcelUtils", "path": "continew-starter-file/continew-starter-file-excel/src/main/java/top/charles7c/continew/starter/file/excel/util/ExcelUtils.java", "snippet": "@Slf4j\n@NoArgsConstructor(access = AccessLevel.PRIVATE)\npublic class ExcelUtils {\n\n /**\n * 导出\n *\n * @param list 导出数据集合\n * @param fileName 文件名\n * @param clazz 导出数据类型\n * @param response 响应对象\n */\n public static <T> void export(List<T> list, String fileName, Class<T> clazz, HttpServletResponse response) {\n export(list, fileName, \"Sheet1\", clazz, response);\n }\n\n /**\n * 导出\n *\n * @param list 导出数据集合\n * @param fileName 文件名\n * @param sheetName 工作表名称\n * @param clazz 导出数据类型\n * @param response 响应对象\n */\n public static <T> void export(List<T> list, String fileName, String sheetName, Class<T> clazz,\n HttpServletResponse response) {\n try {\n fileName =\n String.format(\"%s_%s.xlsx\", fileName, DateUtil.format(new Date(), DatePattern.PURE_DATETIME_PATTERN));\n fileName = URLUtil.encode(fileName);\n response.setHeader(\"Content-disposition\", \"attachment;filename=\" + fileName);\n response.setContentType(\"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8\");\n EasyExcel.write(response.getOutputStream(), clazz).autoCloseStream(false)\n // 自动适配宽度\n .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())\n // 自动转换大数值\n .registerConverter(new ExcelBigNumberConverter()).sheet(sheetName).doWrite(list);\n } catch (Exception e) {\n log.error(\"Export excel occurred an error: {}. fileName: {}.\", e.getMessage(), fileName, e);\n throw new BaseException(\"导出 Excel 出现错误\");\n }\n }\n}" } ]
import cn.hutool.core.bean.BeanUtil; import cn.hutool.core.bean.copier.CopyOptions; import cn.hutool.core.collection.CollUtil; import cn.hutool.core.convert.Convert; import cn.hutool.core.lang.Opt; import cn.hutool.core.lang.tree.Tree; import cn.hutool.core.lang.tree.TreeNodeConfig; import cn.hutool.core.util.ClassUtil; import cn.hutool.core.util.ReflectUtil; import cn.hutool.core.util.StrUtil; import cn.hutool.extra.spring.SpringUtil; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import jakarta.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Sort; import org.springframework.transaction.annotation.Transactional; import top.charles7c.continew.starter.core.util.ExceptionUtils; import top.charles7c.continew.starter.core.util.ReflectUtils; import top.charles7c.continew.starter.core.util.validate.CheckUtils; import top.charles7c.continew.starter.data.mybatis.plus.base.BaseMapper; import top.charles7c.continew.starter.data.mybatis.plus.query.QueryHelper; import top.charles7c.continew.starter.extension.crud.annotation.TreeField; import top.charles7c.continew.starter.extension.crud.model.query.PageQuery; import top.charles7c.continew.starter.extension.crud.model.query.SortQuery; import top.charles7c.continew.starter.extension.crud.model.resp.PageDataResp; import top.charles7c.continew.starter.extension.crud.util.TreeUtils; import top.charles7c.continew.starter.file.excel.util.ExcelUtils; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List;
8,818
/* * Copyright (c) 2022-present Charles7c Authors. All Rights Reserved. * <p> * Licensed under the GNU LESSER GENERAL PUBLIC LICENSE 3.0; * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p> * http://www.gnu.org/licenses/lgpl.html * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package top.charles7c.continew.starter.extension.crud.base; /** * 业务实现基类 * * @param <M> Mapper 接口 * @param <T> 实体类 * @param <L> 列表信息 * @param <D> 详情信息 * @param <Q> 查询条件 * @param <C> 创建或修改信息 * @author Charles7c * @since 1.0.0 */ public abstract class BaseServiceImpl<M extends BaseMapper<T>, T extends BaseDO, L, D, Q, C extends BaseReq> implements BaseService<L, D, Q, C> { @Autowired protected M baseMapper; private final Class<T> entityClass; private final Class<L> listClass; private final Class<D> detailClass; protected BaseServiceImpl() { this.entityClass = (Class<T>) ClassUtil.getTypeArgument(this.getClass(), 1); this.listClass = (Class<L>) ClassUtil.getTypeArgument(this.getClass(), 2); this.detailClass = (Class<D>) ClassUtil.getTypeArgument(this.getClass(), 3); } @Override
/* * Copyright (c) 2022-present Charles7c Authors. All Rights Reserved. * <p> * Licensed under the GNU LESSER GENERAL PUBLIC LICENSE 3.0; * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p> * http://www.gnu.org/licenses/lgpl.html * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package top.charles7c.continew.starter.extension.crud.base; /** * 业务实现基类 * * @param <M> Mapper 接口 * @param <T> 实体类 * @param <L> 列表信息 * @param <D> 详情信息 * @param <Q> 查询条件 * @param <C> 创建或修改信息 * @author Charles7c * @since 1.0.0 */ public abstract class BaseServiceImpl<M extends BaseMapper<T>, T extends BaseDO, L, D, Q, C extends BaseReq> implements BaseService<L, D, Q, C> { @Autowired protected M baseMapper; private final Class<T> entityClass; private final Class<L> listClass; private final Class<D> detailClass; protected BaseServiceImpl() { this.entityClass = (Class<T>) ClassUtil.getTypeArgument(this.getClass(), 1); this.listClass = (Class<L>) ClassUtil.getTypeArgument(this.getClass(), 2); this.detailClass = (Class<D>) ClassUtil.getTypeArgument(this.getClass(), 3); } @Override
public PageDataResp<L> page(Q query, PageQuery pageQuery) {
5
2023-11-16 15:48:18+00:00
12k
xIdentified/Devotions
src/main/java/me/xidentified/devotions/Deity.java
[ { "identifier": "Blessing", "path": "src/main/java/me/xidentified/devotions/effects/Blessing.java", "snippet": "public class Blessing extends Effect {\n\n private final PotionEffectType potionEffectType;\n\n public Blessing(String type, int duration, int potency, PotionEffectType potionEffectType) {\n super(type, duration, potency);\n this.potionEffectType = potionEffectType;\n }\n\n public void applyTo(Player player) {\n player.addPotionEffect(new PotionEffect(potionEffectType, duration * 20, potency - 1, false, false, false));\n }\n\n public void applyVisualEffect(Player player) {\n player.spawnParticle(Particle.VILLAGER_HAPPY, player.getLocation(), 10);\n }\n\n public void applyAudioEffect(Player player) {\n Devotions.getInstance().playConfiguredSound(player, \"blessingReceived\");\n }\n}" }, { "identifier": "Curse", "path": "src/main/java/me/xidentified/devotions/effects/Curse.java", "snippet": "public class Curse extends Effect {\n\n private final PotionEffectType potionEffectType;\n\n public Curse(String type, int duration, int potency, PotionEffectType potionEffectType) {\n super(type, duration, potency);\n this.potionEffectType = potionEffectType;\n }\n\n public void applyTo(Player player) {\n player.addPotionEffect(new PotionEffect(potionEffectType, duration * 20, potency - 1, false, false, true));\n }\n\n public void applyVisualEffect(Player player) {\n player.spawnParticle(Particle.SMOKE_LARGE, player.getLocation(), 10);\n }\n\n public void applyAudioEffect(Player player) {\n Devotions.getInstance().playConfiguredSound(player, \"curseReceived\");\n }\n\n}" }, { "identifier": "CooldownManager", "path": "src/main/java/me/xidentified/devotions/managers/CooldownManager.java", "snippet": "public class CooldownManager {\n private final Devotions plugin;\n private final Map<UUID, Map<String, Long>> playerCooldowns = new HashMap<>();\n private final Map<String, Long> cooldowns = new HashMap<>();\n\n public CooldownManager(Devotions plugin) {\n this.plugin = plugin;\n loadCooldownsFromConfig();\n }\n\n private void loadCooldownsFromConfig() {\n cooldowns.put(\"blessing\", getCooldownFromConfig(\"blessing-cooldown\", \"10m\"));\n cooldowns.put(\"curse\", getCooldownFromConfig(\"curse-cooldown\", \"30m\"));\n cooldowns.put(\"ritual\", getCooldownFromConfig(\"ritual-cooldown\", \"3s\"));\n cooldowns.put(\"offering\", getCooldownFromConfig(\"offering-cooldown\", \"3s\"));\n cooldowns.put(\"miracle\", getCooldownFromConfig(\"miracle-cooldown\", \"1d\"));\n cooldowns.put(\"shrine\", getCooldownFromConfig(\"shrine-cooldown\", \"3s\"));\n }\n\n private final Map<UUID, Map<String, Long>> playerActionTimestamps = new HashMap<>();\n\n\n public long isActionAllowed(Player player, String action) {\n long currentTime = System.currentTimeMillis();\n Long cooldownTime = cooldowns.get(action);\n if (cooldownTime == null) {\n return 0; // No cooldown defined for this action\n }\n\n Map<String, Long> playerTimestamps = playerActionTimestamps.computeIfAbsent(player.getUniqueId(), k -> new HashMap<>());\n Long nextAllowedActionTime = playerTimestamps.get(action);\n\n if (nextAllowedActionTime != null && currentTime < nextAllowedActionTime) {\n return nextAllowedActionTime - currentTime;\n }\n\n playerTimestamps.put(action, currentTime + cooldownTime);\n return 0;\n }\n\n // Method to set cooldowns from the config\n public void setCooldown(Player player, String action, long cooldownTimeMs) {\n playerCooldowns\n .computeIfAbsent(player.getUniqueId(), k -> new HashMap<>())\n .put(action, System.currentTimeMillis() + cooldownTimeMs);\n }\n\n public long parseCooldown(String input) {\n Pattern pattern = Pattern.compile(\"(\\\\d+)([dhms])\");\n Matcher matcher = pattern.matcher(input);\n long totalMillis = 0;\n\n while (matcher.find()) {\n int value = Integer.parseInt(matcher.group(1));\n switch (matcher.group(2)) {\n case \"d\" -> totalMillis += TimeUnit.DAYS.toMillis(value);\n case \"h\" -> totalMillis += TimeUnit.HOURS.toMillis(value);\n case \"m\" -> totalMillis += TimeUnit.MINUTES.toMillis(value);\n case \"s\" -> totalMillis += TimeUnit.SECONDS.toMillis(value);\n }\n }\n\n return totalMillis;\n }\n\n public long getCooldownFromConfig(String path, String defaultValue) {\n String cooldownStr = plugin.getConfig().getString(path, defaultValue);\n return parseCooldown(cooldownStr);\n }\n\n}" }, { "identifier": "RitualManager", "path": "src/main/java/me/xidentified/devotions/managers/RitualManager.java", "snippet": "public class RitualManager {\n private final Devotions plugin;\n private static volatile RitualManager instance; // Use this instance throughout plugin\n public final Map<String, Ritual> rituals; // Defined rituals\n private final Map<Player, Ritual> playerRituals = new ConcurrentHashMap<>(); // Track what ritual each player is doing\n public final Map<Player, Item> ritualDroppedItems = new ConcurrentHashMap<>(); // Track dropped item so we can remove later\n\n public RitualManager(Devotions plugin) {\n this.plugin = plugin;\n rituals = new ConcurrentHashMap<>();\n }\n\n // Use one instance of RitualManager throughout the plugin!\n public static RitualManager getInstance(Devotions plugin) {\n if (instance == null) {\n synchronized (RitualManager.class) {\n if (instance == null) {\n instance = new RitualManager(plugin);\n plugin.debugLog(\"New RitualManager instance initialized.\");\n }\n }\n }\n return instance;\n }\n\n public Ritual getRitualByKey(String ritualKey) {\n plugin.debugLog(\"Attempting to get ritual with key: \" + ritualKey);\n Ritual ritual = rituals.get(ritualKey);\n\n if (ritual != null) {\n plugin.debugLog(\"Found ritual: \" + ritual.getDisplayName());\n } else {\n plugin.debugLog(\"No ritual found for key: \" + ritualKey);\n }\n return ritual;\n }\n\n public List<String> getAllRitualNames() {\n return new ArrayList<>(rituals.keySet());\n }\n\n public boolean startRitual(Player player, ItemStack item, Item droppedItem) {\n plugin.debugLog(\"Inside startRitual method\");\n\n // Make sure player isn't already in a ritual before starting another one\n if (RitualManager.getInstance(plugin).getCurrentRitualForPlayer(player) != null) return false;\n\n // Retrieve the ritual associated with the item\n Ritual ritual = RitualManager.getInstance(plugin).getRitualByItem(item);\n plugin.debugLog(\"Ritual retrieved: \" + ritual.getDisplayName() + ritual.getDescription() + ritual.getFavorAmount() + ritual.getObjectives());\n\n ritual.reset();\n associateDroppedItem(player, droppedItem);\n\n // Validate the ritual and its conditions\n if (ritual.validateConditions(player)) {\n plugin.getShrineListener().takeItemInHand(player, item);\n ritual.provideFeedback(player, \"START\");\n\n List<RitualObjective> objectives = ritual.getObjectives(); // Directly fetch from the ritual object\n\n if (objectives != null) {\n for (RitualObjective objective : objectives) {\n // If it's a purification ritual, we'll spawn the desired mobs around the player\n if (objective.getType() == RitualObjective.Type.PURIFICATION) {\n EntityType entityType = EntityType.valueOf(objective.getTarget());\n Location playerLocation = player.getLocation();\n plugin.spawnRitualMobs(playerLocation, entityType, objective.getCount(), 2);\n }\n if (objective.getType() == RitualObjective.Type.MEDITATION) {\n plugin.getMeditationManager().startMeditation(player, ritual, objective);\n }\n plugin.sendMessage(player, plugin.getTranslations().process(objective.getDescription()));\n }\n }\n\n // Set the ritual for the player, so we can track it\n RitualManager.getInstance(plugin).setRitualForPlayer(player, ritual);\n return true; // Ritual started successfully\n } else {\n if (droppedItem != null) droppedItem.remove();\n ritual.provideFeedback(player, \"FAILURE\");\n return false; // Ritual did not start\n }\n }\n\n public void addRitual(String key, Ritual ritual) {\n if (key == null || key.isEmpty()) {\n plugin.getLogger().warning(\"Attempted to add ritual with empty or null key.\");\n return;\n }\n if (ritual == null) {\n plugin.getLogger().warning(\"Attempted to add null ritual for key: \" + key);\n return;\n }\n rituals.put(key, ritual);\n }\n\n public Ritual getCurrentRitualForPlayer(Player player) {\n return playerRituals.get(player);\n }\n\n public void setRitualForPlayer(Player player, Ritual ritual) {\n playerRituals.put(player, ritual);\n }\n\n public void removeRitualForPlayer(Player player) {\n playerRituals.remove(player);\n }\n\n public Ritual getRitualByItem(ItemStack item) {\n plugin.debugLog(\"Itemstack in getRitualbyItem returns: \" + item);\n if (item == null) return null;\n\n String itemId = getItemId(item);\n plugin.debugLog(\"Looking for ritual associated with item ID \" + itemId);\n\n for (Ritual ritual : rituals.values()) {\n RitualItem keyRitualItem = ritual.getItem();\n if (keyRitualItem != null && keyRitualItem.getUniqueId().equals(itemId)) {\n plugin.debugLog(\"Checking if Ritual item \" + keyRitualItem + \" equals Item ID \" + itemId);\n return ritual;\n }\n }\n return null;\n }\n\n // Translates item ID from config to match ritual ID in rituals table\n private String getItemId(ItemStack item) {\n plugin.debugLog(\"Checking for vanilla item ritual key: VANILLA:\" + item.getType().name());\n // constructs vanilla item IDs\n return \"VANILLA:\" + item.getType().name();\n }\n\n public void completeRitual(Player player, Ritual ritual, MeditationManager meditationManager) {\n // Get rid of item on shrine\n Item ritualDroppedItem = getAssociatedDroppedItem(player);\n if (ritualDroppedItem != null) ritualDroppedItem.remove();\n removeDroppedItemAssociation(player);\n\n // Execute outcome and provide feedback\n ritual.getOutcome().executeOutcome(player);\n ritual.provideFeedback(player, \"SUCCESS\");\n\n // Mark ritual as complete and clear data\n ritual.isCompleted = true;\n removeRitualForPlayer(player);\n meditationManager.cancelMeditationTimer(player);\n meditationManager.clearMeditationData(player);\n }\n\n /**\n * Associates an item frame with the player's current ritual\n *\n * @param player The player performing the ritual.\n * @param droppedItem The associated item frame.\n */\n public void associateDroppedItem(Player player, Item droppedItem) {\n ritualDroppedItems.put(player, droppedItem);\n }\n\n /**\n * Retrieves the item frame associated with a player's ongoing ritual.\n *\n * @param player The player performing the ritual.\n * @return The associated item frame, or null if none exists.\n */\n public Item getAssociatedDroppedItem(Player player) {\n return ritualDroppedItems.get(player);\n }\n\n /**\n * Removes the association between a player and an item frame.\n *\n * @param player The player to remove the association for.\n */\n public void removeDroppedItemAssociation(Player player) {\n ritualDroppedItems.remove(player);\n }\n\n}" }, { "identifier": "Ritual", "path": "src/main/java/me/xidentified/devotions/rituals/Ritual.java", "snippet": "@Getter\npublic class Ritual {\n public boolean isCompleted = false;\n private final Devotions plugin;\n private final DevotionManager devotionManager;\n private final String displayName;\n private final String description;\n private final RitualItem item;\n private final int favorAmount;\n private final RitualConditions conditions;\n private final RitualOutcome outcome;\n private final List<RitualObjective> objectives;\n\n public Ritual(Devotions plugin, String displayName, String description, RitualItem item, int favorAmount,\n RitualConditions conditions, RitualOutcome outcome, List<RitualObjective> objectives) {\n this.plugin = plugin;\n this.devotionManager = plugin.getDevotionManager();\n this.displayName = displayName;\n this.description = description;\n this.item = item;\n this.favorAmount = favorAmount;\n this.conditions = conditions;\n this.outcome = outcome;\n this.objectives = objectives;\n }\n\n // Validate ritual conditions against a player and environment.\n public boolean validateConditions(Player player) {\n plugin.debugLog(\"Validating Conditions for ritual \" + this.getDisplayName());\n\n // Time condition\n if (conditions.time() != null) {\n long time = player.getWorld().getTime();\n if ((\"DAY\".equalsIgnoreCase(conditions.time()) && time >= 12300) ||\n (\"NIGHT\".equalsIgnoreCase(conditions.time()) && time < 12300)) {\n return false;\n }\n }\n\n // Biome condition\n if (conditions.biome() != null && !player.getLocation().getBlock().getBiome().toString().equalsIgnoreCase(conditions.biome())) {\n return false;\n }\n\n // Weather condition\n if (conditions.weather() != null) {\n boolean isRaining = player.getWorld().hasStorm();\n if ((\"RAIN\".equalsIgnoreCase(conditions.weather()) && !isRaining) ||\n (\"CLEAR\".equalsIgnoreCase(conditions.weather()) && isRaining)) {\n return false;\n }\n }\n\n // Moon phase condition\n if (conditions.moonPhase() != null && player.getWorld().getFullTime() / 24000L % 8 != conditions.getMoonPhaseNumber(conditions.moonPhase())) {\n return false;\n }\n\n // Altitude condition\n if (conditions.minAltitude() != 0.0 && player.getLocation().getY() < conditions.minAltitude()) {\n return false;\n }\n\n // Experience condition\n if (conditions.minExperience() != 0 && player.getTotalExperience() < conditions.minExperience()) {\n return false;\n }\n\n // Health condition\n if (conditions.minHealth() != 0.0 && player.getHealth() < conditions.minHealth()) {\n return false;\n }\n\n // Hunger condition\n return conditions.minHunger() == 0 || player.getFoodLevel() >= conditions.minHunger();\n\n // All conditions are met\n }\n\n\n public void provideFeedback(Player player, String feedbackType) {\n FavorManager favorManager = devotionManager.getPlayerDevotion(player.getUniqueId());\n Location location = player.getLocation().add(0, 1, 0); // Elevate the location slightly\n switch (feedbackType) {\n case \"START\" -> {\n plugin.playConfiguredSound(player, \"ritualStarted\");\n plugin.spawnParticles(location, Particle.ENCHANTMENT_TABLE, 50, 2.0, 0.5);\n plugin.sendMessage(player, Messages.RITUAL_START.formatted(Placeholder.unparsed(\"ritual\", displayName)));\n }\n case \"SUCCESS\" -> {\n plugin.playConfiguredSound(player, \"ritualComplete\");\n plugin.spawnParticles(location, Particle.VILLAGER_HAPPY, 50, 2.0, 0.5);\n plugin.sendMessage(player, Messages.RITUAL_SUCCESS.formatted(Placeholder.unparsed(\"ritual\", displayName)));\n favorManager.increaseFavor(25);\n }\n case \"FAILURE\" -> {\n plugin.playConfiguredSound(player, \"ritualFailed\");\n plugin.spawnParticles(location, Particle.REDSTONE, 50, 2.0, 0.5);\n player.damage(5);\n plugin.sendMessage(player, Messages.RITUAL_FAILURE.formatted(Placeholder.unparsed(\"ritual\", displayName)));\n favorManager.decreaseFavor(15);\n }\n }\n }\n\n public boolean isCompleted() {\n return this.isCompleted;\n }\n\n public String getParsedItemName() {\n String id = item.id();\n if (id == null || id.isEmpty()) {\n return \"\";\n }\n StringBuilder readableName = new StringBuilder();\n String[] words = id.split(\"_\");\n for (String word : words) {\n if (!word.isEmpty()) {\n readableName.append(word.substring(0, 1).toUpperCase())\n .append(word.substring(1).toLowerCase())\n .append(\" \");\n }\n }\n return readableName.toString().trim();\n }\n\n public void reset() {\n for (RitualObjective objective : this.getObjectives()) {\n objective.reset();\n }\n this.isCompleted = false;\n }\n\n}" }, { "identifier": "Messages", "path": "src/main/java/me/xidentified/devotions/util/Messages.java", "snippet": "public class Messages {\n\n\tpublic static final Message GENERAL_PLAYER_NOT_FOUND = new MessageBuilder(\"general.player_not_found\")\n\t\t\t.withDefault(\"<prefix_negative>Player not found: {name}\")\n\t\t\t.build();\n\tpublic static final Message DEVOTION_RELOAD_SUCCESS = new MessageBuilder(\"devotion.reload_success\")\n\t\t\t.withDefault(\"<prefix>Devotions successfully reloaded!\")\n\t\t\t.build();\n\tpublic static final Message DEVOTION_SET = new MessageBuilder(\"devotion.set\")\n\t\t\t.withDefault(\"<prefix>You are now devoted to {name}. Your favor is {favor}.\")\n\t\t\t.withPlaceholder(\"name\", \"favor\")\n\t\t\t.build();\n\tpublic static final Message DEITY_NOT_FOUND = new MessageBuilder(\"deity.not_found\")\n\t\t\t.withDefault(\"<prefix_negative>Unknown deity. Please choose a valid deity name.\")\n\t\t\t.build();\n\tpublic static final Message DEITY_NO_DEITY_FOUND = new MessageBuilder(\"deity.no_deity_found\")\n\t\t\t.withDefault(\"<prefix_negative>No deities found.\")\n\t\t\t.build();\n\tpublic static final Message DEITY_BLESSED = new MessageBuilder(\"deity.blessed\")\n\t\t\t.withDefault(\"<prefix>{deity} has blessed you with {blessing}!\")\n\t\t\t.withPlaceholders(\"deity\", \"blessing\")\n\t\t\t.build();\n\tpublic static final Message DEITY_CURSED = new MessageBuilder(\"deity.cursed\")\n\t\t\t.withDefault(\"<prefix>{deity} has cursed you with {curse}!\")\n\t\t\t.withPlaceholders(\"deity\", \"curse\")\n\t\t\t.build();\n\tpublic static final Message DEITY_CMD_USAGE = new MessageBuilder(\"deity.cmd.usage\")\n\t\t\t.withDefault(\"<offset>Usage: <cmd_syntax>/deity <arg>select|info</arg> <arg_opt>DeityName</arg_opt></cmd_syntax>\")\n\t\t\t.build();\n\tpublic static final Message DEITY_CMD_SPECIFY_DEITY = new MessageBuilder(\"deity.cmd.specify_deity\")\n\t\t\t.withDefault(\"<prefix_warning>Please specify the deity you wish to worship.\")\n\t\t\t.build();\n\tpublic static final Message DEITY_SPECIFY_PLAYER = new MessageBuilder(\"deity.cmd.specify_player\")\n\t\t\t.withDefault(\"<prefix_warning>Please specify the deity whose information you wish to view.\")\n\t\t\t.build();\n\tpublic static final Message DEITY_LIST_HEADER = new MessageBuilder(\"deity.list.header\")\n\t\t\t.withDefault(\"<primary>Available Deities:\")\n\t\t\t.build();\n\tpublic static final Message DEITY_LIST_ENTRY = new MessageBuilder(\"deity.list.entry\")\n\t\t\t.withDefault(\"<text>- {name}</text>\")\n\t\t\t.withPlaceholder(\"name\")\n\t\t\t.build();\n\tpublic static final Message DEITY_INFO = new MessageBuilder(\"deity.info\")\n\t\t\t.withDefault(\"\"\"\n\t\t\t\t\t<primary>Details of {name}\n\t\t\t\t\t<offset>Lore: <text>{lore}\n\t\t\t\t\t<offset>Domain: <text>{domain}\n\t\t\t\t\t<offset>Alignment: <text>{alignment}\n\t\t\t\t\t<offset>Favored Rituals: <text>{rituals}\n\t\t\t\t\t<offset>Favored Offerings: <text>{offerings}\"\"\")\n\t\t\t.withPlaceholders(\"name\", \"lore\", \"domain\", \"alignment\", \"rituals\", \"offerings\")\n\t\t\t.build();\n\n\tpublic static final Message MEDITATION_COMPLETE = new MessageBuilder(\"meditation.complete\")\n\t\t\t.withDefault(\"<prefix>Meditation complete! You can now move.\")\n\t\t\t.build();\n\tpublic static final Message MEDIDATION_CANCELLED = new MessageBuilder(\"meditation.cancelled\")\n\t\t\t.withDefault(\"<prefix_negative>You moved during meditation! Restarting timer...\")\n\t\t\t.build();\n\n\tpublic static final Message SHRINE_NO_PERM_LIST = new MessageBuilder(\"shrines.list.no_perm\")\n\t\t\t.withDefault(\"<prefix_negative>You don't have permission to list shrines.\")\n\t\t\t.build();\n\tpublic static final Message SHRINE_NO_DESIGNATED_SHRINE = new MessageBuilder(\"shrines.list.no_shrines\")\n\t\t\t.withDefault(\"<prefix_negative>There are no designated shrines.\")\n\t\t\t.build();\n\tpublic static final Message SHRINE_LIST = new MessageBuilder(\"shrines.list.header\")\n\t\t\t.withDefault(\"<offset>Shrines:\")\n\t\t\t.build();\n\tpublic static final Message SHRINE_INFO = new MessageBuilder(\"shrines.list.shrine\")\n\t\t\t.withDefault(\"<click:run_command:\\\"/teleport @p {x} {y} {z}\\\"><hover:show_text:Click to teleport>{deity} at {x:#.#}, {y:#.#}, {z:#.#}</hover></click>\")\n\t\t\t.withPlaceholders(\"deity\", \"x\", \"y\", \"z\")\n\t\t\t.build();\n\tpublic static final Message SHRINE_NO_PERM_REMOVE = new MessageBuilder(\"shrines.remove.no_perm\")\n\t\t\t.withDefault(\"<prefix_negative>You don't have permission to remove shrines.\")\n\t\t\t.build();\n\tpublic static final Message SHRINE_NO_PERM_SET = new MessageBuilder(\"shrines.set.no_perm\")\n\t\t\t.withDefault(\"<prefix_negative>You don't have permission to set a shrine.\")\n\t\t\t.build();\n\tpublic static final Message SHRINE_RC_TO_REMOVE = new MessageBuilder(\"shrines.right_click_to_remove\")\n\t\t\t.withDefault(\"<prefix_warning>Right-click on a shrine to remove it.\")\n\t\t\t.build();\n\tpublic static final Message SHRINE_LIMIT_REACHED = new MessageBuilder(\"shrines.limit_reached\")\n\t\t\t.withDefault(\"<prefix_negative>You have reached the maximum number of shrines ({limit}).\")\n\t\t\t.withPlaceholder(\"limit\")\n\t\t\t.build();\n\tpublic static final Message SHRINE_FOLLOW_DEITY_TO_DESIGNATE = new MessageBuilder(\"shrines.follow_deity_to_designate\")\n\t\t\t.withDefault(\"<prefix_negative>You need to follow a deity to designate a shrine!\")\n\t\t\t.build();\n\tpublic static final Message SHRINE_NOT_FOLLOWING_DEITY = new MessageBuilder(\"shrines.not_following_deity\")\n\t\t\t.withDefault(\"<prefix_negative>Only followers of {deity} may use this shrine.\")\n\t\t\t.withPlaceholder(\"deity\")\n\t\t\t.build();\n\tpublic static final Message SHRINE_COOLDOWN = new MessageBuilder(\"shrines.cooldown\")\n\t\t\t.withDefault(\"<prefix_negative>You must wait {cooldown:'m'}m {cooldown:'s'}s before performing another ritual.\")\n\t\t\t.build();\n\tpublic static final Message SHRINE_ALREADY_EXISTS = new MessageBuilder(\"shrines.cooldown\")\n\t\t\t.withDefault(\"<prefix_negative>A shrine already exists at this location!\")\n\t\t\t.build();\n\tpublic static final Message SHRINE_CLICK_BLOCK_TO_DESIGNATE = new MessageBuilder(\"shrines.click_block_to_create\")\n\t\t\t.withDefault(\"<prefix_warning>Right-click on a block to designate it as a shrine for {deity}\")\n\t\t\t.withPlaceholder(\"deity\")\n\t\t\t.build();\n\tpublic static final Message SHRINE_SUCCESS = new MessageBuilder(\"shrines.shrine_created\")\n\t\t\t.withDefault(\"<prefix>Successfully designated a shrine for {deity}!\")\n\t\t\t.withPlaceholder(\"deity\")\n\t\t\t.build();\n\tpublic static final Message SHRINE_DEITY_NOT_FOUND = new MessageBuilder(\"shrines.deity_not_found\")\n\t\t\t.withDefault(\"<prefix_negative>Could not determine your deity, please inform an admin.\")\n\t\t\t.build();\n\tpublic static final Message SHRINE_REMOVED = new MessageBuilder(\"shrines.remove.success\")\n\t\t\t.withDefault(\"<prefix>Shrine removed successfully!\")\n\t\t\t.build();\n\tpublic static final Message SHRINE_REMOVE_FAIL = new MessageBuilder(\"shrines.remove.not_found\")\n\t\t\t.withDefault(\"<prefix_negative>Failed to remove shrine. You might not own it.\")\n\t\t\t.build();\n\tpublic static final Message SHRINE_REMOVE_NOT_FOUND = new MessageBuilder(\"shrines.remove.not_found\")\n\t\t\t.withDefault(\"<prefix_negative>No shrine found at this location.\")\n\t\t\t.build();\n\tpublic static final Message SHRINE_OFFERING_ACCEPTED = new MessageBuilder(\"shrines.offering_accepted\")\n\t\t\t.withDefault(\"<prefix>Your offering has been accepted!\")\n\t\t\t.build();\n\tpublic static final Message SHRINE_PLACE_ON_TOP = new MessageBuilder(\"shrines.cannot_place_on_top\")\n\t\t\t.withDefault(\"<prefix_negative>You cannot place blocks on top of a shrine!\")\n\t\t\t.build();\n\tpublic static final Message SHRINE_CANNOT_BREAK = new MessageBuilder(\"shrines.cannot_break_shrines\")\n\t\t\t.withDefault(\"<prefix_negative>You cannot destroy shrines! Remove with <cmd_syntax>/shrine remove</cmd_syntax>.\")\n\t\t\t.build();\n\tpublic static final Message SHRINE_OFFERING_DECLINED = new MessageBuilder(\"shrines.offering_declined\")\n\t\t\t.withDefault(\"<prefix_negative>Your offering was not accepted by {subject}.\")\n\t\t\t.withPlaceholder(\"subject\")\n\t\t\t.build();\n\n\tpublic static final Message FAVOR_CMD_USAGE = new MessageBuilder(\"favor.cmd.usage\")\n\t\t\t.withDefault(\"<prefix_warning>Usage: <cmd_syntax>/favor <arg>set|give|take</arg> <arg>playername</arg> <arg>amount</arg></cmd_syntax>\")\n\t\t\t.build();\n\tpublic static final Message FAVOR_CMD_PLAYER_DOESNT_WORSHIP = new MessageBuilder(\"favor.cmd.player_does_not_worship\")\n\t\t\t.withDefault(\"<prefix_negative>{player} doesn't worship any deity.\")\n\t\t\t.withPlaceholder(\"player\")\n\t\t\t.build();\n\tpublic static final Message FAVOR_CMD_INVALID_ACTION = new MessageBuilder(\"favor.cmd.invalid_action\")\n\t\t\t.withDefault(\"<prefix_negative>Invalid action. Use set, give, or take.\")\n\t\t\t.build();\n\tpublic static final Message FAVOR_CMD_NUMBER_FORMAT = new MessageBuilder(\"favor.cmd.invalid_number_format\")\n\t\t\t.withDefault(\"<prefix_negative>Invalid amount. Please enter a number.\")\n\t\t\t.build();\n\tpublic static final Message FAVOR_CURRENT = new MessageBuilder(\"favor.amount.current_favor\")\n\t\t\t.withDefault(\"<offset>Your current favor with {deity} is <favor_col>{favor}\")\n\t\t\t.withPlaceholder(\"deity\")\n\t\t\t.withPlaceholder(\"favor\")\n\t\t\t.withPlaceholder(\"favor_col\")\n\t\t\t.build();\n\tpublic static final Message FAVOR_NO_DEVOTION_SET = new MessageBuilder(\"favor.cmd.no_devotion_set\")\n\t\t\t.withDefault(\"<prefix_negative>You don't have any devotion set.\")\n\t\t\t.build();\n\tpublic static final Message FAVOR_SET_TO = new MessageBuilder(\"favor.amount.set_to\")\n\t\t\t.withDefault(\"<offset>Your favor has been set to <favor_col>{favor}\")\n\t\t\t.withPlaceholders(\"favor\", \"favor_col\")\n\t\t\t.build();\n\tpublic static final Message FAVOR_INCREASED = new MessageBuilder(\"favor.amount.favor_increased\")\n\t\t\t.withDefault(\"<prefix>Your favor with {deity} has increased to <favor_col>{favor}\")\n\t\t\t.build();\n\tpublic static final Message FAVOR_DECREASED = new MessageBuilder(\"favor.amount.favor_decreased\")\n\t\t\t.withDefault(\"<prefix_negative>Your favor with {deity} has decreased to <favor_col>{favor}\")\n\t\t\t.withPlaceholders(\"favor\", \"favor_col\", \"deity\")\n\t\t\t.build();\n\tpublic static final Message RITUAL_CMD_USAGE = new MessageBuilder(\"ritual.cmd.usage\")\n\t\t\t.withDefault(\"<prefix_warning>Usage: <cmd_syntax>/ritual <arg>info</arg> <arg_opt>RitualName</arg_opt></cmd_syntax>\")\n\t\t\t.build();\n\tpublic static final Message RITUAL_CMD_SPECIFY = new MessageBuilder(\"ritual.cmd.specify_ritual\")\n\t\t\t.withDefault(\"<offset>Please specify the ritual you'd like to lookup information for.\")\n\t\t\t.build();\n\tpublic static final Message RITUAL_INFO = new MessageBuilder(\"ritual.info\")\n\t\t\t.withDefault(\"\"\"\n\t\t\t\t\t<primary>Details of {display-name}\n\t\t\t\t\t<offset>Description: <text>{description}\n\t\t\t\t\t<offset>Key Item: <text>{item-name}\n\t\t\t\t\t<offset>Favor Rewarded: <text>{favour-amount}\"\"\")\n\t\t\t.withPlaceholders(\"display-name\", \"description\", \"item-name\", \"favour-amount\")\n\t\t\t.build();\n\tpublic static final Message RITUAL_NOT_FOUND = new MessageBuilder(\"ritual.not_found\")\n\t\t\t.withDefault(\"<prefix_negative>Unknown ritual. Please choose a valid ritual name.\")\n\t\t\t.build();\n\tpublic static final Message RITUAL_START = new MessageBuilder(\"ritual.start\")\n\t\t\t.withDefault(\"<accent>The {ritual} has begun...\")\n\t\t\t.withPlaceholder(\"ritual\")\n\t\t\t.build();\n\tpublic static final Message RITUAL_FAILURE = new MessageBuilder(\"ritual.failure\")\n\t\t\t.withDefault(\"<prefix>{ritual} was a success! Blessings upon ye!\")\n\t\t\t.withPlaceholder(\"ritual\")\n\t\t\t.build();\n\tpublic static final Message RITUAL_SUCCESS = new MessageBuilder(\"ritual.success\")\n\t\t\t.withDefault(\"<prefix_negative>{ritual} has failed - the conditions were not met!\")\n\t\t\t.withPlaceholder(\"ritual\")\n\t\t\t.build();\n\tpublic static final Message RITUAL_RETURN_TO_RESUME = new MessageBuilder(\"ritual.return_to_resume\")\n\t\t\t.withDefault(\"<accent>Return to the shrine to complete the ritual.\")\n\t\t\t.build();\n\n\tpublic static final Message MIRACLE_CMD_USAGE = new MessageBuilder(\"miracle.cmd.usage\")\n\t\t\t.withDefault(\"<prefix_warning>Usage: <cmd_syntax>/testmiracle <arg>number</arg></cmd_syntax>\")\n\t\t\t.build();\n\tpublic static final Message MIRACLE_CMD_NO_MIRACLES = new MessageBuilder(\"miracle.cmd.no_miracles\")\n\t\t\t.withDefault(\"<prefix_negative>No miracles are loaded.\")\n\t\t\t.build();\n\tpublic static final Message MIRACLE_CMD_AVAILABLE = new MessageBuilder(\"miracles.cmd.list_available\")\n\t\t\t.withDefault(\"<prefix>Available miracles: <offset>{miracles}\")\n\t\t\t.withPlaceholder(\"miracles\")\n\t\t\t.build();\n\tpublic static final Message MIRACLE_CMD_UNKNOWN_MIRACLE = new MessageBuilder(\"miracle.cmd.unknown_miracle\")\n\t\t\t.withDefault(\"<prefix_negative>Unknown miracle\")\n\t\t\t.withPlaceholder(\"miracle\")\n\t\t\t.build();\n\tpublic static final Message MIRACLE_BESTOWED = new MessageBuilder(\"miracle.bestowed\")\n\t\t\t.withDefault(\"<prefix>A miracle has been bestowed upon ye!\")\n\t\t\t.build();\n\tpublic static final Message MIRACLE_SAVED_FROM_DEATH = new MessageBuilder(\"miracle.saved_from_death\")\n\t\t\t.withDefault(\"<prefix>A miracle has revived you upon death!\")\n\t\t\t.build();\n\tpublic static final Message MIRACLE_HERO_OF_VILLAGE = new MessageBuilder(\"miracle.hero_of_the_village\")\n\t\t\t.withDefault(\"<prefix>A miracle has granted you the Hero of the Village effect!\")\n\t\t\t.build();\n\tpublic static final Message MIRACLE_FIRE_RESISTANCE = new MessageBuilder(\"miracle.fire_resistance\")\n\t\t\t.withDefault(\"<prefix>A miracle has granted you Fire Resistance!\")\n\t\t\t.build();\n\tpublic static final Message MIRACLE_REPAIR = new MessageBuilder(\"miracle.repair\")\n\t\t\t.withDefault(\"<prefix>A miracle has repaired all your items!\")\n\t\t\t.build();\n\tpublic static final Message MIRACLE_HARVEST = new MessageBuilder(\"miracle.harvest\")\n\t\t\t.withDefault(\"<prefix>A miracle has blessed you with a bountiful harvest!\")\n\t\t\t.build();\n\tpublic static final Message MIRACLE_GOLEM = new MessageBuilder(\"miracle.iron_golem\")\n\t\t\t.withDefault(\"<prefix>A miracle has summoned Iron Golems to aid you!\")\n\t\t\t.build();\n\tpublic static final Message MIRACLE_WOLVES = new MessageBuilder(\"miracle.wolves\")\n\t\t\t.withDefault(\"<prefix>A miracle has summoned friendly Wolves to protect you!\")\n\t\t\t.build();\n}" } ]
import lombok.Getter; import me.xidentified.devotions.effects.Blessing; import me.xidentified.devotions.effects.Curse; import me.xidentified.devotions.managers.CooldownManager; import me.xidentified.devotions.managers.RitualManager; import me.xidentified.devotions.rituals.Ritual; import me.xidentified.devotions.util.Messages; import net.kyori.adventure.text.minimessage.tag.resolver.Placeholder; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import java.util.Arrays; import java.util.List; import java.util.Random; import java.util.stream.Collectors;
8,858
package me.xidentified.devotions; public class Deity { private final Devotions plugin; // Getter methods below @Getter public final String name; @Getter private final String lore; @Getter private final String alignment; private final String domain; private final List<Offering> offerings; private final List<String> rituals; private final List<Blessing> blessings; private final List<Curse> curses; private final List<Miracle> miracles; public Deity(Devotions plugin, String name, String lore, String domain, String alignment, List<Offering> offerings, List<String> rituals, List<Blessing> blessings, List<Curse> curses, List<Miracle> miracles) { this.plugin = plugin; this.name = name; this.lore = lore; this.domain = domain; this.alignment = alignment; this.offerings = offerings; this.rituals = rituals; this.blessings = blessings; this.curses = curses; this.miracles = miracles; } private CooldownManager cooldownManager() {return plugin.getCooldownManager();} public void applyBlessing(Player player, Deity deity) { if (blessings.isEmpty()) return; long remainingCooldown = cooldownManager().isActionAllowed(player, "blessing"); if (remainingCooldown <= 0) { // Randomly select a blessing Blessing blessing = blessings.get(new Random().nextInt(blessings.size())); // Apply the blessing blessing.applyTo(player); blessing.applyVisualEffect(player); blessing.applyAudioEffect(player); // Start cooldown long blessingCooldown = cooldownManager().getCooldownFromConfig("blessing-cooldown", "5s"); plugin.getCooldownManager().setCooldown(player, "blessing", blessingCooldown); // Provide feedback plugin.debugLog("Blessing applied to player " + player.getName()); plugin.sendMessage(player, Messages.DEITY_BLESSED.formatted( Placeholder.unparsed("deity", deity.getName()), Placeholder.unparsed("blessing", blessing.getName()) )); } } public void applyCurse(Player player, Deity deity) { if (curses.isEmpty()) return; long remainingCooldown = cooldownManager().isActionAllowed(player, "curse"); if (remainingCooldown <= 0) { // Randomly select a curse Curse curse = curses.get(new Random().nextInt(curses.size())); // Apply the curse curse.applyTo(player); curse.applyVisualEffect(player); curse.applyAudioEffect(player); // Start cooldown long curseCooldown = cooldownManager().getCooldownFromConfig("curse-cooldown", "5s"); plugin.getCooldownManager().setCooldown(player, "curse", curseCooldown); // Provide feedback plugin.debugLog("Curse applied to player " + player.getName()); plugin.sendMessage(player, Messages.DEITY_CURSED.formatted( Placeholder.unparsed("deity", deity.getName()), Placeholder.unparsed("curse", curse.getName()) )); } } public void applyMiracle(Player player) { if (miracles.isEmpty()) return; Miracle selectedMiracle = selectMiracleForPlayer(player); if (selectedMiracle != null) { selectedMiracle.apply(player); plugin.debugLog("Miracle " + selectedMiracle.getName() + " applied to player " + player.getName()); } } private Miracle selectMiracleForPlayer(Player player) { // Log the total number of miracles before filtering plugin.debugLog("Total miracles: " + miracles.size()); List<Miracle> applicableMiracles = miracles.stream() .filter(miracle -> { boolean canTrigger = miracle.canTrigger(player); // Log the names of each miracle that passes the canTrigger check if (canTrigger) { plugin.debugLog("Miracle " + miracle.getName() + " can be applied."); } else { plugin.debugLog("Miracle " + miracle.getName() + " cannot be applied."); } return canTrigger; }) .toList(); // Log the total number of applicable miracles after filtering plugin.debugLog("Number of applicable miracles: " + applicableMiracles.size()); if (applicableMiracles.isEmpty()) { return null; // No miracles can be applied } // Randomly select from applicable miracles int randomIndex = new Random().nextInt(applicableMiracles.size()); return applicableMiracles.get(randomIndex); } public CharSequence getDomain() { return this.domain; } // Return offerings as a well formatted list public String getOfferings() { return offerings.stream() .map(offering -> { ItemStack itemStack = offering.getItemStack(); String[] parts = itemStack.getType().name().split("_"); return Arrays.stream(parts) .map(word -> word.substring(0, 1).toUpperCase() + word.substring(1).toLowerCase()) .collect(Collectors.joining(" ")); }) .collect(Collectors.joining(", ")); } // Return rituals as a well formatted list public String getRituals() { return rituals.stream() .map(ritualKey -> { // Retrieve the ritual using the configuration name (ritualKey)
package me.xidentified.devotions; public class Deity { private final Devotions plugin; // Getter methods below @Getter public final String name; @Getter private final String lore; @Getter private final String alignment; private final String domain; private final List<Offering> offerings; private final List<String> rituals; private final List<Blessing> blessings; private final List<Curse> curses; private final List<Miracle> miracles; public Deity(Devotions plugin, String name, String lore, String domain, String alignment, List<Offering> offerings, List<String> rituals, List<Blessing> blessings, List<Curse> curses, List<Miracle> miracles) { this.plugin = plugin; this.name = name; this.lore = lore; this.domain = domain; this.alignment = alignment; this.offerings = offerings; this.rituals = rituals; this.blessings = blessings; this.curses = curses; this.miracles = miracles; } private CooldownManager cooldownManager() {return plugin.getCooldownManager();} public void applyBlessing(Player player, Deity deity) { if (blessings.isEmpty()) return; long remainingCooldown = cooldownManager().isActionAllowed(player, "blessing"); if (remainingCooldown <= 0) { // Randomly select a blessing Blessing blessing = blessings.get(new Random().nextInt(blessings.size())); // Apply the blessing blessing.applyTo(player); blessing.applyVisualEffect(player); blessing.applyAudioEffect(player); // Start cooldown long blessingCooldown = cooldownManager().getCooldownFromConfig("blessing-cooldown", "5s"); plugin.getCooldownManager().setCooldown(player, "blessing", blessingCooldown); // Provide feedback plugin.debugLog("Blessing applied to player " + player.getName()); plugin.sendMessage(player, Messages.DEITY_BLESSED.formatted( Placeholder.unparsed("deity", deity.getName()), Placeholder.unparsed("blessing", blessing.getName()) )); } } public void applyCurse(Player player, Deity deity) { if (curses.isEmpty()) return; long remainingCooldown = cooldownManager().isActionAllowed(player, "curse"); if (remainingCooldown <= 0) { // Randomly select a curse Curse curse = curses.get(new Random().nextInt(curses.size())); // Apply the curse curse.applyTo(player); curse.applyVisualEffect(player); curse.applyAudioEffect(player); // Start cooldown long curseCooldown = cooldownManager().getCooldownFromConfig("curse-cooldown", "5s"); plugin.getCooldownManager().setCooldown(player, "curse", curseCooldown); // Provide feedback plugin.debugLog("Curse applied to player " + player.getName()); plugin.sendMessage(player, Messages.DEITY_CURSED.formatted( Placeholder.unparsed("deity", deity.getName()), Placeholder.unparsed("curse", curse.getName()) )); } } public void applyMiracle(Player player) { if (miracles.isEmpty()) return; Miracle selectedMiracle = selectMiracleForPlayer(player); if (selectedMiracle != null) { selectedMiracle.apply(player); plugin.debugLog("Miracle " + selectedMiracle.getName() + " applied to player " + player.getName()); } } private Miracle selectMiracleForPlayer(Player player) { // Log the total number of miracles before filtering plugin.debugLog("Total miracles: " + miracles.size()); List<Miracle> applicableMiracles = miracles.stream() .filter(miracle -> { boolean canTrigger = miracle.canTrigger(player); // Log the names of each miracle that passes the canTrigger check if (canTrigger) { plugin.debugLog("Miracle " + miracle.getName() + " can be applied."); } else { plugin.debugLog("Miracle " + miracle.getName() + " cannot be applied."); } return canTrigger; }) .toList(); // Log the total number of applicable miracles after filtering plugin.debugLog("Number of applicable miracles: " + applicableMiracles.size()); if (applicableMiracles.isEmpty()) { return null; // No miracles can be applied } // Randomly select from applicable miracles int randomIndex = new Random().nextInt(applicableMiracles.size()); return applicableMiracles.get(randomIndex); } public CharSequence getDomain() { return this.domain; } // Return offerings as a well formatted list public String getOfferings() { return offerings.stream() .map(offering -> { ItemStack itemStack = offering.getItemStack(); String[] parts = itemStack.getType().name().split("_"); return Arrays.stream(parts) .map(word -> word.substring(0, 1).toUpperCase() + word.substring(1).toLowerCase()) .collect(Collectors.joining(" ")); }) .collect(Collectors.joining(", ")); } // Return rituals as a well formatted list public String getRituals() { return rituals.stream() .map(ritualKey -> { // Retrieve the ritual using the configuration name (ritualKey)
Ritual ritual = RitualManager.getInstance(plugin).getRitualByKey(ritualKey);
4
2023-11-10 07:03:24+00:00
12k
SplitfireUptown/datalinkx
datalinkx-server/src/main/java/com/datalinkx/dataserver/service/impl/DsService.java
[ { "identifier": "genKey", "path": "datalinkx-common/src/main/java/com/datalinkx/common/utils/IdUtils.java", "snippet": "public static String genKey(String prefix) {\n\tString uuid = UUID.randomUUID().toString().replaceAll(\"-\", \"\");\n\treturn String.format(\"%s_%s\", prefix, uuid);\n}" }, { "identifier": "MetaConstants", "path": "datalinkx-common/src/main/java/com/datalinkx/common/constants/MetaConstants.java", "snippet": "public final class MetaConstants {\n private MetaConstants() {\n }\n /**\n * 数据源类型管理\n */\n public static class DsType {\n // 数据源类型\n public static final Integer MYSQL = 1;\n public static final Integer ELASTICSEARCH = 2;\n }\n\n public static class JobStatus {\n public static final int JOB_TABLE_CREATE = 0;\n public static final int JOB_TABLE_SYNCING = 1;\n public static final int JOB_TABLE_NORMAL = 2;\n public static final int JOB_TABLE_ERROR = 3;\n public static final int JOB_TABLE_QUEUE = 4;\n public static final int JOB_TABLE_STOP = 5;\n\n public static final int JOB_STATUS_CREATE = 0;\n public static final int JOB_STATUS_SYNC = 1;\n public static final int JOB_STATUS_SUCCESS = 2;\n public static final int JOB_STATUS_ERROR = 3;\n public static final int JOB_STATUS_QUEUE = 4;\n public static final int JOB_STATUS_STOP = 5;\n\n public static final String SSE_JOB_STATUS = \"jobList\";\n }\n\n public static class JobSyncMode {\n public static final String INCREMENT_MODE = \"increment\";\n public static final String OVERWRITE_MODE = \"overwrite\";\n }\n\n public static class CommonConstant {\n public static final String TRACE_ID = \"trace_id\";\n }\n}" }, { "identifier": "DsDriverFactory", "path": "datalinkx-driver/src/main/java/com/datalinkx/driver/dsdriver/DsDriverFactory.java", "snippet": "@Slf4j\npublic final class DsDriverFactory {\n\n private DsDriverFactory() {\n\n }\n private static Map<String, Class> dsDriverMap = new ConcurrentHashMap<>();\n static {\n dsDriverMap.put(\"elasticsearch\", EsDriver.class);\n dsDriverMap.put(\"mysql\", MysqlDriver.class);\n }\n\n public static IDsReader getDsReader(String connectId) throws Exception {\n String dsType = ConnectIdUtils.getDsType(connectId);\n Class clazz = dsDriverMap.get(dsType.toLowerCase());\n try {\n Constructor constructor = clazz.getDeclaredConstructor(String.class);\n try {\n IDsReader dsReader = (IDsReader) constructor.newInstance(connectId);\n return dsReader;\n } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {\n log.error(\"create ds dsdriver error\", e);\n }\n } catch (NoSuchMethodException e) {\n log.error(\"create ds dsdriver error\", e);\n }\n\n throw new Exception(\"no dsdriver\");\n }\n\n public static IDsWriter getDsWriter(String connectId) throws Exception {\n String dsType = ConnectIdUtils.getDsType(connectId);\n Class clazz = dsDriverMap.get(dsType);\n try {\n Constructor constructor = clazz.getDeclaredConstructor(String.class);\n try {\n IDsWriter dsWriter = (IDsWriter) constructor.newInstance(connectId);\n return dsWriter;\n } catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {\n log.error(\"create ds dsdriver error\", e);\n }\n } catch (NoSuchMethodException e) {\n log.error(\"create ds dsdriver error\", e);\n }\n\n throw new Exception(\"no dsdriver\");\n }\n}" }, { "identifier": "IDsReader", "path": "datalinkx-driver/src/main/java/com/datalinkx/driver/dsdriver/IDsReader.java", "snippet": "public interface IDsReader extends IDsDriver {\n String retrieveMax(FlinkActionParam param, String field) throws Exception;\n Object getReaderInfo(FlinkActionParam param) throws Exception;\n SqlOperator genWhere(FlinkActionParam param) throws Exception;\n List<DbTree> tree(Boolean fetchTable) throws Exception;\n List<DbTree.DbTreeTable> treeTable(String catalog, String schema) throws Exception;\n List<TableField> getFields(String catalog, String schema, String tableName) throws Exception;\n default Boolean judgeIncrementalField(String catalog, String schema, String tableName, String field) throws Exception {\n return false; \n }\n void afterRead(FlinkActionParam param);\n}" }, { "identifier": "DbTree", "path": "datalinkx-driver/src/main/java/com/datalinkx/driver/dsdriver/base/model/DbTree.java", "snippet": "@Data\npublic class DbTree {\n String name;\n // catalog, schema, table\n String level;\n String ref;\n List<DbTreeTable> table;\n List<DbTree> folder;\n\n @Data\n public static class DbTreeTable extends DbTree {\n String remark;\n String type;\n }\n}" }, { "identifier": "TableField", "path": "datalinkx-driver/src/main/java/com/datalinkx/driver/dsdriver/base/model/TableField.java", "snippet": "@Data\n@Builder\n@AllArgsConstructor\n@NoArgsConstructor\npublic class TableField {\n String id;\n String name;\n String remark;\n String type;\n @JsonProperty(\"raw_type\")\n String rawType;\n @JsonProperty(\"uniq_index\")\n Boolean uniqIndex = false;\n Integer seqNo;\n Boolean allowNull;\n}" }, { "identifier": "EsSetupInfo", "path": "datalinkx-driver/src/main/java/com/datalinkx/driver/dsdriver/esdriver/EsSetupInfo.java", "snippet": "@Data\n@JsonIgnoreProperties(ignoreUnknown = true)\npublic class EsSetupInfo extends SetupInfo {\n private String address;\n private String version;\n private String uid;\n private String pwd;\n\n @JsonProperty(\"kerberos_user\")\n private String kerberosUser;\n\n @JsonProperty(\"kerberos_krb5_path\")\n private String kerberosKrb5Path;\n\n @JsonProperty(\"kerberos_keytab_path\")\n private String kerberosKeytabPath;\n\n @JsonProperty(\"kerberos_jaas_path\")\n private String kerberosJaasPath;\n}" }, { "identifier": "MysqlSetupInfo", "path": "datalinkx-driver/src/main/java/com/datalinkx/driver/dsdriver/mysqldriver/MysqlSetupInfo.java", "snippet": "@Data\n@JsonIgnoreProperties(ignoreUnknown = true)\npublic class MysqlSetupInfo extends JdbcSetupInfo {\n private String useCursorFetch = \"true\";\n private String useUnicode = \"true\";\n private String zeroDateTimeBehavior = \"round\";\n private String characterEncoding = \"UTF8\";\n private String useInformationSchema = \"true\";\n private String serverTimezone;\n\n public String getServerTimezone() {\n if (!ObjectUtils.isEmpty(serverTimezone)) {\n return serverTimezone;\n }\n return serverTimezoneStr();\n }\n\n public String serverTimezoneStr() {\n int timezoneOffsetHours = TimeZone.getDefault().getRawOffset() / (1000 * 60 * 60);\n if(timezoneOffsetHours < 0) {\n return \"GMT%2B\" + (-timezoneOffsetHours);\n } else if (timezoneOffsetHours > 0) {\n return \"GMT-\" + timezoneOffsetHours;\n } else {\n return \"GMT\";\n }\n }\n}" }, { "identifier": "StatusCode", "path": "datalinkx-common/src/main/java/com/datalinkx/common/result/StatusCode.java", "snippet": "public enum StatusCode {\n NORMAL(0),\n COOKIE_EXPIRED(1),\n API_INTERNAL_ERROR(2),\n INVALID_ARGUMENTS(3),\n DS_NOT_EXISTS(101),\n TB_NOT_EXISTS(201),\n\n JOB_IS_RUNNING(1001),\n SYNC_STATUS_ERROR(1002),\n JOB_NOT_EXISTS(1000),\n JOB_CONFIG_ERROR(1001),\n\n\n XTB_NOT_EXISTS(2000);\n\n private final int value;\n\n @Getter\n private String msg;\n\n\n StatusCode(int code) {\n this.value = code;\n }\n\n StatusCode(int code, String msg) {\n this.value = code;\n this.msg = msg;\n }\n\n\n public int getValue() {\n return this.value;\n }\n\n public static StatusCode getByCode(int code) {\n for (StatusCode enums : StatusCode.values()) {\n if (enums.getValue() == code) {\n return enums;\n }\n }\n return null;\n }\n\n\tpublic static Integer getCodeByName(String name) {\n \ttry {\n\t\t\treturn StatusCode.valueOf(name).getValue();\n\t\t} catch (IllegalArgumentException e) {\n \t\treturn null;\n\t\t}\n\n\t}\n\n}" }, { "identifier": "Base64Utils", "path": "datalinkx-common/src/main/java/com/datalinkx/common/utils/Base64Utils.java", "snippet": "public final class Base64Utils {\n\tprivate Base64Utils() {\n\t}\n\tpublic static String encodeBase64(byte[] src) throws UnsupportedEncodingException {\n\n\t\treturn Base64.getEncoder().encodeToString(src);\n\t}\n\n\tpublic static byte[] decodeBase64(String src) throws UnsupportedEncodingException {\n\t\treturn Base64.getDecoder().decode(src);\n\t}\n}" }, { "identifier": "ConnectIdUtils", "path": "datalinkx-common/src/main/java/com/datalinkx/common/utils/ConnectIdUtils.java", "snippet": "@Slf4j\npublic final class ConnectIdUtils {\n\n private ConnectIdUtils() { }\n\n public static String encodeConnectId(String s) {\n try {\n Map<String, Object> setUp = JsonUtils.json2Map(s);\n String setupStr = JsonUtils.toJson(new TreeMap<>(setUp));\n\n return GzipUtils.compress2Str(setupStr, \"+-\");\n } catch (Exception e) {\n log.error(\"encodeConnectId\", e);\n }\n\n return null;\n }\n\n public static String decodeConnectId(String s) {\n try {\n return GzipUtils.uncompress2Str(s, \"+-\");\n } catch (IOException e) {\n log.error(\"decodeConnectId failed\", e);\n }\n\n return \"{}\";\n }\n\n public static String getDsType(String connectId) {\n return JsonUtils.json2Map(decodeConnectId(connectId)).get(\"type\").toString();\n }\n}" }, { "identifier": "JsonUtils", "path": "datalinkx-common/src/main/java/com/datalinkx/common/utils/JsonUtils.java", "snippet": "public final class JsonUtils {\n\tprivate static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();\n\tstatic {\n\t\tOBJECT_MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);\n\t}\n\n\t/**\n\t * 防止反射调用构造器创建对象\n\t */\n\tprivate JsonUtils() {\n\t\tthrow new AssertionError();\n\t}\n\n\t/**\n\t * 自定义日期反序列化处理类\n\t * LocalDate\n\t * jdk8 support\n\t */\n\tpublic static class JsonLocalDateDeserializer extends JsonDeserializer<LocalDate> {\n\t\t@Override\n\t\tpublic LocalDate deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {\n\t\t\tString str = jsonParser.getText().trim();\n\t\t\treturn LocalDate.parse(str, DateTimeFormatter.ISO_DATE);\n\t\t}\n\t}\n\n\t/**\n\t * 自定义日期序列化类\n\t * LocalDate\n\t * jdk8 support\n\t */\n\tpublic static class JsonLocalDateSerializer extends JsonSerializer<LocalDate> {\n\t\t@Override\n\t\tpublic void serialize(LocalDate localDate, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {\n\t\t\tString localdateStr = localDate.format(DateTimeFormatter.ISO_DATE);\n\t\t\tjsonGenerator.writeString(localdateStr);\n\t\t}\n\t}\n\n\t/**\n\t * json数据转pojo\n\t *\n\t * @param jsonStr json字符串\n\t * @param cls 映射类型\n\t * @param <T> 推导类型\n\t * @return 推导类型json对象\n\t */\n\tpublic static <T> T toObject(String jsonStr, Class<T> cls) {\n\t\tT object = null;\n\t\ttry {\n\t\t\tif (StringUtils.isEmpty(jsonStr)) {\n\t\t\t\treturn cls.newInstance();\n\t\t\t}\n\t\t\tobject = OBJECT_MAPPER.readValue(jsonStr, cls);\n\t\t} catch (Exception e) {\n\t\t\tthrow new RuntimeException(e);\n\t\t}\n\t\treturn object;\n\t}\n\n\n\t/**\n\t * json数据转PojoList\n\t *\n\t * @param jsonArray json数据\n\t * @param cls 类型\n\t * @param <T> 推导类型\n\t * @return pojoList\n\t */\n\tpublic static <T> List<T> toList(String jsonArray, Class<T> cls) {\n\t\tList<T> pojoList = null;\n\t\ttry {\n\t\t\tCollectionType listType = OBJECT_MAPPER.getTypeFactory().constructCollectionType(List.class, cls);\n\t\t\tpojoList = OBJECT_MAPPER.readValue(jsonArray, listType);\n\t\t} catch (IOException e) {\n\t\t\tthrow new RuntimeException(e);\n\t\t}\n\t\treturn pojoList;\n\t}\n\n\n\t/**\n\t * pojo转json\n\t *\n\t * @param obj pojo\n\t * @return json字符串\n\t */\n\tpublic static String toJson(Object obj) {\n\t\tString jsonStr = \"\";\n\t\ttry {\n\t\t\tjsonStr = OBJECT_MAPPER.writeValueAsString(obj);\n\t\t} catch (JsonProcessingException e) {\n\t\t\tthrow new RuntimeException(e);\n\t\t}\n\t\treturn jsonStr;\n\t}\n\n\t/**\n\t * json转listMap\n\t *\n\t * @param jsonArray jsonArray字符串\n\t * @return Listmap对象\n\t */\n\tpublic static List<Map<String, Object>> toListMap(String jsonArray) {\n\t\tList<Map<String, Object>> convertedListMap = null;\n\t\ttry {\n\t\t\tconvertedListMap = OBJECT_MAPPER.readValue(jsonArray, new TypeReference<List<Map<String, Object>>>() {\n\t\t\t});\n\t\t} catch (IOException e) {\n\t\t\tthrow new RuntimeException(e);\n\t\t}\n\t\treturn convertedListMap;\n\t}\n\n\t/**\n\t * json转map\n\t *\n\t * @param json json字符串\n\t * @return map对象\n\t */\n\tpublic static Map<Integer, Map<String, Object>> toInnerMap(String json) {\n\t\tMap<Integer, Map<String, Object>> convertedMap = null;\n\t\ttry {\n\t\t\tconvertedMap = OBJECT_MAPPER.readValue(json, new TypeReference<Map<Integer, Map<String, Object>>>() {\n\t\t\t});\n\t\t} catch (IOException e) {\n\t\t\tthrow new RuntimeException(e);\n\t\t}\n\t\treturn convertedMap;\n\t}\n\n\t/**\n\t * json转map\n\t *\n\t * @param json json字符串\n\t * @return map对象\n\t */\n\tpublic static Map<String, Object> json2Map(String json) {\n\t\tMap<String, Object> convertedMap = null;\n\t\ttry {\n\t\t\tconvertedMap = OBJECT_MAPPER.readValue(json, new TypeReference<Map<String, Object>>() {\n\t\t\t});\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\treturn convertedMap;\n\t}\n\n\t/**\n\t * json转map\n\t *\n\t * @param json json字符串\n\t * @return map对象\n\t */\n\tpublic static Map<Integer, Map<String, Object>> json2MapMap(String json) {\n\t\tMap<Integer, Map<String, Object>> convertedMap = null;\n\t\ttry {\n\t\t\tconvertedMap = OBJECT_MAPPER.readValue(json, new TypeReference<Map<Integer, Map<String, Object>>>() {\n\t\t\t});\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\treturn convertedMap;\n\t}\n\n\n\t/**\n\t * listMap转json\n\t *\n\t * @param listMap listMap\n\t * @return\n\t */\n\tpublic static String listMap2JsonArray(List<Map<String, Object>> listMap) {\n\t\tString jsonStr = \"\";\n\t\ttry {\n\t\t\tjsonStr = OBJECT_MAPPER.writeValueAsString(listMap);\n\t\t} catch (JsonProcessingException e) {\n\t\t\tthrow new RuntimeException(e);\n\t\t}\n\t\treturn jsonStr;\n\t}\n\n\t/**\n\t * 将json转为JsonNode对象\n\t * @param json\n\t * @return\n\t */\n\tpublic static JsonNode toJsonNode(String json) {\n\t\tJsonNode jsonNode = null;\n\t\ttry {\n\t\t\tjsonNode = OBJECT_MAPPER.readTree(json);\n\t\t} catch (JsonProcessingException e) {\n\t\t\tthrow new RuntimeException(e);\n\t\t}\n\n\t\treturn jsonNode;\n\t}\n\n\t/**\n\t * 获取 ObjectNode\n\t * @return\n\t */\n\tpublic static ObjectNode getObjectNode() {\n\t\treturn OBJECT_MAPPER.createObjectNode();\n\t}\n\n\t/**\n\t * 获取 ArrayNode\n\t * @return\n\t */\n\tpublic static ArrayNode getArrayNode() {\n\t\treturn OBJECT_MAPPER.createArrayNode();\n\t}\n\n\tpublic static String map2Json(Map<String, Object> map) {\n\t\tString jsonStr = \"\";\n\t\ttry {\n\t\t\tjsonStr = OBJECT_MAPPER.writeValueAsString(map);\n\t\t} catch (JsonProcessingException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\treturn jsonStr;\n\t}\n\n\tpublic static String list2Json(List<?> list) {\n\t\tString jsonStr = \"\";\n\t\ttry {\n\t\t\tjsonStr = OBJECT_MAPPER.writeValueAsString(list);\n\t\t} catch (JsonProcessingException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\treturn jsonStr;\n\t}\n\n\tpublic static <T> List<T> json2List(String json) {\n\t\tList<T> convertedList = null;\n\t\ttry {\n\t\t\tconvertedList = OBJECT_MAPPER.readValue(json, new TypeReference<List<T>>() {\n\t\t\t});\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t\treturn convertedList;\n\t}\n}" }, { "identifier": "DsBean", "path": "datalinkx-server/src/main/java/com/datalinkx/dataserver/bean/domain/DsBean.java", "snippet": "@ApiModel(description = \"数据源\")\n@Data\n@FieldNameConstants\n@SuperBuilder(toBuilder = true)\n@AllArgsConstructor\n@NoArgsConstructor\n@ToString(callSuper = true)\n@Entity\n@DynamicInsert\n@DynamicUpdate\n@Table(name = \"DS\")\npublic class DsBean extends BaseDomainBean {\n\n\tprivate static final long serialVersionUID = 1L;\n\t@Column(name = \"ds_id\", nullable = true, length = 35, columnDefinition = \"char(35)\")\n\tprivate String dsId;\n\t@Column(name = \"`name`\", nullable = true, length = 64, columnDefinition = \"varchar(64)\")\n\tprivate String name;\n\t@Column(name = \"type\", nullable = true, columnDefinition = \"int(11)\")\n\tprivate Integer type;\n\t@Column(name = \"`host`\", nullable = true, length = 64, columnDefinition = \"varchar(64)\")\n\tprivate String host;\n\t@Column(name = \"`port`\", nullable = true, columnDefinition = \"int(11)\")\n\tprivate Integer port;\n\t@Column(name = \"username\", nullable = true, length = 128, columnDefinition = \"varchar(128)\")\n\tprivate String username;\n\t@Column(name = \"`password`\", nullable = true, length = 256, columnDefinition = \"varchar(256)\")\n\tprivate String password;\n\t@Column(name = \"config\", nullable = true, length = 65535, columnDefinition = \"text\")\n\tprivate String config;\n//\t@Column(name = \"ds_desc\", nullable = true, columnDefinition = \"varchar(256)\")\n//\tprivate String dsDesc;\n\t@Column(name = \"`database`\", nullable = true, length = 64, columnDefinition = \"varchar(64)\")\n\tprivate String database;\n\t@Column(name = \"`schema`\", nullable = true, length = 64, columnDefinition = \"varchar(64)\")\n\tprivate String schema;\n}" }, { "identifier": "DsTbBean", "path": "datalinkx-server/src/main/java/com/datalinkx/dataserver/bean/domain/DsTbBean.java", "snippet": "@ApiModel(description = \"数据表\")\n\n@Data\n@FieldNameConstants\n@SuperBuilder\n@AllArgsConstructor\n@NoArgsConstructor\n@EqualsAndHashCode(callSuper = true)\n@ToString(callSuper = true)\n@Entity\n@DynamicInsert\n@DynamicUpdate\n@Table(name = \"DS_TB\")\npublic class DsTbBean extends BaseDomainBean {\n\tprivate static final long serialVersionUID = 1L;\n\n\t@NotBlank\n\t@ApiModelProperty(value = \"tb_3444441234 ,虚拟表的id\")\n\t@Column(name = \"tb_id\", nullable = false, length = 40, columnDefinition = \"char(40)\")\n\tprivate String tbId;\n\t@ApiModelProperty(value = \"所属数据源\")\n\t@Column(name = \"ds_id\", nullable = true, length = 40, columnDefinition = \"char(40)\")\n\tprivate String dsId;\n\t@NotBlank\n\t@ApiModelProperty(value = \"表名,不可修改\")\n\t@Column(name = \"name\", nullable = false, length = 1024, columnDefinition = \"varchar(1024)\")\n\tprivate String name;\n\t@Column(name = \"status\", nullable = true, columnDefinition = \"tinyint(2) unsigned\")\n\tprivate Integer status;\n}" }, { "identifier": "PageVo", "path": "datalinkx-server/src/main/java/com/datalinkx/dataserver/bean/vo/PageVo.java", "snippet": "@Data\n@Builder\n@NoArgsConstructor\n@AllArgsConstructor\npublic class PageVo<T> {\n\t//当前查询的页码\n\tprivate Integer pageNo;\n\t//每页条数\n\tprivate Integer pageSize;\n\t//总数据量\n\tprivate Long total;\n\n\tprivate Integer totalPage;\n\n\tprivate T data;\n\n}" }, { "identifier": "DsForm", "path": "datalinkx-server/src/main/java/com/datalinkx/dataserver/controller/form/DsForm.java", "snippet": "public class DsForm {\n\n\t@Data\n\t@JsonIgnoreProperties(ignoreUnknown = true)\n\tpublic static final class DsCreateForm {\n\t\tprivate String dsId;\n\t\t@ApiModelProperty(value = \"数据源创建\")\n\t\t@JsonProperty(\"name\")\n\t\tprivate String name;\n\t\tprivate String host;\n\t\tprivate String username;\n\t\tprivate String password;\n\t\t@JsonProperty(\"database\")\n\t\tprivate String database = \"\";\n\t\tprivate Integer port;\n\t\tprivate Integer type;\n//\t\tprivate ConfigForm config;\n\t\t@JsonProperty(\"tb_name_list\")\n\t\tprivate List<String> tbNameList;\n\t}\n\n\t@Data\n\t@NoArgsConstructor\n\t@AllArgsConstructor\n\t@JsonIgnoreProperties(ignoreUnknown = true)\n\tpublic static final class ConfigForm {\n\t\tprivate String schema;\n\t\t// es需要额外配置的参数\n\t\t@JsonProperty(\"is_security\")\n\t\tprivate Integer isSecurity;\n\t\t@JsonProperty(\"is_net_ssl\")\n\t\tprivate Integer isNetSSL;\n\t}\n\n\t@Data\n\tpublic static class DataSourcePageForm {\n\t\tprivate String name;\n\n\t\t@ApiModelProperty(value = \"当前页\")\n\t\t@JsonProperty(\"page_no\")\n\t\tprivate Integer pageNo = 1;\n\n\t\t@ApiModelProperty(value = \"展示数量\")\n\t\t@JsonProperty(\"page_size\")\n\t\tprivate Integer pageSize = 10;\n\t}\n}" }, { "identifier": "DatalinkXServerException", "path": "datalinkx-common/src/main/java/com/datalinkx/common/exception/DatalinkXServerException.java", "snippet": "public class DatalinkXServerException extends RuntimeException {\n\tprivate static final long serialVersionUID = -940285811464169752L;\n\n\tprivate StatusCode status;\n\n\t@JsonProperty(\"err_parameter\")\n\tprivate Map<String, Object> errorParam;\n\n\tpublic DatalinkXServerException(String msg) {\n\t\tsuper(msg);\n\t\tstatus = StatusCode.API_INTERNAL_ERROR;\n\t}\n\n\tpublic DatalinkXServerException(StatusCode status, String msg) {\n\t\tsuper(msg);\n\t\tthis.status = status;\n\t}\n\n\tpublic DatalinkXServerException(StatusCode status) {\n\t\tsuper(status.getMsg());\n\t\tthis.status = status;\n\t}\n\n\tpublic DatalinkXServerException(Throwable throwable) {\n\t\tsuper(throwable);\n\t\tstatus = StatusCode.API_INTERNAL_ERROR;\n\t}\n\n\tpublic DatalinkXServerException(String msg, Throwable throwable) {\n\t\tsuper(msg, throwable);\n\t\tstatus = StatusCode.API_INTERNAL_ERROR;\n\t}\n\n\tpublic DatalinkXServerException(String msg, Throwable throwable, StatusCode status) {\n\t\tsuper(msg, throwable);\n\t\tthis.status = status;\n\t}\n\n\tpublic DatalinkXServerException(Throwable throwable, StatusCode status) {\n\t\tsuper(throwable);\n\t\tthis.status = status;\n\t}\n\n\tpublic DatalinkXServerException(StatusCode status, String msg, Map<String, Object> errorParam) {\n\t\tsuper(msg);\n\t\tthis.status = status;\n\t\tthis.errorParam = errorParam;\n\t}\n\n\tpublic StatusCode getStatus() {\n\t\treturn status;\n\t}\n\n\tpublic Map<String, Object> getErrorParam() {\n\t\treturn errorParam;\n\t}\n}" }, { "identifier": "DsRepository", "path": "datalinkx-server/src/main/java/com/datalinkx/dataserver/repository/DsRepository.java", "snippet": "@Repository\npublic interface DsRepository extends CRUDRepository<DsBean, String> {\n\n\tOptional<DsBean> findByDsId(String dsId);\n\n\tList<DsBean> findAllByIsDel(Integer isDel);\n\n\t@Query(value = \"select * from DS where name = :name and is_del = 0\", nativeQuery = true)\n\tDsBean findByName(String name);\n\n\tList<DsBean> findAllByDsIdIn(List<String> dsIds);\n\n\t@Query(value = \" select * from DS where is_del = 0 and if(:name != '', name like concat('%', :name, '%'), 1=1) \", nativeQuery = true)\n Page<DsBean> pageQuery(Pageable pageable, String name);\n\n\t@Transactional\n\t@Modifying\n\t@Query(value = \"update DS set is_del = 1 where ds_id = :dsId\", nativeQuery = true)\n\tvoid deleteByDsId(String dsId);\n}" }, { "identifier": "DsTbRepository", "path": "datalinkx-server/src/main/java/com/datalinkx/dataserver/repository/DsTbRepository.java", "snippet": "@Transactional\n@Repository\npublic interface DsTbRepository extends CRUDRepository<DsTbBean, String> {\n\n\tOptional<DsTbBean> findByTbId(String tbId);\n\n\tDsTbBean findTopByNameAndDsId(String name, String dsId);\n\n\tList<DsTbBean> findAllByTbIdIn(List<String> tbIds);\n}" } ]
import static com.datalinkx.common.utils.IdUtils.genKey; import java.io.UnsupportedEncodingException; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; import com.datalinkx.common.constants.MetaConstants; import com.datalinkx.driver.dsdriver.DsDriverFactory; import com.datalinkx.driver.dsdriver.IDsReader; import com.datalinkx.driver.dsdriver.base.model.DbTree; import com.datalinkx.driver.dsdriver.base.model.TableField; import com.datalinkx.driver.dsdriver.esdriver.EsSetupInfo; import com.datalinkx.driver.dsdriver.mysqldriver.MysqlSetupInfo; import com.datalinkx.common.result.StatusCode; import com.datalinkx.common.utils.Base64Utils; import com.datalinkx.common.utils.ConnectIdUtils; import com.datalinkx.common.utils.JsonUtils; import com.datalinkx.dataserver.bean.domain.DsBean; import com.datalinkx.dataserver.bean.domain.DsTbBean; import com.datalinkx.dataserver.bean.vo.PageVo; import com.datalinkx.dataserver.controller.form.DsForm; import com.datalinkx.common.exception.DatalinkXServerException; import com.datalinkx.dataserver.repository.DsRepository; import com.datalinkx.dataserver.repository.DsTbRepository; import lombok.SneakyThrows; import lombok.extern.log4j.Log4j2; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.stereotype.Component; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.ObjectUtils;
7,529
package com.datalinkx.dataserver.service.impl; @Component @Service @Log4j2 public class DsService { @Autowired private DsRepository dsRepository; @Autowired private DsTbRepository dsTbRepository; public Map<Integer, String> genTypeToDbNameMap() { Map<Integer, String> typeToDbNameMap = new HashMap<>(); typeToDbNameMap.put(MetaConstants.DsType.MYSQL, "mysql"); typeToDbNameMap.put(MetaConstants.DsType.ELASTICSEARCH, "elasticsearch"); return typeToDbNameMap; } /** * @Description //数据源创建 * @Date 2021/1/12 6:13 下午 * @param form * @return String dsId **/ @Transactional(rollbackFor = Exception.class) @SneakyThrows public String create(DsForm.DsCreateForm form) { String dsId = genKey("ds"); // 检测数据源是否重复,重名或者已接入 DsBean nameCheck = dsRepository.findByName(form.getName()); if (!ObjectUtils.isEmpty(nameCheck)) { throw new DatalinkXServerException(form.getName() + " 数据源名称存在"); } // 获取数据源配置信息 DsBean dsBean = new DsBean(); dsBean.setDsId(dsId); dsBean.setType(form.getType()); dsBean.setUsername(form.getUsername()); dsBean.setHost(form.getHost()); dsBean.setPort(form.getPort()); dsBean.setName(form.getName()); dsBean.setDatabase(form.getDatabase()); if (form.getPassword() != null) { dsBean.setPassword(Base64Utils.encodeBase64(form.getPassword().getBytes(StandardCharsets.UTF_8))); } // ExportDsForm.ConfigForm config = form.getConfig(); // if (!ObjectUtils.isEmpty(config)) { // if (StringUtils.isEmpty(config.getSchema())) { // dsBean.setSchema(config.getSchema()); // } // } // // dsBean.setConfig(JsonUtils.toJson(config)); checkConnect(dsBean); //获取选中的表并创建 List<String> tbNameList = ObjectUtils.isEmpty(form.getTbNameList()) ? new ArrayList<>() : form.getTbNameList(); for (String tbName : tbNameList) { xtbCreate(tbName, dsId); } dsRepository.save(dsBean); return dsId; } public String xtbCreate(String tbName, String dsId) { String xtbId = genKey("xtb"); DsTbBean dsTbBean = new DsTbBean(); dsTbBean.setTbId(xtbId); dsTbBean.setName(tbName); dsTbBean.setDsId(dsId); dsTbRepository.save(dsTbBean); return xtbId; } private void checkConnect(DsBean dsBean) { try { IDsReader ignored = DsDriverFactory.getDsReader(getConnectId(dsBean)); ignored.connect(true); log.info("connect success"); } catch (Exception e) { log.error("connect error", e); throw new DatalinkXServerException(e.getMessage()); } } public String getConnectId(DsBean dsBean) { String toType = Optional.ofNullable(genTypeToDbNameMap().get(dsBean.getType())).orElse("").toLowerCase(); switch (toType) { case "mysql": MysqlSetupInfo mysqlSetupInfo = new MysqlSetupInfo(); mysqlSetupInfo.setServer(dsBean.getHost()); mysqlSetupInfo.setPort(dsBean.getPort()); mysqlSetupInfo.setType(toType); mysqlSetupInfo.setUid(dsBean.getUsername()); mysqlSetupInfo.setPwd(dsBean.getPassword()); mysqlSetupInfo.setIsExport(1); mysqlSetupInfo.setCrypter(false);
package com.datalinkx.dataserver.service.impl; @Component @Service @Log4j2 public class DsService { @Autowired private DsRepository dsRepository; @Autowired private DsTbRepository dsTbRepository; public Map<Integer, String> genTypeToDbNameMap() { Map<Integer, String> typeToDbNameMap = new HashMap<>(); typeToDbNameMap.put(MetaConstants.DsType.MYSQL, "mysql"); typeToDbNameMap.put(MetaConstants.DsType.ELASTICSEARCH, "elasticsearch"); return typeToDbNameMap; } /** * @Description //数据源创建 * @Date 2021/1/12 6:13 下午 * @param form * @return String dsId **/ @Transactional(rollbackFor = Exception.class) @SneakyThrows public String create(DsForm.DsCreateForm form) { String dsId = genKey("ds"); // 检测数据源是否重复,重名或者已接入 DsBean nameCheck = dsRepository.findByName(form.getName()); if (!ObjectUtils.isEmpty(nameCheck)) { throw new DatalinkXServerException(form.getName() + " 数据源名称存在"); } // 获取数据源配置信息 DsBean dsBean = new DsBean(); dsBean.setDsId(dsId); dsBean.setType(form.getType()); dsBean.setUsername(form.getUsername()); dsBean.setHost(form.getHost()); dsBean.setPort(form.getPort()); dsBean.setName(form.getName()); dsBean.setDatabase(form.getDatabase()); if (form.getPassword() != null) { dsBean.setPassword(Base64Utils.encodeBase64(form.getPassword().getBytes(StandardCharsets.UTF_8))); } // ExportDsForm.ConfigForm config = form.getConfig(); // if (!ObjectUtils.isEmpty(config)) { // if (StringUtils.isEmpty(config.getSchema())) { // dsBean.setSchema(config.getSchema()); // } // } // // dsBean.setConfig(JsonUtils.toJson(config)); checkConnect(dsBean); //获取选中的表并创建 List<String> tbNameList = ObjectUtils.isEmpty(form.getTbNameList()) ? new ArrayList<>() : form.getTbNameList(); for (String tbName : tbNameList) { xtbCreate(tbName, dsId); } dsRepository.save(dsBean); return dsId; } public String xtbCreate(String tbName, String dsId) { String xtbId = genKey("xtb"); DsTbBean dsTbBean = new DsTbBean(); dsTbBean.setTbId(xtbId); dsTbBean.setName(tbName); dsTbBean.setDsId(dsId); dsTbRepository.save(dsTbBean); return xtbId; } private void checkConnect(DsBean dsBean) { try { IDsReader ignored = DsDriverFactory.getDsReader(getConnectId(dsBean)); ignored.connect(true); log.info("connect success"); } catch (Exception e) { log.error("connect error", e); throw new DatalinkXServerException(e.getMessage()); } } public String getConnectId(DsBean dsBean) { String toType = Optional.ofNullable(genTypeToDbNameMap().get(dsBean.getType())).orElse("").toLowerCase(); switch (toType) { case "mysql": MysqlSetupInfo mysqlSetupInfo = new MysqlSetupInfo(); mysqlSetupInfo.setServer(dsBean.getHost()); mysqlSetupInfo.setPort(dsBean.getPort()); mysqlSetupInfo.setType(toType); mysqlSetupInfo.setUid(dsBean.getUsername()); mysqlSetupInfo.setPwd(dsBean.getPassword()); mysqlSetupInfo.setIsExport(1); mysqlSetupInfo.setCrypter(false);
return ConnectIdUtils.encodeConnectId(JsonUtils.toJson(mysqlSetupInfo));
11
2023-11-16 02:22:52+00:00
12k
12manel123/tsys-my-food-api-1011
src/main/java/com/myfood/controllers/OrderController.java
[ { "identifier": "Dish", "path": "src/main/java/com/myfood/dto/Dish.java", "snippet": "@Entity\n@Table(name = \"dishes\")\npublic class Dish {\n\n @Id\n @Column(name = \"id\")\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long id;\n \n\t@Column(name = \"name\", nullable = false)\n\tprivate String name;\n\n\t@Column(name = \"description\", nullable = false)\n\tprivate String description;\n\n\t@Column(name = \"image\")\n\tprivate String image;\n\n\t@Column(name = \"price\", nullable = false)\n\tprivate double price;\n\n\t@Column(name = \"category\", nullable = false)\n\tprivate String category;\n\t\n\t@Column(name = \"attributes\")\n\tprivate List<String> attributes;\n\t\n\t@Column(name = \"visible\")\n private boolean visible = false; \n\t\n\t@ManyToMany(fetch = FetchType.EAGER)\n\t@JoinTable(\n\t name = \"dish_atribut_dish\",\n\t joinColumns = @JoinColumn(name = \"dish_id\"),\n\t inverseJoinColumns = @JoinColumn(name = \"atribut_dish_id\")\n\t)\n\t@JsonIgnore\n\tprivate List<Atribut_Dish> atribut_dish;\n\t\t\n\t@OneToMany(mappedBy = \"dish\", cascade = CascadeType.ALL, orphanRemoval = true)\n @JsonIgnore\n private List<ListOrder> listOrder;\n\t\n\t@ManyToOne(cascade = CascadeType.REMOVE)\n\t@JsonIgnore\n\t@JoinColumn(name = \"menu_id\")\n\tprivate Menu menu;\n\n\n\t\n\t\n\tpublic Dish(Long id, String name, String description, String image, double price, String category,\n\t\t\tList<String> attributes, boolean visible, List<Atribut_Dish> atribut_dish, List<ListOrder> listOrder,\n\t\t\tMenu menu) {\n\n\t\tthis.id = id;\n\t\tthis.name = name;\n\t\tthis.description = description;\n\t\tthis.image = image;\n\t\tthis.price = price;\n\t\tthis.category = category;\n\t\tthis.attributes = attributes;\n\t\tthis.visible = visible;\n\t\tthis.atribut_dish = atribut_dish;\n\t\tthis.listOrder = listOrder;\n\t\tthis.menu = menu;\n\t}\n\n\tpublic Dish() {\n\n\t}\n\n\tpublic Long getId() {\n\t\treturn id;\n\t}\n\n\tpublic void setId(Long id) {\n\t\tthis.id = id;\n\t}\n\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\n\tpublic void setName(String name) {\n\t\tthis.name = name;\n\t}\n\n\tpublic String getDescription() {\n\t\treturn description;\n\t}\n\n\tpublic void setDescription(String description) {\n\t\tthis.description = description;\n\t}\n\n\tpublic String getImage() {\n\t\treturn image;\n\t}\n\n\tpublic void setImage(String image) {\n\t\tthis.image = image;\n\t}\n\n\tpublic double getPrice() {\n\t\treturn price;\n\t}\n\n\tpublic void setPrice(double price) {\n\t\tthis.price = price;\n\t}\n\n\tpublic String getCategory() {\n\t\treturn category;\n\t}\n\n\tpublic void setCategory(String category) {\n\t\tthis.category = category;\n\t}\n\n\n\tpublic void setAttributes(List<String> attributes) {\n\t\tthis.attributes = attributes;\n\t}\n\n\tpublic boolean isVisible() {\n\t\treturn visible;\n\t}\n\n\tpublic void setVisible(boolean visible) {\n\t\tthis.visible = visible;\n\t}\n\n\tpublic List<Atribut_Dish> getAtribut_dish() {\n\t\treturn atribut_dish;\n\t}\n\n\tpublic void setAtribut_dish(List<Atribut_Dish> atribut_dish) {\n\t\tthis.atribut_dish = atribut_dish;\n\t}\n\n\tpublic List<ListOrder> getListOrder() {\n\t\treturn listOrder;\n\t}\n\n\tpublic void setListOrder(List<ListOrder> listOrder) {\n\t\tthis.listOrder = listOrder;\n\t}\n\n\tpublic Menu getMenu() {\n\t\treturn menu;\n\t}\n\n\tpublic void setMenu(Menu menu) {\n\t\tthis.menu = menu;\n\t}\n\t\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Dish [id=\" + id + \", name=\" + name + \", description=\" + description + \", image=\" + image + \", price=\"\n\t\t\t\t+ price + \", category=\" + category + \", attributes=\" + attributes + \", visible=\" + visible\n\t\t\t\t+ \", atribut_dish=\" + atribut_dish + \", listOrder=\" + listOrder + \", menu=\" + menu + \"]\";\n\t}\n\n\tpublic String[] getAttributes() {\n\t if (atribut_dish != null && !atribut_dish.isEmpty()) {\n\t return atribut_dish.stream()\n\t .map(Atribut_Dish::getAttributes)\n\t .toArray(String[]::new);\n\t }\n\t return new String[0]; \n\t}\n\n\t\n\n}" }, { "identifier": "ListOrder", "path": "src/main/java/com/myfood/dto/ListOrder.java", "snippet": "@Entity\n@Table(name = \"list_orders\")\npublic class ListOrder {\n\n\t@Id\n\t@Column(name = \"id\")\n\t@GeneratedValue(strategy = GenerationType.IDENTITY)\n\tprivate Long id;\n\n\t@ManyToOne\n\t@JoinColumn(name = \"menu_id\")\n\tprivate Menu menu;\n\n\t@ManyToOne\n\t@JoinColumn(name = \"dish_id\")\n\tprivate Dish dish;\n\n\t@ManyToOne(cascade = CascadeType.REMOVE)\n\t@JoinColumn(name = \"order_id\")\n\tprivate Order order;\n\t\n\tpublic ListOrder() {\n\t}\n\n\tpublic ListOrder(Long id, Menu menu, Dish dish, Order order) {\n\t\tsuper();\n\t\tthis.id = id;\n\t\tthis.menu = menu;\n\t\tthis.dish = dish;\n\t\tthis.order = order;\n\t}\n\n\tpublic Long getId() {\n\t\treturn id;\n\t}\n\n\tpublic void setId(Long id) {\n\t\tthis.id = id;\n\t}\n\n\tpublic Menu getMenu() {\n\t\treturn menu;\n\t}\n\n\tpublic void setMenu(Menu menu) {\n\t\tthis.menu = menu;\n\t}\n\n\tpublic Dish getDish() {\n\t\treturn dish;\n\t}\n\n\tpublic void setDish(Dish dish) {\n\t\tthis.dish = dish;\n\t}\n\n\tpublic Order getOrder() {\n\t\treturn order;\n\t}\n\n\tpublic void setOrder(Order order) {\n\t\tthis.order = order;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"ListOrder [id=\" + id + \", menu=\" + menu + \", dish=\" + dish + \", order=\" + order + \"]\";\n\t}\n\n}" }, { "identifier": "Order", "path": "src/main/java/com/myfood/dto/Order.java", "snippet": "@Entity\n@Table(name = \"orders\")\npublic class Order {\n\n @Id\n @Column(name = \"id\")\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long id;\n\n @Column(name = \"maked\", nullable = false)\n private boolean maked;\n\n @ManyToOne\n @JoinColumn(name = \"user_id\")\n private User user;\n\n @ManyToOne\n @JoinColumn(name = \"slot_id\")\n private Slot slot;\n\n @Column(name = \"total_price\")\n private Double totalPrice;\n\n @Column(name = \"actual_date\")\n private LocalDateTime actualDate;\n \n \n @OneToMany(mappedBy = \"order\",cascade = CascadeType.ALL, orphanRemoval = false)\n @JsonIgnore\n private List<ListOrder> listOrder;\n\n public Long getId() {\n return id;\n }\n\n public void setId(Long id) {\n this.id = id;\n }\n\n public boolean isMaked() {\n return maked;\n }\n\n public void setMaked(boolean maked) {\n this.maked = maked;\n }\n\n public User getUser() {\n return user;\n }\n\n public void setUser(User user) {\n this.user = user;\n }\n\n public Slot getSlot() {\n return slot;\n }\n\n public void setSlot(Slot slot) {\n this.slot = slot;\n }\n\n public Double getTotalPrice() {\n return totalPrice;\n }\n\n public void setTotalPrice(Double totalPrice) {\n this.totalPrice = totalPrice;\n }\n\n public LocalDateTime getActualDate() {\n return actualDate;\n }\n\n public void setActualDate(LocalDateTime actualDate) {\n this.actualDate = actualDate;\n }\n\n public List<ListOrder> getListOrder() {\n\t\treturn listOrder;\n\t}\n\n\tpublic void setListOrder(List<ListOrder> listOrder) {\n\t\tthis.listOrder = listOrder;\n\t}\n\n\t@Override\n public String toString() {\n return \"Order{\" +\n \"id=\" + id +\n \", maked=\" + maked +\n \", userId=\" + user +\n \", slot=\" + slot +\n \", totalPrice=\" + totalPrice +\n \", actualDate=\" + actualDate +\n '}';\n }\n}" }, { "identifier": "OrderCookDTO", "path": "src/main/java/com/myfood/dto/OrderCookDTO.java", "snippet": "public class OrderCookDTO {\n private Long orderId;\n private boolean maked;\n private Slot slot;\n private List<Dish> dishes;\n private Double totalPrice;\n private LocalDateTime actualDate;\n \n public OrderCookDTO() {\n\t}\n\n\t\n\n public OrderCookDTO(Long orderId, boolean maked, Slot slot, List<Dish> dishes, Double totalPrice,\n\t\t\tLocalDateTime actualDate) {\n\t\tsuper();\n\t\tthis.orderId = orderId;\n\t\tthis.maked = maked;\n\t\tthis.slot = slot;\n\t\tthis.dishes = dishes;\n\t\tthis.totalPrice = totalPrice;\n\t\tthis.actualDate = actualDate;\n\t}\n\n\n\n\tpublic Long getOrderId() {\n return orderId;\n }\n\n public void setOrderId(Long orderId) {\n this.orderId = orderId;\n }\n\n public boolean isMaked() {\n return maked;\n }\n\n public void setMaked(boolean maked) {\n this.maked = maked;\n }\n\n public Slot getSlot() {\n return slot;\n }\n\n public void setSlot(Slot slot) {\n this.slot = slot;\n }\n\n public List<Dish> getDishes() {\n return dishes;\n }\n\n public void setDishes(List<Dish> dishes) {\n this.dishes = dishes;\n }\n \n public Double getTotalPrice() {\n\t\treturn totalPrice;\n\t}\n\n\tpublic void setTotalPrice(Double totalPrice) {\n\t\tthis.totalPrice = totalPrice;\n\t}\n\n\tpublic LocalDateTime getActualDate() {\n\t\treturn actualDate;\n\t}\n\n\tpublic void setActualDate(LocalDateTime actualDate) {\n\t\tthis.actualDate = actualDate;\n\t}\n}" }, { "identifier": "OrderUserDTO", "path": "src/main/java/com/myfood/dto/OrderUserDTO.java", "snippet": "public class OrderUserDTO {\n\t\n private Long id;\n private boolean maked;\n private Slot slot;\n private Double totalPrice;\n private LocalDateTime actualDate;\n\n \n\tpublic OrderUserDTO(Long id, boolean maked, Slot slot, Double totalPrice, LocalDateTime actualDate) {\n\t\tsuper();\n\t\tthis.id = id;\n\t\tthis.maked = maked;\n\t\tthis.slot = slot;\n\t\tthis.totalPrice = totalPrice;\n\t\tthis.actualDate = actualDate;\n\t}\n\n\tpublic OrderUserDTO() {\n\t}\n\n\tpublic Long getId() {\n\t\treturn id;\n\t}\n\n\tpublic void setId(Long id) {\n\t\tthis.id = id;\n\t}\n\n\tpublic boolean isMaked() {\n\t\treturn maked;\n\t}\n\n\tpublic void setMaked(boolean maked) {\n\t\tthis.maked = maked;\n\t}\n\n\tpublic Slot getSlot() {\n\t\treturn slot;\n\t}\n\n\tpublic void setSlot(Slot slot) {\n\t\tthis.slot = slot;\n\t}\n\n\tpublic Double getTotalPrice() {\n\t\treturn totalPrice;\n\t}\n\n\tpublic void setTotalPrice(Double totalPrice) {\n\t\tthis.totalPrice = totalPrice;\n\t}\n\n\tpublic LocalDateTime getActualDate() {\n\t\treturn actualDate;\n\t}\n\n\tpublic void setActualDate(LocalDateTime actualDate) {\n\t\tthis.actualDate = actualDate;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"OrderUserDTO [id=\" + id + \", maked=\" + maked + \", slot=\" + slot + \", totalPrice=\" + totalPrice\n\t\t\t\t+ \", actualDate=\" + actualDate + \"]\";\n\t}\n\n\t\n}" }, { "identifier": "Slot", "path": "src/main/java/com/myfood/dto/Slot.java", "snippet": "@Entity\n@Table(name = \"slots\")\npublic class Slot {\n\n @Id\n @Column(name = \"id\")\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long id;\n\n @Column(name = \"time\", nullable = false)\n private String time;\n\n @Column(name = \"limit_slot\", nullable = false)\n private int limitSlot;\n\n @Column(name = \"actual\", nullable = false)\n private int actual;\n \n @OneToMany(mappedBy = \"slot\")\n @JsonIgnore\n private List<Order> orders;\n\n public Long getId() {\n return id;\n }\n\n public void setId(Long id) {\n this.id = id;\n }\n\n public String getTime() {\n return time;\n }\n\n public void setTime(String time) {\n this.time = time;\n }\n\n public int getLimitSlot() {\n return limitSlot;\n }\n\n public void setLimitSlot(int limitSlot) {\n this.limitSlot = limitSlot;\n }\n\n public int getActual() {\n return actual;\n }\n\n public void setActual(int actual) {\n this.actual = actual;\n }\n \n public List<Order> getOrders() {\n return orders;\n }\n\n public void setOrders(List<Order> orders) {\n this.orders = orders;\n }\n\n @Override\n public String toString() {\n return \"Slot{\" +\n \"id=\" + id +\n \", time='\" + time + '\\'' +\n \", limitSlot=\" + limitSlot +\n \", actual=\" + actual +\n '}';\n }\n}" }, { "identifier": "User", "path": "src/main/java/com/myfood/dto/User.java", "snippet": "@Entity\n@Table(name = \"users\")\npublic class User {\n\t\n\t/**\n\t* The unique identifier for the user.\n\t*/\n\t@Id\n\t@Column(name = \"id\")\n\t@GeneratedValue(strategy = GenerationType.IDENTITY)\n\tprivate Long id;\n\t\n\t/**\n\t* The email address of the user. It is unique and cannot be null.\n\t*/\n\t@Email\n\t@NotBlank\n\t@Size(max = 80)\n\t@Column(name = \"email\", unique = true)\n\tprivate String email;\n\t\n\t/**\n\t* The password associated with the user. It cannot be null.\n\t*/\n\t@NotBlank\n\t@Column(name = \"password\")\n\tprivate String password;\n\t\n\t/**\n\t* The username of the user. It cannot be null.\n\t*/\n\t@NotBlank\n\t@Size(max = 60)\n\t@Column(name = \"name\", unique = true)\n\tprivate String username;\n\t\n\t/**\n\t* Represents the role of the user within the system. Multiple users can share the same role.\n\t* This field is mapped as a one-to-one relationship with the {@code Role} entity,\n\t* and it includes cascading persistence to ensure the role is persisted along with the user.\n\t*/\n\t@ManyToOne\n\tprivate Role role;\n\n @OneToMany(mappedBy = \"user\" ,fetch = FetchType.EAGER ,cascade = CascadeType.ALL )\n @JsonIgnore\n private List<Order> orders;\n \n @Column(name = \"created_at\")\n @Temporal(TemporalType.TIMESTAMP)\n private LocalDateTime createdAt;\n\n @Column(name = \"updated_at\")\n @Temporal(TemporalType.TIMESTAMP)\n private LocalDateTime updatedAt;\n\n\t/**\n\t * Default constructor for the {@code User} class.\n\t */\n\tpublic User() {\n\t}\n\t\n\tpublic User(Long id, String email, String password, String username , LocalDateTime createdAt ,LocalDateTime updatedAt) {\n\t\tthis.id = id;\n\t\tthis.email = email;\n\t\tthis.password = password;\n\t\tthis.username = username;\n\t\tthis.role = new Role();\n\t\tthis.createdAt = createdAt;\n\t\tthis.updatedAt = updatedAt;\n\t}\n\n\t/**\n\t * Parameterized constructor for the {@code User} class.\n\t *\n\t * @param id The unique identifier for the user.\n\t * @param email The email address of the user.\n\t * @param password The password associated with the user.\n\t * @param username The username of the user.\n\t * @param role The role of the user in the system.\n\t */\n\tpublic User(Long id, String email, String password, String username, Role role, LocalDateTime createdAt ,LocalDateTime updatedAt ) {\n\t\tthis.id = id;\n\t\tthis.email = email;\n\t\tthis.password = password;\n\t\tthis.username = username;\n\t\tthis.role = role;\n\t\tthis.createdAt = createdAt;\n\t\tthis.updatedAt = updatedAt;\n\t}\n\n\t/**\n\t * Get the unique identifier of the user.\n\t *\n\t * @return The unique identifier of the user.\n\t */\n\tpublic Long getId() {\n\t\treturn id;\n\t}\n\n\t/**\n\t * Set the unique identifier of the user.\n\t *\n\t * @param id The unique identifier of the user.\n\t */\n\tpublic void setId(Long id) {\n\t\tthis.id = id;\n\t}\n\n\t/**\n\t * Get the email address of the user.\n\t *\n\t * @return The email address of the user.\n\t */\n\tpublic String getEmail() {\n\t\treturn email;\n\t}\n\n\t/**\n\t * Set the email address of the user.\n\t *\n\t * @param email The email address of the user.\n\t */\n\tpublic void setEmail(String email) {\n\t\tthis.email = email;\n\t}\n\n\t/**\n\t * Get the password associated with the user.\n\t *\n\t * @return The password associated with the user.\n\t */\n\tpublic String getPassword() {\n\t\treturn password;\n\t}\n\n\t/**\n\t * Set the password associated with the user.\n\t *\n\t * @param password The password associated with the user.\n\t */\n\tpublic void setPassword(String password) {\n\t\tthis.password = password;\n\t}\n\n\t/**\n\t * Get the username of the user.\n\t *\n\t * @return The username of the user.\n\t */\n\tpublic String getUsername() {\n\t\treturn username;\n\t}\n\n\t/**\n\t * Set the username of the user.\n\t *\n\t * @param username The username of the user.\n\t */\n\tpublic void setUsername(String username) {\n\t\tthis.username = username;\n\t}\n\n\t/**\n\t * Get the role of the user in the system.\n\t *\n\t * @return The role of the user.\n\t */\n\tpublic Role getRole() {\n\t\treturn role;\n\t}\n\n\t/**\n\t * Set the role of the user in the system.\n\t *\n\t * @param role The role of the user.\n\t */\n\tpublic void setRole(Role role) {\n\t\tthis.role = role;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"User [id=\" + id + \", email=\" + email + \", password=\" + password + \", username=\" + username + \", role=\"\n\t\t\t\t+ role + \"]\";\n\t}\n\n\n\t/**\n\t * @return the orders\n\t */\n\tpublic List<Order> getOrders() {\n\t\treturn orders;\n\t}\n\n\t/**\n\t * @param orders the orders to set\n\t */\n\tpublic void setOrders(List<Order> orders) {\n\t\tthis.orders = orders;\n\t}\n\n\t/**\n\t * @return the createdAt\n\t */\n\tpublic LocalDateTime getCreatedAt() {\n\t\treturn createdAt;\n\t}\n\n\t/**\n\t * @param createdAt the createdAt to set\n\t */\n\tpublic void setCreatedAt(LocalDateTime createdAt) {\n\t\tthis.createdAt = createdAt;\n\t}\n\n\t/**\n\t * @return the updatedAt\n\t */\n\tpublic LocalDateTime getUpdatedAt() {\n\t\treturn updatedAt;\n\t}\n\n\t/**\n\t * @param updatedAt the updatedAt to set\n\t */\n\tpublic void setUpdatedAt(LocalDateTime updatedAt) {\n\t\tthis.updatedAt = updatedAt;\n\t}\n}" }, { "identifier": "OrderServiceImpl", "path": "src/main/java/com/myfood/services/OrderServiceImpl.java", "snippet": "@Service\npublic class OrderServiceImpl implements IOrderService {\n\n @Autowired\n private IOrderDAO orderDAO;\n\n @Override\n public List<Order> getAllOrders() {\n return orderDAO.findAll();\n }\n\n @Override\n public Optional<Order> getOneOrder(Long id) {\n return orderDAO.findById(id);\n }\n\n @Override\n public Order createOrder(Order entity) {\n return orderDAO.save(entity);\n }\n\n @Override\n public Order updateOrder(Order entity) {\n return orderDAO.save(entity);\n }\n\n @Override\n public void deleteOrder(Long id) {\n orderDAO.deleteById(id);\n }\n\n @Override\n public Order markOrderAsMaked(Order entity) {\n return orderDAO.save(entity);\n }\n\n @Override\n public Order updateOrderSlot(Order entity) {\n return orderDAO.save(entity);\n }\n\n @Override\n public List<Order> getAllOrdersForCook() {\n return orderDAO.findAllByMakedIsFalse();\n }\n\n @Override\n public List<Order> getAllOrdersForUserId(Long id) {\n return orderDAO.findAllByUserIdOrderByActualDateDesc(id);\n }\n\n @Override\n public Page<Order> getAllOrdersWithPagination(Pageable pageable) {\n return orderDAO.findAll(pageable);\n }\n\n}" }, { "identifier": "SlotServiceImpl", "path": "src/main/java/com/myfood/services/SlotServiceImpl.java", "snippet": "@Service\npublic class SlotServiceImpl implements ISlotService {\n\n @Autowired\n private ISlotDAO slotDAO;\n\n @Override\n public List<Slot> getAllSlots() {\n return slotDAO.findAll();\n }\n\n @Override\n public Optional<Slot> getOneSlot(Long id) {\n return slotDAO.findById(id);\n }\n\n @Override\n public Slot createSlot(Slot entity) {\n return slotDAO.save(entity);\n }\n\n @Override\n public Slot updateSlot(Slot entity) {\n return slotDAO.save(entity);\n }\n\n @Override\n public void deleteSlot(Long id) {\n slotDAO.deleteById(id);\n }\n}" }, { "identifier": "UserServiceImpl", "path": "src/main/java/com/myfood/services/UserServiceImpl.java", "snippet": "@Service\npublic class UserServiceImpl implements IUserService {\n\t\n\t@Autowired\n\tprivate IUserDAO userDao;\n\n\t@Override\n\tpublic List<User> getAllUsers() {\n\t\treturn userDao.findAll();\n\t}\n\n\t@Override\n\tpublic Optional<User> getOneUser(Long id){\n\t\treturn userDao.findById(id);\n\t}\n\n\t@Override\n\tpublic User createUser(User entity) {\n\t\treturn userDao.save(entity);\n\t}\n\n\t@Override\n\tpublic User updateUser(User entity) {\n\t\treturn userDao.save(entity);\n\t}\n\n\t@Override\n\tpublic void deleteUser(Long id) {\n\t\tuserDao.deleteById(id);;\n\t}\n\n /**\n * Get a user by username.\n *\n * @param username The username of the user.\n * @return The user with the specified username, or null if not found.\n */\n public User getUserByUsername(String username) {\n return userDao.findByUsername(username);\n }\n\n\n\tpublic Page<User> findAllWithPagination(Pageable pageable) {\n\t\treturn userDao.findAll(pageable);\n\t}\n\n\t\n\n}" } ]
import java.time.LocalDateTime; import java.time.ZoneId; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.stream.Collectors; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.PageRequest; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; import org.springframework.data.domain.Pageable; import com.myfood.dto.Dish; import com.myfood.dto.ListOrder; import com.myfood.dto.Order; import com.myfood.dto.OrderCookDTO; import com.myfood.dto.OrderUserDTO; import com.myfood.dto.Slot; import com.myfood.dto.User; import com.myfood.services.OrderServiceImpl; import com.myfood.services.SlotServiceImpl; import com.myfood.services.UserServiceImpl; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.security.SecurityRequirement; import jakarta.transaction.Transactional;
9,152
@Transactional @Operation(summary = "Endpoint for USER", security = @SecurityRequirement(name = "bearerAuth")) @PutMapping("/order/finish/{orderId}/{slotId}") public ResponseEntity<?> updateOrderSlot( @PathVariable(name = "orderId") Long orderId, @PathVariable(name = "slotId") Long slotId) { Optional<Order> optionalOrder = orderService.getOneOrder(orderId); if (optionalOrder.isPresent()) { Order order = optionalOrder.get(); if (order.getActualDate() != null) { return createErrorResponse("Order is confirmed previously", HttpStatus.BAD_REQUEST); } if (order.getListOrder() == null || order.getListOrder().isEmpty()) { return createErrorResponse("Order must have at least one ListOrder associated", HttpStatus.BAD_REQUEST); } Optional<Slot> slotOptional = slotService.getOneSlot(slotId); if (slotOptional.isPresent()) { Slot slot = slotOptional.get(); if (slot.getActual() >= slot.getLimitSlot()) { return createErrorResponse("Too many orders for this slot to create order", HttpStatus.BAD_REQUEST); } Double totalPrice = calculateTotalPrice(order); ZoneId madridZone = ZoneId.of("Europe/Madrid"); order.setActualDate(LocalDateTime.now(madridZone)); order.setSlot(slot); order.setTotalPrice(totalPrice); slot.setActual(slot.getActual() + 1); orderService.updateOrder(order); slotService.updateSlot(slot); OrderUserDTO orderUserDTO = new OrderUserDTO(order.getId(), order.isMaked(), order.getSlot(),order.getTotalPrice(),order.getActualDate()); return ResponseEntity.accepted().body(orderUserDTO); } else { return createErrorResponse("The slot not exists", HttpStatus.BAD_REQUEST); } } else { return createErrorResponse("The order not exists", HttpStatus.BAD_REQUEST); } } private Double calculateTotalPrice(Order order) { List<ListOrder> listOrders = order.getListOrder(); List<Dish> dishes = listOrders.stream() .map(ListOrder::getDish) .filter(Objects::nonNull) .collect(Collectors.toList()); List<Dish> menuDishes = listOrders.stream() .map(listOrder -> listOrder.getMenu()) .filter(Objects::nonNull) .flatMap(menu -> Arrays .asList(menu.getAppetizer(), menu.getFirst(), menu.getSecond(), menu.getDessert()).stream()) .filter(Objects::nonNull) .collect(Collectors.toList()); List<Dish> allDishes = new ArrayList<>(menuDishes); allDishes.addAll(dishes); Double totalPrice = allDishes.stream() .mapToDouble(Dish::getPrice) .sum(); return totalPrice; } @Transactional @Operation(summary = "Endpoint for USER", security = @SecurityRequirement(name = "bearerAuth")) @PutMapping("/order/finish/{orderId}/{slotId}/{price}") public ResponseEntity<?> updateOrderSlotPrice( @PathVariable(name = "orderId") Long orderId, @PathVariable(name = "slotId") Long slotId, @PathVariable(name = "price") Double price) { Optional<Order> optionalOrder = orderService.getOneOrder(orderId); if (optionalOrder.isPresent()) { Order order = optionalOrder.get(); if (order.getActualDate() != null) { return createErrorResponse("Order is confirmed previously", HttpStatus.BAD_REQUEST); } if (order.getListOrder() == null || order.getListOrder().isEmpty()) { return createErrorResponse("Order must have at least one ListOrder associated", HttpStatus.BAD_REQUEST); } Optional<Slot> slotOptional = slotService.getOneSlot(slotId); if (slotOptional.isPresent()) { Slot slot = slotOptional.get(); if (slot.getActual() >= slot.getLimitSlot()) { return createErrorResponse("Too many orders for this slot to create order", HttpStatus.BAD_REQUEST); } Double totalPrice = price; ZoneId madridZone = ZoneId.of("Europe/Madrid"); order.setActualDate(LocalDateTime.now(madridZone)); order.setSlot(slot); order.setTotalPrice(totalPrice); slot.setActual(slot.getActual() + 1); orderService.updateOrder(order); slotService.updateSlot(slot); OrderUserDTO orderUserDTO = new OrderUserDTO(order.getId(), order.isMaked(), order.getSlot(),order.getTotalPrice(),order.getActualDate()); return ResponseEntity.accepted().body(orderUserDTO); } else { return createErrorResponse("The slot not exists", HttpStatus.BAD_REQUEST); } } else { return createErrorResponse("The order not exists", HttpStatus.BAD_REQUEST); } } /** * Creates and saves a new order for the specified user. It's for the USER * * @param userId The ID of the user for whom the order is created. * @return ResponseEntity containing the OrderUserDTO representing the newly * created order. * @see UserService#getOneUser(Long) * @see OrderService#createOrder(Order) * @see OrderUserDTO */ @Operation(summary = "Endpoint for USER", security = @SecurityRequirement(name = "bearerAuth")) @PostMapping("/order/{userId}") public ResponseEntity<?> saveOrder(@PathVariable(name = "userId") Long userId) {
package com.myfood.controllers; @RestController @RequestMapping("api/v1") public class OrderController { @Autowired private OrderServiceImpl orderService; @Autowired private SlotServiceImpl slotService; @Autowired private UserServiceImpl userService; /** * Retrieves a paginated list of user orders with Dishes. It's for the ADMIN * * @param page The page number (default is 0). * @param size The number of orders per page (default is 10). * @return ResponseEntity containing a paginated list of {@link OrderUserDTO}. * @see OrderService#getAllOrdersWithPagination(Pageable) */ @Transactional @Operation(summary = "Endpoint for ADMIN", security = @SecurityRequirement(name = "bearerAuth")) @GetMapping("/orders") public ResponseEntity<Page<OrderCookDTO>> getAllOrdersWithDish( @RequestParam(defaultValue = "0") int page, @RequestParam(defaultValue = "8") int size) { List<Order> ordersForCook = orderService.getAllOrders(); List<Order> filteredOrders = ordersForCook.stream() .filter(order -> order.getActualDate() != null) .collect(Collectors.toList()); Pageable pageable = PageRequest.of(page, size); Page<Order> paginatedOrders = paginate(filteredOrders, pageable); List<OrderCookDTO> orderCookDTOList = paginatedOrders.getContent().stream() .map(this::mapToOrderCookDTOWithDishes) .collect(Collectors.toList()); return ResponseEntity.ok(new PageImpl<>(orderCookDTOList, pageable, filteredOrders.size())); } /** * Retrieves details of a specific order identified by its ID. It's for the ADMIN * * @param id The unique identifier of the order. * @return ResponseEntity containing the details of the order as an {@link OrderUserDTO}. * @throws DataNotFoundException If the specified order does not exist. * @see OrderService#getOneOrder(Long) */ @Operation(summary = "Endpoint for ADMIN", security = @SecurityRequirement(name = "bearerAuth")) @PreAuthorize("hasRole('ADMIN')") @GetMapping("/order/{id}") public ResponseEntity<?> getOneOrder(@PathVariable(name = "id") Long id) { Optional<Order> entity = orderService.getOneOrder(id); if (entity.isPresent()) { Order order = entity.get(); OrderUserDTO orderUserDTO = new OrderUserDTO(order.getId(), order.isMaked(), order.getSlot(),order.getTotalPrice(),order.getActualDate()); return ResponseEntity.ok(orderUserDTO); } else { return createErrorResponse("The order not exists", HttpStatus.NOT_FOUND); } } /** * Creates a new order based on the provided order details. It's for the ADMIN * * @param entity The order details provided in the request body. * @return ResponseEntity containing the details of the created order as an {@link OrderUserDTO}. * {@link OrderUserDTO} and returned in the ResponseEntity with status 200 (OK). * @see OrderService#createOrder(Order) */ @Operation(summary = "Endpoint for ADMIN", security = @SecurityRequirement(name = "bearerAuth")) @PreAuthorize("hasRole('ADMIN')") @PostMapping("/order") public ResponseEntity<OrderUserDTO> saveOrder(@RequestBody Order entity) { Order savedOrder = orderService.createOrder(entity); OrderUserDTO orderUserDTO = new OrderUserDTO(savedOrder.getId(), savedOrder.isMaked(), savedOrder.getSlot(),savedOrder.getTotalPrice(),savedOrder.getActualDate()); return ResponseEntity.ok(orderUserDTO); } /** * Updates an existing order with the provided order details. It's for ADMIN * * @param id The identifier of the order to be updated. * @param entity The updated order details provided in the request body. * @return ResponseEntity containing a message and the details of the updated * order as an {@link OrderUserDTO}. * @see OrderService#getOneOrder(Long) * @see OrderService#updateOrder(Long, Order) */ @Operation(summary = "Endpoint for ADMIN", security = @SecurityRequirement(name = "bearerAuth")) @PreAuthorize("hasRole('ADMIN')") @PutMapping("/order/{id}") public ResponseEntity<?> updateOrder(@PathVariable(name = "id") Long id, @RequestBody Order entity) { Optional<Order> entityOld = orderService.getOneOrder(id); if (entityOld.isPresent()) { return ResponseEntity.ok(Map.of("Message", "Updated order", "order", new OrderUserDTO(id, entity.isMaked(), entity.getSlot(),entity.getTotalPrice(),entity.getActualDate()))); } else { return createErrorResponse("The order not exists", HttpStatus.NOT_FOUND); } } /** * Deletes an existing order based on the provided order ID. It's for ADMIN * * @param id The identifier of the order to be deleted. * @return ResponseEntity indicating the success or failure of the delete operation. * @see OrderService#getOneOrder(Long) * @see OrderService#deleteOrder(Long) */ @Transactional @Operation(summary = "Endpoint for ADMIN", security = @SecurityRequirement(name = "bearerAuth")) @PreAuthorize("hasRole('ADMIN')") @DeleteMapping("/order/{id}") public ResponseEntity<?> deleteOrder(@PathVariable(name = "id") Long id) { Optional<Order> entity = orderService.getOneOrder(id); if (entity.isPresent()) { Order order = entity.get(); order.setActualDate(null); order.setSlot(null); orderService.deleteOrder(id); return ResponseEntity.status(204).body(Map.of("Message", "Order deleted")); } else { return createErrorResponse("The order not exists", HttpStatus.BAD_REQUEST); } } /** * Retrieves a paginated list of orders suitable for a cook, including * associated dishes. It's for CHEF * * @param page The page number for pagination (default is 0). * @param size The number of orders per page (default is 8). * @return ResponseEntity containing a paginated list of OrderCookDTO objects. * @see OrderService#getAllOrdersForCook() * @see OrderController#mapToOrderCookDTO(Order) * @see OrderController#paginate(List, Pageable) * @see OrderCookDTO */ @Transactional @Operation(summary = "Endpoint for CHEF and ADMIN", security = @SecurityRequirement(name = "bearerAuth")) @GetMapping("/orders/chef") public ResponseEntity<Page<OrderCookDTO>> getAllOrdersForChef( @RequestParam(defaultValue = "0") int page, @RequestParam(defaultValue = "8") int size) { List<Order> ordersForCook = orderService.getAllOrdersForCook(); List<Order> filteredOrders = ordersForCook.stream() .filter(order -> order.getActualDate() != null) .collect(Collectors.toList()); Pageable pageable = PageRequest.of(page, size); Page<Order> paginatedOrders = paginate(filteredOrders, pageable); List<OrderCookDTO> orderCookDTOList = paginatedOrders.getContent().stream() .map(this::mapToOrderCookDTOWithDishes) .collect(Collectors.toList()); return ResponseEntity.ok(new PageImpl<>(orderCookDTOList, pageable, filteredOrders.size())); } private OrderCookDTO mapToOrderCookDTOWithDishes(Order order) { OrderCookDTO orderCookDTO = new OrderCookDTO(); orderCookDTO.setOrderId(order.getId()); orderCookDTO.setMaked(order.isMaked()); orderCookDTO.setSlot(order.getSlot()); orderCookDTO.setActualDate(order.getActualDate()); orderCookDTO.setTotalPrice(order.getTotalPrice()); List<ListOrder> listOrders = order.getListOrder(); List<Dish> dishDTOList = listOrders.stream() .map(this::mapToListOrderDishDTO) .collect(Collectors.toList()); for (ListOrder listOrder : listOrders) { if (listOrder.getMenu() != null) { dishDTOList.addAll(Arrays.asList( listOrder.getMenu().getAppetizer(), listOrder.getMenu().getFirst(), listOrder.getMenu().getSecond(), listOrder.getMenu().getDessert()).stream() .filter(Objects::nonNull) .collect(Collectors.toList())); } } orderCookDTO.setDishes(dishDTOList); return orderCookDTO; } private Dish mapToListOrderDishDTO(ListOrder listOrder) { Dish dishDTO = new Dish(); dishDTO.setId(listOrder.getDish().getId()); dishDTO.setName(listOrder.getDish().getName()); dishDTO.setPrice(listOrder.getDish().getPrice()); return dishDTO; } /** * Retrieves a paginated list of orders for a specific user. It's for the * history for USER * * @param page The page number for pagination (default is 0). * @param size The number of orders per page (default is 10). * @param userId The ID of the user for whom to retrieve orders. * @return ResponseEntity containing a paginated list of OrderUserDTO objects. * @see UserService#getOneUser(Long) * @see OrderService#getAllOrdersForUserId(Long) * @see OrderUserDTO */ @Operation(summary = "Endpoint for USER", security = @SecurityRequirement(name = "bearerAuth")) @GetMapping("/orders/{userId}") public ResponseEntity<?> getAllOrdersForUserPaginate( @RequestParam(defaultValue = "0") int page, @RequestParam(defaultValue = "10") int size, @PathVariable(name = "userId") Long userId) { if (!userService.getOneUser(userId).isPresent()) { return ResponseEntity.notFound().build(); } List<Order> userOrders = orderService.getAllOrdersForUserId(userId); Pageable pageable = PageRequest.of(page, size); Page<Order> paginatedOrders = paginate(userOrders, pageable); List<OrderUserDTO> orderUserDTOList = paginatedOrders.getContent().stream() .map(order -> new OrderUserDTO(order.getId(), order.isMaked(), order.getSlot(),order.getTotalPrice(),order.getActualDate())) .collect(Collectors.toList()); return ResponseEntity.ok(new PageImpl<>(orderUserDTOList, pageable, paginatedOrders.getTotalElements())); } /** * Marks an order as "maked" (fulfilled) based on the provided order ID. It's * for CHEFF * * @param id The ID of the order to be marked as "maked." * @return ResponseEntity containing the updated OrderUserDTO after marking the * order as "maked." * @see OrderService#getOneOrder(Long) * @see OrderService#updateOrder(Order) * @see OrderUserDTO */ @Operation(summary = "Endpoint for CHEF and ADMIN", security = @SecurityRequirement(name = "bearerAuth")) @PreAuthorize("hasRole('CHEF') or hasRole('ADMIN')") @PutMapping("/order/markAsMaked/{id}") public ResponseEntity<?> markOrderAsMaked(@PathVariable(name = "id") Long id) { Optional<Order> optionalOrder = orderService.getOneOrder(id); if (optionalOrder.isPresent()) { Order order = optionalOrder.get(); order.setMaked(true); Order updatedOrder = orderService.updateOrder(order); OrderUserDTO orderUserDTO = new OrderUserDTO(updatedOrder.getId(), updatedOrder.isMaked(),updatedOrder.getSlot(),updatedOrder.getTotalPrice(),updatedOrder.getActualDate()); return ResponseEntity.ok(orderUserDTO); } else { return createErrorResponse("The order not exists", HttpStatus.BAD_REQUEST); } } /** * Updates the slot of an order and confirms it, setting the actual date. Also, * calculates and sets the total price of the order. It's for USER * * @param orderId The ID of the order to be updated. * @param slotId The ID of the slot to be associated with the order. * @return ResponseEntity containing the updated OrderUserDTO after updating the * order slot and confirming it. * @see OrderService#getOneOrder(Long) * @see SlotService#getOneSlot(Long) * @see OrderService#updateOrder(Order) * @see SlotService#updateSlot(Slot) * @see #calculateTotalPrice(Order) * @see OrderUserDTO */ @Transactional @Operation(summary = "Endpoint for USER", security = @SecurityRequirement(name = "bearerAuth")) @PutMapping("/order/finish/{orderId}/{slotId}") public ResponseEntity<?> updateOrderSlot( @PathVariable(name = "orderId") Long orderId, @PathVariable(name = "slotId") Long slotId) { Optional<Order> optionalOrder = orderService.getOneOrder(orderId); if (optionalOrder.isPresent()) { Order order = optionalOrder.get(); if (order.getActualDate() != null) { return createErrorResponse("Order is confirmed previously", HttpStatus.BAD_REQUEST); } if (order.getListOrder() == null || order.getListOrder().isEmpty()) { return createErrorResponse("Order must have at least one ListOrder associated", HttpStatus.BAD_REQUEST); } Optional<Slot> slotOptional = slotService.getOneSlot(slotId); if (slotOptional.isPresent()) { Slot slot = slotOptional.get(); if (slot.getActual() >= slot.getLimitSlot()) { return createErrorResponse("Too many orders for this slot to create order", HttpStatus.BAD_REQUEST); } Double totalPrice = calculateTotalPrice(order); ZoneId madridZone = ZoneId.of("Europe/Madrid"); order.setActualDate(LocalDateTime.now(madridZone)); order.setSlot(slot); order.setTotalPrice(totalPrice); slot.setActual(slot.getActual() + 1); orderService.updateOrder(order); slotService.updateSlot(slot); OrderUserDTO orderUserDTO = new OrderUserDTO(order.getId(), order.isMaked(), order.getSlot(),order.getTotalPrice(),order.getActualDate()); return ResponseEntity.accepted().body(orderUserDTO); } else { return createErrorResponse("The slot not exists", HttpStatus.BAD_REQUEST); } } else { return createErrorResponse("The order not exists", HttpStatus.BAD_REQUEST); } } private Double calculateTotalPrice(Order order) { List<ListOrder> listOrders = order.getListOrder(); List<Dish> dishes = listOrders.stream() .map(ListOrder::getDish) .filter(Objects::nonNull) .collect(Collectors.toList()); List<Dish> menuDishes = listOrders.stream() .map(listOrder -> listOrder.getMenu()) .filter(Objects::nonNull) .flatMap(menu -> Arrays .asList(menu.getAppetizer(), menu.getFirst(), menu.getSecond(), menu.getDessert()).stream()) .filter(Objects::nonNull) .collect(Collectors.toList()); List<Dish> allDishes = new ArrayList<>(menuDishes); allDishes.addAll(dishes); Double totalPrice = allDishes.stream() .mapToDouble(Dish::getPrice) .sum(); return totalPrice; } @Transactional @Operation(summary = "Endpoint for USER", security = @SecurityRequirement(name = "bearerAuth")) @PutMapping("/order/finish/{orderId}/{slotId}/{price}") public ResponseEntity<?> updateOrderSlotPrice( @PathVariable(name = "orderId") Long orderId, @PathVariable(name = "slotId") Long slotId, @PathVariable(name = "price") Double price) { Optional<Order> optionalOrder = orderService.getOneOrder(orderId); if (optionalOrder.isPresent()) { Order order = optionalOrder.get(); if (order.getActualDate() != null) { return createErrorResponse("Order is confirmed previously", HttpStatus.BAD_REQUEST); } if (order.getListOrder() == null || order.getListOrder().isEmpty()) { return createErrorResponse("Order must have at least one ListOrder associated", HttpStatus.BAD_REQUEST); } Optional<Slot> slotOptional = slotService.getOneSlot(slotId); if (slotOptional.isPresent()) { Slot slot = slotOptional.get(); if (slot.getActual() >= slot.getLimitSlot()) { return createErrorResponse("Too many orders for this slot to create order", HttpStatus.BAD_REQUEST); } Double totalPrice = price; ZoneId madridZone = ZoneId.of("Europe/Madrid"); order.setActualDate(LocalDateTime.now(madridZone)); order.setSlot(slot); order.setTotalPrice(totalPrice); slot.setActual(slot.getActual() + 1); orderService.updateOrder(order); slotService.updateSlot(slot); OrderUserDTO orderUserDTO = new OrderUserDTO(order.getId(), order.isMaked(), order.getSlot(),order.getTotalPrice(),order.getActualDate()); return ResponseEntity.accepted().body(orderUserDTO); } else { return createErrorResponse("The slot not exists", HttpStatus.BAD_REQUEST); } } else { return createErrorResponse("The order not exists", HttpStatus.BAD_REQUEST); } } /** * Creates and saves a new order for the specified user. It's for the USER * * @param userId The ID of the user for whom the order is created. * @return ResponseEntity containing the OrderUserDTO representing the newly * created order. * @see UserService#getOneUser(Long) * @see OrderService#createOrder(Order) * @see OrderUserDTO */ @Operation(summary = "Endpoint for USER", security = @SecurityRequirement(name = "bearerAuth")) @PostMapping("/order/{userId}") public ResponseEntity<?> saveOrder(@PathVariable(name = "userId") Long userId) {
Optional<User> userOptional = userService.getOneUser(userId);
6
2023-11-10 16:09:43+00:00
12k
kotmatross28729/EnviroMine-continuation
src/main/java/enviromine/handlers/crafting/CamelPackRefillHandler.java
[ { "identifier": "EM_Settings", "path": "src/main/java/enviromine/core/EM_Settings.java", "snippet": "public class EM_Settings\n{\n\tpublic static final UUID FROST1_UUID = UUID.fromString(\"B0C5F86A-78F3-417C-8B5A-527B90A1E919\");\n\tpublic static final UUID FROST2_UUID = UUID.fromString(\"5C4111A7-A66C-40FB-9FAD-1C6ADAEE7E27\");\n\tpublic static final UUID FROST3_UUID = UUID.fromString(\"721E793E-2203-4F6F-883F-6F44D7DDCCE1\");\n\tpublic static final UUID HEAT1_UUID = UUID.fromString(\"CA6E2CFA-4C53-4CD2-AAD3-3D6177A4F126\");\n\tpublic static final UUID DEHY1_UUID = UUID.fromString(\"38909A39-E1A1-4E93-9016-B2CCBE83D13D\");\n\n\tpublic static File worldDir = null;\n\n\t//Mod Data\n\tpublic static final String VERSION = \"@VERSION@\";\n\tpublic static final String MOD_ID = \"enviromine\";\n\tpublic static final String MOD_NAME = \"EnviroMine\";\n\tpublic static final String MOD_NAME_COLORIZED = EnumChatFormatting.AQUA + MOD_NAME + EnumChatFormatting.RESET;\n\tpublic static final String Channel = \"EM_CH\";\n\tpublic static final String Proxy = \"enviromine.core.proxies\";\n\tpublic static final String URL = \"https://modrinth.com/mod/enviromine-for-galaxy-odyssey\";\n\tpublic static final String VERSION_CHECKER_URL = \"https://gitgud.io/AstroTibs/enviromine-for-galaxy-odyssey/-/raw/1.7.10/CURRENT_VERSION\";\n\tpublic static final String GUI_FACTORY = MOD_ID+\".client.gui.menu.config.EnviroMineGuiFactory\";\n\n\tpublic static boolean versionChecker;\n\n\tpublic static int loggerVerbosity;\n\n public static boolean DeathFromHeartAttack;\n\n public static int HeartAttackTimeToDie;\n public static int HbmGasMaskBreakMultiplier;\n\n public static int EnviromineGasMaskBreakMultiplier;\n public static int HbmGasMaskBreakChanceNumber;\n\n public static boolean hardcoregases = false;\n\n\tpublic static boolean enablePhysics = false;\n\tpublic static boolean enableLandslide = true;\n\tpublic static boolean waterCollapse = true; // Added out of necessity/annoyance -- AstroTibs\n\n\tpublic static float blockTempDropoffPower = 0.75F;\n\tpublic static int scanRadius = 6;\n\tpublic static float auraRadius = 0.5F;\n\n\t@ShouldOverride\n\tpublic static boolean enableAirQ = true;\n\t@ShouldOverride\n\tpublic static boolean enableHydrate = true;\n\t@ShouldOverride\n\tpublic static boolean enableSanity = true;\n\t@ShouldOverride\n\tpublic static boolean enableBodyTemp = true;\n\n\tpublic static boolean trackNonPlayer = false;\n\n\tpublic static boolean spreadIce = false;\n\n\tpublic static boolean useFarenheit = false;\n\tpublic static String heatBarPos;\n\tpublic static String waterBarPos;\n\tpublic static String sanityBarPos;\n\tpublic static String oxygenBarPos;\n\n\tpublic static int dirtBottleID = 5001;\n\tpublic static int saltBottleID = 5002;\n\tpublic static int coldBottleID = 5003;\n\tpublic static int camelPackID = 5004;\n\n\tpublic static final String GAS_MASK_FILL_TAG_KEY = \"gasMaskFill\";\n\tpublic static final String GAS_MASK_MAX_TAG_KEY = \"gasMaskMax\";\n\tpublic static final String CAMEL_PACK_FILL_TAG_KEY = \"camelPackFill\";\n\tpublic static final String CAMEL_PACK_MAX_TAG_KEY = \"camelPackMax\";\n\tpublic static final String IS_CAMEL_PACK_TAG_KEY = \"isCamelPack\";\n\tpublic static int gasMaskMax = 1000;\n\tpublic static int filterRestore = 500;\n\tpublic static int camelPackMax = 100;\n\tpublic static float gasMaskUpdateRestoreFraction = 1F;\n\n\t/*\n\tpublic static int gasMaskID = 5005;\n\tpublic static int airFilterID = 5006;\n\tpublic static int hardHatID = 5007;\n\tpublic static int rottenFoodID = 5008;\n\n\tpublic static int blockElevatorTopID = 501;\n\tpublic static int blockElevatorBottomID = 502;\n\tpublic static int gasBlockID = 503;\n\tpublic static int fireGasBlockID = 504;\n\t*/\n\n\tpublic static int hypothermiaPotionID = 27;\n\tpublic static int heatstrokePotionID = 28;\n\tpublic static int frostBitePotionID = 29;\n\tpublic static int dehydratePotionID = 30;\n\tpublic static int insanityPotionID = 31;\n\n\tpublic static boolean enableHypothermiaGlobal = true;\n\tpublic static boolean enableHeatstrokeGlobal = true;\n\tpublic static boolean enableFrostbiteGlobal = true;\n\tpublic static boolean frostbitePermanent = true;\n\n\t//Gases\n\tpublic static boolean renderGases = false;\n\tpublic static int gasTickRate = 32; //GasFires are 4x faster than this\n\tpublic static int gasPassLimit = -1;\n\tpublic static boolean gasWaterLike = true;\n\tpublic static boolean slowGases = true; // Normal gases use random ticks to move\n\tpublic static boolean noGases = false;\n\n\t//World Gen\n\tpublic static boolean shaftGen = true;\n\tpublic static boolean gasGen = true;\n\tpublic static boolean oldMineGen = true;\n\n\t//Properties\n\t//@ShouldOverride(\"enviromine.network.packet.encoders.ArmorPropsEncoder\")\n\t@ShouldOverride({String.class, ArmorProperties.class})\n\tpublic static HashMap<String,ArmorProperties> armorProperties = new HashMap<String,ArmorProperties>();\n\t//@ShouldOverride(\"enviromine.network.packet.encoders.BlocksPropsEncoder\")\n\t@ShouldOverride({String.class, BlockProperties.class})\n\tpublic static HashMap<String,BlockProperties> blockProperties = new HashMap<String,BlockProperties>();\n\t@ShouldOverride({Integer.class, EntityProperties.class})\n\tpublic static HashMap<Integer,EntityProperties> livingProperties = new HashMap<Integer,EntityProperties>();\n\t@ShouldOverride({String.class, ItemProperties.class})\n\tpublic static HashMap<String,ItemProperties> itemProperties = new HashMap<String,ItemProperties>();\n\t@ShouldOverride({Integer.class, BiomeProperties.class})\n\tpublic static HashMap<Integer,BiomeProperties> biomeProperties = new HashMap<Integer,BiomeProperties>();\n\t@ShouldOverride({Integer.class, DimensionProperties.class})\n\tpublic static HashMap<Integer,DimensionProperties> dimensionProperties = new HashMap<Integer,DimensionProperties>();\n\n\tpublic static HashMap<String,StabilityType> stabilityTypes = new HashMap<String,StabilityType>();\n\n\t@ShouldOverride({String.class, RotProperties.class})\n\tpublic static HashMap<String,RotProperties> rotProperties = new HashMap<String,RotProperties>();\n\n\tpublic static boolean streamsDrink = true;\n\tpublic static boolean witcheryVampireImmunities = true;\n\tpublic static boolean witcheryWerewolfImmunities = true;\n\tpublic static boolean matterOverdriveAndroidImmunities = true;\n\n\tpublic static int updateCap = 128;\n\tpublic static boolean stoneCracks = true;\n\tpublic static String defaultStability = \"loose\";\n\n\tpublic static double sanityMult = 1.0D;\n\tpublic static double hydrationMult = 1.0D;\n\tpublic static double tempMult = 1.0D;\n\tpublic static double airMult = 1.0D;\n\n\t//public static boolean updateCheck = true;\n\t//public static boolean useDefaultConfig = true;\n\tpublic static boolean genConfigs = false;\n\tpublic static boolean genDefaults = false;\n\n\tpublic static int physInterval = 6;\n\tpublic static int worldDelay = 1000;\n\tpublic static int chunkDelay = 1000;\n\tpublic static int entityFailsafe = 1;\n\tpublic static boolean villageAssist = true;\n\n\tpublic static boolean minimalHud;\n\tpublic static boolean limitCauldron;\n\tpublic static boolean allowTinting = true;\n\tpublic static boolean torchesBurn = true;\n\tpublic static boolean torchesGoOut = true;\n\tpublic static boolean genFlammableCoal = true; // In case you don't want burny-coal\n\tpublic static boolean randomizeInsanityPitch = true;\n\tpublic static boolean catchFireAtHighTemps = true;\n\n\tpublic static int caveDimID = -3;\n\tpublic static int caveBiomeID = 23;\n\tpublic static boolean disableCaves = false;\n\tpublic static int limitElevatorY = 10;\n\tpublic static boolean caveOreEvent = true;\n\tpublic static boolean caveLava = false;\n\tpublic static int caveRavineRarity = 30;\n\tpublic static int caveTunnelRarity = 7;\n\tpublic static int caveDungeons = 8;\n\tpublic static int caveLiquidY = 32;\n\tpublic static boolean caveFlood = true;\n\tpublic static boolean caveRespawn = false;\n\tpublic static boolean enforceWeights = false;\n\tpublic static ArrayList<CaveGenProperties> caveGenProperties = new ArrayList<CaveGenProperties>();\n\tpublic static HashMap<Integer, CaveSpawnProperties> caveSpawnProperties = new HashMap<Integer, CaveSpawnProperties>();\n\n\tpublic static boolean foodSpoiling = true;\n\tpublic static int foodRotTime = 7;\n\n\t/** Whether or not this overridden with server settings */\n\tpublic static boolean isOverridden = false;\n\tpublic static boolean enableConfigOverride = false;\n\tpublic static boolean profileOverride = false;\n\tpublic static String profileSelected = \"default\";\n\n\tpublic static boolean enableQuakes = true;\n\tpublic static boolean quakePhysics = true;\n\tpublic static int quakeRarity = 100;\n\n\tpublic static boolean finiteWater = false;\n\tpublic static float thingChance = 0.000001F;\n\tpublic static boolean noNausea = false;\n\tpublic static boolean keepStatus = false;\n\tpublic static boolean renderGear = true;\n\tpublic static String[] cauldronHeatingBlocks = new String[]{ // Added on request - AstroTibs\n\t\t\t\"minecraft:fire\",\n\t\t\t\"minecraft:lava\",\n\t\t\t\"minecraft:flowing_lava\",\n\t\t\t\"campfirebackport:campfire\",\n\t\t\t\"campfirebackport:soul_campfire\",\n\t\t\t\"CaveBiomes:stone_lavacrust\",\n\t\t\t\"demonmobs:hellfire\",\n\t\t\t\"etfuturum:magma\",\n\t\t\t\"infernomobs:purelava\",\n\t\t\t\"infernomobs:scorchfire\",\n\t\t\t\"netherlicious:FoxFire\",\n\t\t\t\"netherlicious:MagmaBlock\",\n\t\t\t\"netherlicious:SoulFire\",\n\t\t\t\"uptodate:magma_block\",\n\t};\n\tpublic static String[] notWaterBlocks = new String[]{ // Added on request - AstroTibs\n\t\t\t\"minecraft:fire\",\n\t\t\t\"minecraft:lava\",\n\t\t\t\"minecraft:flowing_lava\",\n\t\t\t\"campfirebackport:campfire\",\n\t\t\t\"campfirebackport:soul_campfire\",\n\t\t\t\"CaveBiomes:stone_lavacrust\",\n\t\t\t\"demonmobs:hellfire\",\n\t\t\t\"etfuturum:magma\",\n\t\t\t\"infernomobs:purelava\",\n\t\t\t\"infernomobs:scorchfire\",\n\t\t\t\"netherlicious:FoxFire\",\n\t\t\t\"netherlicious:MagmaBlock\",\n\t\t\t\"netherlicious:SoulFire\",\n\t\t\t\"uptodate:magma_block\",\n\t};\n\n\tpublic static boolean voxelMenuExists = false;\n\n\t/**\n\t * Tells the server that this field should be sent to the client to overwrite<br>\n\t * Usage:<br>\n\t * <tt>@ShouldOverride</tt> - for ints/booleans/floats/Strings<br>\n\t * <tt>@ShouldOverride(Class[] value)</tt> - for ArrayList or HashMap types\n\t * */\n\t@Target(ElementType.FIELD)\n\t@Retention(RetentionPolicy.RUNTIME)\n\tpublic @interface ShouldOverride\n\t{\n\t\tClass<?>[] value() default {};\n\t}\n}" }, { "identifier": "ItemProperties", "path": "src/main/java/enviromine/trackers/properties/ItemProperties.java", "snippet": "public class ItemProperties implements SerialisableProperty, PropertyBase {\n public static final ItemProperties base = new ItemProperties();\n static String[] IPName;\n\n public String name;\n public int meta;\n\n public boolean enableTemp;\n\n public float ambTemp;\n public float ambAir;\n public float ambSanity;\n\n public float effTemp;\n public float effAir;\n public float effSanity;\n public float effHydration;\n\n public float effTempCap;\n\n public int camelFill;\n public String fillReturnItem;\n public int fillReturnMeta;\n\n public String loadedFrom;\n\n\n public ItemProperties(NBTTagCompound tags) {\n this.ReadFromNBT(tags);\n }\n\n public ItemProperties() {\n // THIS CONSTRUCTOR IS FOR STATIC PURPOSES ONLY!\n\n if (base != null && base != this) {\n throw new IllegalStateException();\n }\n }\n\n\tpublic ItemProperties(String name, int meta, boolean enableTemp, float ambTemp, float ambAir, float ambSanity, float effTemp, float effAir, float effSanity, float effHydration, float effTempCap, int camelFill, String fillReturnItem, int fillReturnMeta, String fileName)\n\t{\n\t\tthis.name = name;\n\t\tthis.meta = meta;\n\t\tthis.enableTemp = enableTemp;\n\n\t\tthis.ambTemp = ambTemp;\n\t\tthis.ambAir = ambAir;\n\t\tthis.ambSanity = ambSanity;\n\n\t\tthis.effTemp = effTemp/2f;\n\t\tthis.effAir = effAir/2f;\n\t\tthis.effSanity = effSanity/2f;\n\t\tthis.effHydration = effHydration/2f;\n\n\t\tthis.effTempCap = effTempCap;\n\t\tthis.camelFill = camelFill;\n\t\tthis.fillReturnItem = fillReturnItem;\n\t\tthis.fillReturnMeta = fillReturnMeta;\n\n\t\tthis.loadedFrom = fileName;\n\t}\n\t/**\n\t * <b>hasProperty(ItemStack stack)</b><bR><br>\n\t * Checks if ItemProperty contains custom properties from ItemStack.\n\t * @param stack\n\t * @return true if has custom properties\n\t */\n\tpublic boolean hasProperty(ItemStack stack)\n\t{\n\t\treturn EM_Settings.itemProperties.containsKey(\"\" + Item.itemRegistry.getNameForObject(stack.getItem()) + \",\" + stack.getItemDamage()) || EM_Settings.itemProperties.containsKey(\"\" + Item.itemRegistry.getNameForObject(stack.getItem()));\n\t}\n\t/**\n\t * \t<b>getProperty(ItemStack stack)</b><bR><br>\n\t * Gets ItemProperty from ItemStack.\n\t * @param stack\n\t * @return ItemProperties\n\t */\n\tpublic ItemProperties getProperty(ItemStack stack)\n\t{\n\t\tItemProperties itemProps;\n\n\t\tif(EM_Settings.itemProperties.containsKey(\"\" + Item.itemRegistry.getNameForObject(stack.getItem()) + \",\" + stack.getItemDamage()))\n\t\t{\n\t\t\titemProps = EM_Settings.itemProperties.get(\"\" + Item.itemRegistry.getNameForObject(stack.getItem()) + \",\" + stack.getItemDamage());\n\t\t} else\n\t\t{\n\t\t\titemProps = EM_Settings.itemProperties.get(\"\" + Item.itemRegistry.getNameForObject(stack.getItem()));\n\t\t}\n\t\treturn itemProps;\n\t}\n\n\t@Override\n\tpublic NBTTagCompound WriteToNBT()\n\t{\n\t\tNBTTagCompound tags = new NBTTagCompound();\n\t\ttags.setString(\"name\", this.name);\n\t\ttags.setBoolean(\"enableTemp\", this.enableTemp);\n\t\ttags.setFloat(\"ambTemp\", this.ambTemp);\n\t\ttags.setFloat(\"ambAir\", this.ambAir);\n\t\ttags.setFloat(\"ambSanity\", this.ambSanity);\n\t\ttags.setFloat(\"effTemp\", this.effTemp);\n\t\ttags.setFloat(\"effAir\", this.effAir);\n\t\ttags.setFloat(\"effHydration\", this.effHydration);\n\t\ttags.setFloat(\"effTempCap\", this.effTempCap);\n\t\treturn tags;\n\t}\n\n\t@Override\n\tpublic void ReadFromNBT(NBTTagCompound tags)\n\t{\n\t\tthis.name = tags.getString(\"name\");\n\t\tthis.enableTemp = tags.getBoolean(\"enableTemp\");\n\t\tthis.ambTemp = tags.getFloat(\"ambTemp\");\n\t\tthis.ambAir = tags.getFloat(\"ambAir\");\n\t\tthis.ambSanity = tags.getFloat(\"ambSanity\");\n\t\tthis.effTemp = tags.getFloat(\"effTemp\");\n\t\tthis.effAir = tags.getFloat(\"effAir\");\n\t\tthis.effHydration = tags.getFloat(\"effHydration\");\n\t\tthis.effTempCap = tags.getFloat(\"effTempCap\");\n\t}\n\n\t@Override\n\tpublic String categoryName()\n\t{\n\t\treturn \"items\";\n\t}\n\n\t@Override\n\tpublic String categoryDescription()\n\t{\n\t\treturn \"Custom effects for items\";\n\t}\n\n\t@Override\n\tpublic void LoadProperty(Configuration config, String category)\n\t{\n\t\tconfig.setCategoryComment(this.categoryName(), this.categoryDescription());\n\t\tString name = config.get(category, IPName[0], \"\").getString();\n\t\tint meta = config.get(category, IPName[1], 0).getInt(0);\n\t\tboolean enableTemp = config.get(category, IPName[2], false).getBoolean(false);\n\t\tfloat ambTemp = (float)config.get(category, IPName[3], 0D).getDouble(0D);\n\t\tfloat ambAir = (float)config.get(category, IPName[4], 0D).getDouble(0D);\n\t\tfloat ambSanity = (float)config.get(category, IPName[5], 0D).getDouble(0D);\n\t\tfloat effTemp = (float)config.get(category, IPName[6], 0D).getDouble(0D);\n\t\tfloat effAir = (float)config.get(category, IPName[7], 0D).getDouble(0D);\n\t\tfloat effSanity = (float)config.get(category, IPName[8], 0D).getDouble(0D);\n\t\tfloat effHydration = (float)config.get(category, IPName[9], 0D).getDouble(0D);\n\t\tfloat effTempCap = (float)config.get(category, IPName[10], 37D).getDouble(37D);\n\t\tint camelFill = config.get(category, IPName[11], 0).getInt(0);\n\t\tString camelReturnItem = config.get(category, IPName[12], \"\").getString();\n\t\tint camelReturnMeta = config.get(category, IPName[13], 0).getInt(0);\n\t\tString filename = config.getConfigFile().getName();\n\n\t\tItemProperties entry = new ItemProperties(name, meta, enableTemp, ambTemp, ambAir, ambSanity, effTemp, effAir, effSanity, effHydration, effTempCap, camelFill, camelReturnItem, camelReturnMeta, filename);\n\n\t\tif(meta < 0)\n\t\t{\n\t\t\t// If item already exist and current file hasn't completely been loaded do this\n\t\t\tif(EM_Settings.itemProperties.containsKey(\"\" + name) && !EM_ConfigHandler.loadedConfigs.contains(filename))\n\t\t\t{\n\t\t\t\tif (EM_Settings.loggerVerbosity >= EnumLogVerbosity.NORMAL.getLevel()) EnviroMine.logger.log(Level.ERROR, \"CONFIG DUPLICATE: Items - \"+ name.toUpperCase() +\" was already added from \"+ EM_Settings.itemProperties.get(name).loadedFrom.toUpperCase() +\" and will be overriden by \"+ filename.toUpperCase());\n\t\t\t}\n\n\t\t\tEM_Settings.itemProperties.put(\"\" + name, entry);\n\t\t} else\n\t\t{\n\t\t\t// If item already exist and current file hasn't completely been loaded do this\n\t\t\tif(EM_Settings.itemProperties.containsKey(\"\" + name + \",\" + meta) && !EM_ConfigHandler.loadedConfigs.contains(filename))\n\t\t\t{\n\t\t\t\tif (EM_Settings.loggerVerbosity >= EnumLogVerbosity.NORMAL.getLevel()) EnviroMine.logger.log(Level.ERROR, \"CONFIG DUPLICATE: Items - \"+ name.toUpperCase() +\" - Meta:\"+ meta +\" was already added from \"+ EM_Settings.itemProperties.get(name).loadedFrom.toUpperCase() +\" and will be overriden by \"+ filename.toUpperCase());\n\t\t\t}\n\n\t\t\tEM_Settings.itemProperties.put(\"\" + name + \",\" + meta, entry);\n\t\t}\n\t}\n\n\t@Override\n\tpublic void SaveProperty(Configuration config, String category)\n\t{\n\t\tconfig.get(category, IPName[0], name).getString();\n\t\tconfig.get(category, IPName[1], meta).getInt(meta);\n\t\tconfig.get(category, IPName[2], enableTemp).getBoolean(enableTemp);\n\t\tconfig.get(category, IPName[3], ambTemp).getDouble(ambTemp);\n\t\tconfig.get(category, IPName[4], ambAir).getDouble(ambAir);\n\t\tconfig.get(category, IPName[5], ambSanity).getDouble(ambSanity);\n\t\tconfig.get(category, IPName[6], effTemp).getDouble(effTemp);\n\t\tconfig.get(category, IPName[7], effAir).getDouble(effAir);\n\t\tconfig.get(category, IPName[8], effSanity).getDouble(effSanity);\n\t\tconfig.get(category, IPName[9], effHydration).getDouble(effHydration);\n\t\tconfig.get(category, IPName[10], effTempCap).getDouble(effTempCap);\n\t\tconfig.get(category, IPName[11], camelFill).getInt(camelFill);\n\t\tconfig.get(category, IPName[12], fillReturnItem).getString();\n\t\tconfig.get(category, IPName[13], fillReturnMeta).getInt(fillReturnMeta);\n\t}\n\n\t@Override\n\tpublic void GenDefaults()\n\t{\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tIterator<Item> iterator = Item.itemRegistry.iterator();\n\n\t\twhile(iterator.hasNext())\n\t\t{\n\t\t\tItem item = iterator.next();\n\t\t\tBlock block = Blocks.air;\n\n\t\t\tif(item == null)\n\t\t\t{\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif(item instanceof ItemBlock)\n\t\t\t{\n\t\t\t\tblock = ((ItemBlock)item).field_150939_a;\n\t\t\t}\n\n\t\t\tString[] regName = Item.itemRegistry.getNameForObject(item).split(\":\");\n\n\t\t\tif(regName.length <= 0)\n\t\t\t{\n\t\t\t\tif (EM_Settings.loggerVerbosity >= EnumLogVerbosity.NORMAL.getLevel()) EnviroMine.logger.log(Level.ERROR, \"Failed to get correctly formatted object name for \" + item.getUnlocalizedName());\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tFile itemFile = new File(EM_ConfigHandler.loadedProfile + EM_ConfigHandler.customPath + EnviroUtils.SafeFilename(regName[0]) + \".cfg\");\n\n\t\t\tif(!itemFile.exists())\n\t\t\t{\n\t\t\t\ttry\n\t\t\t\t{\n\t\t\t\t\titemFile.createNewFile();\n\t\t\t\t} catch(Exception e)\n\t\t\t\t{\n\t\t\t\t\tif (EM_Settings.loggerVerbosity >= EnumLogVerbosity.LOW.getLevel()) EnviroMine.logger.log(Level.ERROR, \"Failed to create file for \" + item.getUnlocalizedName(), e);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tConfiguration config = new Configuration(itemFile, true);\n\n\t\t\tString category = this.categoryName() + \".\" + EnviroUtils.replaceULN(item.getUnlocalizedName() +\"_\"+ regName[1]);\n\n\t\t\tconfig.load();\n\n\t\t\tif(item == Items.glass_bottle)\n\t\t\t{\n\t\t\t\tconfig.get(category, IPName[0], Item.itemRegistry.getNameForObject(item)).getString();\n\t\t\t\tconfig.get(category, IPName[1], -1).getInt(-1);\n\t\t\t\tconfig.get(category, IPName[2], false).getBoolean(false);\n\t\t\t\tconfig.get(category, IPName[3], 37D).getDouble(37D);\n\t\t\t\tconfig.get(category, IPName[4], 0D).getDouble(0D);\n\t\t\t\tconfig.get(category, IPName[5], 0D).getDouble(0D);\n\t\t\t\tconfig.get(category, IPName[6], 0D).getDouble(0D);\n\t\t\t\tconfig.get(category, IPName[7], 0D).getDouble(0D);\n\t\t\t\tconfig.get(category, IPName[8], 0D).getDouble(0D);\n\t\t\t\tconfig.get(category, IPName[9], 0D).getDouble(0D);\n\t\t\t\tconfig.get(category, IPName[10], 37D).getDouble(37D);\n\t\t\t\tconfig.get(category, IPName[11], -25).getInt(-25);\n\t\t\t\tconfig.get(category, IPName[12], \"minecraft:potion\").getString();\n\t\t\t\tconfig.get(category, IPName[13], 0).getInt(0);\n\t\t\t} else if(item == Items.potionitem)\n\t\t\t{\n\t\t\t\tconfig.get(category, IPName[0], Item.itemRegistry.getNameForObject(item)).getString();\n\t\t\t\tconfig.get(category, IPName[1], -1).getInt(-1);\n\t\t\t\tconfig.get(category, IPName[2], false).getBoolean(false);\n\t\t\t\tconfig.get(category, IPName[3], 0D).getDouble(0D);\n\t\t\t\tconfig.get(category, IPName[4], 0D).getDouble(0D);\n\t\t\t\tconfig.get(category, IPName[5], 0D).getDouble(0D);\n\t\t\t\tconfig.get(category, IPName[6], -0.1D).getDouble(-0.1D);\n\t\t\t\tconfig.get(category, IPName[7], 0D).getDouble(0D);\n\t\t\t\tconfig.get(category, IPName[8], 0D).getDouble(0D);\n\t\t\t\tconfig.get(category, IPName[9], 25D).getDouble(25D);\n\t\t\t\tconfig.get(category, IPName[10], 37D).getDouble(37D);\n\t\t\t\tconfig.get(category, IPName[11], 0).getInt(0);\n\t\t\t\tconfig.get(category, IPName[12], \"\").getString();\n\t\t\t\tconfig.get(category, IPName[13], 0).getInt(0);\n\n\t\t\t\tcategory = category + \"_(water)\";\n\n\t\t\t\tconfig.get(category, IPName[0], Item.itemRegistry.getNameForObject(item)).getString();\n\t\t\t\tconfig.get(category, IPName[1], 0).getInt(0);\n\t\t\t\tconfig.get(category, IPName[2], false).getBoolean(false);\n\t\t\t\tconfig.get(category, IPName[3], 0D).getDouble(0D);\n\t\t\t\tconfig.get(category, IPName[4], 0D).getDouble(0D);\n\t\t\t\tconfig.get(category, IPName[5], 0D).getDouble(0D);\n\t\t\t\tconfig.get(category, IPName[6], -0.1D).getDouble(-0.1D);\n\t\t\t\tconfig.get(category, IPName[7], 0D).getDouble(0D);\n\t\t\t\tconfig.get(category, IPName[8], 0D).getDouble(0D);\n\t\t\t\tconfig.get(category, IPName[9], 25D).getDouble(25D);\n\t\t\t\tconfig.get(category, IPName[10], 37D).getDouble(37D);\n\t\t\t\tconfig.get(category, IPName[11], 25).getInt(25);\n\t\t\t\tconfig.get(category, IPName[12], \"minecraft:glass_bottle\").getString();\n\t\t\t\tconfig.get(category, IPName[13], 0).getInt(0);\n\t\t\t} else if(item == Items.melon || item == Items.carrot || item == Items.apple)\n\t\t\t{\n\t\t\t\tconfig.get(category, IPName[0], Item.itemRegistry.getNameForObject(item)).getString();\n\t\t\t\tconfig.get(category, IPName[1], -1).getInt(-1);\n\t\t\t\tconfig.get(category, IPName[2], false).getBoolean(false);\n\t\t\t\tconfig.get(category, IPName[3], 0D).getDouble(0D);\n\t\t\t\tconfig.get(category, IPName[4], 0D).getDouble(0D);\n\t\t\t\tconfig.get(category, IPName[5], 0D).getDouble(0D);\n\t\t\t\tconfig.get(category, IPName[6], -0.025D).getDouble(-0.025D);\n\t\t\t\tconfig.get(category, IPName[7], 0D).getDouble(0D);\n\t\t\t\tconfig.get(category, IPName[8], 0D).getDouble(0D);\n\t\t\t\tconfig.get(category, IPName[9], 5D).getDouble(5D);\n\t\t\t\tconfig.get(category, IPName[10], 37D).getDouble(37D);\n\t\t\t\tconfig.get(category, IPName[11], 0).getInt(0);\n\t\t\t\tconfig.get(category, IPName[12], \"\").getString();\n\t\t\t\tconfig.get(category, IPName[13], 0).getInt(0);\n\t\t\t}\n\n else if(isHbmLoaded()) {\n if(item == ModItems.cigarette_normal || item == ModItems.crackpipe || item == ModItems.cigarette)\n {\n config.get(category, IPName[0], Item.itemRegistry.getNameForObject(item)).getString();\n config.get(category, IPName[1], -1).getInt(-1);\n config.get(category, IPName[2], false).getBoolean(false);\n config.get(category, IPName[3], 0D).getDouble(0D);\n config.get(category, IPName[4], 0D).getDouble(0D);\n config.get(category, IPName[5], 0D).getDouble(0D);\n config.get(category, IPName[6], -0.025D).getDouble(-0.025D);\n config.get(category, IPName[7], item == ModItems.cigarette_normal ? -5D : item == ModItems.crackpipe ? -1D : -10D).getDouble(item == ModItems.cigarette_normal ? -5D : item == ModItems.crackpipe ? -1D : -10D);\n config.get(category, IPName[8], item == ModItems.cigarette_normal ? 15D : item == ModItems.crackpipe ? 40D : 30D).getDouble(item == ModItems.cigarette_normal ? 15D : item == ModItems.crackpipe ? 40D : 30D);\n config.get(category, IPName[9], 5D).getDouble(5D);\n config.get(category, IPName[10], 37D).getDouble(37D);\n config.get(category, IPName[11], 0).getInt(0);\n config.get(category, IPName[12], \"\").getString();\n config.get(category, IPName[13], 0).getInt(0);\n }\n } else if(block == Blocks.snow || block == Blocks.snow_layer)\n\t\t\t{\n\t\t\t\tconfig.get(category, IPName[0], Item.itemRegistry.getNameForObject(item)).getString();\n\t\t\t\tconfig.get(category, IPName[1], -1).getInt(-1);\n\t\t\t\tconfig.get(category, IPName[2], true).getBoolean(true);\n\t\t\t\tconfig.get(category, IPName[3], -0.1D).getDouble(-0.1D);\n\t\t\t\tconfig.get(category, IPName[4], 0D).getDouble(0D);\n\t\t\t\tconfig.get(category, IPName[5], 0D).getDouble(0D);\n\t\t\t\tconfig.get(category, IPName[6], 0D).getDouble(0D);\n\t\t\t\tconfig.get(category, IPName[7], 0D).getDouble(0D);\n\t\t\t\tconfig.get(category, IPName[8], 0D).getDouble(0D);\n\t\t\t\tconfig.get(category, IPName[9], 0D).getDouble(0D);\n\t\t\t\tconfig.get(category, IPName[10], 37D).getDouble(37D);\n\t\t\t\tconfig.get(category, IPName[11], 0).getInt(0);\n\t\t\t\tconfig.get(category, IPName[12], \"\").getString();\n\t\t\t\tconfig.get(category, IPName[13], 0).getInt(0);\n\t\t\t} else if(block == Blocks.ice || block == Blocks.packed_ice)\n\t\t\t{\n\t\t\t\tconfig.get(category, IPName[0], Item.itemRegistry.getNameForObject(item)).getString();\n\t\t\t\tconfig.get(category, IPName[1], -1).getInt(-1);\n\t\t\t\tconfig.get(category, IPName[2], true).getBoolean(true);\n\t\t\t\tconfig.get(category, IPName[3], -0.5D).getDouble(-0.5D);\n\t\t\t\tconfig.get(category, IPName[4], 0D).getDouble(0D);\n\t\t\t\tconfig.get(category, IPName[5], 0D).getDouble(0D);\n\t\t\t\tconfig.get(category, IPName[6], 0D).getDouble(0D);\n\t\t\t\tconfig.get(category, IPName[7], 0D).getDouble(0D);\n\t\t\t\tconfig.get(category, IPName[8], 0D).getDouble(0D);\n\t\t\t\tconfig.get(category, IPName[9], 0D).getDouble(0D);\n\t\t\t\tconfig.get(category, IPName[10], 37D).getDouble(37D);\n\t\t\t\tconfig.get(category, IPName[12], \"\").getString();\n\t\t\t\tconfig.get(category, IPName[13], 0).getInt(0);\n\t\t\t} else if(block == Blocks.netherrack || block == Blocks.nether_brick || block == Blocks.nether_brick_fence || block == Blocks.nether_brick_stairs)\n\t\t\t{\n\t\t\t\tconfig.get(category, IPName[0], Item.itemRegistry.getNameForObject(item)).getString();\n\t\t\t\tconfig.get(category, IPName[1], -1).getInt(-1);\n\t\t\t\tconfig.get(category, IPName[2], true).getBoolean(true);\n\t\t\t\tconfig.get(category, IPName[3], 50D).getDouble(50D);\n\t\t\t\tconfig.get(category, IPName[4], 0D).getDouble(0D);\n\t\t\t\tconfig.get(category, IPName[5], 0D).getDouble(0D);\n\t\t\t\tconfig.get(category, IPName[6], 0D).getDouble(0D);\n\t\t\t\tconfig.get(category, IPName[7], 0D).getDouble(0D);\n\t\t\t\tconfig.get(category, IPName[8], 0D).getDouble(0D);\n\t\t\t\tconfig.get(category, IPName[9], 0D).getDouble(0D);\n\t\t\t\tconfig.get(category, IPName[10], 37D).getDouble(37D);\n\t\t\t\tconfig.get(category, IPName[12], \"\").getString();\n\t\t\t\tconfig.get(category, IPName[13], 0).getInt(0);\n\t\t\t} else if(block == Blocks.soul_sand || item == Items.skull || block == Blocks.skull)\n\t\t\t{\n\t\t\t\tconfig.get(category, IPName[0], Item.itemRegistry.getNameForObject(item)).getString();\n\t\t\t\tconfig.get(category, IPName[1], -1).getInt(-1);\n\t\t\t\tconfig.get(category, IPName[2], false).getBoolean(false);\n\t\t\t\tconfig.get(category, IPName[3], 0D).getDouble(0D);\n\t\t\t\tconfig.get(category, IPName[4], 0D).getDouble(0D);\n\t\t\t\tconfig.get(category, IPName[5], -1D).getDouble(-1D);\n\t\t\t\tconfig.get(category, IPName[6], 0D).getDouble(0D);\n\t\t\t\tconfig.get(category, IPName[7], 0D).getDouble(0D);\n\t\t\t\tconfig.get(category, IPName[8], 0D).getDouble(0D);\n\t\t\t\tconfig.get(category, IPName[9], 0D).getDouble(0D);\n\t\t\t\tconfig.get(category, IPName[10], 37D).getDouble(37D);\n\t\t\t\tconfig.get(category, IPName[11], 0).getInt(0);\n\t\t\t\tconfig.get(category, IPName[12], \"\").getString();\n\t\t\t\tconfig.get(category, IPName[13], 0).getInt(0);\n\t\t\t} else if((block == Blocks.flower_pot || block == Blocks.grass || block instanceof BlockLeavesBase || block instanceof BlockFlower || block instanceof BlockBush || block.getMaterial() == Material.grass || block.getMaterial() == Material.leaves || block.getMaterial() == Material.plants || block.getMaterial() == Material.vine) && (regName[0].equals(\"minecraft\") || EM_Settings.genConfigs))\n\t\t\t{\n\t\t\t\tconfig.get(category, IPName[0], Item.itemRegistry.getNameForObject(item)).getString();\n\t\t\t\tconfig.get(category, IPName[1], -1).getInt(-1);\n\t\t\t\tconfig.get(category, IPName[2], false).getBoolean(false);\n\t\t\t\tconfig.get(category, IPName[3], 0D).getDouble(0D);\n\t\t\t\tconfig.get(category, IPName[4], 0.025D).getDouble(0.025D);\n\t\t\t\tconfig.get(category, IPName[5], 0.1D).getDouble(0.1D);\n\t\t\t\tconfig.get(category, IPName[6], 0D).getDouble(0D);\n\t\t\t\tconfig.get(category, IPName[7], 0D).getDouble(0D);\n\t\t\t\tconfig.get(category, IPName[8], 0D).getDouble(0D);\n\t\t\t\tconfig.get(category, IPName[9], 0D).getDouble(0D);\n\t\t\t\tconfig.get(category, IPName[10], 37D).getDouble(37D);\n\t\t\t\tconfig.get(category, IPName[11], 0).getInt(0);\n\t\t\t\tconfig.get(category, IPName[12], \"\").getString();\n\t\t\t\tconfig.get(category, IPName[13], 0).getInt(0);\n\t\t\t} else if(item == Items.lava_bucket)\n\t\t\t{\n\t\t\t\tconfig.get(category, IPName[0], Item.itemRegistry.getNameForObject(item)).getString();\n\t\t\t\tconfig.get(category, IPName[1], -1).getInt(-1);\n\t\t\t\tconfig.get(category, IPName[2], true).getBoolean(true);\n\t\t\t\tconfig.get(category, IPName[3], 100D).getDouble(100D);\n\t\t\t\tconfig.get(category, IPName[4], 0D).getDouble(0D);\n\t\t\t\tconfig.get(category, IPName[5], 0D).getDouble(0D);\n\t\t\t\tconfig.get(category, IPName[6], 0D).getDouble(0D);\n\t\t\t\tconfig.get(category, IPName[7], 0D).getDouble(0D);\n\t\t\t\tconfig.get(category, IPName[8], 0D).getDouble(0D);\n\t\t\t\tconfig.get(category, IPName[9], 0D).getDouble(0D);\n\t\t\t\tconfig.get(category, IPName[10], 37D).getDouble(37D);\n\t\t\t\tconfig.get(category, IPName[11], 0).getInt(0);\n\t\t\t\tconfig.get(category, IPName[12], \"\").getString();\n\t\t\t\tconfig.get(category, IPName[13], 0).getInt(0);\n\t\t\t} else if(EM_Settings.genConfigs)\n\t\t\t{\n\t\t\t\tthis.generateEmpty(config, item);\n\t\t\t}\n\n\t\t\tconfig.save();\n\t\t}\n\t}\n\n\t@Override\n\tpublic File GetDefaultFile()\n\t{\n\t\treturn new File(EM_ConfigHandler.loadedProfile + EM_ConfigHandler.customPath + \"Items.cfg\");\n\t}\n\n\t@Override\n\tpublic void generateEmpty(Configuration config, Object obj)\n\t{\n\t\tif(obj == null || !(obj instanceof Item))\n\t\t{\n\t\t\tif (EM_Settings.loggerVerbosity >= EnumLogVerbosity.ALL.getLevel()) EnviroMine.logger.log(Level.ERROR, \"Tried to register config with non item object!\", new Exception());\n\t\t\treturn;\n\t\t}\n\n\t\tItem item = (Item)obj;\n\n\t\tString[] regName = Item.itemRegistry.getNameForObject(item).split(\":\");\n\n\t\tif(regName.length <= 0)\n\t\t{\n\t\t\tif (EM_Settings.loggerVerbosity >= EnumLogVerbosity.NORMAL.getLevel()) EnviroMine.logger.log(Level.ERROR, \"Failed to get correctly formatted object name for \" + item.getUnlocalizedName() +\"_\"+ regName[1]);\n\t\t\treturn;\n\t\t}\n\n\t\tString category = this.categoryName() + \".\" + EnviroUtils.replaceULN(item.getUnlocalizedName() +\"_\"+ regName[1]);\n\n\t\tconfig.get(category, IPName[0], Item.itemRegistry.getNameForObject(item)).getString();\n\t\tconfig.get(category, IPName[1], -1).getInt(-1);\n\t\tconfig.get(category, IPName[2], false).getBoolean(false);\n\t\tconfig.get(category, IPName[3], 37D).getDouble(37D);\n\t\tconfig.get(category, IPName[4], 0D).getDouble(0D);\n\t\tconfig.get(category, IPName[5], 0D).getDouble(0D);\n\t\tconfig.get(category, IPName[6], 0D).getDouble(0D);\n\t\tconfig.get(category, IPName[7], 0D).getDouble(0D);\n\t\tconfig.get(category, IPName[8], 0D).getDouble(0D);\n\t\tconfig.get(category, IPName[9], 0D).getDouble(0D);\n\t\tconfig.get(category, IPName[10], 37D).getDouble(37D);\n\t\tconfig.get(category, IPName[11], 0).getInt(0);\n\t\tconfig.get(category, IPName[12], \"\").getString();\n\t\tconfig.get(category, IPName[13], 0).getInt(0);\n\t}\n\n\t@Override\n\tpublic boolean useCustomConfigs()\n\t{\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic void customLoad()\n\t{\n\t}\n\n\tstatic\n\t{\n\t\tIPName = new String[14];\n\t\tIPName[0] = \"01.Name\";\n\t\tIPName[1] = \"02.Damage\";\n\t\tIPName[2] = \"03.Enable Ambient Temperature\";\n\t\tIPName[3] = \"04.Ambient Temperature\";\n\t\tIPName[4] = \"05.Ambient Air Quality\";\n\t\tIPName[5] = \"06.Ambient Santity\";\n\t\tIPName[6] = \"07.Effect Temperature\";\n\t\tIPName[7] = \"08.Effect Air Quality\";\n\t\tIPName[8] = \"09.Effect Sanity\";\n\t\tIPName[9] = \"10.Effect Hydration\";\n\t\tIPName[10] = \"11.Effect Temperature Cap\";\n\t\tIPName[11] = \"12.CamelPack Fill Amount\";\n\t\tIPName[12] = \"13.CamelPack Return Item\";\n\t\tIPName[13] = \"14.CamelPack Return Meta\";\n\t}\n}" } ]
import java.util.HashMap; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import cpw.mods.fml.common.gameevent.PlayerEvent; import enviromine.core.EM_Settings; import enviromine.trackers.properties.ItemProperties; import net.minecraft.init.Items; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.InventoryCrafting; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.IRecipe; import net.minecraft.world.World;
10,230
package enviromine.handlers.crafting; public class CamelPackRefillHandler implements IRecipe { public int totalFill; public HashMap<ItemStack,ItemStack> fullItems = new HashMap<ItemStack,ItemStack>(); public ItemStack emptyItem = null; public ItemStack pack; @Override public boolean matches(InventoryCrafting inv, World world) { if (!inv.getInventoryName().equals("container.crafting")) { return false; } this.totalFill = 0; this.pack = null; this.fullItems.clear(); this.emptyItem = null; for (int i = inv.getSizeInventory() - 1; i >= 0; i--) { ItemStack item = inv.getStackInSlot(i); if (item == null) { continue; }
package enviromine.handlers.crafting; public class CamelPackRefillHandler implements IRecipe { public int totalFill; public HashMap<ItemStack,ItemStack> fullItems = new HashMap<ItemStack,ItemStack>(); public ItemStack emptyItem = null; public ItemStack pack; @Override public boolean matches(InventoryCrafting inv, World world) { if (!inv.getInventoryName().equals("container.crafting")) { return false; } this.totalFill = 0; this.pack = null; this.fullItems.clear(); this.emptyItem = null; for (int i = inv.getSizeInventory() - 1; i >= 0; i--) { ItemStack item = inv.getStackInSlot(i); if (item == null) { continue; }
ItemProperties itemProps = EM_Settings.itemProperties.get(Item.itemRegistry.getNameForObject(item.getItem()) + "," + item.getItemDamage());
1
2023-11-16 18:15:29+00:00
12k
spring-projects/spring-rewrite-commons
spring-rewrite-commons-launcher/src/test/java/org/springframework/rewrite/parsers/RewriteProjectParserParityTest.java
[ { "identifier": "ComparingParserFactory", "path": "spring-rewrite-commons-launcher/src/test/java/org/springframework/rewrite/parsers/maven/ComparingParserFactory.java", "snippet": "public class ComparingParserFactory {\n\n\t@NotNull\n\tpublic RewriteMavenProjectParser createComparingParser() {\n\t\treturn createComparingParser(new SpringRewriteProperties());\n\t}\n\n\tpublic RewriteMavenProjectParser createComparingParser(SpringRewriteProperties springRewriteProperties) {\n\t\tMavenPlexusContainer plexusContainer = new MavenPlexusContainer();\n\t\tConfigurableListableBeanFactory beanFactory = mock(ConfigurableListableBeanFactory.class);\n\t\tScanScope scanScope = mock(ScanScope.class);\n\t\tApplicationEventPublisher eventPublisher = mock(ApplicationEventPublisher.class);\n\t\tRewriteParsingEventListenerAdapter parsingListener = new RewriteParsingEventListenerAdapter(eventPublisher);\n\t\tMavenExecutionRequestFactory requestFactory = new MavenExecutionRequestFactory(new MavenConfigFileParser());\n\t\tRewriteMavenProjectParser mavenProjectParser1 = new RewriteMavenProjectParser(plexusContainer, parsingListener,\n\t\t\t\tnew MavenExecutor(requestFactory, plexusContainer),\n\t\t\t\tnew MavenMojoProjectParserFactory(springRewriteProperties), scanScope, beanFactory,\n\t\t\t\tnew InMemoryExecutionContext(t -> {\n\t\t\t\t\tthrow new RuntimeException(t);\n\t\t\t\t}));\n\t\treturn mavenProjectParser1;\n\t}\n\n}" }, { "identifier": "RewriteMavenProjectParser", "path": "spring-rewrite-commons-launcher/src/test/java/org/springframework/rewrite/parsers/maven/RewriteMavenProjectParser.java", "snippet": "public class RewriteMavenProjectParser {\n\n\tprivate final MavenPlexusContainer mavenPlexusContainer;\n\n\tprivate final ParsingEventListener parsingListener;\n\n\tprivate final MavenExecutor mavenRunner;\n\n\tprivate final MavenMojoProjectParserFactory mavenMojoProjectParserFactory;\n\n\tprivate final ScanScope scanScope;\n\n\tprivate final ConfigurableListableBeanFactory beanFactory;\n\n\tprivate final ExecutionContext executionContext;\n\n\tpublic RewriteMavenProjectParser(MavenPlexusContainer mavenPlexusContainer, ParsingEventListener parsingListener,\n\t\t\tMavenExecutor mavenRunner, MavenMojoProjectParserFactory mavenMojoProjectParserFactory, ScanScope scanScope,\n\t\t\tConfigurableListableBeanFactory beanFactory, ExecutionContext executionContext) {\n\t\tthis.mavenPlexusContainer = mavenPlexusContainer;\n\t\tthis.parsingListener = parsingListener;\n\t\tthis.mavenRunner = mavenRunner;\n\t\tthis.mavenMojoProjectParserFactory = mavenMojoProjectParserFactory;\n\t\tthis.scanScope = scanScope;\n\t\tthis.beanFactory = beanFactory;\n\t\tthis.executionContext = executionContext;\n\t}\n\n\t/**\n\t * Parses a list of {@link Resource}s in given {@code baseDir} to OpenRewrite AST. It\n\t * uses default settings for configuration.\n\t */\n\tpublic RewriteProjectParsingResult parse(Path baseDir) {\n\t\tParsingExecutionContextView.view(executionContext).setParsingListener(parsingListener);\n\t\treturn parse(baseDir, executionContext);\n\t}\n\n\t@NotNull\n\tpublic RewriteProjectParsingResult parse(Path baseDir, ExecutionContext executionContext) {\n\t\tfinal Path absoluteBaseDir = getAbsolutePath(baseDir);\n\t\tPlexusContainer plexusContainer = mavenPlexusContainer.get();\n\t\tRewriteProjectParsingResult parsingResult = parseInternal(absoluteBaseDir, executionContext, plexusContainer);\n\t\treturn parsingResult;\n\t}\n\n\tprivate RewriteProjectParsingResult parseInternal(Path baseDir, ExecutionContext executionContext,\n\t\t\tPlexusContainer plexusContainer) {\n\t\tclearScanScopedBeans();\n\n\t\tAtomicReference<RewriteProjectParsingResult> parsingResult = new AtomicReference<>();\n\t\tmavenRunner.onProjectSucceededEvent(baseDir, List.of(\"clean\", \"package\"), event -> {\n\t\t\ttry {\n\t\t\t\tMavenSession session = event.getSession();\n\t\t\t\tList<MavenProject> mavenProjects = session.getAllProjects();\n\t\t\t\tMavenMojoProjectParser rewriteProjectParser = mavenMojoProjectParserFactory.create(baseDir,\n\t\t\t\t\t\tmavenProjects, plexusContainer, session);\n\t\t\t\tList<NamedStyles> styles = List.of();\n\t\t\t\tList<SourceFile> sourceFiles = parseSourceFiles(rewriteProjectParser, mavenProjects, styles,\n\t\t\t\t\t\texecutionContext);\n\t\t\t\tparsingResult.set(new RewriteProjectParsingResult(sourceFiles, executionContext));\n\t\t\t}\n\t\t\tcatch (Exception e) {\n\t\t\t\tthrow new RuntimeException(e);\n\t\t\t}\n\t\t});\n\t\treturn parsingResult.get();\n\t}\n\n\tprivate void clearScanScopedBeans() {\n\t\tscanScope.clear(beanFactory);\n\t}\n\n\tprivate List<SourceFile> parseSourceFiles(MavenMojoProjectParser rewriteProjectParser,\n\t\t\tList<MavenProject> mavenProjects, List<NamedStyles> styles, ExecutionContext executionContext) {\n\t\ttry {\n\t\t\tStream<SourceFile> sourceFileStream = rewriteProjectParser.listSourceFiles(\n\t\t\t\t\tmavenProjects.get(mavenProjects.size() - 1), // FIXME: Order and\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// access to root\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// module\n\t\t\t\t\tstyles, executionContext);\n\t\t\treturn sourcesWithAutoDetectedStyles(sourceFileStream);\n\t\t}\n\t\tcatch (DependencyResolutionRequiredException | MojoExecutionException e) {\n\t\t\tthrow new RuntimeException(e);\n\t\t}\n\t}\n\n\t@NotNull\n\tprivate static Path getAbsolutePath(Path baseDir) {\n\t\tif (!baseDir.isAbsolute()) {\n\t\t\tbaseDir = baseDir.toAbsolutePath().normalize();\n\t\t}\n\t\treturn baseDir;\n\t}\n\n\t// copied from OpenRewrite for now, TODO: remove and reuse\n\tList<SourceFile> sourcesWithAutoDetectedStyles(Stream<SourceFile> sourceFiles) {\n\t\torg.openrewrite.java.style.Autodetect.Detector javaDetector = org.openrewrite.java.style.Autodetect.detector();\n\t\torg.openrewrite.xml.style.Autodetect.Detector xmlDetector = org.openrewrite.xml.style.Autodetect.detector();\n\t\tList<SourceFile> sourceFileList = sourceFiles.peek(javaDetector::sample)\n\t\t\t.peek(xmlDetector::sample)\n\t\t\t.collect(toList());\n\n\t\tMap<Class<? extends Tree>, NamedStyles> stylesByType = new HashMap<>();\n\t\tstylesByType.put(JavaSourceFile.class, javaDetector.build());\n\t\tstylesByType.put(Xml.Document.class, xmlDetector.build());\n\n\t\treturn ListUtils.map(sourceFileList, applyAutodetectedStyle(stylesByType));\n\t}\n\n\t// copied from OpenRewrite for now, TODO: remove and reuse\n\tUnaryOperator<SourceFile> applyAutodetectedStyle(Map<Class<? extends Tree>, NamedStyles> stylesByType) {\n\t\treturn before -> {\n\t\t\tfor (Map.Entry<Class<? extends Tree>, NamedStyles> styleTypeEntry : stylesByType.entrySet()) {\n\t\t\t\tif (styleTypeEntry.getKey().isAssignableFrom(before.getClass())) {\n\t\t\t\t\tbefore = before.withMarkers(before.getMarkers().add(styleTypeEntry.getValue()));\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn before;\n\t\t};\n\t}\n\n}" }, { "identifier": "DummyResource", "path": "spring-rewrite-commons-launcher/src/test/java/org/springframework/rewrite/test/util/DummyResource.java", "snippet": "public class DummyResource implements Resource {\n\n\tprivate final Path path;\n\n\tprivate final String content;\n\n\tpublic DummyResource(Path path, String content) {\n\t\tthis.path = path;\n\t\tthis.content = content;\n\t}\n\n\tpublic DummyResource(String path, String content) {\n\t\tthis(Path.of(path), content);\n\t}\n\n\tpublic DummyResource(Path baseDir, String sourcePath, String pom) {\n\t\tthis(baseDir.resolve(sourcePath).toAbsolutePath().normalize(), pom);\n\t}\n\n\t@Override\n\tpublic boolean exists() {\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic URL getURL() throws IOException {\n\t\treturn null;\n\t}\n\n\t@Override\n\tpublic URI getURI() throws IOException {\n\t\treturn null;\n\t}\n\n\t@Override\n\tpublic File getFile() throws IOException {\n\t\treturn new File(path.toAbsolutePath().toString());\n\t}\n\n\t@Override\n\tpublic long contentLength() throws IOException {\n\t\treturn 0;\n\t}\n\n\t@Override\n\tpublic long lastModified() throws IOException {\n\t\treturn 0;\n\t}\n\n\t@Override\n\tpublic Resource createRelative(String relativePath) throws IOException {\n\t\treturn null;\n\t}\n\n\t@Override\n\tpublic String getFilename() {\n\t\treturn path.getFileName().toString();\n\t}\n\n\t@Override\n\tpublic String getDescription() {\n\t\treturn null;\n\t}\n\n\t@Override\n\tpublic InputStream getInputStream() throws IOException {\n\t\treturn new ByteArrayInputStream(content.getBytes());\n\t}\n\n}" }, { "identifier": "ParserParityTestHelper", "path": "spring-rewrite-commons-launcher/src/test/java/org/springframework/rewrite/test/util/ParserParityTestHelper.java", "snippet": "public class ParserParityTestHelper {\n\n\tprivate final Path baseDir;\n\n\tprivate SpringRewriteProperties springRewriteProperties = new SpringRewriteProperties();\n\n\tprivate boolean isParallelParse = true;\n\n\tprivate ExecutionContext executionContext;\n\n\tprivate ParserParityTestHelper(Path baseDir) {\n\t\tthis.baseDir = baseDir;\n\t}\n\n\tpublic static ParserParityTestHelper scanProjectDir(Path baseDir) {\n\t\tParserParityTestHelper helper = new ParserParityTestHelper(baseDir);\n\t\treturn helper;\n\t}\n\n\t/**\n\t * Sequentially parse given project using tested parser and then comparing parser. The\n\t * parsers are executed in parallel by default.\n\t */\n\tpublic ParserParityTestHelper parseSequentially() {\n\t\tthis.isParallelParse = false;\n\t\treturn this;\n\t}\n\n\tpublic ParserParityTestHelper withParserProperties(SpringRewriteProperties springRewriteProperties) {\n\t\tthis.springRewriteProperties = springRewriteProperties;\n\t\treturn this;\n\t}\n\n\tpublic ParserParityTestHelper withExecutionContextForComparingParser(ExecutionContext executionContext) {\n\t\tthis.executionContext = executionContext;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Use this method when no additional assertions required.\n\t */\n\tpublic void verifyParity() {\n\t\tverifyParity((expectedParsingResult, actualParsingResult) -> {\n\t\t\t// nothing extra to verify\n\t\t});\n\t}\n\n\t/**\n\t * Use this method if additional assertions are required.\n\t */\n\tpublic void verifyParity(CustomParserResultParityChecker customParserResultParityChecker) {\n\t\tRewriteProjectParsingResult expectedParserResult = null;\n\t\tRewriteProjectParsingResult actualParserResult = null;\n\n\t\tresolveDependencies();\n\n\t\tParserExecutionHelper parserExecutionHelper = new ParserExecutionHelper();\n\t\tif (isParallelParse) {\n\t\t\tParallelParsingResult result = parserExecutionHelper.parseParallel(baseDir, springRewriteProperties,\n\t\t\t\t\texecutionContext);\n\t\t\texpectedParserResult = result.expectedParsingResult();\n\t\t\tactualParserResult = result.actualParsingResult();\n\t\t}\n\t\telse {\n\t\t\tactualParserResult = parserExecutionHelper.parseWithRewriteProjectParser(baseDir, springRewriteProperties);\n\t\t\texpectedParserResult = parserExecutionHelper.parseWithComparingParser(baseDir, springRewriteProperties,\n\t\t\t\t\texecutionContext);\n\t\t}\n\n\t\tDefaultParserResultParityChecker.verifyParserResultParity(baseDir, expectedParserResult, actualParserResult);\n\n\t\t// additional checks\n\t\tcustomParserResultParityChecker.accept(actualParserResult, expectedParserResult);\n\t}\n\n\tprivate void resolveDependencies() {\n\t\ttry {\n\t\t\tDefaultInvoker defaultInvoker = new DefaultInvoker();\n\t\t\tInvocationRequest request = new DefaultInvocationRequest();\n\t\t\trequest.setGoals(List.of(\"clean\", \"test-compile\"));\n\t\t\trequest.setBaseDirectory(baseDir.toFile());\n\t\t\t// request.setBatchMode(true);\n\t\t\trequest.setPomFile(baseDir.resolve(\"pom.xml\").toFile());\n\n\t\t\tString mavenHome = \"\";\n\t\t\tif (System.getenv(\"MAVEN_HOME\") != null) {\n\t\t\t\tmavenHome = System.getenv(\"MAVEN_HOME\");\n\t\t\t}\n\t\t\telse if (System.getenv(\"MVN_HOME\") != null) {\n\t\t\t\tmavenHome = System.getenv(\"MVN_HOME\");\n\t\t\t}\n\t\t\telse if (System.getenv(\"M2_HOME\") != null) {\n\t\t\t\tmavenHome = System.getenv(\"M2_HOME\");\n\t\t\t}\n\t\t\telse {\n\t\t\t\tthrow new IllegalStateException(\"Neither MVN_HOME nor MAVEN_HOME set but required by MavenInvoker.\");\n\t\t\t}\n\n\t\t\tSystem.out.println(\"Using Maven %s\".formatted(mavenHome));\n\n\t\t\trequest.setMavenHome(new File(mavenHome));\n\t\t\tdefaultInvoker.execute(request);\n\t\t}\n\t\tcatch (MavenInvocationException e) {\n\t\t\tthrow new RuntimeException(e);\n\t\t}\n\t}\n\n\tpublic interface CustomParserResultParityChecker\n\t\t\textends BiConsumer<RewriteProjectParsingResult, RewriteProjectParsingResult> {\n\n\t\t@Override\n\t\tvoid accept(RewriteProjectParsingResult expectedParsingResult, RewriteProjectParsingResult actualParsingResult);\n\n\t}\n\n\tprivate class DefaultParserResultParityChecker {\n\n\t\tpublic static void verifyParserResultParity(Path baseDir, RewriteProjectParsingResult expectedParserResult,\n\t\t\t\tRewriteProjectParsingResult actualParserResult) {\n\t\t\tverifyEqualNumberOfParsedResources(expectedParserResult, actualParserResult);\n\t\t\tverifyEqualResourcePaths(baseDir, expectedParserResult, actualParserResult);\n\t\t\tRewriteMarkerParityVerifier.verifyEqualMarkers(expectedParserResult, actualParserResult);\n\t\t}\n\n\t\tprivate static void verifyEqualResourcePaths(Path baseDir, RewriteProjectParsingResult expectedParserResult,\n\t\t\t\tRewriteProjectParsingResult actualParserResult) {\n\t\t\tList<String> expectedResultPaths = expectedParserResult.sourceFiles()\n\t\t\t\t.stream()\n\t\t\t\t.map(sf -> baseDir.resolve(sf.getSourcePath()).toAbsolutePath().normalize().toString())\n\t\t\t\t.toList();\n\t\t\tList<String> actualResultPaths = actualParserResult.sourceFiles()\n\t\t\t\t.stream()\n\t\t\t\t.map(sf -> baseDir.resolve(sf.getSourcePath()).toAbsolutePath().normalize().toString())\n\t\t\t\t.toList();\n\t\t\tassertThat(actualResultPaths).containsExactlyInAnyOrder(expectedResultPaths.toArray(String[]::new));\n\t\t}\n\n\t\tprivate static void verifyEqualNumberOfParsedResources(RewriteProjectParsingResult expectedParserResult,\n\t\t\t\tRewriteProjectParsingResult actualParserResult) {\n\t\t\tassertThat(actualParserResult.sourceFiles().size())\n\t\t\t\t.as(renderErrorMessage(expectedParserResult, actualParserResult))\n\t\t\t\t.isEqualTo(expectedParserResult.sourceFiles().size());\n\t\t}\n\n\t\tprivate static String renderErrorMessage(RewriteProjectParsingResult expectedParserResult,\n\t\t\t\tRewriteProjectParsingResult actualParserResult) {\n\t\t\tList<SourceFile> collect = new ArrayList<>();\n\t\t\tif (expectedParserResult.sourceFiles().size() > actualParserResult.sourceFiles().size()) {\n\t\t\t\tcollect = expectedParserResult.sourceFiles()\n\t\t\t\t\t.stream()\n\t\t\t\t\t.filter(element -> !actualParserResult.sourceFiles().contains(element))\n\t\t\t\t\t.collect(Collectors.toList());\n\t\t\t}\n\t\t\telse {\n\t\t\t\tcollect = actualParserResult.sourceFiles()\n\t\t\t\t\t.stream()\n\t\t\t\t\t.filter(element -> !expectedParserResult.sourceFiles().contains(element))\n\t\t\t\t\t.collect(Collectors.toList());\n\t\t\t}\n\n\t\t\treturn \"ComparingParserResult had %d sourceFiles whereas TestedParserResult had %d sourceFiles. Files were %s\"\n\t\t\t\t.formatted(expectedParserResult.sourceFiles().size(), actualParserResult.sourceFiles().size(), collect);\n\t\t}\n\n\t}\n\n\tprivate static class RewriteMarkerParityVerifier {\n\n\t\tstatic void verifyEqualMarkers(RewriteProjectParsingResult expectedParserResult,\n\t\t\t\tRewriteProjectParsingResult actualParserResult) {\n\t\t\tList<SourceFile> expectedSourceFiles = expectedParserResult.sourceFiles();\n\t\t\tList<SourceFile> actualSourceFiles = actualParserResult.sourceFiles();\n\n\t\t\t// bring to same order\n\t\t\texpectedSourceFiles.sort(Comparator.comparing(SourceFile::getSourcePath));\n\t\t\tactualSourceFiles.sort(Comparator.comparing(SourceFile::getSourcePath));\n\n\t\t\t// Compare and verify markers of all source files\n\t\t\tfor (SourceFile curExpectedSourceFile : expectedSourceFiles) {\n\t\t\t\tint index = expectedSourceFiles.indexOf(curExpectedSourceFile);\n\t\t\t\tSourceFile curGivenSourceFile = actualSourceFiles.get(index);\n\t\t\t\tverifyEqualSourceFileMarkers(curExpectedSourceFile, curGivenSourceFile);\n\t\t\t}\n\t\t}\n\n\t\tstatic void verifyEqualSourceFileMarkers(SourceFile curExpectedSourceFile, SourceFile curGivenSourceFile) {\n\t\t\tMarkers expectedMarkers = curExpectedSourceFile.getMarkers();\n\t\t\tList<Marker> expectedMarkersList = expectedMarkers.getMarkers();\n\t\t\tMarkers givenMarkers = curGivenSourceFile.getMarkers();\n\t\t\tList<Marker> actualMarkersList = givenMarkers.getMarkers();\n\n\t\t\tassertThat(actualMarkersList.size()).isEqualTo(expectedMarkersList.size());\n\n\t\t\tSoftAssertions softAssertions = new SoftAssertions();\n\n\t\t\tactualMarkersList.sort(Comparator.comparing(o -> o.getClass().getName()));\n\t\t\texpectedMarkersList.sort(Comparator.comparing(o -> o.getClass().getName()));\n\n\t\t\texpectedMarkersList.forEach(expectedMarker -> {\n\t\t\t\tint i = expectedMarkersList.indexOf(expectedMarker);\n\t\t\t\tMarker actualMarker = actualMarkersList.get(i);\n\n\t\t\t\tassertThat(actualMarker).isInstanceOf(expectedMarker.getClass());\n\n\t\t\t\tif (MavenResolutionResult.class.isInstance(actualMarker)) {\n\t\t\t\t\tMavenResolutionResult expected = (MavenResolutionResult) expectedMarker;\n\t\t\t\t\tMavenResolutionResult actual = (MavenResolutionResult) actualMarker;\n\t\t\t\t\tcompareMavenResolutionResultMarker(softAssertions, expected, actual);\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tcompareMarker(softAssertions, expectedMarker, actualMarker);\n\t\t\t\t}\n\n\t\t\t});\n\n\t\t\tsoftAssertions.assertAll();\n\n\t\t\tif (curExpectedSourceFile.getMarkers().findFirst(JavaSourceSet.class).isPresent()) {\n\t\t\t\t// Tested parser must have JavaSourceSet marker when comparing parser has\n\t\t\t\t// it\n\t\t\t\tassertThat(givenMarkers.findFirst(JavaSourceSet.class)).isPresent();\n\n\t\t\t\t// assert classpath equality\n\t\t\t\tList<String> expectedClasspath = expectedMarkers.findFirst(JavaSourceSet.class)\n\t\t\t\t\t.get()\n\t\t\t\t\t.getClasspath()\n\t\t\t\t\t.stream()\n\t\t\t\t\t.map(JavaType.FullyQualified::getFullyQualifiedName)\n\t\t\t\t\t.toList();\n\t\t\t\tList<String> actualClasspath = givenMarkers.findFirst(JavaSourceSet.class)\n\t\t\t\t\t.get()\n\t\t\t\t\t.getClasspath()\n\t\t\t\t\t.stream()\n\t\t\t\t\t.map(JavaType.FullyQualified::getFullyQualifiedName)\n\t\t\t\t\t.toList();\n\n\t\t\t\tassertThat(actualClasspath.size()).isEqualTo(expectedClasspath.size());\n\n\t\t\t\tassertThat(expectedClasspath).withFailMessage(() -> {\n\t\t\t\t\tList<String> additionalElementsInExpectedClasspath = expectedClasspath.stream()\n\t\t\t\t\t\t.filter(element -> !actualClasspath.contains(element))\n\t\t\t\t\t\t.collect(Collectors.toList());\n\n\t\t\t\t\tif (!additionalElementsInExpectedClasspath.isEmpty()) {\n\t\t\t\t\t\treturn \"Classpath of comparing and tested parser differ: comparing classpath contains additional entries: %s\"\n\t\t\t\t\t\t\t.formatted(additionalElementsInExpectedClasspath);\n\t\t\t\t\t}\n\n\t\t\t\t\tList<String> additionalElementsInActualClasspath = actualClasspath.stream()\n\t\t\t\t\t\t.filter(element -> !expectedClasspath.contains(element))\n\t\t\t\t\t\t.collect(Collectors.toList());\n\n\t\t\t\t\tif (!additionalElementsInActualClasspath.isEmpty()) {\n\t\t\t\t\t\treturn \"Classpath of comparing and tested parser differ: tested classpath contains additional entries: %s\"\n\t\t\t\t\t\t\t.formatted(additionalElementsInActualClasspath);\n\t\t\t\t\t}\n\n\t\t\t\t\tthrow new IllegalStateException(\"Something went terribly wrong...\");\n\t\t\t\t}).containsExactlyInAnyOrder(actualClasspath.toArray(String[]::new));\n\t\t\t}\n\t\t}\n\n\t\tstatic void compareMavenResolutionResultMarker(SoftAssertions softAssertions, MavenResolutionResult expected,\n\t\t\t\tMavenResolutionResult actual) {\n\t\t\tsoftAssertions.assertThat(actual)\n\t\t\t\t.usingRecursiveComparison()\n\t\t\t\t.withEqualsForFieldsMatchingRegexes(customRepositoryEquals(\"mavenSettings.localRepository\"),\n\t\t\t\t\t\t\"mavenSettings.localRepository\", \".*\\\\.repository\", \"mavenSettings.mavenLocal.uri\")\n\t\t\t\t.ignoringFields(\"modules\", // checked further down\n\t\t\t\t\t\t\"dependencies\", // checked further down\n\t\t\t\t\t\t\"parent.modules\" // TODO:\n\t\t\t\t// https://github.com/spring-projects-experimental/spring-boot-migrator/issues/991\n\t\t\t\t)\n\t\t\t\t.ignoringFieldsOfTypes(UUID.class)\n\t\t\t\t.isEqualTo(expected);\n\n\t\t\t// verify modules\n\t\t\tverifyEqualModulesInMavenResolutionResult(softAssertions, expected, actual);\n\n\t\t\t// verify dependencies\n\t\t\tverifyEqualDependencies(softAssertions, expected, actual);\n\t\t}\n\n\t\tprivate static void verifyEqualDependencies(SoftAssertions softAssertions, MavenResolutionResult expected,\n\t\t\t\tMavenResolutionResult actual) {\n\t\t\tSet<Scope> keys = expected.getDependencies().keySet();\n\t\t\tkeys.forEach(k -> {\n\t\t\t\tList<ResolvedDependency> expectedDependencies = expected.getDependencies().get(k);\n\t\t\t\tList<ResolvedDependency> actualDependencies = actual.getDependencies().get(k);\n\n\t\t\t\t// same order\n\t\t\t\texpectedDependencies.sort(Comparator.comparing(o -> o.getGav().toString()));\n\t\t\t\tactualDependencies.sort(Comparator.comparing(o -> o.getGav().toString()));\n\n\t\t\t\tsoftAssertions.assertThat(actualDependencies)\n\t\t\t\t\t.usingRecursiveComparison()\n\t\t\t\t\t.withEqualsForFieldsMatchingRegexes(customRepositoryEquals(\".*\\\\.repository\"), \".*\\\\.repository\")\n\t\t\t\t\t.ignoringFieldsOfTypes(UUID.class)\n\t\t\t\t\t.isEqualTo(expectedDependencies);\n\t\t\t});\n\t\t}\n\n\t\tprivate static void verifyEqualModulesInMavenResolutionResult(SoftAssertions softAssertions,\n\t\t\t\tMavenResolutionResult expected, MavenResolutionResult actual) {\n\t\t\tList<MavenResolutionResult> expectedModules = expected.getModules();\n\t\t\tList<MavenResolutionResult> actualModules = actual.getModules();\n\t\t\t// bring modules in same order\n\t\t\texpectedModules.sort(Comparator.comparing(o -> o.getPom().getGav().toString()));\n\t\t\tactualModules.sort(Comparator.comparing(o -> o.getPom().getGav().toString()));\n\t\t\t// test modules\n\t\t\texpectedModules.forEach(cm -> {\n\t\t\t\tMavenResolutionResult actualMavenResolutionResult = actualModules.get(expectedModules.indexOf(cm));\n\t\t\t\tcompareMavenResolutionResultMarker(softAssertions, cm, actualMavenResolutionResult);\n\t\t\t});\n\t\t}\n\n\t\t/**\n\t\t * Custom equals comparing fields names with 'repository' URI. This is required\n\t\t * because the repository URI can be 'file:host' or 'file//host' which is\n\t\t * effectively the same. But the strict comparison fails. This custom equals\n\t\t * method can be used instead. <pre>\n\t\t * .withEqualsForFieldsMatchingRegexes(\n\t\t * customRepositoryEquals(),\n\t\t * \".*\\\\.repository\"\n\t\t * )\n\t\t * </pre>\n\t\t */\n\t\t@NotNull\n\t\tprivate static BiPredicate<Object, Object> customRepositoryEquals(String s) {\n\t\t\t// System.out.println(s);\n\t\t\treturn (Object actual, Object expected) -> {\n\t\t\t\t// field null?\n\t\t\t\tif (actual == null) {\n\t\t\t\t\tif (expected == null) {\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\t// normal equals?\n\t\t\t\tboolean equals = actual.equals(expected);\n\t\t\t\tif (equals) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\t// Compare Repository URI\n\t\t\t\tif (actual.getClass() == actual.getClass()) {\n\t\t\t\t\tif (actual instanceof URI) {\n\t\t\t\t\t\tURI f1 = (URI) actual;\n\t\t\t\t\t\tURI f2 = (URI) expected;\n\t\t\t\t\t\treturn equals ? true\n\t\t\t\t\t\t\t\t: f1.getScheme().equals(f2.getScheme()) && f1.getHost().equals(f2.getHost())\n\t\t\t\t\t\t\t\t\t\t&& f1.getPath().equals(f2.getPath())\n\t\t\t\t\t\t\t\t\t\t&& f1.getFragment().equals(f2.getFragment());\n\t\t\t\t\t}\n\t\t\t\t\telse if (actual instanceof String) {\n\t\t\t\t\t\tURI f1 = new File((String) actual).toURI();\n\t\t\t\t\t\tURI f2 = new File((String) expected).toURI();\n\t\t\t\t\t\t// @formatter:off\n return\n f1.getScheme() != null && f2.getScheme() != null ? f1.getScheme().equals(f2.getScheme()) : f1.getScheme() == null && f2.getScheme() == null ? true : false\n &&\n f1.getHost() != null && f2.getHost() != null ? f1.getHost().equals(f2.getHost()) : f1.getHost() == null && f2.getHost() == null ? true : false\n &&\n f1.getPath() != null && f2.getPath() != null ? f1.getPath().equals(f2.getPath()) : f1.getPath() == null && f2.getPath() == null ? true : false\n &&\n f1.getFragment() != null && f2.getFragment() != null ? f1.getFragment().equals(f2.getFragment()) : f1.getFragment() == null && f2.getFragment() == null ? true : false;\n // @formatter:on\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\n\t\t\t};\n\t\t}\n\n\t\tstatic void compareMarker(SoftAssertions softAssertions, Marker expectedMarker, Marker actualMarker) {\n\t\t\tsoftAssertions.assertThat(actualMarker)\n\t\t\t\t.usingRecursiveComparison()\n\t\t\t\t.withStrictTypeChecking()\n\t\t\t\t.ignoringCollectionOrder()\n\t\t\t\t.withEqualsForFields(equalsClasspath(), \"classpath\")\n\t\t\t\t.ignoringFields(\n\t\t\t\t\t\t// FIXME:\n\t\t\t\t\t\t// https://github.com/spring-projects-experimental/spring-boot-migrator/issues/982\n\t\t\t\t\t\t\"styles\")\n\t\t\t\t.ignoringFieldsOfTypes(UUID.class,\n\t\t\t\t\t\t// FIXME:\n\t\t\t\t\t\t// https://github.com/spring-projects-experimental/spring-boot-migrator/issues/982\n\t\t\t\t\t\tStyle.class)\n\t\t\t\t.isEqualTo(expectedMarker);\n\t\t}\n\n\t\tprivate static BiPredicate<?, ?> equalsClasspath() {\n\t\t\treturn (List<JavaType.FullyQualified> c1, List<JavaType.FullyQualified> c2) -> {\n\t\t\t\tList<String> c1Sorted = c1.stream()\n\t\t\t\t\t.map(JavaType.FullyQualified::getFullyQualifiedName)\n\t\t\t\t\t.sorted()\n\t\t\t\t\t.toList();\n\t\t\t\tList<String> c2Sorted = c2.stream()\n\t\t\t\t\t.map(JavaType.FullyQualified::getFullyQualifiedName)\n\t\t\t\t\t.sorted()\n\t\t\t\t\t.toList();\n\t\t\t\treturn c1Sorted.equals(c2Sorted);\n\t\t\t};\n\t\t}\n\n\t}\n\n}" }, { "identifier": "TestProjectHelper", "path": "spring-rewrite-commons-launcher/src/test/java/org/springframework/rewrite/test/util/TestProjectHelper.java", "snippet": "public class TestProjectHelper {\n\n\tprivate final Path targetDir;\n\n\tprivate List<Resource> resources = new ArrayList<>();\n\n\tprivate boolean initializeGitRepo;\n\n\tprivate String gitUrl;\n\n\tprivate String gitTag;\n\n\tprivate boolean deleteDirIfExists = false;\n\n\tpublic TestProjectHelper(Path targetDir) {\n\t\tthis.targetDir = targetDir;\n\t}\n\n\tpublic static Path getMavenProject(String s) {\n\t\treturn Path.of(\"./testcode/maven-projects/\").resolve(s).toAbsolutePath().normalize();\n\t}\n\n\tpublic static TestProjectHelper createTestProject(Path targetDir) {\n\t\treturn new TestProjectHelper(targetDir);\n\t}\n\n\tpublic static TestProjectHelper createTestProject(String targetDir) {\n\t\treturn new TestProjectHelper(Path.of(targetDir).toAbsolutePath().normalize());\n\t}\n\n\tpublic TestProjectHelper withResources(Resource... resources) {\n\t\tthis.resources.addAll(Arrays.asList(resources));\n\t\treturn this;\n\t}\n\n\tpublic TestProjectHelper initializeGitRepo() {\n\t\tthis.initializeGitRepo = true;\n\t\treturn this;\n\t}\n\n\tpublic TestProjectHelper cloneGitProject(String url) {\n\t\tthis.gitUrl = url;\n\t\treturn this;\n\t}\n\n\tpublic TestProjectHelper checkoutTag(String tag) {\n\t\tthis.gitTag = tag;\n\t\treturn this;\n\t}\n\n\tpublic TestProjectHelper deleteDirIfExists() {\n\t\tthis.deleteDirIfExists = true;\n\t\treturn this;\n\t}\n\n\tpublic void writeToFilesystem() {\n\t\tif (deleteDirIfExists) {\n\t\t\ttry {\n\t\t\t\tFileUtils.deleteDirectory(targetDir.toFile());\n\t\t\t}\n\t\t\tcatch (IOException e) {\n\t\t\t\tthrow new RuntimeException(e);\n\t\t\t}\n\t\t}\n\n\t\tif (initializeGitRepo) {\n\t\t\ttry {\n\t\t\t\tGit.init().setDirectory(targetDir.toFile()).call();\n\t\t\t}\n\t\t\tcatch (GitAPIException e) {\n\t\t\t\tthrow new RuntimeException(e);\n\t\t\t}\n\t\t}\n\t\telse if (gitUrl != null) {\n\t\t\ttry {\n\t\t\t\tFile directory = targetDir.toFile();\n\t\t\t\tGit git = Git.cloneRepository().setDirectory(directory).setURI(this.gitUrl).call();\n\n\t\t\t\tif (gitTag != null) {\n\t\t\t\t\tgit.checkout().setName(\"refs/tags/\" + gitTag).call();\n\t\t\t\t}\n\t\t\t}\n\t\t\tcatch (GitAPIException e) {\n\t\t\t\tthrow new RuntimeException(e);\n\t\t\t}\n\t\t}\n\t\tResourceUtil.write(targetDir, resources);\n\t}\n\n}" } ]
import org.intellij.lang.annotations.Language; import org.jetbrains.annotations.NotNull; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.condition.DisabledOnOs; import org.junit.jupiter.api.condition.OS; import org.junit.jupiter.api.io.TempDir; import org.junitpioneer.jupiter.Issue; import org.openrewrite.ExecutionContext; import org.openrewrite.InMemoryExecutionContext; import org.openrewrite.Parser; import org.openrewrite.SourceFile; import org.openrewrite.shaded.jgit.api.errors.GitAPIException; import org.openrewrite.tree.ParsingEventListener; import org.openrewrite.tree.ParsingExecutionContextView; import org.springframework.rewrite.parsers.maven.ComparingParserFactory; import org.springframework.rewrite.parsers.maven.RewriteMavenProjectParser; import org.springframework.rewrite.test.util.DummyResource; import org.springframework.rewrite.test.util.ParserParityTestHelper; import org.springframework.rewrite.test.util.TestProjectHelper; import java.nio.file.Path; import java.time.Instant; import java.time.ZoneId; import java.time.format.DateTimeFormatter; import java.time.format.FormatStyle; import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.Set; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.AssertionsForClassTypes.fail;
8,187
/* * Copyright 2021 - 2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.rewrite.parsers; /** * Test parity between OpenRewrite parser logic and RewriteProjectParser. * * RewriteMavenProjectParser resembles the parser logic from OpenRewrite's Maven plugin * * @author Fabian Krüger */ @DisabledOnOs(value = OS.WINDOWS, disabledReason = "The repository URIs of dependencies differ.") @Issue("https://github.com/spring-projects/spring-rewrite-commons/issues/12") class RewriteProjectParserParityTest { @Test @DisplayName("Parsing Simplistic Maven Project ") void parsingSimplisticMavenProject(@TempDir Path tempDir) throws GitAPIException { @Language("xml") String pomXml = """ <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.example</groupId> <artifactId>root-project</artifactId> <version>1.0.0</version> <properties> <maven.compiler.target>17</maven.compiler.target> <maven.compiler.source>17</maven.compiler.source> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <repositories> <repository> <id>jcenter</id> <name>jcenter</name> <url>https://jcenter.bintray.com</url> </repository> <repository> <id>mavencentral</id> <name>mavencentral</name> <url>https://repo.maven.apache.org/maven2</url> </repository> </repositories> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> <version>3.1.1</version> </dependency> </dependencies> </project> """; @Language("java") String javaClass = """ package com.example; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class MyMain { public static void main(String[] args){ SpringApplication.run(MyMain.class, args); } } """; TestProjectHelper.createTestProject(tempDir) .withResources(new DummyResource(tempDir.resolve("src/main/java/com/example/MyMain.java"), javaClass), new DummyResource(tempDir.resolve("pom.xml"), pomXml)) .initializeGitRepo() // trigger creation of GIT related marker .writeToFilesystem(); SpringRewriteProperties comparingSpringRewriteProperties = new SpringRewriteProperties(); Set<String> ignoredPathPatterns = Set.of("**/testcode/**", "testcode/**", ".rewrite-cache/**", "**/target/**", "**/.git/**"); comparingSpringRewriteProperties.setIgnoredPathPatterns(ignoredPathPatterns); comparingSpringRewriteProperties.setPomCacheEnabled(true); comparingSpringRewriteProperties.setPomCacheEnabled(true); ParserParityTestHelper.scanProjectDir(tempDir) .withParserProperties(comparingSpringRewriteProperties) .verifyParity(); } @NotNull private static InMemoryExecutionContext createExecutionContext() { return new InMemoryExecutionContext(t -> t.printStackTrace()); } @Test @DisplayName("Parse multi-module-1") void parseMultiModule1() { Path baseDir = getMavenProject("multi-module-1"); ParserParityTestHelper.scanProjectDir(baseDir).verifyParity(); } @Test @DisplayName("Should Parse Maven Config Project") @Disabled("https://github.com/openrewrite/rewrite/issues/3409") void shouldParseMavenConfigProject() { Path baseDir = Path.of("./testcode/maven-projects/maven-config").toAbsolutePath().normalize(); SpringRewriteProperties springRewriteProperties = new SpringRewriteProperties(); springRewriteProperties.setIgnoredPathPatterns(Set.of(".mvn"));
/* * Copyright 2021 - 2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.rewrite.parsers; /** * Test parity between OpenRewrite parser logic and RewriteProjectParser. * * RewriteMavenProjectParser resembles the parser logic from OpenRewrite's Maven plugin * * @author Fabian Krüger */ @DisabledOnOs(value = OS.WINDOWS, disabledReason = "The repository URIs of dependencies differ.") @Issue("https://github.com/spring-projects/spring-rewrite-commons/issues/12") class RewriteProjectParserParityTest { @Test @DisplayName("Parsing Simplistic Maven Project ") void parsingSimplisticMavenProject(@TempDir Path tempDir) throws GitAPIException { @Language("xml") String pomXml = """ <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.example</groupId> <artifactId>root-project</artifactId> <version>1.0.0</version> <properties> <maven.compiler.target>17</maven.compiler.target> <maven.compiler.source>17</maven.compiler.source> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <repositories> <repository> <id>jcenter</id> <name>jcenter</name> <url>https://jcenter.bintray.com</url> </repository> <repository> <id>mavencentral</id> <name>mavencentral</name> <url>https://repo.maven.apache.org/maven2</url> </repository> </repositories> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> <version>3.1.1</version> </dependency> </dependencies> </project> """; @Language("java") String javaClass = """ package com.example; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class MyMain { public static void main(String[] args){ SpringApplication.run(MyMain.class, args); } } """; TestProjectHelper.createTestProject(tempDir) .withResources(new DummyResource(tempDir.resolve("src/main/java/com/example/MyMain.java"), javaClass), new DummyResource(tempDir.resolve("pom.xml"), pomXml)) .initializeGitRepo() // trigger creation of GIT related marker .writeToFilesystem(); SpringRewriteProperties comparingSpringRewriteProperties = new SpringRewriteProperties(); Set<String> ignoredPathPatterns = Set.of("**/testcode/**", "testcode/**", ".rewrite-cache/**", "**/target/**", "**/.git/**"); comparingSpringRewriteProperties.setIgnoredPathPatterns(ignoredPathPatterns); comparingSpringRewriteProperties.setPomCacheEnabled(true); comparingSpringRewriteProperties.setPomCacheEnabled(true); ParserParityTestHelper.scanProjectDir(tempDir) .withParserProperties(comparingSpringRewriteProperties) .verifyParity(); } @NotNull private static InMemoryExecutionContext createExecutionContext() { return new InMemoryExecutionContext(t -> t.printStackTrace()); } @Test @DisplayName("Parse multi-module-1") void parseMultiModule1() { Path baseDir = getMavenProject("multi-module-1"); ParserParityTestHelper.scanProjectDir(baseDir).verifyParity(); } @Test @DisplayName("Should Parse Maven Config Project") @Disabled("https://github.com/openrewrite/rewrite/issues/3409") void shouldParseMavenConfigProject() { Path baseDir = Path.of("./testcode/maven-projects/maven-config").toAbsolutePath().normalize(); SpringRewriteProperties springRewriteProperties = new SpringRewriteProperties(); springRewriteProperties.setIgnoredPathPatterns(Set.of(".mvn"));
RewriteMavenProjectParser mavenProjectParser = new ComparingParserFactory().createComparingParser();
1
2023-11-14 23:02:37+00:00
12k
exadel-inc/etoolbox-anydiff
core/src/test/java/com/exadel/etoolbox/anydiff/runner/FilterHelperTest.java
[ { "identifier": "AnyDiff", "path": "core/src/main/java/com/exadel/etoolbox/anydiff/AnyDiff.java", "snippet": "public class AnyDiff {\n\n private String[] leftStrings;\n private Path[] leftPaths;\n private String leftLabel;\n private String[] rightStrings;\n private Path[] rightPaths;\n private String rightLabel;\n\n private Boolean arrangeAttributes;\n private ContentType contentType;\n private Integer columnWidth;\n private Boolean ignoreSpaces;\n private Boolean normalize;\n private List<Filter> filters;\n\n /* -------\n Strings\n ------- */\n\n // Left\n\n /**\n * Assigns the left side of the comparison\n * @param value The left-side value to compare. Can represent either a simple text, a path, or an URI\n * @return This instance\n */\n public AnyDiff left(String value) {\n if (value == null) {\n return this;\n }\n return left(new String[]{value});\n }\n\n /**\n * Assigns the left side of the comparison\n * @param value The left-side strings to compare. Can represent either a simple text, a path, or an URI\n * @return This instance\n */\n public AnyDiff left(String[] value) {\n return left(value, null);\n }\n\n /**\n * Assigns the left side of the comparison\n * @param value The left-side strings to compare. Can represent either a simple text, a path, or an URI\n * @param label The label to use for the left side of the comparison in the report\n * @return This instance\n */\n public AnyDiff left(String[] value, String label) {\n if (ArrayUtils.isEmpty(value)) {\n return this;\n }\n leftStrings = value;\n leftLabel = label;\n return this;\n }\n\n // Right\n\n /**\n * Assigns the right side of the comparison\n * @param value The right-side value to compare. Can represent either a simple text, a path, or an URI\n * @return This instance\n */\n public AnyDiff right(String value) {\n if (value == null) {\n return this;\n }\n return right(new String[] {value});\n }\n\n /**\n * Assigns the right side of the comparison\n * @param value The right-side strings to compare. Can represent either a simple text, a path, or an URI\n * @return This instance\n */\n public AnyDiff right(String[] value) {\n return right(value, null);\n }\n\n /**\n * Assigns the right side of the comparison\n * @param value The right-side strings to compare. Can represent either a simple text, a path, or an URI\n * @param label The label to use for the right side of the comparison in the report\n * @return This instance\n */\n public AnyDiff right(String[] value, String label) {\n if (ArrayUtils.isEmpty(value)) {\n return this;\n }\n rightStrings = value;\n rightLabel = label;\n return this;\n }\n\n /* -----\n Paths\n ----- */\n\n // Left\n\n /**\n * Assigns the left side of the comparison\n * @param value A {@link Path} that represents the left-side data to compare\n * @param label The label to use for the left side of the comparison in the report\n * @return This instance\n */\n public AnyDiff left(Path value, String label) {\n if (value == null) {\n return this;\n }\n return left(new Path[] {value}, label);\n }\n\n /**\n * Assigns the left side of the comparison\n * @param value An array of {@link Path} objects that represent the left-side data to compare\n * @param label The label to use for the left side of the comparison in the report\n * @return This instance\n */\n public AnyDiff left(Path[] value, String label) {\n if (ArrayUtils.isEmpty(value)) {\n return this;\n }\n leftPaths = value;\n leftLabel = label;\n return this;\n }\n\n // Right\n\n /**\n * Assigns the right side of the comparison\n * @param value A {@link Path} that represents the right-side data to compare\n * @param label The label to use for the right side of the comparison in the report\n * @return This instance\n */\n public AnyDiff right(Path value, String label) {\n if (value == null) {\n return this;\n }\n return right(new Path[] {value}, label);\n }\n\n /**\n * Assigns the right side of the comparison\n * @param value An array of {@link Path} objects that represent the right-side data to compare\n * @param label The label to use for the right side of the comparison in the report\n * @return This instance\n */\n public AnyDiff right(Path[] value, String label) {\n if (ArrayUtils.isEmpty(value)) {\n return this;\n }\n rightPaths = value;\n rightLabel = label;\n return this;\n }\n\n /* -------\n Filters\n ------- */\n\n /**\n * Assigns a {@link Filter} to the comparison\n * @param value A {@code Filter} object to use for the comparison\n * @return This instance\n */\n public AnyDiff filter(Filter value) {\n return filter(Collections.singletonList(value));\n }\n\n /**\n * Assigns a list of {@link Filter} objects to the comparison\n * @param value A list of {@code Filter} objects to use for the comparison\n * @return This instance\n */\n public AnyDiff filter(List<Filter> value) {\n if (CollectionUtils.isEmpty(value)) {\n return this;\n }\n if (filters == null) {\n filters = new ArrayList<>();\n }\n filters.addAll(value);\n return this;\n }\n\n /* --------------\n Misc arguments\n -------------- */\n\n /**\n * Assigns the flag telling whether to arrange tag attributes of markup content before comparison for more accurate\n * results\n * @param value Boolean value\n * @return This instance\n */\n public AnyDiff arrangeAttributes(boolean value) {\n this.arrangeAttributes = value;\n return this;\n }\n\n /**\n * Assigns the content type to use for the comparison\n * @param value A {@link ContentType} value to use for the comparison\n * @return This instance\n */\n public AnyDiff contentType(ContentType value) {\n this.contentType = value;\n return this;\n }\n\n /**\n * Assigns the column width to use for the comparison reports\n * @param value A positive integer value\n * @return This instance\n */\n public AnyDiff columnWidth(int value) {\n this.columnWidth = value;\n return this;\n }\n\n /**\n * Assigns the flag telling whether to ignore spaces between words in comparison\n * @param value Boolean value\n * @return This instance\n */\n public AnyDiff ignoreSpaces(boolean value) {\n this.ignoreSpaces = value;\n return this;\n }\n\n /**\n * Assigns the flag telling whether to normalize markup content before comparison for more granular results\n * @param value Boolean value\n * @return This instance\n */\n public AnyDiff normalize(boolean value) {\n this.normalize = value;\n return this;\n }\n\n /* -------\n Actions\n ------- */\n\n /**\n * Performs the comparison\n * @return A list of {@link Diff} objects that represent the differences between the left and right sides of the\n * comparison. Can be empty but not {@code null}\n */\n public List<Diff> compare() {\n DiffRunner diffRunner = ArrayUtils.isNotEmpty(leftPaths) && ArrayUtils.isNotEmpty(rightPaths)\n ? DiffRunner.forValues(leftPaths, leftLabel, rightPaths, rightLabel)\n : DiffRunner.forValues(leftStrings, leftLabel, rightStrings, rightLabel);\n TaskParameters taskParameters = TaskParameters\n .builder()\n .arrangeAttributes(arrangeAttributes)\n .columnWidth(columnWidth)\n .normalize(normalize)\n .ignoreSpaces(ignoreSpaces)\n .build();\n return diffRunner\n .withFilters(filters)\n .withContentType(contentType)\n .withTaskParameters(taskParameters)\n .run();\n }\n\n /**\n * Checks if the left and right sides of the comparison do not have pending differences. Either there are no\n * differences or all differences have been filtered out or else accepted as passable\n * @return True or false\n */\n public boolean isMatch() {\n List<Diff> differences = compare();\n return isMatch(differences);\n }\n\n /* ----------------\n Actions (static)\n ---------------- */\n\n /**\n * Checks if the specified list of {@link Diff} objects does not have pending differences. Either there are no\n * differences or all differences have been filtered out or else accepted as passable\n * @param value A list of {@code Diff} objects\n * @return True or false\n */\n public static boolean isMatch(List<Diff> value) {\n return CollectionUtils.isEmpty(value) || value.stream().allMatch(diff -> diff.getPendingCount() == 0);\n }\n}" }, { "identifier": "ContentType", "path": "core/src/main/java/com/exadel/etoolbox/anydiff/ContentType.java", "snippet": "@RequiredArgsConstructor(access = AccessLevel.PRIVATE)\n@Getter\npublic enum ContentType {\n\n UNDEFINED {\n @Override\n public boolean matchesMime(String value) {\n return false;\n }\n\n @Override\n boolean matchesExtension(String value) {\n return false;\n }\n },\n\n XML {\n @Override\n public boolean matchesMime(String value) {\n return StringUtils.containsIgnoreCase(value, \"xml\");\n }\n\n @Override\n boolean matchesExtension(String value) {\n return StringUtils.equalsIgnoreCase(value, \"xml\");\n }\n },\n\n HTML {\n @Override\n public boolean matchesMime(String value) {\n return StringUtils.containsIgnoreCase(value, \"html\");\n }\n\n @Override\n boolean matchesExtension(String value) {\n return StringUtils.equalsAnyIgnoreCase(\n value,\n \"htl\",\n \"html\",\n \"htm\");\n }\n },\n\n TEXT {\n @Override\n public boolean matchesMime(String value) {\n return StringUtils.containsIgnoreCase(value, \"text\");\n }\n\n @Override\n boolean matchesExtension(String value) {\n return StringUtils.equalsAnyIgnoreCase(\n value,\n \"css\",\n \"csv\",\n \"ecma\",\n \"info\",\n \"java\",\n \"jsp\",\n \"jspx\",\n \"js\",\n \"json\",\n \"log\",\n \"md\",\n \"mf\",\n \"php\",\n \"properties\",\n \"ts\",\n \"txt\");\n }\n };\n\n /**\n * Checks if the given MIME-type is matched by the current content type\n * @param value MIME-type to check\n * @return True or false\n */\n abstract boolean matchesMime(String value);\n\n /**\n * Checks if the given file extension is matched by the current content type\n * @param value File extension to check\n * @return True or false\n */\n abstract boolean matchesExtension(String value);\n\n /**\n * Gets the content type that matches the given MIME type\n * @param value MIME-type\n * @return {@code ContentType} enum value\n */\n public static ContentType fromMimeType(String value) {\n if (StringUtils.isBlank(value)) {\n return UNDEFINED;\n }\n String effectiveType = StringUtils.substringBefore(value, \";\");\n for (ContentType contentType : values()) {\n if (contentType.matchesMime(effectiveType)) {\n return contentType;\n }\n }\n return UNDEFINED;\n }\n\n /**\n * Gets the content type that matches the given file extension\n * @param value File extension\n * @return {@code ContentType} enum value\n */\n public static ContentType fromExtension(String value) {\n if (StringUtils.isBlank(value)) {\n return UNDEFINED;\n }\n for (ContentType contentType : values()) {\n if (contentType.matchesExtension(value)) {\n return contentType;\n }\n }\n return UNDEFINED;\n }\n}" }, { "identifier": "DiffTask", "path": "core/src/main/java/com/exadel/etoolbox/anydiff/comparison/DiffTask.java", "snippet": "@Builder(builderClassName = \"Builder\")\npublic class DiffTask {\n\n private static final UnaryOperator<String> EMPTY_NORMALIZER = StringUtils::defaultString;\n\n private final ContentType contentType;\n\n private final String leftId;\n private String leftLabel;\n private final Object leftContent;\n\n private final String rightId;\n private String rightLabel;\n private final Object rightContent;\n\n private final Predicate<DiffEntry> filter;\n\n private DiffState anticipatedState;\n\n private TaskParameters taskParameters;\n\n /* ------------------\n Property accessors\n ------------------ */\n\n private Preprocessor getPreprocessor(String contentId) {\n return Preprocessor.forType(contentType, taskParameters).withContentId(contentId);\n }\n\n private Postprocessor getPostprocessor() {\n return Postprocessor.forType(contentType, taskParameters);\n }\n\n /* ---------\n Execution\n --------- */\n\n /**\n * Performs the comparison between the left and right content\n * @return {@link Diff} object\n */\n public Diff run() {\n if (Objects.equals(leftContent, rightContent)) {\n return new DiffImpl(leftId, rightId); // This object will report the \"equals\" state\n }\n int columnWidth = taskParameters.getColumnWidth() - 1;\n if (anticipatedState == DiffState.CHANGE) {\n BlockImpl change = BlockImpl\n .builder()\n .leftLabel(leftLabel)\n .rightLabel(rightLabel)\n .columnWidth(columnWidth)\n .lines(Collections.singletonList(new LineImpl(\n new MarkedString(String.valueOf(leftContent)).markPlaceholders(Marker.DELETE),\n new MarkedString(String.valueOf(rightContent)).markPlaceholders(Marker.INSERT)\n )))\n .build(DisparityBlockImpl::new);\n return new DiffImpl(leftId, rightId).withChildren(change);\n }\n if (leftContent == null || anticipatedState == DiffState.LEFT_MISSING) {\n MissBlockImpl miss = MissBlockImpl\n .left(rightId)\n .leftLabel(leftLabel)\n .rightLabel(rightLabel)\n .columnWidth(columnWidth)\n .build();\n return new DiffImpl(leftId, rightId).withChildren(miss);\n }\n if (rightContent == null || anticipatedState == DiffState.RIGHT_MISSING) {\n MissBlockImpl miss = MissBlockImpl\n .right(leftId)\n .leftLabel(leftLabel)\n .rightLabel(rightLabel)\n .columnWidth(columnWidth)\n .build();\n return new DiffImpl(leftId, rightId).withChildren(miss);\n }\n return contentType == ContentType.UNDEFINED ? runForBinary() : runForText();\n }\n\n private Diff runForBinary() {\n DiffImpl result = new DiffImpl(leftId, rightId);\n DisparityBlockImpl disparity = DisparityBlockImpl\n .builder()\n .leftContent(leftContent)\n .rightContent(rightContent)\n .columnWidth(taskParameters.getColumnWidth() - 1)\n .leftLabel(leftLabel)\n .rightLabel(rightLabel)\n .build(DisparityBlockImpl::new);\n return result.withChildren(disparity);\n }\n\n private Diff runForText() {\n DiffRowGenerator generator = DiffRowGenerator\n .create()\n .ignoreWhiteSpaces(taskParameters.ignoreSpaces())\n .showInlineDiffs(true)\n .oldTag(isStart -> isStart ? Marker.DELETE.toString() : Marker.RESET.toString())\n .newTag(isStart -> isStart ? Marker.INSERT.toString() : Marker.RESET.toString())\n .lineNormalizer(EMPTY_NORMALIZER) // One needs this to override the OOTB preprocessor that spoils HTML\n .inlineDiffBySplitter(SplitterUtil::getTokens)\n .build();\n String leftPreprocessed = getPreprocessor(leftId).apply(leftContent.toString());\n String rightPreprocessed = getPreprocessor(rightId).apply(rightContent.toString());\n List<String> leftLines = StringUtil.splitByNewline(leftPreprocessed);\n List<String> rightLines = StringUtil.splitByNewline(rightPreprocessed);\n List<DiffRow> diffRows = getPostprocessor().apply(generator.generateDiffRows(leftLines, rightLines));\n\n DiffImpl result = new DiffImpl(leftId, rightId);\n List<AbstractBlock> blocks = getDiffBlocks(diffRows)\n .stream()\n .peek(block -> block.setDiff(result))\n .filter(filter != null ? filter : entry -> true)\n .collect(Collectors.toList());\n return result.withChildren(blocks);\n }\n\n private List<AbstractBlock> getDiffBlocks(List<DiffRow> allRows) {\n List<AbstractBlock> result = new ArrayList<>();\n BlockImpl pendingDiffBlock = null;\n for (int i = 0; i < allRows.size(); i++) {\n DiffRow row = allRows.get(i);\n boolean isNeutralRow = row.getTag() == DiffRow.Tag.EQUAL;\n boolean isNonNeutralStreakEnding = isNeutralRow && pendingDiffBlock != null;\n if (isNonNeutralStreakEnding) {\n pendingDiffBlock.addContext(row);\n result.add(pendingDiffBlock);\n pendingDiffBlock = null;\n }\n if (isNeutralRow) {\n continue;\n }\n if (pendingDiffBlock == null) {\n List<DiffRow> lookbehindContext = getLookbehindContext(allRows, i);\n pendingDiffBlock = BlockImpl\n .builder()\n .path(getContextPath(allRows, i))\n .compactify(taskParameters.normalize())\n .contentType(contentType)\n .ignoreSpaces(taskParameters.ignoreSpaces())\n .leftLabel(leftLabel)\n .rightLabel(rightLabel)\n .columnWidth(taskParameters.getColumnWidth() - 1)\n .build(BlockImpl::new);\n pendingDiffBlock.addContext(lookbehindContext);\n }\n pendingDiffBlock.add(row);\n }\n if (pendingDiffBlock != null) {\n result.add(pendingDiffBlock);\n }\n return result;\n }\n\n private String getContextPath(List<DiffRow> allRows, int position) {\n if (contentType != ContentType.HTML && contentType != ContentType.XML) {\n return StringUtils.EMPTY;\n }\n return PathUtil.getPath(allRows, position);\n }\n\n private List<DiffRow> getLookbehindContext(List<DiffRow> allRows, int position) {\n if (position == 0) {\n return null;\n }\n if (contentType != ContentType.HTML && contentType != ContentType.XML) {\n return Collections.singletonList(allRows.get(position - 1));\n }\n\n int nearestTagRowIndex = PathUtil.getPrecedingTagRowIndex(allRows, position - 1);\n if (nearestTagRowIndex >= 0) {\n return truncateContext(allRows.subList(nearestTagRowIndex, position));\n }\n return Collections.singletonList(allRows.get(position - 1));\n }\n\n private static List<DiffRow> truncateContext(List<DiffRow> rows) {\n if (rows.size() <= Constants.MAX_CONTEXT_LENGTH) {\n return rows;\n }\n List<DiffRow> upperPart = rows.subList(0, Constants.MAX_CONTEXT_LENGTH / 2);\n List<DiffRow> lowerPart = rows.subList(rows.size() - Constants.MAX_CONTEXT_LENGTH / 2, rows.size());\n List<DiffRow> result = new ArrayList<>(upperPart);\n result.add(new DiffRow(DiffRow.Tag.EQUAL, Marker.ELLIPSIS, Marker.ELLIPSIS));\n result.addAll(lowerPart);\n return result;\n }\n\n /**\n * Creates a builder for constructing a new {@code DiffTask} object\n * @return {@link DiffTask.Builder} instance\n */\n public static Builder builder() {\n return new InitializingBuilder();\n }\n\n /**\n * Constructs a new {@code DiffTask} instance with critical values initialized\n */\n private static class InitializingBuilder extends DiffTask.Builder {\n @Override\n public DiffTask build() {\n DiffTask result = super.build();\n\n TaskParameters perRequest = result.taskParameters;\n TaskParameters perContentType = TaskParameters.from(result.contentType);\n result.taskParameters = TaskParameters.merge(perContentType, perRequest);\n\n if (result.anticipatedState == null) {\n result.anticipatedState = DiffState.UNCHANGED;\n }\n\n result.leftLabel = StringUtils.defaultIfBlank(result.leftLabel, Constants.LABEL_LEFT);\n result.rightLabel = StringUtils.defaultIfBlank(result.rightLabel, Constants.LABEL_RIGHT);\n\n return result;\n }\n }\n}" }, { "identifier": "Diff", "path": "core/src/main/java/com/exadel/etoolbox/anydiff/diff/Diff.java", "snippet": "public interface Diff extends PrintableEntry, EntryHolder {\n\n /**\n * Gets the \"kind\" of difference. E.g., \"change\", \"insertion\", \"deletion\", etc.\n * @return {@link DiffState} instance\n */\n DiffState getState();\n\n /**\n * Gets the number of differences detected between the two pieces of content represented by the current {@link Diff}\n * @return Integer value\n */\n int getCount();\n\n /**\n * Gets the number of differences detected between the two pieces of content represented by the current {@link Diff}.\n * Counts only the differences that have not been \"silenced\" (accepted) with a {@link Filter}\n * @return Integer value\n */\n int getPendingCount();\n\n /**\n * Gets the left part of the comparison\n * @return String value\n */\n String getLeft();\n\n /**\n * Gets the right part of the comparison\n * @return String value\n */\n String getRight();\n}" }, { "identifier": "DiffEntry", "path": "core/src/main/java/com/exadel/etoolbox/anydiff/diff/DiffEntry.java", "snippet": "public interface DiffEntry extends Adaptable {\n\n /* ---------\n Accessors\n --------- */\n\n /**\n * Gets the {@link Diff} instance this entry belongs to\n * @return {@link Diff} instance\n */\n Diff getDiff();\n\n /**\n * Gets the name to distinguish the type of difference. Defaults to the name of the implementing class\n * @return String value. A non-empty string is expected\n */\n default String getName() {\n return StringUtils.removeEnd(getClass().getSimpleName(), \"Impl\");\n }\n\n /*\n * Gets the \"kind\" of difference. E.g., \"change\", \"insertion\", \"deletion\", etc.\n * @return {@link DiffState} instance\n */\n DiffState getState();\n\n /* -------\n Content\n ------- */\n\n /**\n * Gets the left part of the comparison included in the current difference\n * @return String value\n */\n default String getLeft() {\n return getLeft(false);\n }\n\n /**\n * Gets the left part of the comparison included in the current difference\n * @param includeContext If set to true, the \"context\" elements (those going before and after the actual difference)\n * are added to the result. Otherwise, only the difference itself is returned\n * @return String value\n */\n String getLeft(boolean includeContext);\n\n /**\n * Gets the right part of the comparison included in the current difference\n * @return String value\n */\n default String getRight() {\n return getRight(false);\n }\n\n /**\n * Gets the right part of the comparison included in the current difference\n * @param includeContext If set to true, the \"context\" elements (those going before and after the actual\n * difference)\n * @return String value\n */\n String getRight(boolean includeContext);\n\n /* ----------\n Operations\n ---------- */\n\n /**\n * Accepts the difference, that is, silences it so that it no longer leads to the {@link AnyDiff} reporting a\n * mismatch. However, the difference is still included in the {@link Diff} and can be displayed to the user\n */\n void accept();\n}" }, { "identifier": "EntryHolder", "path": "core/src/main/java/com/exadel/etoolbox/anydiff/diff/EntryHolder.java", "snippet": "public interface EntryHolder {\n\n /**\n * Gets the list of child {@link DiffEntry} instances\n * @return {@code List} of {@code DiffEntry} instances\n */\n List<? extends DiffEntry> children();\n\n /**\n * Instructs the {@code EntryHolder} to exclude the specified {@link DiffEntry} from the list of its children\n * @param value {@code DiffEntry} instance to exclude\n */\n void exclude(DiffEntry value);\n}" }, { "identifier": "Fragment", "path": "core/src/main/java/com/exadel/etoolbox/anydiff/diff/Fragment.java", "snippet": "public interface Fragment extends CharSequence, Adaptable {\n\n /**\n * Gets the string (either the left or the right part of the comparison) this {@link Fragment} belongs to\n * @return A non-null string\n */\n String getSource();\n\n /**\n * Gets whether this {@link Fragment} represents an insertion (i.e., a part of the line to the right that is missing\n * in the line to the left)\n * @return True or false\n */\n boolean isInsert();\n\n /**\n * Gets whether this {@link Fragment} represents a deletion (i.e., a part of the line to the left that is missing in\n * the line to the right)\n * @return True or false\n */\n boolean isDelete();\n\n /**\n * Gets whether the difference is \"pending\", that is, has not been silenced and will eventually make\n * {@link AnyDiff} report a mismatch\n * @return True or false\n */\n default boolean isPending() {\n return isInsert() || isDelete();\n }\n\n /**\n * Gets whether this {@link Fragment} equals to the provided other string content-wise\n * @param other String value to compare to\n * @return True or false\n */\n default boolean equals(String other) {\n return StringUtils.equals(toString(), other);\n }\n}" }, { "identifier": "FragmentHolder", "path": "core/src/main/java/com/exadel/etoolbox/anydiff/diff/FragmentHolder.java", "snippet": "public interface FragmentHolder {\n\n /* -------\n Content\n ------- */\n\n /**\n * Gets the list of {@link Fragment} instances from the left side of the comparison\n * @return A list of {@code Fragment} objects\n */\n List<Fragment> getLeftFragments();\n\n /**\n * Gets the list of {@link Fragment} instances from the right side of the comparison\n * @return A list of {@code Fragment} objects\n */\n List<Fragment> getRightFragments();\n\n /**\n * Gets the list of {@link Fragment} instances from both sides of the comparison\n * @return A list of {@code Fragment} objects\n */\n default List<Fragment> getFragments() {\n return Stream.concat(getLeftFragments().stream(), getRightFragments().stream()).collect(Collectors.toList());\n }\n\n /* ----------\n Operations\n ---------- */\n\n /**\n * Accepts the fragment, that is, silences it so that it no longer leads to the {@link AnyDiff} reporting a\n * mismatch. However, the fragment is still included in the {@link Diff} and can be displayed to the user\n */\n void accept(Fragment value);\n\n /**\n * Instructs the {@code FragmentHolder} to exclude the specified {@link Fragment} from the list of its children\n * @param value {@code Fragment} object to exclude\n */\n void exclude(Fragment value);\n}" }, { "identifier": "FragmentPair", "path": "core/src/main/java/com/exadel/etoolbox/anydiff/diff/FragmentPair.java", "snippet": "public interface FragmentPair {\n\n /**\n * Gets the left fragment of the pair\n * @return String value\n */\n String getLeft();\n\n /**\n * Gets the right fragment of the pair\n * @return String value\n */\n String getRight();\n\n /**\n * Gets the left fragment of the pair as a {@link Fragment} instance\n * @return {@code Fragment} instance\n */\n Fragment getLeftFragment();\n\n /**\n * Gets the right fragment of the pair as a {@link Fragment} instance\n * @return {@code Fragment} instance\n */\n Fragment getRightFragment();\n\n /**\n * Accepts the pair of fragments, that is, silences them so that they no longer lead to the {@link AnyDiff}\n * reporting a mismatch. However, the pair is still included in the {@link Diff} and can be displayed to the\n * user\n */\n void accept();\n}" }, { "identifier": "MarkupFragment", "path": "core/src/main/java/com/exadel/etoolbox/anydiff/diff/MarkupFragment.java", "snippet": "public interface MarkupFragment extends Fragment {\n\n /**\n * Gets whether the current fragment is situated inside an XML/HTML attribute with the given name\n * @param name Name of the attribute. A non-empty string value is expected\n * @return True or false\n */\n boolean isAttributeValue(String name);\n\n /**\n * Gets whether the current fragment is situated inside an XML/HTML tag with the given name (that is, in between the\n * {@code <tag...} opener and the closing or self-closing ({@code >} or {@code />}) bracket)\n * @param name Name of the tag. A non-empty string value is expected\n * @return True or false\n */\n boolean isInsideTag(String name);\n\n /**\n * Gets whether the current fragment is situated inside the content (that is, anywhere among the children) of an\n * XML/HTML tag with the given name\n * @param name Name of the tag. A non-empty string value is expected\n * @return True or false\n */\n boolean isTagContent(String name);\n}" }, { "identifier": "Filter", "path": "core/src/main/java/com/exadel/etoolbox/anydiff/filter/Filter.java", "snippet": "public interface Filter {\n\n /**\n * When overridden in a derived class, instructs the {@code Filter} to accept (\"silence\") the specified {@link Diff}\n * object\n * @param value {@code Diff} object. A non-null value is expected\n * @return {@code True} if the {@code Diff} object is processed and accepted, {@code false} otherwise\n */\n default boolean acceptDiff(Diff value) {\n return false;\n }\n\n /**\n * When overridden in a derived class, instructs the {@code Filter} to exclude the specified {@link Diff} object\n * from the result of the comparison\n * @param value {@code Diff} object. A non-null value is expected\n * @return {@code True} if the {@code Diff} object is processed and accepted, {@code false} otherwise\n */\n default boolean skipDiff(Diff value) {\n return false;\n }\n\n /**\n * When overridden in a derived class, instructs the {@code Filter} to accept (\"silence\") the specified\n * {@link DiffEntry} object representing a text block\n * @param value {@code DiffEntry} object. A non-null value is expected\n * @return {@code True} if the {@code DiffEntry} object is processed and accepted, {@code false} otherwise\n */\n default boolean acceptBlock(DiffEntry value) {\n return false;\n }\n\n /**\n * When overridden in a derived class, instructs the {@code Filter} to exclude the specified {@link DiffEntry}\n * object representing a text block from the result of the comparison\n * @param value {@code DiffEntry} object. A non-null value is expected\n * @return {@code True} if the {@code DiffEntry} object is processed and accepted, {@code false} otherwise\n */\n default boolean skipBlock(DiffEntry value) {\n return false;\n }\n\n /**\n * When overridden in a derived class, instructs the {@code Filter} to accept (\"silence\") the specified\n * {@link DiffEntry} object representing a line\n * @param value {@code DiffEntry} object. A non-null value is expected\n * @return {@code True} if the {@code DiffEntry} object is processed and accepted, {@code false} otherwise\n */\n default boolean acceptLine(DiffEntry value) {\n return false;\n }\n\n /**\n * When overridden in a derived class, instructs the {@code Filter} to exclude the specified {@link DiffEntry}\n * object representing a line from the result of the comparison\n * @param value {@code DiffEntry} object. A non-null value is expected\n * @return {@code True} if the {@code DiffEntry} object is processed and accepted, {@code false} otherwise\n */\n default boolean skipLine(DiffEntry value) {\n return false;\n }\n\n /**\n * When overridden in a derived class, instructs the {@code Filter} to accept (\"silence\") the specified\n * {@link FragmentPair} object\n * @param value {@code FragmentPair} object. A non-null value is expected\n * @return {@code True} if the {@code FragmentPair} object is processed and accepted, {@code false} otherwise\n */\n default boolean acceptFragments(FragmentPair value) {\n return false;\n }\n\n default boolean skipFragments(FragmentPair value) {\n return false;\n }\n\n /**\n * When overridden in a derived class, instructs the {@code Filter} to accept (\"silence\") the specified\n * {@link Fragment}\n * @param value {@code Fragment} object. A non-null value is expected\n * @return {@code True} if the {@code Fragment} object is processed and accepted, {@code false} otherwise\n */\n default boolean acceptFragment(Fragment value) {\n return false;\n }\n\n /**\n * When overridden in a derived class, instructs the {@code Filter} to exclude the specified {@link Fragment} from\n * the result of the comparison\n * @param value {@code Fragment} object. A non-null value is expected\n * @return {@code True} if the {@code Fragment} object is processed and accepted, {@code false} otherwise\n */\n default boolean skipFragment(Fragment value) {\n return false;\n }\n}" } ]
import java.util.List; import java.util.function.Predicate; import com.exadel.etoolbox.anydiff.AnyDiff; import com.exadel.etoolbox.anydiff.ContentType; import com.exadel.etoolbox.anydiff.comparison.DiffTask; import com.exadel.etoolbox.anydiff.diff.Diff; import com.exadel.etoolbox.anydiff.diff.DiffEntry; import com.exadel.etoolbox.anydiff.diff.EntryHolder; import com.exadel.etoolbox.anydiff.diff.Fragment; import com.exadel.etoolbox.anydiff.diff.FragmentHolder; import com.exadel.etoolbox.anydiff.diff.FragmentPair; import com.exadel.etoolbox.anydiff.diff.MarkupFragment; import com.exadel.etoolbox.anydiff.filter.Filter; import lombok.RequiredArgsConstructor; import org.junit.Assert; import org.junit.Test; import java.util.Arrays; import java.util.Collections;
9,471
/* * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.exadel.etoolbox.anydiff.runner; public class FilterHelperTest { static final String LEFT = "Lorem ipsum\nDolor sit amet\nConsectetur adipiscing elit"; static final String RIGHT = "Lorem ipsum\nDolor sat amet\nConsectetur adipiscing elit"; @Test public void shouldNotFilterWhenNoRuleMatches() { List<? extends DiffEntry> entries = DiffTask.builder().leftContent(LEFT).rightContent(RIGHT).build().run().children(); Assert.assertEquals(1, entries.size()); // Number of blocks Assert.assertEquals(3, entries.get(0).as(EntryHolder.class).children().size()); // Number of lines in a block DiffEntry block = entries.get(0); Predicate<DiffEntry> processingFilter = FilterHelper.getEntryFilter(Collections.singletonList(new SkipNone())); Assert.assertTrue(processingFilter.test(block)); } @Test public void shouldFilterFullDiff() { List<Diff> result = new AnyDiff() .left(LEFT) .right(RIGHT) .filter(Collections.singletonList(new SkipAnyDiff())) .compare(); Assert.assertTrue(result.isEmpty()); } @Test public void shouldFilterByBlock() { List<? extends DiffEntry> entries = DiffTask .builder() .leftContent(LEFT) .rightContent(RIGHT.replace("elit", "ilet")) .build() .run() .children(); Assert.assertEquals(1, entries.size()); DiffEntry block = entries.get(0); Predicate<DiffEntry> processingFilter = FilterHelper.getEntryFilter(Collections.singletonList(new SkipBlock())); Assert.assertFalse(processingFilter.test(block)); } @Test public void shouldFilterByLine() { List<? extends DiffEntry> entries = DiffTask .builder() .leftContent(LEFT) .rightContent(RIGHT) .build() .run() .children(); Assert.assertEquals(1, entries.size()); DiffEntry block = entries.get(0); Predicate<DiffEntry> processingFilter = FilterHelper.getEntryFilter(Collections.singletonList(new SkipWhenContainsFragment("sit"))); Assert.assertFalse(processingFilter.test(block)); } @Test public void shouldFilterByFragmentPair() { List<? extends DiffEntry> entries = DiffTask .builder() .leftContent(LEFT) .rightContent(RIGHT) .build() .run() .children(); Assert.assertEquals(1, entries.size()); DiffEntry block = entries.get(0); Predicate<DiffEntry> processingFilter = FilterHelper.getEntryFilter(Arrays.asList( new SkipNone(), new SkipFragmentPair("sit", "sat"))); Assert.assertFalse(processingFilter.test(block)); } @Test public void shouldFilterMarkupByFragmentPair() { List<? extends DiffEntry> entries = DiffTask .builder() .contentType(ContentType.HTML) .leftContent("<div class=\"lorem\">Lorem <span>ipsum</span> dolor sit amet</div> consectetur adipiscing elit") .rightContent("<div class=\"lorum\">Lorem <span>dolorum</span> dolor sat amet</div> consectetur adipiscing elet") .build() .run() .children(); Assert.assertEquals(3, entries.size()); DiffEntry block0 = entries.get(0); Predicate<DiffEntry> processingFilter = FilterHelper.getEntryFilter(Arrays.asList(new SkipNone(), new SkipMarkupFragments())); boolean testResult = processingFilter.test(block0);
/* * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.exadel.etoolbox.anydiff.runner; public class FilterHelperTest { static final String LEFT = "Lorem ipsum\nDolor sit amet\nConsectetur adipiscing elit"; static final String RIGHT = "Lorem ipsum\nDolor sat amet\nConsectetur adipiscing elit"; @Test public void shouldNotFilterWhenNoRuleMatches() { List<? extends DiffEntry> entries = DiffTask.builder().leftContent(LEFT).rightContent(RIGHT).build().run().children(); Assert.assertEquals(1, entries.size()); // Number of blocks Assert.assertEquals(3, entries.get(0).as(EntryHolder.class).children().size()); // Number of lines in a block DiffEntry block = entries.get(0); Predicate<DiffEntry> processingFilter = FilterHelper.getEntryFilter(Collections.singletonList(new SkipNone())); Assert.assertTrue(processingFilter.test(block)); } @Test public void shouldFilterFullDiff() { List<Diff> result = new AnyDiff() .left(LEFT) .right(RIGHT) .filter(Collections.singletonList(new SkipAnyDiff())) .compare(); Assert.assertTrue(result.isEmpty()); } @Test public void shouldFilterByBlock() { List<? extends DiffEntry> entries = DiffTask .builder() .leftContent(LEFT) .rightContent(RIGHT.replace("elit", "ilet")) .build() .run() .children(); Assert.assertEquals(1, entries.size()); DiffEntry block = entries.get(0); Predicate<DiffEntry> processingFilter = FilterHelper.getEntryFilter(Collections.singletonList(new SkipBlock())); Assert.assertFalse(processingFilter.test(block)); } @Test public void shouldFilterByLine() { List<? extends DiffEntry> entries = DiffTask .builder() .leftContent(LEFT) .rightContent(RIGHT) .build() .run() .children(); Assert.assertEquals(1, entries.size()); DiffEntry block = entries.get(0); Predicate<DiffEntry> processingFilter = FilterHelper.getEntryFilter(Collections.singletonList(new SkipWhenContainsFragment("sit"))); Assert.assertFalse(processingFilter.test(block)); } @Test public void shouldFilterByFragmentPair() { List<? extends DiffEntry> entries = DiffTask .builder() .leftContent(LEFT) .rightContent(RIGHT) .build() .run() .children(); Assert.assertEquals(1, entries.size()); DiffEntry block = entries.get(0); Predicate<DiffEntry> processingFilter = FilterHelper.getEntryFilter(Arrays.asList( new SkipNone(), new SkipFragmentPair("sit", "sat"))); Assert.assertFalse(processingFilter.test(block)); } @Test public void shouldFilterMarkupByFragmentPair() { List<? extends DiffEntry> entries = DiffTask .builder() .contentType(ContentType.HTML) .leftContent("<div class=\"lorem\">Lorem <span>ipsum</span> dolor sit amet</div> consectetur adipiscing elit") .rightContent("<div class=\"lorum\">Lorem <span>dolorum</span> dolor sat amet</div> consectetur adipiscing elet") .build() .run() .children(); Assert.assertEquals(3, entries.size()); DiffEntry block0 = entries.get(0); Predicate<DiffEntry> processingFilter = FilterHelper.getEntryFilter(Arrays.asList(new SkipNone(), new SkipMarkupFragments())); boolean testResult = processingFilter.test(block0);
List<Fragment> fragments = block0.as(EntryHolder.class).children().get(1).as(FragmentHolder.class).getFragments();
7
2023-11-16 14:29:45+00:00
12k
Walter-Stroebel/Jllama
src/main/java/nl/infcomtec/jllama/OllamaChatFrame.java
[ { "identifier": "ImageObject", "path": "src/main/java/nl/infcomtec/simpleimage/ImageObject.java", "snippet": "public class ImageObject extends Image {\n\n private BufferedImage image;\n private final Semaphore lock = new Semaphore(0);\n private final List<ImageObjectListener> listeners = new LinkedList<>();\n\n public ImageObject(Image image) {\n putImage(image);\n }\n\n /**\n * @return The most recent image.\n */\n public BufferedImage getImage() {\n return image;\n }\n\n /**\n * Stay informed.\n *\n * @param listener called when another client changes the image.\n */\n public synchronized void addListener(ImageObjectListener listener) {\n listeners.add(listener);\n }\n\n void sendSignal(Object msg) {\n for (ImageObjectListener listener : listeners) {\n listener.signal(msg);\n }\n }\n\n public enum MouseEvents {\n clicked_left, clicked_right, dragged, moved, pressed_left, released_left, pressed_right, released_right\n };\n\n public synchronized void forwardMouse(MouseEvents ev, Point2D p) {\n for (ImageObjectListener listener : listeners) {\n listener.mouseEvent(this, ev, p);\n }\n }\n\n /**\n * Replace image.\n *\n * @param replImage If null image may still have been altered in place, else\n * replace image with replImage. All listeners will be notified.\n */\n public synchronized final void putImage(Image replImage) {\n int oldWid = null == this.image ? 0 : this.image.getWidth();\n if (null != replImage) {\n this.image = new BufferedImage(replImage.getWidth(null), replImage.getHeight(null), BufferedImage.TYPE_INT_ARGB);\n Graphics2D g2 = this.image.createGraphics();\n g2.drawImage(replImage, 0, 0, null);\n g2.dispose();\n }\n for (ImageObjectListener listener : listeners) {\n if (0 == oldWid) {\n listener.imageChanged(this, 1.0);\n } else {\n listener.imageChanged(this, 1.0 * oldWid / this.image.getWidth());\n }\n }\n }\n\n public int getWidth() {\n return getWidth(null);\n }\n\n @Override\n public int getWidth(ImageObserver io) {\n return image.getWidth(io);\n }\n\n @Override\n public int getHeight(ImageObserver io) {\n return image.getHeight(io);\n }\n\n public int getHeight() {\n return getHeight(null);\n }\n\n @Override\n public ImageProducer getSource() {\n return image.getSource();\n }\n\n @Override\n public Graphics getGraphics() {\n return image.getGraphics();\n }\n\n @Override\n public Object getProperty(String string, ImageObserver io) {\n return image.getProperty(string, null);\n }\n\n public HashMap<String, BitShape> calculateClosestAreas(final Map<String, Point2D> pois) {\n long nanos = System.nanoTime();\n final HashMap<String, BitShape> ret = new HashMap<>();\n for (Map.Entry<String, Point2D> e : pois.entrySet()) {\n ret.put(e.getKey(), new BitShape(getWidth()));\n }\n\n int numThreads = Runtime.getRuntime().availableProcessors() - 2; // Number of threads to use, leaving some cores for routine work.\n if (numThreads < 1) {\n numThreads = 1;\n }\n ExecutorService executor = Executors.newFixedThreadPool(numThreads);\n\n int rowsPerThread = getHeight() / numThreads;\n for (int i = 0; i < numThreads; i++) {\n final int yStart = i * rowsPerThread;\n final int yEnd = (i == numThreads - 1) ? getHeight() : yStart + rowsPerThread;\n executor.submit(new Runnable() {\n @Override\n public void run() {\n for (int y = yStart; y < yEnd; y++) {\n for (int x = 0; x < getWidth(); x++) {\n double d = 0;\n String poi = null;\n for (Map.Entry<String, Point2D> e : pois.entrySet()) {\n double d2 = e.getValue().distance(x, y);\n if (poi == null || d2 < d) {\n poi = e.getKey();\n d = d2;\n }\n }\n synchronized (ret.get(poi)) {\n ret.get(poi).set(new Point2D.Double(x, y));\n }\n }\n }\n }\n });\n }\n executor.shutdown();\n try {\n if (!executor.awaitTermination(1, TimeUnit.MINUTES)) {\n throw new RuntimeException(\"This cannot be right.\");\n }\n } catch (InterruptedException ex) {\n throw new RuntimeException(\"We are asked to stop?\", ex);\n }\n System.out.format(\"calculateClosestAreas W=%d,H=%d,P=%d,T=%.2f ms\\n\",\n getWidth(), getHeight(), pois.size(), (System.nanoTime() - nanos) / 1e6);\n return ret;\n }\n\n /**\n * Callback listener.\n */\n public static class ImageObjectListener {\n\n public final String name;\n\n public ImageObjectListener(String name) {\n this.name = name;\n }\n\n /**\n * Image may have been altered.\n *\n * @param imgObj Source.\n * @param resizeHint The width of the previous image divided by the\n * width of the new image. See ImageViewer why this is useful.\n */\n public void imageChanged(ImageObject imgObj, double resizeHint) {\n // default is no action\n }\n\n /**\n * Used to forward mouse things by viewer implementations.\n *\n * @param imgObj Source.\n * @param ev Our event definition.\n * @param p Point of the event in image pixels.\n */\n public void mouseEvent(ImageObject imgObj, MouseEvents ev, Point2D p) {\n // default ignore\n }\n\n /**\n * Generic signal, generally causes viewer implementations to repaint.\n *\n * @param any\n */\n public void signal(Object any) {\n // default ignore\n }\n }\n}" }, { "identifier": "ImageViewer", "path": "src/main/java/nl/infcomtec/simpleimage/ImageViewer.java", "snippet": "public class ImageViewer {\n\n private static final int MESSAGE_HEIGHT = 200;\n private static final int MESSAGE_WIDTH = 800;\n public List<Component> tools;\n private String message = null;\n private long messageMillis = 0;\n private long shownLast = 0;\n private Font messageFont = UIManager.getFont(\"Label.font\");\n\n protected final ImageObject imgObj;\n private LUT lut;\n private List<Marker> marks;\n\n public ImageViewer(ImageObject imgObj) {\n this.imgObj = imgObj;\n }\n\n public ImageViewer(Image image) {\n imgObj = new ImageObject(image);\n }\n\n public synchronized void flashMessage(Font font, String msg, long millis) {\n messageFont = font;\n messageMillis = millis;\n message = msg;\n shownLast = 0;\n imgObj.sendSignal(null);\n }\n\n public synchronized void flashMessage(String msg, long millis) {\n flashMessage(messageFont, msg, millis);\n }\n\n public synchronized void flashMessage(String msg) {\n flashMessage(messageFont, msg, 3000);\n }\n\n public synchronized void addMarker(Marker marker) {\n if (null == marks) {\n marks = new LinkedList<>();\n }\n marks.add(marker);\n imgObj.putImage(null);\n }\n\n public synchronized void clearMarkers() {\n marks = null;\n imgObj.putImage(null);\n }\n\n public ImageViewer(File f) {\n ImageObject tmp;\n try {\n tmp = new ImageObject(ImageIO.read(f));\n } catch (Exception ex) {\n tmp = showError(f);\n }\n imgObj = tmp;\n }\n\n /**\n * Although there are many reasons an image may not load, all we can do\n * about it is tell the user by creating an image with the failure.\n *\n * @param f File we tried to load.\n */\n private ImageObject showError(File f) {\n BufferedImage img = new BufferedImage(MESSAGE_WIDTH, MESSAGE_HEIGHT, BufferedImage.TYPE_BYTE_BINARY);\n Graphics2D gr = img.createGraphics();\n String msg1 = \"Cannot open image:\";\n String msg2 = f.getAbsolutePath();\n Font font = gr.getFont();\n float points = 24;\n int w, h;\n do {\n font = font.deriveFont(points);\n gr.setFont(font);\n FontMetrics metrics = gr.getFontMetrics(font);\n w = Math.max(metrics.stringWidth(msg1), metrics.stringWidth(msg2));\n h = metrics.getHeight() * 2; // For two lines of text\n if (w > MESSAGE_WIDTH - 50 || h > MESSAGE_HEIGHT / 3) {\n points--;\n }\n } while (w > MESSAGE_WIDTH || h > MESSAGE_HEIGHT / 3);\n gr.drawString(msg1, 50, MESSAGE_HEIGHT / 3);\n gr.drawString(msg2, 50, MESSAGE_HEIGHT / 3 * 2);\n gr.dispose();\n return new ImageObject(img);\n }\n\n /**\n * Often images have overly bright or dark areas. This permits to have a\n * lighter or darker view.\n *\n * @return this for chaining.\n */\n public synchronized ImageViewer addShadowView() {\n ButtonGroup bg = new ButtonGroup();\n addChoice(bg, new AbstractAction(\"Dark\") {\n @Override\n public void actionPerformed(ActionEvent ae) {\n lut = LUT.darker();\n imgObj.putImage(null);\n }\n });\n addChoice(bg, new AbstractAction(\"Normal\") {\n @Override\n public void actionPerformed(ActionEvent ae) {\n lut = LUT.unity();\n imgObj.putImage(null);\n }\n }, true);\n addChoice(bg, new AbstractAction(\"Bright\") {\n @Override\n public void actionPerformed(ActionEvent ae) {\n lut = LUT.brighter();\n imgObj.putImage(null);\n }\n });\n addChoice(bg, new AbstractAction(\"Brighter\") {\n @Override\n public void actionPerformed(ActionEvent ae) {\n lut = LUT.sqrt(0);\n imgObj.putImage(null);\n }\n });\n addChoice(bg, new AbstractAction(\"Extreme\") {\n @Override\n public void actionPerformed(ActionEvent ae) {\n lut = LUT.sqrt2();\n imgObj.putImage(null);\n }\n });\n return this;\n }\n\n /**\n * Add a choice,\n *\n * @param group If not null, only one choice in the group can be active.\n * @param action Choice.\n * @return For chaining.\n */\n public synchronized ImageViewer addChoice(ButtonGroup group, Action action) {\n return addChoice(group, action, false);\n }\n\n /**\n * Add a choice,\n *\n * @param group If not null, only one choice in the group can be active.\n * @param action Choice.\n * @param selected Only useful if true.\n * @return For chaining.\n */\n public synchronized ImageViewer addChoice(ButtonGroup group, Action action, boolean selected) {\n if (null == tools) {\n tools = new LinkedList<>();\n }\n JCheckBox button = new JCheckBox(action);\n button.setSelected(selected);\n if (null != group) {\n group.add(button);\n if (selected) {\n group.setSelected(button.getModel(), selected);\n }\n }\n tools.add(button);\n return this;\n }\n\n public synchronized ImageViewer addButton(Action action) {\n if (null == tools) {\n tools = new LinkedList<>();\n }\n tools.add(new JButton(action));\n return this;\n }\n\n public synchronized ImageViewer addMaxButton(String dsp) {\n if (null == tools) {\n tools = new LinkedList<>();\n }\n tools.add(new JButton(new AbstractAction(dsp) {\n @Override\n public void actionPerformed(ActionEvent ae) {\n imgObj.sendSignal(ScaleCommand.SCALE_MAX);\n }\n }));\n return this;\n }\n\n public synchronized ImageViewer addOrgButton(String dsp) {\n if (null == tools) {\n tools = new LinkedList<>();\n }\n tools.add(new JButton(new AbstractAction(dsp) {\n @Override\n public void actionPerformed(ActionEvent ae) {\n imgObj.sendSignal(ScaleCommand.SCALE_ORG);\n }\n }));\n return this;\n }\n\n public synchronized ImageViewer addAnything(Component comp) {\n if (null == tools) {\n tools = new LinkedList<>();\n }\n tools.add(comp);\n return this;\n }\n\n /**\n * Show the image in a JPanel component with simple pan(drag) and zoom(mouse\n * wheel).\n *\n * @return the JPanel.\n */\n public JPanel getScalePanPanel() {\n final JPanel ret = new JPanelImpl();\n return ret;\n }\n\n /**\n * Show the image in a JPanel component with simple pan(drag) and zoom(mouse\n * wheel). Includes a JToolbar if tools are provided, see add functions.\n *\n * @return the JPanel.\n */\n public JPanel getScalePanPanelTools() {\n final JPanel outer = new JPanel();\n outer.setLayout(new BorderLayout());\n outer.add(new JPanelImpl(), BorderLayout.CENTER);\n if (null != tools) {\n JToolBar tb = new JToolBar();\n for (Component c : tools) {\n tb.add(c);\n }\n outer.add(tb, BorderLayout.NORTH);\n }\n return outer;\n }\n\n /**\n * Show the image in a JFrame component with simple pan(drag) and zoom(mouse\n * wheel). Includes a JToolbar if tools are provided, see add functions.\n *\n * @return the JFrame.\n */\n public JFrame getScalePanFrame() {\n final JFrame ret = new JFrame();\n ret.setAlwaysOnTop(true);\n ret.getContentPane().setLayout(new BorderLayout());\n ret.getContentPane().add(new JPanelImpl(), BorderLayout.CENTER);\n if (null != tools) {\n JToolBar tb = new JToolBar();\n for (Component c : tools) {\n tb.add(c);\n }\n ret.getContentPane().add(tb, BorderLayout.NORTH);\n }\n ret.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);\n ret.pack();\n EventQueue.invokeLater(new Runnable() {\n @Override\n public void run() {\n ret.setVisible(true);\n }\n });\n return ret;\n }\n\n public ImageObject getImageObject() {\n return imgObj;\n }\n\n public enum ScaleCommand {\n SCALE_ORG, SCALE_MAX\n }\n\n private class JPanelImpl extends JPanel {\n\n int ofsX = 0;\n int ofsY = 0;\n double scale = 1;\n private BufferedImage dispImage = null;\n\n private Point pixelMouse(MouseEvent e) {\n int ax = e.getX() - ofsX;\n int ay = e.getY() - ofsY;\n ax = (int) Math.round(ax / scale);\n ay = (int) Math.round(ay / scale);\n return new Point(ax, ay);\n }\n\n public JPanelImpl() {\n MouseAdapter ma = new MouseAdapter() {\n private int lastX, lastY;\n\n @Override\n public void mousePressed(MouseEvent e) {\n if (SwingUtilities.isRightMouseButton(e)) {\n imgObj.forwardMouse(ImageObject.MouseEvents.pressed_right, pixelMouse(e));\n } else {\n lastX = e.getX();\n lastY = e.getY();\n }\n }\n\n @Override\n public void mouseReleased(MouseEvent e) {\n if (SwingUtilities.isRightMouseButton(e)) {\n imgObj.forwardMouse(ImageObject.MouseEvents.released_right, pixelMouse(e));\n } else {\n imgObj.forwardMouse(ImageObject.MouseEvents.released_left, pixelMouse(e));\n }\n }\n\n @Override\n public void mouseClicked(MouseEvent e) {\n if (SwingUtilities.isRightMouseButton(e)) {\n imgObj.forwardMouse(ImageObject.MouseEvents.clicked_right, pixelMouse(e));\n } else {\n imgObj.forwardMouse(ImageObject.MouseEvents.clicked_left, pixelMouse(e));\n }\n }\n\n @Override\n public void mouseDragged(MouseEvent e) {\n if (SwingUtilities.isRightMouseButton(e)) {\n imgObj.forwardMouse(ImageObject.MouseEvents.dragged, pixelMouse(e));\n } else {\n ofsX += e.getX() - lastX;\n ofsY += e.getY() - lastY;\n lastX = e.getX();\n lastY = e.getY();\n repaint(); // Repaint the panel to reflect the new position\n }\n }\n\n @Override\n public void mouseWheelMoved(MouseWheelEvent e) {\n int notches = e.getWheelRotation();\n scale += notches * 0.1; // Adjust the scaling factor\n if (scale < 0.1) {\n scale = 0.1; // Prevent the scale from becoming too small\n }\n dispImage = null;\n repaint(); // Repaint the panel to reflect the new scale\n }\n };\n addMouseListener(ma);\n addMouseMotionListener(ma);\n addMouseWheelListener(ma);\n imgObj.addListener(new ImageObject.ImageObjectListener(\"Repaint\") {\n @Override\n public void imageChanged(ImageObject imgObj, double resizeHint) {\n // If the image we are displaying is for instance 512 pixels and\n // the new image is 1536, we need to adjust scaling to match.\n scale *= resizeHint;\n dispImage = null;\n repaint(); // Repaint the panel to reflect any changes\n }\n\n @Override\n public void signal(Object any) {\n if (any instanceof ScaleCommand) {\n ScaleCommand sc = (ScaleCommand) any;\n switch (sc) {\n case SCALE_MAX: {\n double w = (1.0 * getWidth()) / imgObj.getWidth();\n double h = (1.0 * getHeight()) / imgObj.getHeight();\n System.out.format(\"%f %f %d %d\\n\", w, h, imgObj.getWidth(), getWidth());\n if (w > h) {\n scale = h;\n } else {\n scale = w;\n }\n }\n break;\n case SCALE_ORG: {\n scale = 1;\n }\n break;\n }\n dispImage = null;\n }\n repaint();\n }\n });\n Dimension dim = new Dimension(imgObj.getWidth(), imgObj.getHeight());\n setPreferredSize(dim);\n }\n\n @Override\n public void paint(Graphics g) {\n g.setColor(Color.DARK_GRAY);\n g.fillRect(0, 0, getWidth(), getHeight());\n if (null == dispImage) {\n int scaledWidth = (int) (imgObj.getWidth() * scale);\n int scaledHeight = (int) (imgObj.getHeight() * scale);\n dispImage = new BufferedImage(scaledWidth, scaledHeight, BufferedImage.TYPE_INT_ARGB);\n Graphics2D g2 = dispImage.createGraphics();\n g2.drawImage(imgObj.getScaledInstance(scaledWidth, scaledHeight, BufferedImage.SCALE_SMOOTH), 0, 0, null);\n g2.dispose();\n if (null != lut) {\n dispImage = lut.apply(dispImage);\n }\n if (null != marks) {\n for (Marker marker : marks) {\n marker.mark(dispImage);\n }\n }\n }\n g.drawImage(dispImage, ofsX, ofsY, null);\n if (null != message) {\n if (0 == shownLast) {\n shownLast = System.currentTimeMillis();\n }\n if (shownLast + messageMillis >= System.currentTimeMillis()) {\n g.setFont(messageFont);\n g.setColor(Color.WHITE);\n g.setXORMode(Color.BLACK);\n int ofs = g.getFontMetrics().getHeight();\n System.out.println(message + \" \" + ofs);\n g.drawString(message, ofs, ofs * 2);\n } else {\n message = null;\n shownLast = 0;\n }\n }\n }\n }\n}" }, { "identifier": "PandocConverter", "path": "src/main/java/nl/infcomtec/tools/PandocConverter.java", "snippet": "public class PandocConverter extends ToolManager {\n\n private String output;\n\n /**\n * Markdown to HTML.\n *\n * @param markdownInput Markdown.\n * @return HTML.\n */\n public String convertMarkdownToHTML(String markdownInput) {\n setInput(markdownInput);\n setCommand(\"pandoc\", \"-f\", \"markdown\", \"-t\", \"html\");\n run();\n return output;\n }\n\n /**\n * Markdown to RTF. Note that RTF support in Java is pretty broken.\n *\n * @param markdownInput Markdown.\n * @return HTML.\n */\n public String convertMarkdownToRTF(String markdownInput) {\n setInput(markdownInput);\n setCommand(\"pandoc\", \"-f\", \"markdown\", \"-t\", \"rtf\");\n run();\n return output;\n }\n\n /**\n * HTML to Markdown.\n *\n * @param htmlInput HTML.\n * @return Markdown.\n */\n public String convertHTMLToMarkdown(String htmlInput) {\n setInput(htmlInput);\n setCommand(\"pandoc\", \"-f\", \"html\", \"-t\", \"markdown\");\n run();\n return output;\n }\n\n /**\n * RTF to Markdown. Note that RTF support in Java is pretty broken.\n *\n * @param rtfInput HTML.\n * @return Markdown.\n */\n public String convertRTFToMarkdown(String rtfInput) {\n setInput(rtfInput);\n setCommand(\"pandoc\", \"-f\", \"rtf\", \"-t\", \"markdown\");\n run();\n return output;\n }\n\n /**\n * MarkDown to plain text.\n *\n * @param markdownInput Markdown.\n * @return Plain text.\n */\n public String convertMarkdownToText(String markdownInput) {\n setInput(markdownInput);\n setCommand(\"pandoc\", \"-f\", \"markdown\", \"--wrap=auto\", \"--columns=80\", \"-t\", \"plain\");\n run();\n return output;\n }\n\n /**\n * MarkDown to file.\n *\n * @param markdownInput Markdown.\n * @param file The result will be determined by the file's extension.\n */\n public void convertMarkdownToFile(String markdownInput, File file) {\n setInput(markdownInput);\n setCommand(\"pandoc\", \"-f\", \"markdown\", \"-o\", file.getAbsolutePath());\n run();\n }\n\n @Override\n public void run() {\n internalRun();\n if (exitCode != 0) {\n output = \"Running pandoc failed, rc=\" + exitCode;\n } else {\n\n if (stdoutStream instanceof ByteArrayOutputStream) {\n output = new String(((ByteArrayOutputStream) stdoutStream).toByteArray(), StandardCharsets.UTF_8);\n }\n }\n }\n\n /**\n * @return the output\n */\n public String getOutput() {\n return output;\n }\n}" } ]
import java.awt.BorderLayout; import java.awt.Color; import java.awt.Container; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.Font; import java.awt.Graphics2D; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Image; import java.awt.Insets; import java.awt.Toolkit; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.StringSelection; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicBoolean; import java.util.logging.Level; import java.util.logging.Logger; import javax.imageio.ImageIO; import javax.swing.AbstractAction; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JEditorPane; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenuItem; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JToolBar; import javax.swing.SwingWorker; import javax.swing.UIManager; import javax.swing.text.html.HTMLEditorKit; import javax.swing.text.html.StyleSheet; import nl.infcomtec.simpleimage.ImageObject; import nl.infcomtec.simpleimage.ImageViewer; import nl.infcomtec.tools.PandocConverter;
7,601
cont.add(pane, BorderLayout.CENTER); Box bottom = Box.createHorizontalBox(); input.setLineWrap(true); input.setWrapStyleWord(true); bottom.add(new JScrollPane(input)); bottom.add(Box.createHorizontalStrut(10)); bottom.add(new JButton(new Interact())); bottom.add(new JButton(new AbstractAction("\u2191 image") { @Override public void actionPerformed(ActionEvent ae) { JFileChooser fileChooser = new JFileChooser(); int returnValue = fileChooser.showOpenDialog(frame); if (returnValue == JFileChooser.APPROVE_OPTION) { File selectedFile = fileChooser.getSelectedFile(); try { BufferedImage originalImage = ImageIO.read(selectedFile); if (originalImage.getHeight() != 256 || originalImage.getWidth() != 256) { Image scaledInstance = originalImage.getScaledInstance(256, 256, BufferedImage.SCALE_SMOOTH); BufferedImage resizedImage = new BufferedImage(256, 256, BufferedImage.TYPE_INT_ARGB); Graphics2D g2d = resizedImage.createGraphics(); g2d.drawImage(scaledInstance, 0, 0, null); g2d.dispose(); uplImage = resizedImage; } else { uplImage = originalImage; } updateSideBar(null); } catch (IOException ex) { Logger.getLogger(OllamaChatFrame.class.getName()).log(Level.SEVERE, null, ex); uplImage = null; } } } })); bottom.setBorder(BorderFactory.createTitledBorder( BorderFactory.createLineBorder(new Color(135, 206, 250), 5), "Input")); cont.add(bottom, BorderLayout.SOUTH); cont.add(sideBar(), BorderLayout.EAST); frame.pack(); if (EventQueue.isDispatchThread()) { finishInit(); } else { try { EventQueue.invokeAndWait(new Runnable() { @Override public void run() { finishInit(); } }); } catch (Exception ex) { Logger.getLogger(OllamaChatFrame.class.getName()).log(Level.SEVERE, null, ex); System.exit(1); } } } private void buttonBar() { buttons.add(new AbstractAction("Exit") { @Override public void actionPerformed(ActionEvent ae) { System.exit(0); } }); buttons.add(new JToolBar.Separator()); String lsHost = Ollama.config.getLastEndpoint(); for (String e : Ollama.getAvailableModels().keySet()) { addToHosts(e); } client = new OllamaClient(lsHost); models.removeAllItems(); for (AvailableModels.AvailableModel am : Ollama.getAvailableModels().get(lsHost).models) { models.addItem(am.name); } if (null != Ollama.config.lastModel) { models.setSelectedItem(Ollama.config.lastModel); } models.invalidate(); hosts.setSelectedItem(lsHost); hosts.addActionListener(new AddSelectHost()); hosts.setEditable(true); buttons.add(new JLabel("Hosts:")); buttons.add(hosts); buttons.add(new JToolBar.Separator()); buttons.add(new JLabel("Models:")); buttons.add(models); buttons.add(new JToolBar.Separator()); buttons.add(new AbstractAction("HTML") { @Override public void actionPerformed(ActionEvent ae) { String markDown = chat.getText(); JFrame html = new JFrame("HTML"); html.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); html.getContentPane().setLayout(new BorderLayout()); JEditorPane pane = new JEditorPane(); pane.setContentType("text/html"); HTMLEditorKit kit = new HTMLEditorKit() { @Override public StyleSheet getStyleSheet() { StyleSheet styleSheet = super.getStyleSheet(); styleSheet.addRule("body { font-family: 'Arial'; font-size: " + Math.round(Ollama.config.fontSize) + "pt; }"); return styleSheet; } }; pane.setEditorKit(kit); pane.setText(new PandocConverter().convertMarkdownToHTML(markDown)); html.getContentPane().add(new JScrollPane(pane), BorderLayout.CENTER); html.pack(); html.setVisible(true); } }); buttons.add(new AbstractAction("Dall-E 3") { @Override public void actionPerformed(ActionEvent ae) { try { String text = chat.getSelectedText(); DallEClient dale = new DallEClient();
package nl.infcomtec.jllama; /** * This is a FULL Ollama chat window. It allow to chat with any model available * at will.<p> * Note that this displays some extra information along with the actual chat * which allows one to get a good insight in how the model performs.</p> * * @author Walter Stroebel */ public class OllamaChatFrame { private final JFrame frame; private final JToolBar buttons; private final JTextArea chat; private final JTextArea input; private OllamaClient client; private final JComboBox<String> hosts; private final JComboBox<String> models; private JLabel curCtxSize; private JLabel outTokens; private JLabel inTokens; private final AtomicBoolean autoMode = new AtomicBoolean(false); private final ExecutorService pool = Executors.newCachedThreadPool(); private JLabel tokensSec; private JLabel modFamily; private JLabel modFamilies; private JLabel modFormat; private JLabel modParmSize; private JLabel modQuant; private JLabel prevImage; private BufferedImage uplImage; /** * Ties all the bits and pieces together into a GUI. */ public OllamaChatFrame() { setupGUI(Ollama.config.fontSize); this.modQuant = new JLabel(); this.modParmSize = new JLabel(); this.modFormat = new JLabel(); this.modFamilies = new JLabel(); this.modFamily = new JLabel(); this.prevImage = new JLabel(); this.models = new JComboBox<>(); this.hosts = new JComboBox<>(); this.buttons = new JToolBar(); this.input = new JTextArea(4, 80); this.chat = new JTextArea(); frame = new JFrame("Ollama chat"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Container cont = frame.getContentPane(); cont.setLayout(new BorderLayout()); buttonBar(); cont.add(buttons, BorderLayout.NORTH); chat.setLineWrap(true); chat.setWrapStyleWord(true); final JPopupMenu popupMenu = new JPopupMenu(); JMenuItem copy = new JMenuItem("Copy"); copy.addActionListener(new AbstractAction("Copy") { @Override public void actionPerformed(ActionEvent ae) { String selectedText = chat.getSelectedText(); if (null != selectedText) { Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); clipboard.setContents(new StringSelection(selectedText), null); } } }); popupMenu.add(copy); chat.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { if (e.isPopupTrigger()) { popupMenu.show(e.getComponent(), e.getX(), e.getY()); } } @Override public void mouseReleased(MouseEvent e) { if (e.isPopupTrigger()) { popupMenu.show(e.getComponent(), e.getX(), e.getY()); } } }); JScrollPane pane = new JScrollPane(chat); pane.setBorder(BorderFactory.createTitledBorder( BorderFactory.createLineBorder(new Color(0, 0, 128), 5), "Chat")); cont.add(pane, BorderLayout.CENTER); Box bottom = Box.createHorizontalBox(); input.setLineWrap(true); input.setWrapStyleWord(true); bottom.add(new JScrollPane(input)); bottom.add(Box.createHorizontalStrut(10)); bottom.add(new JButton(new Interact())); bottom.add(new JButton(new AbstractAction("\u2191 image") { @Override public void actionPerformed(ActionEvent ae) { JFileChooser fileChooser = new JFileChooser(); int returnValue = fileChooser.showOpenDialog(frame); if (returnValue == JFileChooser.APPROVE_OPTION) { File selectedFile = fileChooser.getSelectedFile(); try { BufferedImage originalImage = ImageIO.read(selectedFile); if (originalImage.getHeight() != 256 || originalImage.getWidth() != 256) { Image scaledInstance = originalImage.getScaledInstance(256, 256, BufferedImage.SCALE_SMOOTH); BufferedImage resizedImage = new BufferedImage(256, 256, BufferedImage.TYPE_INT_ARGB); Graphics2D g2d = resizedImage.createGraphics(); g2d.drawImage(scaledInstance, 0, 0, null); g2d.dispose(); uplImage = resizedImage; } else { uplImage = originalImage; } updateSideBar(null); } catch (IOException ex) { Logger.getLogger(OllamaChatFrame.class.getName()).log(Level.SEVERE, null, ex); uplImage = null; } } } })); bottom.setBorder(BorderFactory.createTitledBorder( BorderFactory.createLineBorder(new Color(135, 206, 250), 5), "Input")); cont.add(bottom, BorderLayout.SOUTH); cont.add(sideBar(), BorderLayout.EAST); frame.pack(); if (EventQueue.isDispatchThread()) { finishInit(); } else { try { EventQueue.invokeAndWait(new Runnable() { @Override public void run() { finishInit(); } }); } catch (Exception ex) { Logger.getLogger(OllamaChatFrame.class.getName()).log(Level.SEVERE, null, ex); System.exit(1); } } } private void buttonBar() { buttons.add(new AbstractAction("Exit") { @Override public void actionPerformed(ActionEvent ae) { System.exit(0); } }); buttons.add(new JToolBar.Separator()); String lsHost = Ollama.config.getLastEndpoint(); for (String e : Ollama.getAvailableModels().keySet()) { addToHosts(e); } client = new OllamaClient(lsHost); models.removeAllItems(); for (AvailableModels.AvailableModel am : Ollama.getAvailableModels().get(lsHost).models) { models.addItem(am.name); } if (null != Ollama.config.lastModel) { models.setSelectedItem(Ollama.config.lastModel); } models.invalidate(); hosts.setSelectedItem(lsHost); hosts.addActionListener(new AddSelectHost()); hosts.setEditable(true); buttons.add(new JLabel("Hosts:")); buttons.add(hosts); buttons.add(new JToolBar.Separator()); buttons.add(new JLabel("Models:")); buttons.add(models); buttons.add(new JToolBar.Separator()); buttons.add(new AbstractAction("HTML") { @Override public void actionPerformed(ActionEvent ae) { String markDown = chat.getText(); JFrame html = new JFrame("HTML"); html.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); html.getContentPane().setLayout(new BorderLayout()); JEditorPane pane = new JEditorPane(); pane.setContentType("text/html"); HTMLEditorKit kit = new HTMLEditorKit() { @Override public StyleSheet getStyleSheet() { StyleSheet styleSheet = super.getStyleSheet(); styleSheet.addRule("body { font-family: 'Arial'; font-size: " + Math.round(Ollama.config.fontSize) + "pt; }"); return styleSheet; } }; pane.setEditorKit(kit); pane.setText(new PandocConverter().convertMarkdownToHTML(markDown)); html.getContentPane().add(new JScrollPane(pane), BorderLayout.CENTER); html.pack(); html.setVisible(true); } }); buttons.add(new AbstractAction("Dall-E 3") { @Override public void actionPerformed(ActionEvent ae) { try { String text = chat.getSelectedText(); DallEClient dale = new DallEClient();
ImageObject io = new ImageObject(dale.getImage(text));
0
2023-11-16 00:37:47+00:00
12k
JustARandomGuyNo512/Gunscraft
src/main/java/sheridan/gunscraft/items/attachments/util/NBTAttachmentsMap.java
[ { "identifier": "ClientProxy", "path": "src/main/java/sheridan/gunscraft/ClientProxy.java", "snippet": "public class ClientProxy extends CommonProxy{\n\n public static HashMap<Item, TransformData> transformDataMap = new HashMap<>();\n public static HashMap<Item, IGunModel> gunModelMap = new HashMap<>();\n public static final IGunRender renderer = new GenericGunRenderer();\n public static final long TICK_LEN = 10L;\n public static int equipDuration = 0;\n @OnlyIn(Dist.CLIENT)\n public static Timer timer;\n public static int clientPlayerId;\n\n public static ClientWeaponStatus mainHandStatus = new ClientWeaponStatus(true);\n public static ClientWeaponStatus offHandStatus = new ClientWeaponStatus(false);\n\n public static volatile float bulletSpread = 0f;\n public static volatile float minBulletSpread = 0f;\n public static volatile float maxBulletSpread = 0f;\n public static volatile int armPose;\n\n public static boolean attachmentsGuiShowing = false;\n\n public static final CapabilityKey<Boolean> AIMING;\n public static final CapabilityKey<Long> LAST_SHOOT_RIGHT;\n public static final CapabilityKey<Long> LAST_SHOOT_LEFT;\n\n\n public static float debugX = 0;\n public static float debugY = 0;\n public static float debugZ = 0;\n public static float debugAccuracy = (float) 0.01;\n\n public static void addSpread(float val) {\n synchronized (Object.class) {\n bulletSpread += val;\n }\n }\n\n static {\n AIMING = CapabilityKey.builder(Serializers.BOOLEAN).setId(new ResourceLocation(Gunscraft.MOD_ID, \"aiming\")).defaultValue(() -> false).resetOnDeath().build();\n LAST_SHOOT_RIGHT = CapabilityKey.builder(Serializers.LONG).setId(new ResourceLocation(Gunscraft.MOD_ID, \"last_shoot_right\")).defaultValue(() -> 0L).build();\n LAST_SHOOT_LEFT = CapabilityKey.builder(Serializers.LONG).setId(new ResourceLocation(Gunscraft.MOD_ID, \"last_shoot_left\")).defaultValue(() -> 0L).build();\n }\n\n @Override\n @OnlyIn(Dist.CLIENT)\n public void setUpClient(FMLClientSetupEvent event) {\n transformDataMap.put(ModItems.PISTOL_9_MM.get(), new TransformData()\n .setFPRightHand(new float[][]{{2.2f, -5.65f, -11.2f},{0, 0, 0},{2.15f, 2.15f, 2.15f}})\n .setFPLeftHand(new float[][]{{-1.6f, -5.65f, -11.2f},{0, 0, 0},{2.15f, 2.15f, 2.15f}})\n .setTPRightHand(new float[][]{{0f, -2.2f, -1.25f},{0, 0, 0},{1, 1, 1}})\n .setTPLeftHand(new float[][]{{0f, -2.2f, -1.25f},{0, 0, 0},{1, 1, 1}})\n .setFrameTrans(new float[][]{{3f, -5f, -0.25f},{0, -90, 0},{2, 2, 2}})\n .setGroundTrans(new float[][]{{0, -3, -1.5f},{0, 0, 0},{1, 1, 1}})\n .setGUITrans(new float[][]{{3, -5, -0.25f},{0, -90, 0},{2, 2, 2}})\n .setHandPoseRightSideRightHand(new float[][]{{0.325f, 0.37f, 1.09f},{-1.5707963267948966f, -0.049f, 0},{1, 1, 1}})\n .setHandPoseRightSideLeftHand(new float[][]{{-0.115f, 0.69f, 0.8f},{-2.08f, 0.5735987755982f, 0.165f},{1, 1, 1}})\n .setHandPoseLeftSide(new float[][]{{-0.35f, 0.37f, 1.09f},{-1.5707963267948966f, 0, 0},{1, 1, 1}})\n .registerMuzzleFlash(\"normal\", new TransformData.TransPair().setTrans(new MuzzleFlashTrans().setScale(new float[] {0.75f, 0.75f, 0.75f}).setTranslate(new float[]{0, -0.075f, -0.52f})).setName(\"pistol_simple\"))\n .setRecoilAnimationData(new RecoilAnimationData(12f,35f, 22f,\n 0.12f,0.095f,0.11f,\n 7.8f, 0.53f, 0.66f,\n 0.115f,0.095f,0.11f,\n 0.268f, 0.1f, 0.0142f, 0.75f, 700))\n .setAimingTrans(new float[] {4.0259995f, -3.108999f, 5.937073f})\n .setBulletShellTrans(new float[]{0, 3f / 16f, 29f / 16f,0,0,0,1,1,1})\n .setBulletShellAniData(new TransformData.BulletShellAniData(50, 40, -3, 30, 0.25f, 3, 1f))\n );\n gunModelMap.put(ModItems.PISTOL_9_MM.get(), new ModelPistol_9mm());\n\n transformDataMap.put(ModItems.AKM.get(), new TransformData()\n .setFPRightHand(new float[][]{{3.48f, -5.6f, -21.25f},{0, 0, 0},{1.8275f, 1.8275f, 1.8275f}})\n .setFPLeftHand(new float[][]{{0, 0, 0},{0, 0, 0},{0, 0, 0}})\n .setTPRightHand(new float[][]{{0f, -2.9f, -9f},{0, 0, 0},{0.85f, 0.85f, 0.85f}})\n .setTPLeftHand(new float[][]{{0f, -0, -0},{0, 0, 0},{0, 0, 0}})\n .setFrameTrans(new float[][]{{15f, -5f, -0.25f},{0, -90, 0},{1.7f, 1.7f, 1.7f}})\n .setGroundTrans(new float[][]{{0, -3, -6f},{0, 0, 0},{0.85f, 0.85f, 0.85f}})\n .setGUITrans(new float[][]{{6, -3, -0f},{0, -80, 0},{0.9f, 0.9f, 0.9f}})\n .setHandPoseRightSideRightHand(new float[][]{{0.325f, 0.6f, 2.5f},{-1.5707963267948966f, -0.049f, 0},{1.0f, 1.0f, 1.0f}})\n .setHandPoseRightSideLeftHand(new float[][]{{-0.16f, 0.5f, 1.6f},{-1.6580627893947f, 0.26179938779917f, 0.30543261909903f},{1.0f, 1.0f, 1.0f}})\n .setHandPoseLeftSide(new float[][]{{-0, 0, 0},{-0, 0, 0},{0, 0, 0}})\n .registerMuzzleFlash(\"normal\", new TransformData.TransPair().setTrans(new MuzzleFlashTrans().setTranslate(new float[]{0, 0, -1})).setName(\"pistol_simple\"))\n .setRecoilAnimationData(new RecoilAnimationData(20f,14.85f, 11.85f,\n 0.1f,0.0886f,0.1f,\n 1.48f, 0.61f, 0.3f,\n 0.1f,0.0875f,0.1f,\n 0.145f, 0.225f, 0.0015f, 0.6f, 650))\n .setAimingTrans(new float[] {2.7699978f, -2.582f, 5.410027f})\n .setBulletShellTrans(new float[]{-5f / 16f, 13f / 16f, 137f / 16f,0,0,0,0.9f,1.1f,1.1f})\n .setBulletShellAniData(new TransformData.BulletShellAniData(50, 35, -5, 17, 1f, 2, 1f))\n );\n gunModelMap.put(ModItems.AKM.get(), new ModelAKM());\n\n transformDataMap.put(ModItems.MP5.get(), new TransformData()\n .setFPRightHand(new float[][]{{3.5f, -5.75f, -15f},{0, 0, 0},{1.892f, 1.892f, 1.892f}})\n .setFPLeftHand(new float[][]{{0, 0, 0},{0, 0, 0},{0, 0, 0}})\n .setTPRightHand(new float[][]{{0f, -3f, -4.8f},{0, 0, 0},{0.88f, 0.88f, 0.88f}})\n .setTPLeftHand(new float[][]{{0f, -0, -0},{0, 0, 0},{0, 0, 0}})\n .setFrameTrans(new float[][]{{7f, -5f, -0.25f},{0, -90, 0},{1.7f, 1.7f, 1.7f}})\n .setGroundTrans(new float[][]{{0, -3, -6f},{0, 0, 0},{0.88f, 0.88f, 0.88f}})\n .setGUITrans(new float[][]{{3, -3, -0f},{0, -90, 0},{0.9f, 0.9f, 0.9f}})\n .setHandPoseRightSideRightHand(new float[][]{{0.325f, 0.6f, 2.0f},{-1.5707963267948966f, -0.049f, 0},{1.0f, 1.0f, 1.0f}})\n .setHandPoseRightSideLeftHand(new float[][]{{-0.1f, 0.468f, 1.15f},{-1.6580627893947f, 0.26179938779917f, 0.34906585039889f},{1.0f, 1.0f, 1.0f}})\n .setHandPoseLeftSide(new float[][]{{-0, 0, 0},{-0, 0, 0},{0, 0, 0}})\n .registerMuzzleFlash(\"normal\", new TransformData.TransPair().setTrans(new MuzzleFlashTrans().setTranslate(new float[]{0, 0, -1})).setName(\"pistol_simple\"))\n .setRecoilAnimationData(new RecoilAnimationData(12f,12f, 10f,\n 0.1f,0.087f,0.1f,\n 1.2f, 0.42f, 0.18f,\n 0.1f,0.0867f,0.1f,\n 0.145f, 0.15f, 0.001f, 0.32f, 500))\n .setAimingTrans(new float[] {2.7109997f, -2.67f, 6.257043f})\n .setBulletShellTrans(new float[]{-1f / 16f, 10f / 16f, 73f / 16f , 0,0,0,1,1,1})\n .setBulletShellAniData(new TransformData.BulletShellAniData(50, 50, 10, 15, 0.35f, 3f, 1f))\n );\n gunModelMap.put(ModItems.MP5.get(), new ModelMp5());\n\n transformDataMap.put(ModItems.MAC10.get(), new TransformData()\n .setFPRightHand(new float[][]{{2.1f, -5.75f, -10.8f},{0, 0, 0},{1.72f, 1.72f, 1.72f}})\n .setFPLeftHand(new float[][]{{0, -0, -0},{0, 0, 0},{0, 0, 0}})\n .setTPRightHand(new float[][]{{0f, -2.35f, -1.26f},{0, 0, 0},{0.8f, 0.8f, 0.8f}})\n .setTPLeftHand(new float[][]{{0f, -0, -0},{0, 0, 0},{0, 0, 0}})\n .setFrameTrans(new float[][]{{3f, -5f, -0.25f},{0, -90, 0},{1.6f, 1.6f, 1.6f}})\n .setGroundTrans(new float[][]{{0, -3, -1.5f},{0, 0, 0},{0.8f, 0.8f, 0.8f}})\n .setGUITrans(new float[][]{{3, -5, -0.25f},{0, -90, 0},{1.6f, 1.6f, 1.6f}})\n .setHandPoseRightSideRightHand(new float[][]{{0.325f, 0.49f, 1.2f},{-1.5707963267948966f, -0.049f, 0},{1, 1, 1}})\n .setHandPoseRightSideLeftHand(new float[][]{{-0.125f, 0.77f, 0.8f},{-2.08f, 0.5735987755982f, 0.165f},{1, 1, 1}})\n .setHandPoseLeftSide(new float[][]{{-0, 0, 0},{-0, 0, 0},{0, 0, 0}})\n .registerMuzzleFlash(\"normal\", new TransformData.TransPair().setTrans(new MuzzleFlashTrans().setScale(new float[] {1f, 1f, 1f}).setTranslate(new float[]{0, -0.45f, -1f})).setName(\"pistol_simple\"))\n .setRecoilAnimationData(new RecoilAnimationData(10f,13.5f, 9f,\n 0.11f,0.0885f,0.1f,\n 4.5f, 0.52f, 0.31f,\n 0.11f,0.088f,0.1f,\n 0.15f, 0.135f, 0.0087f, 0.52f, 500))\n .setAimingTrans(new float[] {4.1240017f, -2.3559993f, 8.63f})\n .setBulletShellTrans(new float[]{-1f/16f, 10f/16f, 41f/16f,0,0,0,1.15f,1.15f,1.15f})\n .setBulletShellAniData(new TransformData.BulletShellAniData(50, 10, 2, 10, 0.35f, 2f, 1f))\n );\n gunModelMap.put(ModItems.MAC10.get(), new ModelMac10());\n\n\n transformDataMap.put(ModItems.M4A1.get(), new TransformData()\n .setFPRightHand(new float[][]{{4.14f, -6.15f, -14.18f},{0, 0, 0},{1.699575f, 1.699575f, 1.699575f}})\n .setFPLeftHand(new float[][]{{0, 0, 0},{0, 0, 0},{0, 0, 0}})\n .setTPRightHand(new float[][]{{0f, -3.2f, -6f},{0, 0, 0},{0.7905f, 0.7905f, 0.7905f}})\n .setTPLeftHand(new float[][]{{0f, -0, -0},{0, 0, 0},{0, 0, 0}})\n .setFrameTrans(new float[][]{{12f, -5f, -0.25f},{0, -90, 0},{1.581f, 1.581f, 1.581f}})\n .setGroundTrans(new float[][]{{0, -3, -6f},{0, 0, 0},{0.7905f, 0.7905f, 0.7905f}})\n .setGUITrans(new float[][]{{6, -3, 0f},{0, -90, 0},{0.837f, 0.837f, 0.837f}})\n .setHandPoseRightSideRightHand(new float[][]{{0.325f, 0.6f, 2.5f},{-1.5707963267948966f, -0.049f, 0},{1.0f, 1.0f, 1.0f}})\n .setHandPoseRightSideLeftHand(new float[][]{{-0.156f, 0.55f, 1.35f},{-1.6580627893947f, 0.26179938779917f, 0.30543261909903f},{1.0f, 1.0f, 1.0f}})\n .setHandPoseLeftSide(new float[][]{{-0, 0, 0},{-0, 0, 0},{0, 0, 0}})\n .registerMuzzleFlash(\"normal\", new TransformData.TransPair().setTrans(new MuzzleFlashTrans().setTranslate(new float[]{0, 0.2f, -3.25f})).setName(\"pistol_simple\"))\n .setRecoilAnimationData(new RecoilAnimationData(16.2f,11f, 10.5f,\n 0.1f,0.0887f,0.1f,\n 0.87f, 0.475f, 0.17f,\n 0.1f,0.0876f,0.1f,\n 0.15f, 0.25f, 0.0015f, 0.22f, 500))\n .setAimingTrans(new float[] {2.0849983f, -1.749f, 5.9f})\n .setBulletShellTrans(new float[]{-5f/16f, 20f/16f, 105f/16f,0,0,0,1,1,1})\n .setBulletShellAniData(new TransformData.BulletShellAniData(60, 15, -2, 20, 0.5f, 2f, 1f))\n );\n gunModelMap.put(ModItems.M4A1.get(), new ModelM4a1());\n\n\n transformDataMap.put(ModItems.MINI_M249.get(), new TransformData()\n .setFPRightHand(new float[][]{{4.25f, -5.74f, -16.52f},{0, 0, 0},{1.64475f, 1.64475f, 1.64475f}})\n .setFPLeftHand(new float[][]{{0, 0, 0},{0, 0, 0},{0, 0, 0}})\n .setTPRightHand(new float[][]{{0f, -3.2f, -7.5f},{0, 0, 0},{0.765f, 0.765f, 0.765f}})\n .setTPLeftHand(new float[][]{{0f, -0, -0},{0, 0, 0},{0, 0, 0}})\n .setFrameTrans(new float[][]{{12f, -5f, -0.25f},{0, -90, 0},{1.53f, 1.53f, 1.53f}})\n .setGroundTrans(new float[][]{{0, -3, -6f},{0, 0, 0},{0.765f, 0.765f, 0.765f}})\n .setGUITrans(new float[][]{{6, -3, 0f},{0, -90, 0},{0.81f, 0.81f, 0.81f}})\n .setHandPoseRightSideRightHand(new float[][]{{0.325f, 0.6f, 2.5f},{-1.5707963267948966f, -0.049f, 0},{1.0f, 1.0f, 1.0f}})\n .setHandPoseRightSideLeftHand(new float[][]{{-0.15f, 0.7f, 1.43f},{-1.6580627893947f, 0.26179938779917f, 0.30543261909903f},{1.0f, 1.0f, 1.0f}})\n .setHandPoseLeftSide(new float[][]{{-0, 0, 0},{-0, 0, 0},{0, 0, 0}})\n .registerMuzzleFlash(\"normal\", new TransformData.TransPair().setTrans(new MuzzleFlashTrans().setTranslate(new float[]{0, 0.0f, -1.85f})).setName(\"pistol_simple\"))\n .setRecoilAnimationData(new RecoilAnimationData(22f,8f, 10.5f,\n 0.1f,0.0887f,0.1f,\n 0.7f, 0.425f, 0.18f,\n 0.1f,0.0876f,0.1f,\n 0.15f, 0.275f, 0.0017f, 0.275f, 500))\n .setAimingTrans(new float[] {1.9719835f, -2.219f, 3.1f})\n .setBulletShellTrans(new float[]{-5f / 16f, 13f / 17f, 121f / 16f, 0, 0, 0, 1, 1, 1})\n .setBulletShellAniData(new TransformData.BulletShellAniData(18,5,-2,15, 0.5f,15f, 1.0f))\n );\n gunModelMap.put(ModItems.MINI_M249.get(), new ModelMiniM249());\n\n\n timer = new Timer();\n timer.schedule(new ClientWeaponTicker(), 0, TICK_LEN);\n\n CapabilityHandler.getInstance().registerKey(AIMING);\n CapabilityHandler.getInstance().registerKey(LAST_SHOOT_RIGHT);\n CapabilityHandler.getInstance().registerKey(LAST_SHOOT_LEFT);\n\n ScreenManager.registerFactory(ModContainers.ATTACHMENTS.get(), AttachmentScreen::new);\n }\n\n @Override\n public void perInit() {\n super.perInit();\n }\n\n @Override\n public void init() {\n super.init();\n }\n\n @Override\n public void postInit() {\n super.postInit();\n }\n\n @Override\n @OnlyIn(Dist.CLIENT)\n public boolean shouldRenderCustom(ItemStack stack, IGenericGun gun, LivingEntity entity, boolean isMainHand) {\n if (!gunModelMap.containsKey(stack.getItem())) {\n return false;\n }\n if (isMainHand) {\n return true;\n } else {\n if (!gun.canHoldInOneHand()) {\n return false;\n }\n if (entity != null && entity instanceof PlayerEntity) {\n PlayerEntity player = (PlayerEntity) entity;\n ItemStack stackMain = player.getHeldItemMainhand();\n if (stackMain.getItem() instanceof IGenericGun) {\n IGenericGun gunMain = (IGenericGun) stackMain.getItem();\n return gunMain.canHoldInOneHand();\n } else {\n return true;\n }\n }\n }\n return gunModelMap.containsKey(stack.getItem());\n }\n\n @Override\n public PlayerEntity getClientPlayer() {\n return Minecraft.getInstance().player;\n }\n\n @OnlyIn(Dist.CLIENT)\n public static void handleFireMain() {\n handleFire(true, System.currentTimeMillis() - mainHandStatus.lastShoot);\n }\n\n @OnlyIn(Dist.CLIENT)\n public static void handleFireOff() {\n handleFire(false, System.currentTimeMillis() - offHandStatus.lastShoot);\n }\n\n @OnlyIn(Dist.CLIENT)\n public static void handleFire(boolean mainHand, long dis) {\n Minecraft minecraft = Minecraft.getInstance();\n PlayerEntity player = minecraft.player;\n if (player != null) {\n ItemStack stack = mainHand? player.getHeldItemMainhand() : player.getHeldItemOffhand();\n if (stack.getItem() instanceof IGenericGun) {\n IGenericGun gun = (IGenericGun) stack.getItem();\n if (gun.preShoot(stack, player, mainHand)) {\n int fireCount = mainHand ? mainHandStatus.fireCount : offHandStatus.fireCount;\n float spread = ClientProxy.bulletSpread;\n int fireDelay = mainHand ? mainHandStatus.shootDelay.get() : offHandStatus.shootDelay.get();\n int fireFactor = fireDelay * 10 * (gun.isPistol() ? 4 : 8);\n if (fireCount == 0 && !gun.isFreeBlot() && dis > fireFactor) {\n spread *= 0.25f;\n }\n gun.shoot(stack, player, true, spread);\n PacketHandler.CommonChannel.sendToServer(new GunFirePacket(mainHand, spread));\n if (mainHand) {\n mainHandStatus.fireCount ++;\n } else {\n offHandStatus.fireCount ++;\n }\n }\n }\n }\n }\n\n public static void updatePlayerData(int entityId, List<CapabilityHandler.Pair<?>> pairs) {\n World world = Minecraft.getInstance().world;\n if(world != null) {\n Entity entity = world.getEntityByID(entityId);\n if(entity != null && entity instanceof PlayerEntity) {\n PlayerEntity player = (PlayerEntity) entity;\n for (CapabilityHandler.Pair<?> pair : pairs) {\n CapabilityHandler.getInstance().updateClientData(player, pair);\n }\n }\n }\n }\n\n}" }, { "identifier": "AttachmentRegistry", "path": "src/main/java/sheridan/gunscraft/items/attachments/AttachmentRegistry.java", "snippet": "public class AttachmentRegistry {\n private static Map<Integer, IGenericAttachment> registryMap = new HashMap<>();\n private static Map<String, Integer> IDMap = new HashMap<>();\n private static Map<Integer, IAttachmentModel> modelMap = new HashMap<>();\n private static int ID = -1;\n\n public static void register(int id, IGenericAttachment attachment) {\n if (!registryMap.containsKey(id)) {\n registryMap.put(id, attachment);\n }\n }\n public static int getIdByName(String name) {\n return IDMap.getOrDefault(name, NONE);\n }\n\n public static void registerModel(int id, IAttachmentModel models) {\n if (!modelMap.containsKey(id)) {\n modelMap.put(id, models);\n }\n }\n\n public static IAttachmentModel getModel(int id) {\n return modelMap.getOrDefault(id, null);\n }\n\n public static IGenericAttachment get(int id) {\n return registryMap.getOrDefault(id, null);\n }\n\n public static int getID(String name) {\n synchronized (Object.class) {\n ++ID;\n IDMap.put(name, ID);\n return ID;\n }\n }\n}" }, { "identifier": "GenericAttachment", "path": "src/main/java/sheridan/gunscraft/items/attachments/GenericAttachment.java", "snippet": "public class GenericAttachment extends Item implements IGenericAttachment{\n public static final String MUZZLE = \"muzzle\", GRIP = \"grip\", MAG = \"mag\", SCOPE = \"scope\", STOCK = \"stock\", HAND_GUARD = \"hand_guard\";\n public static final int NONE = -1;\n protected int id;\n protected String type;\n protected String name;\n\n public String getType() {\n return type;\n }\n\n public GenericAttachment(Properties properties, int id, String type, String name) {\n super(properties);\n this.id = id;\n this.type = type;\n this.name = name;\n }\n\n @Override\n public void onAttach(ItemStack stack, IGenericGun gun) {\n\n }\n\n @Override\n public void onOff(ItemStack stack, IGenericGun gun) {\n\n }\n\n @Override\n public int getId() {\n return this.id;\n }\n\n @Override\n public String getSlotType() {\n return type;\n }\n\n @Override\n public int getID() {\n return id;\n }\n\n @Override\n public String getAttachmentName() {\n return name;\n }\n\n\n @Override\n public void handleParams(GunRenderContext params) {\n switch (this.type) {\n case MUZZLE:\n params.occupiedMuzzle = true;\n break;\n case HAND_GUARD:\n params.occupiedHandGuard = true;\n break;\n case MAG:\n params.occupiedMag = true;\n break;\n case SCOPE:\n params.occupiedIS = true;\n break;\n case STOCK:\n params.occupiedStock = true;\n break;\n case GRIP:\n params.occupiedGrip = true;\n break;\n }\n }\n\n @Override\n public int getItemId() {\n return Item.getIdFromItem(this);\n }\n\n}" }, { "identifier": "IGenericAttachment", "path": "src/main/java/sheridan/gunscraft/items/attachments/IGenericAttachment.java", "snippet": "public interface IGenericAttachment {\n void onAttach(ItemStack stack, IGenericGun gun);\n void onOff(ItemStack stack, IGenericGun gun);\n int getId();\n\n @OnlyIn(Dist.CLIENT)\n default void beforePreShoot() {}\n @OnlyIn(Dist.CLIENT)\n default void afterPreShoot() {}\n\n default void onAiming(ItemStack stack, IGenericGun gun, MatrixStack matrixStack) {}\n\n default void beforeShoot() {}\n default void afterShoot() {}\n\n @OnlyIn(Dist.CLIENT)\n default void beforeRenderGun() {}\n @OnlyIn(Dist.CLIENT)\n default void afterRenderGun() {}\n\n String getSlotType();\n int getID();\n String getAttachmentName();\n void handleParams(GunRenderContext params);\n int getItemId();\n}" }, { "identifier": "IGenericGun", "path": "src/main/java/sheridan/gunscraft/items/guns/IGenericGun.java", "snippet": "public interface IGenericGun {\n ResourceLocation getTexture(int index);\n int getCurrentTextureIndex(ItemStack stack);\n boolean preShoot(ItemStack stack, LivingEntity entity, boolean mainHand);\n void shoot(ItemStack stack, LivingEntity entity, boolean mainHand, float spread);\n boolean preReload(ItemStack stack, LivingEntity entity, boolean mainHand);\n void reload(ItemStack stack, LivingEntity entity, boolean mainHand);\n boolean canHoldInOneHand();\n int getMagSize(ItemStack stack);\n void setMagSize(ItemStack stack, int magSize);\n int getAmmoLeft(ItemStack stack);\n void setAmmoLeft(ItemStack stack, int count);\n int getFireMode(ItemStack stack);\n void setFireMode(ItemStack stack, int mode);\n void switchFireMode(ItemStack stack);\n int getShootDelay();\n float getMinSpread(ItemStack stack);\n float getMaxSpread(ItemStack stack);\n boolean isFreeBlot();\n boolean isPistol();\n int getReloadLength(ItemStack stack);\n String getMuzzleFlashState(ItemStack stack);\n int getBurstCount();\n float getAimingSpeed(ItemStack stack);\n float getRecoilUp(ItemStack stack);\n float getRecoilRandom(ItemStack stack);\n float getRecoilDec(ItemStack stack);\n GunAttachmentSlot getSlot(String name);\n List<GunAttachmentSlot> getAllSlots();\n String getSeriesName();\n String getBulletType();\n}" }, { "identifier": "IAttachmentModel", "path": "src/main/java/sheridan/gunscraft/model/IAttachmentModel.java", "snippet": "public interface IAttachmentModel {\n void render(MatrixStack matrixStack, ItemCameraTransforms.TransformType transformType,\n int packedLight, int packedOverlay, int bulletLeft,\n long lastFireTime, boolean mainHand, int fireMode, IGenericGun gun);\n}" } ]
import com.mojang.blaze3d.matrix.MatrixStack; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.RenderType; import net.minecraft.client.renderer.model.ItemCameraTransforms; import net.minecraft.item.ItemStack; import net.minecraft.nbt.*; import sheridan.gunscraft.ClientProxy; import sheridan.gunscraft.items.attachments.AttachmentRegistry; import sheridan.gunscraft.items.attachments.GenericAttachment; import sheridan.gunscraft.items.attachments.IGenericAttachment; import sheridan.gunscraft.items.guns.IGenericGun; import sheridan.gunscraft.model.IAttachmentModel; import java.util.List;
8,078
package sheridan.gunscraft.items.attachments.util; public class NBTAttachmentsMap{ private static CompoundNBT createEmptySlot(String slotName) { CompoundNBT slot = new CompoundNBT(); slot.putString("slot_name", slotName); slot.putBoolean("empty", true);
package sheridan.gunscraft.items.attachments.util; public class NBTAttachmentsMap{ private static CompoundNBT createEmptySlot(String slotName) { CompoundNBT slot = new CompoundNBT(); slot.putString("slot_name", slotName); slot.putBoolean("empty", true);
slot.putInt("attachment_id", GenericAttachment.NONE);
2
2023-11-14 14:00:55+00:00
12k
zpascual/5419-Arm-Example
src/main/java/com/team5419/frc2023/subsystems/ServoMotorSubsystem.java
[ { "identifier": "TalonFXFactory", "path": "src/main/java/com/team254/lib/drivers/TalonFXFactory.java", "snippet": "public class TalonFXFactory {\n\n private final static int kTimeoutMs = 100;\n\n public static class Configuration {\n public NeutralMode NEUTRAL_MODE = NeutralMode.Coast;\n // factory default\n public double NEUTRAL_DEADBAND = 0.04;\n\n public boolean ENABLE_CURRENT_LIMIT = false;\n public boolean ENABLE_SOFT_LIMIT = false;\n public boolean ENABLE_LIMIT_SWITCH = false;\n public int FORWARD_SOFT_LIMIT = 0;\n public int REVERSE_SOFT_LIMIT = 0;\n\n public boolean INVERTED = false;\n public boolean SENSOR_PHASE = false;\n\n public int CONTROL_FRAME_PERIOD_MS = 20; // 10\n public int MOTION_CONTROL_FRAME_PERIOD_MS = 100;\n public int GENERAL_STATUS_FRAME_RATE_MS = 20; // 10\n public int FEEDBACK_STATUS_FRAME_RATE_MS = 100;\n public int QUAD_ENCODER_STATUS_FRAME_RATE_MS = 1000;\n public int ANALOG_TEMP_VBAT_STATUS_FRAME_RATE_MS = 1000;\n public int PULSE_WIDTH_STATUS_FRAME_RATE_MS = 1000;\n\n public SensorVelocityMeasPeriod VELOCITY_MEASUREMENT_PERIOD = SensorVelocityMeasPeriod.Period_100Ms;\n public int VELOCITY_MEASUREMENT_ROLLING_AVERAGE_WINDOW = 64;\n\n public StatorCurrentLimitConfiguration STATOR_CURRENT_LIMIT = new StatorCurrentLimitConfiguration(false, 300, 700, 1);\n public SupplyCurrentLimitConfiguration SUPPLY_CURRENT_LIMIT = new SupplyCurrentLimitConfiguration(false, 40, 100, 1);\n\n public double OPEN_LOOP_RAMP_RATE = 0.0;\n public double CLOSED_LOOP_RAMP_RATE = 0.0;\n }\n\n private static final Configuration kDefaultConfiguration = new Configuration();\n private static final Configuration kSlaveConfiguration = new Configuration();\n\n static {\n // This control frame value seems to need to be something reasonable to avoid the Talon's\n // LEDs behaving erratically. Potentially try to increase as much as possible.\n kSlaveConfiguration.ENABLE_SOFT_LIMIT = false;\n }\n\n // create a CANTalon with the default (out of the box) configuration\n public static TalonFX createDefaultTalon(int id) {\n return createTalon(id, kDefaultConfiguration);\n }\n\n public static TalonFX createDefaultTalon(int id, String canbus) {\n return createTalon(id, kDefaultConfiguration, canbus);\n }\n\n public static TalonFX createPermanentSlaveTalon(int id, int master_id) {\n final TalonFX talon = createTalon(id, kSlaveConfiguration);\n talon.set(ControlMode.Follower, master_id);\n return talon;\n }\n\n public static TalonFX createTalon(int id, Configuration config) {\n return createTalon(id, config, \"canivore1\"); \n }\n\n public static TalonFX createTalon(int id, Configuration config, String canbus) {\n TalonFX talon = new LazyTalonFX(id, canbus);\n talon.set(ControlMode.PercentOutput, 0.0);\n\n talon.changeMotionControlFramePeriod(config.MOTION_CONTROL_FRAME_PERIOD_MS);\n talon.clearMotionProfileHasUnderrun(kTimeoutMs);\n talon.clearMotionProfileTrajectories();\n\n talon.clearStickyFaults(kTimeoutMs);\n\n talon.configForwardLimitSwitchSource(LimitSwitchSource.FeedbackConnector,\n LimitSwitchNormal.Disabled, kTimeoutMs);\n talon.configReverseLimitSwitchSource(LimitSwitchSource.FeedbackConnector,\n LimitSwitchNormal.Disabled, kTimeoutMs);\n talon.overrideLimitSwitchesEnable(config.ENABLE_LIMIT_SWITCH);\n\n // Turn off re-zeroing by default.\n talon.configSetParameter(\n ParamEnum.eClearPositionOnLimitF, 0, 0, 0, kTimeoutMs);\n talon.configSetParameter(\n ParamEnum.eClearPositionOnLimitR, 0, 0, 0, kTimeoutMs);\n\n talon.configNominalOutputForward(0, kTimeoutMs);\n talon.configNominalOutputReverse(0, kTimeoutMs);\n talon.configNeutralDeadband(config.NEUTRAL_DEADBAND, kTimeoutMs);\n\n talon.configPeakOutputForward(1.0, kTimeoutMs);\n talon.configPeakOutputReverse(-1.0, kTimeoutMs);\n\n talon.setNeutralMode(config.NEUTRAL_MODE);\n\n talon.configForwardSoftLimitThreshold(config.FORWARD_SOFT_LIMIT, kTimeoutMs);\n talon.configForwardSoftLimitEnable(config.ENABLE_SOFT_LIMIT, kTimeoutMs);\n\n talon.configReverseSoftLimitThreshold(config.REVERSE_SOFT_LIMIT, kTimeoutMs);\n talon.configReverseSoftLimitEnable(config.ENABLE_SOFT_LIMIT, kTimeoutMs);\n talon.overrideSoftLimitsEnable(config.ENABLE_SOFT_LIMIT);\n\n talon.setInverted(config.INVERTED);\n talon.setSensorPhase(config.SENSOR_PHASE);\n\n talon.selectProfileSlot(0, 0);\n\n talon.configVelocityMeasurementPeriod(config.VELOCITY_MEASUREMENT_PERIOD, kTimeoutMs);\n talon.configVelocityMeasurementWindow(config.VELOCITY_MEASUREMENT_ROLLING_AVERAGE_WINDOW,\n kTimeoutMs);\n\n talon.configOpenloopRamp(config.OPEN_LOOP_RAMP_RATE, kTimeoutMs);\n talon.configClosedloopRamp(config.CLOSED_LOOP_RAMP_RATE, kTimeoutMs);\n\n talon.configVoltageCompSaturation(0.0, kTimeoutMs);\n talon.configVoltageMeasurementFilter(32, kTimeoutMs);\n talon.enableVoltageCompensation(false);\n\n talon.configStatorCurrentLimit(config.STATOR_CURRENT_LIMIT);\n talon.configSupplyCurrentLimit(config.SUPPLY_CURRENT_LIMIT);\n\n talon.setStatusFramePeriod(StatusFrameEnhanced.Status_1_General,\n config.GENERAL_STATUS_FRAME_RATE_MS, kTimeoutMs);\n talon.setStatusFramePeriod(StatusFrameEnhanced.Status_2_Feedback0,\n config.FEEDBACK_STATUS_FRAME_RATE_MS, kTimeoutMs);\n\n talon.setStatusFramePeriod(StatusFrameEnhanced.Status_3_Quadrature,\n config.QUAD_ENCODER_STATUS_FRAME_RATE_MS, kTimeoutMs);\n talon.setStatusFramePeriod(StatusFrameEnhanced.Status_4_AinTempVbat,\n config.ANALOG_TEMP_VBAT_STATUS_FRAME_RATE_MS, kTimeoutMs);\n talon.setStatusFramePeriod(StatusFrameEnhanced.Status_8_PulseWidth,\n config.PULSE_WIDTH_STATUS_FRAME_RATE_MS, kTimeoutMs);\n\n talon.setControlFramePeriod(ControlFrame.Control_3_General, config.CONTROL_FRAME_PERIOD_MS);\n\n return talon;\n }\n}" }, { "identifier": "TalonUtil", "path": "src/main/java/com/team254/lib/drivers/TalonUtil.java", "snippet": "public class TalonUtil {\n /**\n * checks the specified error code for issues\n *\n * @param errorCode error code\n * @param message message to print if error happens\n */\n public static void checkError(ErrorCode errorCode, String message) {\n if (errorCode != ErrorCode.OK) {\n DriverStation.reportError(message + errorCode, false);\n }\n }\n}" }, { "identifier": "MotionProfileConstraints", "path": "src/main/java/com/team254/lib/motion/MotionProfileConstraints.java", "snippet": "public class MotionProfileConstraints {\n protected double max_abs_vel = Double.POSITIVE_INFINITY;\n protected double max_abs_acc = Double.POSITIVE_INFINITY;\n\n public MotionProfileConstraints(double max_vel, double max_acc) {\n this.max_abs_vel = Math.abs(max_vel);\n this.max_abs_acc = Math.abs(max_acc);\n }\n\n /**\n * @return The (positive) maximum allowed velocity.\n */\n public double max_abs_vel() {\n return max_abs_vel;\n }\n\n /**\n * @return The (positive) maximum allowed acceleration.\n */\n public double max_abs_acc() {\n return max_abs_acc;\n }\n\n @Override\n public boolean equals(Object obj) {\n if (!(obj instanceof MotionProfileConstraints)) {\n return false;\n }\n final MotionProfileConstraints other = (MotionProfileConstraints) obj;\n return (other.max_abs_acc() == max_abs_acc()) && (other.max_abs_vel() == max_abs_vel());\n }\n}" }, { "identifier": "MotionState", "path": "src/main/java/com/team254/lib/motion/MotionState.java", "snippet": "public class MotionState {\n protected final double t;\n protected final double pos;\n protected final double vel;\n protected final double acc;\n\n public static MotionState kInvalidState = new MotionState(Double.NaN, Double.NaN, Double.NaN, Double.NaN);\n\n public MotionState(double t, double pos, double vel, double acc) {\n this.t = t;\n this.pos = pos;\n this.vel = vel;\n this.acc = acc;\n }\n\n public MotionState(MotionState state) {\n this(state.t, state.pos, state.vel, state.acc);\n }\n\n public double t() {\n return t;\n }\n\n public double pos() {\n return pos;\n }\n\n public double vel() {\n return vel;\n }\n\n public double vel2() {\n return vel * vel;\n }\n\n public double acc() {\n return acc;\n }\n\n /**\n * Extrapolates this MotionState to the specified time by applying this MotionState's acceleration.\n *\n * @param t The time of the new MotionState.\n * @return A MotionState that is a valid predecessor (if t<=0) or successor (if t>=0) of this state.\n */\n public MotionState extrapolate(double t) {\n return extrapolate(t, acc);\n }\n\n /**\n * Extrapolates this MotionState to the specified time by applying a given acceleration to the (t, pos, vel) portion\n * of this MotionState.\n *\n * @param t The time of the new MotionState.\n * @param acc The acceleration to apply.\n * @return A MotionState that is a valid predecessor (if t<=0) or successor (if t>=0) of this state (with the\n * specified accel).\n */\n public MotionState extrapolate(double t, double acc) {\n final double dt = t - this.t;\n return new MotionState(t, pos + vel * dt + .5 * acc * dt * dt, vel + acc * dt, acc);\n }\n\n /**\n * Find the next time (first time > MotionState.t()) that this MotionState will be at pos. This is an inverse of the\n * extrapolate() method.\n *\n * @param pos The position to query.\n * @return The time when we are next at pos() if we are extrapolating with a positive dt. NaN if we never reach pos.\n */\n public double nextTimeAtPos(double pos) {\n if (epsilonEquals(pos, this.pos, kEpsilon)) {\n // Already at pos.\n return t;\n }\n if (epsilonEquals(acc, 0.0, kEpsilon)) {\n // Zero acceleration case.\n final double delta_pos = pos - this.pos;\n if (!epsilonEquals(vel, 0.0, kEpsilon) && Math.signum(delta_pos) == Math.signum(vel)) {\n // Constant velocity heading towards pos.\n return delta_pos / vel + t;\n }\n return Double.NaN;\n }\n\n // Solve the quadratic formula.\n // ax^2 + bx + c == 0\n // x = dt\n // a = .5 * acc\n // b = vel\n // c = this.pos - pos\n final double disc = vel * vel - 2.0 * acc * (this.pos - pos);\n if (disc < 0.0) {\n // Extrapolating this MotionState never reaches the desired pos.\n return Double.NaN;\n }\n final double sqrt_disc = Math.sqrt(disc);\n final double max_dt = (-vel + sqrt_disc) / acc;\n final double min_dt = (-vel - sqrt_disc) / acc;\n if (min_dt >= 0.0 && (max_dt < 0.0 || min_dt < max_dt)) {\n return t + min_dt;\n }\n if (max_dt >= 0.0) {\n return t + max_dt;\n }\n // We only reach the desired pos in the past.\n return Double.NaN;\n }\n\n @Override\n public String toString() {\n return \"(t=\" + t + \", pos=\" + pos + \", vel=\" + vel + \", acc=\" + acc + \")\";\n }\n\n /**\n * Checks if two MotionStates are epsilon-equals (all fields are equal within a nominal tolerance).\n */\n @Override\n public boolean equals(Object other) {\n return (other instanceof MotionState) && equals((MotionState) other, kEpsilon);\n }\n\n /**\n * Checks if two MotionStates are epsilon-equals (all fields are equal within a specified tolerance).\n */\n public boolean equals(MotionState other, double epsilon) {\n return coincident(other, epsilon) && epsilonEquals(acc, other.acc, epsilon);\n }\n\n /**\n * Checks if two MotionStates are coincident (t, pos, and vel are equal within a nominal tolerance, but acceleration\n * may be different).\n */\n public boolean coincident(MotionState other) {\n return coincident(other, kEpsilon);\n }\n\n /**\n * Checks if two MotionStates are coincident (t, pos, and vel are equal within a specified tolerance, but\n * acceleration may be different).\n */\n public boolean coincident(MotionState other, double epsilon) {\n return epsilonEquals(t, other.t, epsilon) && epsilonEquals(pos, other.pos, epsilon)\n && epsilonEquals(vel, other.vel, epsilon);\n }\n\n /**\n * Returns a MotionState that is the mirror image of this one. Pos, vel, and acc are all negated, but time is not.\n */\n public MotionState flipped() {\n return new MotionState(t, -pos, -vel, -acc);\n }\n}" }, { "identifier": "SetpointGenerator", "path": "src/main/java/com/team254/lib/motion/SetpointGenerator.java", "snippet": "public class SetpointGenerator {\n /**\n * A Setpoint is just a MotionState and an additional flag indicating whether this is setpoint achieves the goal\n * (useful for higher-level logic to know that it is now time to do something else).\n */\n public static class Setpoint {\n public MotionState motion_state;\n public boolean final_setpoint;\n\n public Setpoint(MotionState motion_state, boolean final_setpoint) {\n this.motion_state = motion_state;\n this.final_setpoint = final_setpoint;\n }\n }\n\n protected MotionProfile mProfile = null;\n protected MotionProfileGoal mGoal = null;\n protected MotionProfileConstraints mConstraints = null;\n\n public SetpointGenerator() {}\n\n /**\n * Force a reset of the profile.\n */\n public void reset() {\n mProfile = null;\n mGoal = null;\n mConstraints = null;\n }\n\n /**\n * Get a new Setpoint (and generate a new MotionProfile if necessary).\n *\n * @param constraints The constraints to use.\n * @param goal The goal to use.\n * @param prev_state The previous setpoint (or measured state of the system to do a reset).\n * @param t The time to generate a setpoint for.\n * @return The new Setpoint at time t.\n */\n public synchronized Setpoint getSetpoint(MotionProfileConstraints constraints, MotionProfileGoal goal,\n MotionState prev_state,\n double t) {\n boolean regenerate = mConstraints == null || !mConstraints.equals(constraints) || mGoal == null\n || !mGoal.equals(goal) || mProfile == null;\n if (!regenerate && !mProfile.isEmpty()) {\n Optional<MotionState> expected_state = mProfile.stateByTime(prev_state.t());\n regenerate = !expected_state.isPresent() || !expected_state.get().equals(prev_state);\n }\n if (regenerate) {\n // Regenerate the profile, as our current profile does not satisfy the inputs.\n mConstraints = constraints;\n mGoal = goal;\n mProfile = MotionProfileGenerator.generateProfile(constraints, goal, prev_state);\n // System.out.println(\"Regenerating profile: \" + mProfile);\n }\n\n // Sample the profile at time t.\n Setpoint rv = null;\n if (!mProfile.isEmpty() && mProfile.isValid()) {\n MotionState setpoint;\n if (t > mProfile.endTime()) {\n setpoint = mProfile.endState();\n } else if (t < mProfile.startTime()) {\n setpoint = mProfile.startState();\n } else {\n setpoint = mProfile.stateByTime(t).get();\n }\n // Shorten the profile and return the new setpoint.\n mProfile.trimBeforeTime(t);\n rv = new Setpoint(setpoint, mProfile.isEmpty() || mGoal.atGoalState(setpoint));\n }\n\n // Invalid or empty profile - just output the same state again.\n if (rv == null) {\n rv = new Setpoint(prev_state, true);\n }\n\n if (rv.final_setpoint) {\n // Ensure the final setpoint matches the goal exactly.\n rv.motion_state = new MotionState(rv.motion_state.t(), mGoal.pos(),\n Math.signum(rv.motion_state.vel()) * Math.max(mGoal.max_abs_vel(), Math.abs(rv.motion_state.vel())),\n 0.0);\n }\n\n return rv;\n }\n\n /**\n * Get the full profile from the latest call to getSetpoint(). Useful to check estimated time or distance to goal.\n *\n * @return The profile from the latest call to getSetpoint(), or null if there is not yet a profile.\n */\n public MotionProfile getProfile() {\n return mProfile;\n }\n}" }, { "identifier": "ReflectingCSVWriter", "path": "src/main/java/com/team254/lib/util/ReflectingCSVWriter.java", "snippet": "public class ReflectingCSVWriter<T> {\n ConcurrentLinkedDeque<String> mLinesToWrite = new ConcurrentLinkedDeque<>();\n PrintWriter mOutput = null;\n Field[] mFields;\n\n public ReflectingCSVWriter(String fileName, Class<T> typeClass) {\n mFields = typeClass.getFields();\n try {\n mOutput = new PrintWriter(fileName);\n } catch (FileNotFoundException e) {\n e.printStackTrace();\n }\n // Write field names.\n StringBuffer line = new StringBuffer();\n for (Field field : mFields) {\n if (line.length() != 0) {\n line.append(\", \");\n }\n line.append(field.getName());\n }\n writeLine(line.toString());\n }\n\n public void add(T value) {\n StringBuffer line = new StringBuffer();\n for (Field field : mFields) {\n if (line.length() != 0) {\n line.append(\", \");\n }\n try {\n if (CSVWritable.class.isAssignableFrom(field.getType())) {\n line.append(((CSVWritable)field.get(value)).toCSV());\n } else {\n line.append(field.get(value).toString());\n }\n } catch (IllegalArgumentException e) {\n e.printStackTrace();\n } catch (IllegalAccessException e) {\n e.printStackTrace();\n }\n }\n mLinesToWrite.add(line.toString());\n }\n\n protected synchronized void writeLine(String line) {\n if (mOutput != null) {\n mOutput.println(line);\n }\n }\n\n // Call this periodically from any thread to write to disk.\n public void write() {\n while (true) {\n String val = mLinesToWrite.pollFirst();\n if (val == null) {\n break;\n }\n writeLine(val);\n }\n }\n\n public synchronized void flush() {\n if (mOutput != null) {\n write();\n mOutput.flush();\n }\n }\n}" }, { "identifier": "Util", "path": "src/main/java/com/team254/lib/util/Util.java", "snippet": "public class Util {\n\n public static final double kEpsilon = 1e-12;\n\n /**\n * Prevent this class from being instantiated.\n */\n private Util() {\n }\n\n /**\n * Limits the given input to the given magnitude.\n */\n public static double limit(double v, double maxMagnitude) {\n return limit(v, -maxMagnitude, maxMagnitude);\n }\n\n public static double limit(double v, double min, double max) {\n return Math.min(max, Math.max(min, v));\n }\n \n public static boolean inRange(double v, double maxMagnitude) {\n return inRange(v, -maxMagnitude, maxMagnitude);\n }\n\n /**\n * Checks if the given input is within the range (min, max), both exclusive.\n */\n public static boolean inRange(double v, double min, double max) {\n return v > min && v < max;\n }\n\n public static double interpolate(double a, double b, double x) {\n x = limit(x, 0.0, 1.0);\n return a + (b - a) * x;\n }\n\n public static String joinStrings(final String delim, final List<?> strings) {\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i < strings.size(); ++i) {\n sb.append(strings.get(i).toString());\n if (i < strings.size() - 1) {\n sb.append(delim);\n }\n }\n return sb.toString();\n }\n\n public static boolean epsilonEquals(double a, double b, double epsilon) {\n return (a - epsilon <= b) && (a + epsilon >= b);\n }\n\n public static boolean epsilonEquals(double a, double b) {\n return epsilonEquals(a, b, kEpsilon);\n }\n\n public static boolean epsilonEquals(int a, int b, int epsilon) {\n return (a - epsilon <= b) && (a + epsilon >= b);\n }\n\n public static boolean allCloseTo(final List<Double> list, double value, double epsilon) {\n boolean result = true;\n for (Double value_in : list) {\n result &= epsilonEquals(value_in, value, epsilon);\n }\n return result;\n }\n}" }, { "identifier": "ILooper", "path": "src/main/java/com/team5419/frc2023/loops/ILooper.java", "snippet": "public interface ILooper {\n void register(Loop loop);\n}" }, { "identifier": "Loop", "path": "src/main/java/com/team5419/frc2023/loops/Loop.java", "snippet": "public interface Loop {\n\n public void onStart(double timestamp);\n\n public void onLoop(double timestamp);\n\n public void onStop(double timestamp);\n}" } ]
import com.ctre.phoenix.motorcontrol.*; import com.ctre.phoenix.motorcontrol.can.TalonFX; import com.team254.lib.drivers.TalonFXFactory; import com.team254.lib.drivers.TalonUtil; import com.team254.lib.motion.MotionProfileConstraints; import com.team254.lib.motion.MotionState; import com.team254.lib.motion.SetpointGenerator; import com.team254.lib.util.ReflectingCSVWriter; import com.team254.lib.util.Util; import com.team5419.frc2023.loops.ILooper; import com.team5419.frc2023.loops.Loop; import edu.wpi.first.wpilibj.DriverStation; import edu.wpi.first.wpilibj.Timer;
8,262
mConstants.kName + ": Could not set kF: "); TalonUtil.checkError(mMaster.configMaxIntegralAccumulator(kMotionProfileSlot, mConstants.kMaxIntegralAccumulator, mConstants.kLongCANTimeoutMs), mConstants.kName + ": Could not set max integral: "); TalonUtil.checkError(mMaster.config_IntegralZone(kMotionProfileSlot, mConstants.kIZone, mConstants.kLongCANTimeoutMs), mConstants.kName + ": Could not set i zone: "); TalonUtil.checkError( mMaster.configAllowableClosedloopError(kMotionProfileSlot, mConstants.kDeadband, mConstants.kLongCANTimeoutMs), mConstants.kName + ": Could not set deadband: "); TalonUtil.checkError(mMaster.config_kP(kPositionPIDSlot, mConstants.kPositionKp, mConstants.kLongCANTimeoutMs), mConstants.kName + ": could not set kP: "); TalonUtil.checkError(mMaster.config_kI(kPositionPIDSlot, mConstants.kPositionKi, mConstants.kLongCANTimeoutMs), mConstants.kName + ": could not set kI: "); TalonUtil.checkError(mMaster.config_kD(kPositionPIDSlot, mConstants.kPositionKd, mConstants.kLongCANTimeoutMs), mConstants.kName + ": could not set kD: "); TalonUtil.checkError(mMaster.config_kF(kPositionPIDSlot, mConstants.kPositionKf, mConstants.kLongCANTimeoutMs), mConstants.kName + ": Could not set kF: "); TalonUtil.checkError(mMaster.configMaxIntegralAccumulator(kPositionPIDSlot, mConstants.kPositionMaxIntegralAccumulator, mConstants.kLongCANTimeoutMs), mConstants.kName + ": Could not set max integral: "); TalonUtil.checkError(mMaster.config_IntegralZone(kPositionPIDSlot, mConstants.kPositionIZone, mConstants.kLongCANTimeoutMs), mConstants.kName + ": Could not set i zone: "); TalonUtil.checkError( mMaster.configAllowableClosedloopError(kPositionPIDSlot, mConstants.kPositionDeadband, mConstants.kLongCANTimeoutMs), mConstants.kName + ": Could not set deadband: "); TalonUtil.checkError( mMaster.configMotionCruiseVelocity(mConstants.kCruiseVelocity, mConstants.kLongCANTimeoutMs), mConstants.kName + ": Could not set cruise velocity: "); TalonUtil.checkError(mMaster.configMotionAcceleration(mConstants.kAcceleration, mConstants.kLongCANTimeoutMs), mConstants.kName + ": Could not set acceleration: "); TalonUtil.checkError(mMaster.configOpenloopRamp(mConstants.kRampRate, mConstants.kLongCANTimeoutMs), mConstants.kName + ": Could not set voltage ramp rate: "); TalonUtil.checkError(mMaster.configClosedloopRamp(mConstants.kRampRate, mConstants.kLongCANTimeoutMs), mConstants.kName + ": Could not set closed loop ramp rate: "); TalonUtil.checkError(mMaster.configSupplyCurrentLimit(new SupplyCurrentLimitConfiguration( mConstants.kEnableSupplyCurrentLimit, mConstants.kSupplyContinuousCurrentLimit, mConstants.kSupplyPeakCurrentLimit, mConstants.kSupplyPeakCurrentDuration)), mConstants.kName + ": Could not set supply current limit."); TalonUtil.checkError(mMaster.configStatorCurrentLimit(new StatorCurrentLimitConfiguration( mConstants.kEnableStatorCurrentLimit, mConstants.kStatorContinuousCurrentLimit, mConstants.kStatorPeakCurrentLimit, mConstants.kStatorPeakCurrentDuration)), mConstants.kName + ": Could not set stator current limit."); mMaster.configVoltageMeasurementFilter(8); TalonUtil.checkError( mMaster.configVoltageCompSaturation(mConstants.kMaxVoltage, mConstants.kLongCANTimeoutMs), mConstants.kName + ": Could not set voltage comp saturation."); mMaster.enableVoltageCompensation(true); mMaster.setInverted(mConstants.kMasterConstants.invert_motor); mMaster.setSensorPhase(mConstants.kMasterConstants.invert_sensor_phase); mMaster.setNeutralMode(NeutralMode.Brake); mMaster.setStatusFramePeriod(StatusFrameEnhanced.Status_2_Feedback0, 5, 20); mMaster.setStatusFramePeriod(StatusFrameEnhanced.Status_10_MotionMagic, 1000, 20); mMaster.setStatusFramePeriod(StatusFrameEnhanced.Status_8_PulseWidth, mConstants.kStatusFrame8UpdateRate, 20); // Start with kMotionProfileSlot. mMaster.selectProfileSlot(kMotionProfileSlot, 0); for (int i = 0; i < mSlaves.length; ++i) { mSlaves[i] = TalonFXFactory.createPermanentSlaveTalon(mConstants.kSlaveConstants[i].id, mConstants.kMasterConstants.id); mSlaves[i].setInverted(mConstants.kSlaveConstants[i].invert_motor); mSlaves[i].setNeutralMode(NeutralMode.Brake); mSlaves[i].follow(mMaster); } // Send a neutral command. stop(); } public static class PeriodicIO { // INPUTS public double timestamp; public double position_ticks; public double position_units; public double velocity_ticks_per_100ms; public double active_trajectory_position; // ticks public double active_trajectory_velocity; // ticks/100ms public double active_trajectory_acceleration; // ticks/100ms/s public double output_percent; public double output_voltage; public double master_current; public double error_ticks; public int encoder_wraps; public int absolute_pulse_offset = 0; // public int absolute_pulse_position; public int absolute_pulse_position_modded; public boolean reset_occured; // OUTPUTS public double demand; public double feedforward; } protected enum ControlState { OPEN_LOOP, MOTION_MAGIC, POSITION_PID, MOTION_PROFILING } protected PeriodicIO mPeriodicIO = new PeriodicIO(); protected ControlState mControlState = ControlState.OPEN_LOOP;
package com.team5419.frc2023.subsystems; /** * Abstract base class for a subsystem with a single sensor servo-mechanism. */ public abstract class ServoMotorSubsystem extends Subsystem { protected static final int kMotionProfileSlot = 0; protected static final int kPositionPIDSlot = 1; // Recommend initializing in a static block! public static class TalonFXConstants { public int id = -1; public boolean invert_motor = false; public boolean invert_sensor_phase = false; public int encoder_ppr = 2048; } // Recommend initializing in a static block! public static class ServoMotorSubsystemConstants { public String kName = "ERROR_ASSIGN_A_NAME"; public double kLooperDt = 0.01; public int kCANTimeoutMs = 10; // use for important on the fly updates public int kLongCANTimeoutMs = 100; // use for constructors public TalonFXConstants kMasterConstants = new TalonFXConstants(); public TalonFXConstants[] kSlaveConstants = new TalonFXConstants[0]; public double kHomePosition = 0.0; // Units public double kTicksPerUnitDistance = 1.0; public double kKp = 0; // Raw output / raw error public double kKi = 0; // Raw output / sum of raw error public double kKd = 0; // Raw output / (err - prevErr) public double kKf = 0; // Raw output / velocity in ticks/100ms public double kKa = 0; // Raw output / accel in (ticks/100ms) / s public double kMaxIntegralAccumulator = 0; public int kIZone = 0; // Ticks public int kDeadband = 0; // Ticks public double kPositionKp = 0; public double kPositionKi = 0; public double kPositionKd = 0; public double kPositionKf = 0; public double kPositionMaxIntegralAccumulator = 0; public int kPositionIZone = 0; // Ticks public int kPositionDeadband = 0; // Ticks public int kCruiseVelocity = 0; // Ticks / 100ms public int kAcceleration = 0; // Ticks / 100ms / s public double kRampRate = 0.0; // s public double kMaxVoltage = 12.0; public int kSupplyContinuousCurrentLimit = 20; // amps public int kSupplyPeakCurrentLimit = 60; // amps public double kSupplyPeakCurrentDuration = 0.2; // seconds public boolean kEnableSupplyCurrentLimit = false; public int kStatorContinuousCurrentLimit = 20; // amps public int kStatorPeakCurrentLimit = 60; // amps public double kStatorPeakCurrentDuration = 0.2; // seconds public boolean kEnableStatorCurrentLimit = false; public double kMaxUnitsLimit = Double.POSITIVE_INFINITY; public double kMinUnitsLimit = Double.NEGATIVE_INFINITY; public int kStatusFrame8UpdateRate = 1000; public boolean kRecoverPositionOnReset = false; } protected final ServoMotorSubsystemConstants mConstants; protected final TalonFX mMaster; protected final TalonFX[] mSlaves; protected MotionState mMotionStateSetpoint = null; protected final int mForwardSoftLimitTicks; protected final int mReverseSoftLimitTicks; protected ServoMotorSubsystem(final ServoMotorSubsystemConstants constants) { mConstants = constants; mMaster = TalonFXFactory.createDefaultTalon(mConstants.kMasterConstants.id); mSlaves = new TalonFX[mConstants.kSlaveConstants.length]; TalonUtil.checkError(mMaster.configSelectedFeedbackSensor(FeedbackDevice.IntegratedSensor, 0, mConstants.kLongCANTimeoutMs), mConstants.kName + ": Could not detect encoder: "); mForwardSoftLimitTicks = (int) ((mConstants.kMaxUnitsLimit - mConstants.kHomePosition) * mConstants.kTicksPerUnitDistance); TalonUtil.checkError( mMaster.configForwardSoftLimitThreshold(mForwardSoftLimitTicks, mConstants.kLongCANTimeoutMs), mConstants.kName + ": Could not set forward soft limit: "); TalonUtil.checkError(mMaster.configForwardSoftLimitEnable(true, mConstants.kLongCANTimeoutMs), mConstants.kName + ": Could not enable forward soft limit: "); mReverseSoftLimitTicks = (int) ((mConstants.kMinUnitsLimit - mConstants.kHomePosition) * mConstants.kTicksPerUnitDistance); TalonUtil.checkError( mMaster.configReverseSoftLimitThreshold(mReverseSoftLimitTicks, mConstants.kLongCANTimeoutMs), mConstants.kName + ": Could not set reverse soft limit: "); TalonUtil.checkError(mMaster.configReverseSoftLimitEnable(true, mConstants.kLongCANTimeoutMs), mConstants.kName + ": Could not enable reverse soft limit: "); TalonUtil.checkError(mMaster.configVoltageCompSaturation(12.0, mConstants.kLongCANTimeoutMs), mConstants.kName + ": Could not set voltage compensation saturation: "); TalonUtil.checkError(mMaster.config_kP(kMotionProfileSlot, mConstants.kKp, mConstants.kLongCANTimeoutMs), mConstants.kName + ": could not set kP: "); TalonUtil.checkError(mMaster.config_kI(kMotionProfileSlot, mConstants.kKi, mConstants.kLongCANTimeoutMs), mConstants.kName + ": could not set kI: "); TalonUtil.checkError(mMaster.config_kD(kMotionProfileSlot, mConstants.kKd, mConstants.kLongCANTimeoutMs), mConstants.kName + ": could not set kD: "); TalonUtil.checkError(mMaster.config_kF(kMotionProfileSlot, mConstants.kKf, mConstants.kLongCANTimeoutMs), mConstants.kName + ": Could not set kF: "); TalonUtil.checkError(mMaster.configMaxIntegralAccumulator(kMotionProfileSlot, mConstants.kMaxIntegralAccumulator, mConstants.kLongCANTimeoutMs), mConstants.kName + ": Could not set max integral: "); TalonUtil.checkError(mMaster.config_IntegralZone(kMotionProfileSlot, mConstants.kIZone, mConstants.kLongCANTimeoutMs), mConstants.kName + ": Could not set i zone: "); TalonUtil.checkError( mMaster.configAllowableClosedloopError(kMotionProfileSlot, mConstants.kDeadband, mConstants.kLongCANTimeoutMs), mConstants.kName + ": Could not set deadband: "); TalonUtil.checkError(mMaster.config_kP(kPositionPIDSlot, mConstants.kPositionKp, mConstants.kLongCANTimeoutMs), mConstants.kName + ": could not set kP: "); TalonUtil.checkError(mMaster.config_kI(kPositionPIDSlot, mConstants.kPositionKi, mConstants.kLongCANTimeoutMs), mConstants.kName + ": could not set kI: "); TalonUtil.checkError(mMaster.config_kD(kPositionPIDSlot, mConstants.kPositionKd, mConstants.kLongCANTimeoutMs), mConstants.kName + ": could not set kD: "); TalonUtil.checkError(mMaster.config_kF(kPositionPIDSlot, mConstants.kPositionKf, mConstants.kLongCANTimeoutMs), mConstants.kName + ": Could not set kF: "); TalonUtil.checkError(mMaster.configMaxIntegralAccumulator(kPositionPIDSlot, mConstants.kPositionMaxIntegralAccumulator, mConstants.kLongCANTimeoutMs), mConstants.kName + ": Could not set max integral: "); TalonUtil.checkError(mMaster.config_IntegralZone(kPositionPIDSlot, mConstants.kPositionIZone, mConstants.kLongCANTimeoutMs), mConstants.kName + ": Could not set i zone: "); TalonUtil.checkError( mMaster.configAllowableClosedloopError(kPositionPIDSlot, mConstants.kPositionDeadband, mConstants.kLongCANTimeoutMs), mConstants.kName + ": Could not set deadband: "); TalonUtil.checkError( mMaster.configMotionCruiseVelocity(mConstants.kCruiseVelocity, mConstants.kLongCANTimeoutMs), mConstants.kName + ": Could not set cruise velocity: "); TalonUtil.checkError(mMaster.configMotionAcceleration(mConstants.kAcceleration, mConstants.kLongCANTimeoutMs), mConstants.kName + ": Could not set acceleration: "); TalonUtil.checkError(mMaster.configOpenloopRamp(mConstants.kRampRate, mConstants.kLongCANTimeoutMs), mConstants.kName + ": Could not set voltage ramp rate: "); TalonUtil.checkError(mMaster.configClosedloopRamp(mConstants.kRampRate, mConstants.kLongCANTimeoutMs), mConstants.kName + ": Could not set closed loop ramp rate: "); TalonUtil.checkError(mMaster.configSupplyCurrentLimit(new SupplyCurrentLimitConfiguration( mConstants.kEnableSupplyCurrentLimit, mConstants.kSupplyContinuousCurrentLimit, mConstants.kSupplyPeakCurrentLimit, mConstants.kSupplyPeakCurrentDuration)), mConstants.kName + ": Could not set supply current limit."); TalonUtil.checkError(mMaster.configStatorCurrentLimit(new StatorCurrentLimitConfiguration( mConstants.kEnableStatorCurrentLimit, mConstants.kStatorContinuousCurrentLimit, mConstants.kStatorPeakCurrentLimit, mConstants.kStatorPeakCurrentDuration)), mConstants.kName + ": Could not set stator current limit."); mMaster.configVoltageMeasurementFilter(8); TalonUtil.checkError( mMaster.configVoltageCompSaturation(mConstants.kMaxVoltage, mConstants.kLongCANTimeoutMs), mConstants.kName + ": Could not set voltage comp saturation."); mMaster.enableVoltageCompensation(true); mMaster.setInverted(mConstants.kMasterConstants.invert_motor); mMaster.setSensorPhase(mConstants.kMasterConstants.invert_sensor_phase); mMaster.setNeutralMode(NeutralMode.Brake); mMaster.setStatusFramePeriod(StatusFrameEnhanced.Status_2_Feedback0, 5, 20); mMaster.setStatusFramePeriod(StatusFrameEnhanced.Status_10_MotionMagic, 1000, 20); mMaster.setStatusFramePeriod(StatusFrameEnhanced.Status_8_PulseWidth, mConstants.kStatusFrame8UpdateRate, 20); // Start with kMotionProfileSlot. mMaster.selectProfileSlot(kMotionProfileSlot, 0); for (int i = 0; i < mSlaves.length; ++i) { mSlaves[i] = TalonFXFactory.createPermanentSlaveTalon(mConstants.kSlaveConstants[i].id, mConstants.kMasterConstants.id); mSlaves[i].setInverted(mConstants.kSlaveConstants[i].invert_motor); mSlaves[i].setNeutralMode(NeutralMode.Brake); mSlaves[i].follow(mMaster); } // Send a neutral command. stop(); } public static class PeriodicIO { // INPUTS public double timestamp; public double position_ticks; public double position_units; public double velocity_ticks_per_100ms; public double active_trajectory_position; // ticks public double active_trajectory_velocity; // ticks/100ms public double active_trajectory_acceleration; // ticks/100ms/s public double output_percent; public double output_voltage; public double master_current; public double error_ticks; public int encoder_wraps; public int absolute_pulse_offset = 0; // public int absolute_pulse_position; public int absolute_pulse_position_modded; public boolean reset_occured; // OUTPUTS public double demand; public double feedforward; } protected enum ControlState { OPEN_LOOP, MOTION_MAGIC, POSITION_PID, MOTION_PROFILING } protected PeriodicIO mPeriodicIO = new PeriodicIO(); protected ControlState mControlState = ControlState.OPEN_LOOP;
protected ReflectingCSVWriter<PeriodicIO> mCSVWriter = null;
5
2023-11-14 06:44:40+00:00
12k
threethan/QuestAudioPatcher
app/src/main/java/com/threethan/questpatcher/activities/APKInstallerActivity.java
[ { "identifier": "APKDetailsFragment", "path": "app/src/main/java/com/threethan/questpatcher/fragments/APKDetailsFragment.java", "snippet": "public class APKDetailsFragment extends Fragment {\n\n @Nullable\n @Override\n public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {\n View mRootView = inflater.inflate(R.layout.recyclerview_layout, container, false);\n\n RecyclerView mRecyclerView = mRootView.findViewById(R.id.recycler_view);\n mRecyclerView.setLayoutManager(new LinearLayoutManager(requireActivity()));\n \n new sExecutor() {\n private APKDetailsAdapter mAdapter;\n @Override\n public void onPreExecute() {\n }\n\n @Override\n public void doInBackground() {\n mAdapter = new APKDetailsAdapter(ExternalAPKData.getData(requireActivity()));\n }\n\n @Override\n public void onPostExecute() {\n mRecyclerView.setAdapter(mAdapter);\n\n }\n }.execute();\n\n return mRootView;\n }\n \n}" }, { "identifier": "CertificateFragment", "path": "app/src/main/java/com/threethan/questpatcher/fragments/CertificateFragment.java", "snippet": "public class CertificateFragment extends Fragment {\n\n @Nullable\n @Override\n public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {\n View mRootView = inflater.inflate(R.layout.textview_layout, container, false);\n\n MaterialTextView mText = mRootView.findViewById(R.id.text);\n\n APKParser mAPKParser = new APKParser();\n\n if (mAPKParser.getCertificate() != null) {\n try {\n mText.setText(mAPKParser.getCertificate());\n } catch (Exception ignored) {\n }\n }\n\n return mRootView;\n }\n \n}" }, { "identifier": "ManifestFragment", "path": "app/src/main/java/com/threethan/questpatcher/fragments/ManifestFragment.java", "snippet": "public class ManifestFragment extends Fragment {\n\n @Nullable\n @Override\n public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {\n View mRootView = inflater.inflate(R.layout.recyclerview_layout, container, false);\n\n RecyclerView mRecyclerView = mRootView.findViewById(R.id.recycler_view);\n mRecyclerView.setLayoutManager(new LinearLayoutManager(requireActivity()));\n\n APKParser mAPKParser = new APKParser();\n\n if (mAPKParser.getManifest() != null) {\n try {\n mRecyclerView.setAdapter(new TextViewAdapter(APKExplorer.getTextViewData(mAPKParser.getManifest(), null, true, requireActivity()), null));\n } catch (Exception ignored) {\n }\n }\n\n return mRootView;\n }\n \n}" }, { "identifier": "PermissionsFragment", "path": "app/src/main/java/com/threethan/questpatcher/fragments/PermissionsFragment.java", "snippet": "public class PermissionsFragment extends Fragment {\n\n @Nullable\n @Override\n public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {\n View mRootView = inflater.inflate(R.layout.textview_layout, container, false);\n\n MaterialTextView mText = mRootView.findViewById(R.id.text);\n\n APKParser mAPKParser = new APKParser();\n\n if (mAPKParser.getPermissions() != null) {\n try {\n StringBuilder sb = new StringBuilder();\n for (String permission : mAPKParser.getPermissions()) {\n sb.append(permission).append(\"\\n\").append(sPermissionUtils.getDescription(permission.replace(\n \"android.permission.\",\"\"), requireActivity())).append(\"\\n\\n\");\n }\n mText.setText(sb.toString());\n } catch (Exception ignored) {\n }\n }\n\n return mRootView;\n }\n \n}" }, { "identifier": "APKExplorer", "path": "app/src/main/java/com/threethan/questpatcher/utils/APKExplorer.java", "snippet": "public class APKExplorer {\n\n public static List<String> getData(File[] files, boolean supported, Activity activity) {\n List<String> mData = new ArrayList<>(), mDir = new ArrayList<>(), mFiles = new ArrayList<>();\n try {\n // Add directories\n for (File mFile : files) {\n if (mFile.isDirectory() && !mFile.getName().matches(\".aeeBackup|.aeeBuild\")) {\n mDir.add(mFile.getAbsolutePath());\n }\n }\n Collections.sort(mDir, String.CASE_INSENSITIVE_ORDER);\n if (!sCommonUtils.getBoolean(\"az_order\", true, activity)) {\n Collections.reverse(mDir);\n }\n mData.addAll(mDir);\n // Add files\n for (File mFile :files) {\n if (supported) {\n if (mFile.isFile()) {\n mFiles.add(mFile.getAbsolutePath());\n }\n } else if (mFile.isFile() && isSupportedFile(mFile.getAbsolutePath())) {\n mFiles.add(mFile.getAbsolutePath());\n\n }\n }\n Collections.sort(mFiles, String.CASE_INSENSITIVE_ORDER);\n if (!sCommonUtils.getBoolean(\"az_order\", true, activity)) {\n Collections.reverse(mFiles);\n }\n mData.addAll(mFiles);\n } catch (NullPointerException ignored) {\n activity.finish();\n }\n return mData;\n }\n\n public static boolean isTextFile(String path) {\n return path.endsWith(\".txt\") || path.endsWith(\".xml\") || path.endsWith(\".json\") || path.endsWith(\".properties\")\n || path.endsWith(\".version\") || path.endsWith(\".sh\") || path.endsWith(\".MF\") || path.endsWith(\".SF\")\n || path.endsWith(\".html\") || path.endsWith(\".ini\") || path.endsWith(\".smali\");\n }\n\n public static boolean isImageFile(String path) {\n return path.endsWith(\".bmp\") || path.endsWith(\".png\") || path.endsWith(\".jpg\");\n }\n\n public static boolean isBinaryXML(String path) {\n return path.endsWith(\".xml\") && (new File(path).getName().equals(\"AndroidManifest.xml\") || path.contains(Common.getAppID() + \"/res/\"));\n }\n\n public static boolean isSmaliEdited(String path) {\n if (getAppData(path) == null) return false;\n try {\n return Objects.requireNonNull(getAppData(path)).getBoolean(\"smali_edited\");\n } catch (JSONException ignored) {\n }\n return false;\n }\n\n public static Bitmap getAppIcon(String path) {\n if (getAppData(path) == null) return null;\n try {\n return stringToBitmap(Objects.requireNonNull(getAppData(path)).getString(\"app_icon\"));\n } catch (JSONException ignored) {\n }\n return null;\n }\n\n public static Bitmap stringToBitmap(String string) {\n try {\n byte[] imageAsBytes = Base64.decode(string.getBytes(), Base64.DEFAULT);\n return BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length);\n } catch (Exception ignored) {}\n return null;\n }\n\n private static boolean isSupportedFile(String path) {\n return path.endsWith(\".apk\") || path.endsWith(\".apks\") || path.endsWith(\".apkm\") || path.endsWith(\".xapk\");\n }\n\n public static JSONObject getAppData(String path) {\n if (sFileUtils.read(new File(path)) == null) return null;\n try {\n return new JSONObject(sFileUtils.read(new File(path)));\n } catch (JSONException ignored) {\n }\n return null;\n }\n\n public static void setIcon(AppCompatImageButton icon, Drawable drawable, Context context) {\n icon.setImageDrawable(drawable);\n icon.setColorFilter(sThemeUtils.isDarkTheme(context) ? ContextCompat.getColor(context, R.color.colorWhite) :\n ContextCompat.getColor(context, R.color.colorBlack));\n }\n\n public static int getSpanCount(Activity activity) {\n return sCommonUtils.getOrientation(activity) == Configuration.ORIENTATION_LANDSCAPE ? 2 : 1;\n }\n\n public static String getAppName(String path) {\n if (getAppData(path) == null) return null;\n try {\n return Objects.requireNonNull(getAppData(path)).getString(\"app_name\");\n } catch (JSONException ignored) {\n }\n return null;\n }\n\n public static String getPackageName(String path) {\n if (getAppData(path) == null) return null;\n try {\n return Objects.requireNonNull(getAppData(path)).getString(\"package_name\");\n } catch (JSONException ignored) {\n }\n return null;\n }\n\n public static List<String> getTextViewData(String path, String searchWord, boolean parsedManifest, Context context) {\n List<String> mData = new ArrayList<>();\n String text = null;\n if (isBinaryXML(path)) {\n try (FileInputStream inputStream = new FileInputStream(path)) {\n text = new aXMLDecoder().decode(inputStream).trim();\n } catch (Exception e) {\n sCommonUtils.toast(context.getString(R.string.xml_decode_failed, new File(path).getName()), context).show();\n }\n } else if (parsedManifest) {\n text = path;\n } else {\n text = sFileUtils.read(new File(path));\n }\n if (text != null) {\n for (String line : text.split(\"\\\\r?\\\\n\")) {\n if (searchWord == null) {\n mData.add(line);\n } else if (Common.isTextMatched(line, searchWord)) {\n mData.add(line);\n }\n }\n }\n return mData;\n }\n\n public static Uri getIconFromPath(String path) {\n File mFile = new File(path);\n if (mFile.exists()) {\n return Uri.fromFile(mFile);\n }\n return null;\n }\n\n public static void saveImage(Bitmap bitmap, String dest, Context context) {\n try {\n OutputStream imageOutStream;\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {\n ContentValues values = new ContentValues();\n values.put(MediaStore.MediaColumns.DISPLAY_NAME, new File(dest).getName());\n values.put(MediaStore.MediaColumns.MIME_TYPE, \"image/png\");\n values.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS);\n Uri uri = context.getContentResolver().insert(MediaStore.Files.getContentUri(\"external\"), values);\n imageOutStream = context.getContentResolver().openOutputStream(uri);\n } else {\n File image = new File(dest);\n imageOutStream = new FileOutputStream(image);\n }\n bitmap.compress(Bitmap.CompressFormat.PNG, 100, imageOutStream);\n imageOutStream.close();\n } catch(Exception ignored) {\n }\n }\n\n public static Bitmap drawableToBitmap(Drawable drawable) {\n Bitmap bitmap;\n if (drawable instanceof BitmapDrawable) {\n BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;\n if(bitmapDrawable.getBitmap() != null) {\n return bitmapDrawable.getBitmap();\n }\n }\n if (drawable.getIntrinsicWidth() <= 0 || drawable.getIntrinsicHeight() <= 0) {\n bitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888);\n } else {\n bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);\n }\n Canvas canvas = new Canvas(bitmap);\n drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());\n drawable.draw(canvas);\n return bitmap;\n }\n\n private static void installAPKs(boolean exit, Activity activity) {\n SplitAPKInstaller.installSplitAPKs(exit, Common.getAPKList(), null, activity);\n }\n\n public static void handleAPKs(boolean exit, Activity activity) {\n if (APKEditorUtils.isFullVersion(activity)) {\n if (sCommonUtils.getString(\"installerAction\", null, activity) == null) {\n new sSingleItemDialog(0, null, new String[] {\n activity.getString(R.string.install),\n activity.getString(R.string.install_resign),\n activity.getString(R.string.resign_only)\n }, activity) {\n\n @Override\n public void onItemSelected(int itemPosition) {\n sCommonUtils.saveBoolean(\"firstSigning\", true, activity);\n if (itemPosition == 0) {\n installAPKs(exit, activity);\n } else if (itemPosition == 1) {\n if (!sCommonUtils.getBoolean(\"firstSigning\", false, activity)) {\n new SigningOptionsDialog(null, exit, activity).show();\n } else {\n new ResignAPKs(null, true, exit, activity).execute();\n }\n } else {\n if (!sCommonUtils.getBoolean(\"firstSigning\", false, activity)) {\n new SigningOptionsDialog(null, exit, activity).show();\n } else {\n new ResignAPKs(null, false, exit, activity).execute();\n }\n }\n }\n }.show();\n } else if (sCommonUtils.getString(\"installerAction\", null, activity).equals(activity.getString(R.string.install))) {\n installAPKs(exit, activity);\n } else {\n if (!sCommonUtils.getBoolean(\"firstSigning\", false, activity)) {\n new SigningOptionsDialog(null, exit, activity).show();\n } else {\n new ResignAPKs(null,true, exit, activity).execute();\n }\n }\n } else {\n installAPKs(exit, activity);\n }\n }\n\n}" }, { "identifier": "Common", "path": "app/src/main/java/com/threethan/questpatcher/utils/Common.java", "snippet": "public class Common {\n\n private static AppCompatEditText mSearchWordApks, mSearchWordApps, mSearchWordProjects;\n private static boolean mBuilding = false, mBusy = false, mCancel = false, mFinish = false,\n mPrivateKey = false, mReloading = false, mRSATemplate = false;\n private static List<File> mFile = null;\n private static List<PackageItems> mPackageData = null;\n private static final List<String> mAPKList = new ArrayList<>(), mErrorList = new ArrayList<>();\n private static int mError = 0, mSuccess = 0;\n private static MaterialCardView mSelect;\n private static MaterialTextView mApksTitle, mAppsTitle, mProjectsTitle;\n private static String mAppID, mFilePath = null, mFileToReplace = null, mPackageName = null,\n mPath = null, mSearchWord, mStatus = null;\n\n public static AppCompatEditText getAPKsSearchWord() {\n return mSearchWordApks;\n }\n\n public static AppCompatEditText getAppsSearchWord() {\n return mSearchWordApps;\n }\n\n public static AppCompatEditText getProjectsSearchWord() {\n return mSearchWordProjects;\n }\n\n public static boolean isBuilding() {\n return mBuilding;\n }\n\n public static boolean isBusy() {\n return mBusy;\n }\n\n public static boolean isCancelled() {\n return mCancel;\n }\n\n public static boolean isFinished() {\n return mFinish;\n }\n\n public static boolean isReloading() {\n return mReloading;\n }\n\n public static boolean isTextMatched(String searchText, String searchWord) {\n for (int a = 0; a < searchText.length() - searchWord.length() + 1; a++) {\n if (searchWord.equalsIgnoreCase(searchText.substring(a, a + searchWord.length()))) {\n return true;\n }\n }\n return false;\n }\n\n public static boolean hasPrivateKey() {\n return mPrivateKey;\n }\n\n public static boolean hasRASATemplate() {\n return mRSATemplate;\n }\n\n public static int getError() {\n return mError;\n }\n\n public static int getSuccess() {\n return mSuccess;\n }\n\n public static List<File> getFiles() {\n return mFile;\n }\n\n public static List<PackageItems> getPackageData() {\n return mPackageData;\n }\n\n public static List<String> getAPKList() {\n return mAPKList;\n }\n\n public static List<String> getErrorList() {\n return mErrorList;\n }\n\n public static MaterialCardView getSelectCard() {\n return mSelect;\n }\n\n public static MaterialTextView getAPKsTitle() {\n return mApksTitle;\n }\n\n public static MaterialTextView getAppsTitle() {\n return mAppsTitle;\n }\n\n public static MaterialTextView getProjectsTitle() {\n return mProjectsTitle;\n }\n\n public static String getAppID() {\n return mAppID;\n }\n\n public static String getFilePath() {\n return mFilePath;\n }\n\n public static String getFileToReplace() {\n return mFileToReplace;\n }\n\n public static String getPackageName() {\n return mPackageName;\n }\n\n public static String getPath() {\n return mPath;\n }\n\n public static String getSearchWord() {\n return mSearchWord;\n }\n\n public static String getStatus() {\n return mStatus;\n }\n\n public static void addToFilesList(File file) {\n if (mFile == null) {\n mFile = new ArrayList<>();\n }\n mFile.add(file);\n }\n\n public static void clearFilesList() {\n mFile = null;\n }\n\n public static void initializeAPKsSearchWord(View view, int id) {\n mSearchWordApks = view.findViewById(id);\n }\n\n public static void initializeAPKsTitle(View view, int id) {\n mApksTitle = view.findViewById(id);\n }\n\n public static void initializeAppsSearchWord(View view, int id) {\n mSearchWordApps = view.findViewById(id);\n }\n\n public static void initializeAppsTitle(View view, int id) {\n mAppsTitle = view.findViewById(id);\n }\n\n public static void initializeProjectsSearchWord(View view, int id) {\n mSearchWordProjects = view.findViewById(id);\n }\n\n public static void initializeProjectsTitle(View view, int id) {\n mProjectsTitle = view.findViewById(id);\n }\n\n public static void initializeView(View view, int id) {\n mSelect = view.findViewById(id);\n }\n\n public static void isBuilding(boolean b) {\n mBuilding = b;\n }\n\n public static void isCancelled(boolean b) {\n mCancel = b;\n }\n\n public static void isReloading(boolean b) {\n mReloading = b;\n }\n\n public static void removeFromFilesList(File file) {\n if (mFile == null || mFile.size() == 0) return;\n mFile.remove(file);\n }\n\n public static void setFinishStatus(boolean b) {\n mFinish = b;\n }\n\n public static void setPrivateKeyStatus(boolean b) {\n mPrivateKey = b;\n }\n\n public static void setRSATemplateStatus(boolean b) {\n mRSATemplate = b;\n }\n\n public static void setAppID(String appID) {\n mAppID = appID;\n }\n\n public static void setError(int i) {\n mError = i;\n }\n\n public static void setFilePath(String filePath) {\n mFilePath = filePath;\n }\n\n public static void setFileToReplace(String fileToReplace) {\n mFileToReplace = fileToReplace;\n }\n\n public static void setPackageName(String packageName) {\n mPackageName = packageName;\n }\n\n public static void setPackageData(List<PackageItems> data) {\n mPackageData = data;\n }\n\n public static void setPath(String path) {\n mPath = path;\n }\n\n public static void setProgress(boolean b, View view) {\n mBusy = b;\n view.setVisibility(b ? View.VISIBLE : View.GONE);\n }\n\n public static void setSearchWord(String searchWord) {\n mSearchWord = searchWord;\n }\n\n public static void setStatus(String status) {\n mStatus = status;\n }\n\n public static void setSuccess(int i) {\n mSuccess = i;\n }\n\n}" }, { "identifier": "InvalidFileDialog", "path": "app/src/main/java/com/threethan/questpatcher/utils/dialogs/InvalidFileDialog.java", "snippet": "public class InvalidFileDialog {\n\n private final MaterialAlertDialogBuilder mDialogBuilder;\n\n public InvalidFileDialog(boolean exit, Activity activity) {\n mDialogBuilder = new MaterialAlertDialogBuilder(activity)\n .setIcon(R.mipmap.ic_launcher)\n .setTitle(R.string.split_apk_installer)\n .setMessage(activity.getString(R.string.wrong_extension, \".apks/.apkm/.xapk\"))\n .setCancelable(false)\n .setPositiveButton(R.string.cancel, (dialogInterface, i) -> {\n if (exit) {\n activity.finish();\n }\n });\n }\n\n public void show() {\n mDialogBuilder.show();\n }\n\n}" }, { "identifier": "SelectBundleDialog", "path": "app/src/main/java/com/threethan/questpatcher/utils/dialogs/SelectBundleDialog.java", "snippet": "public class SelectBundleDialog {\n\n private final MaterialAlertDialogBuilder mDialogBuilder;\n\n public SelectBundleDialog(String path, boolean exit, Activity activity) {\n mDialogBuilder = new MaterialAlertDialogBuilder(activity)\n .setIcon(R.mipmap.ic_launcher)\n .setTitle(R.string.split_apk_installer)\n .setMessage(activity.getString(R.string.install_bundle_question))\n .setCancelable(false)\n .setNegativeButton(R.string.cancel, (dialogInterface, i) -> {\n if (exit) {\n activity.finish();\n }\n })\n .setPositiveButton(R.string.yes, (dialogInterface, i) ->\n SplitAPKInstaller.handleAppBundle(exit, path, activity)\n );\n }\n\n public void show() {\n mDialogBuilder.show();\n }\n\n}" }, { "identifier": "ExploreAPK", "path": "app/src/main/java/com/threethan/questpatcher/utils/tasks/ExploreAPK.java", "snippet": "public class ExploreAPK extends sExecutor {\n\n private final Context mContext;\n private File mBackUpPath, mExplorePath;\n private File mAPKFile;\n private final String mPackageName;\n private final Uri mUri;\n\n public ExploreAPK(String packageName, File apkFile, Uri uri, Context context) {\n mPackageName = packageName;\n mAPKFile = apkFile;\n mUri = uri;\n mContext = context;\n }\n\n @SuppressLint(\"StringFormatInvalid\")\n @Override\n public void onPreExecute() {\n Common.isBuilding(false);\n Common.isCancelled(false);\n Common.setFinishStatus(false);\n if (mUri != null) {\n String fileName = Objects.requireNonNull(DocumentFile.fromSingleUri(mContext, mUri)).getName();\n mAPKFile = new File(mContext.getExternalFilesDir(\"APK\"), Objects.requireNonNull(fileName));\n sFileUtils.copy(mUri, mAPKFile, mContext);\n }\n Common.setAppID(mPackageName != null ? mPackageName : mAPKFile.getName());\n mExplorePath = new File(mContext.getCacheDir().getPath(), mPackageName != null ? mPackageName : mAPKFile.getName());\n mBackUpPath = new File(mExplorePath, \".aeeBackup\");\n\n // Bypass backup/cache\n sFileUtils.delete(mExplorePath);\n sFileUtils.delete(mBackUpPath);\n\n\n Common.setPath(mExplorePath.getAbsolutePath());\n if (!mExplorePath.exists()) {\n Common.setFinishStatus(false);\n Common.setStatus(null);\n Intent apkTasks = new Intent(mContext, APKTasksActivity.class);\n mContext.startActivity(apkTasks);\n Common.setStatus(mContext.getString(R.string.exploring, mPackageName != null ? sPackageUtils.getAppName(mPackageName, mContext) : mAPKFile.getName()));\n } else if (!sFileUtils.exist(new File(mBackUpPath, \"appData\"))) {\n sFileUtils.delete(mExplorePath);\n }\n }\n\n @SuppressLint(\"StringFormatInvalid\")\n @Override\n public void doInBackground() {\n if (!mExplorePath.exists()) {\n sFileUtils.mkdir(mExplorePath);\n sFileUtils.mkdir(mBackUpPath);\n // Store basic information about the app\n try {\n ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();\n if (mPackageName != null) {\n Bitmap.createScaledBitmap(APKExplorer.drawableToBitmap(sPackageUtils.getAppIcon(mPackageName, mContext)),\n 150, 150, true).compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);\n byte[] byteArray = byteArrayOutputStream.toByteArray();\n JSONObject mJSONObject = new JSONObject();\n mJSONObject.put(\"app_icon\", Base64.encodeToString(byteArray, Base64.DEFAULT));\n mJSONObject.put(\"app_name\", sPackageUtils.getAppName(mPackageName, mContext));\n mJSONObject.put(\"package_name\", mPackageName);\n mJSONObject.put(\"smali_edited\", false);\n sFileUtils.create(mJSONObject.toString(), new File(mBackUpPath, \"appData\"));\n } else {\n Bitmap.createScaledBitmap(APKExplorer.drawableToBitmap(sAPKUtils.getAPKIcon(mAPKFile.getAbsolutePath(), mContext)),\n 150, 150, true).compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);\n byte[] byteArray = byteArrayOutputStream.toByteArray();\n JSONObject mJSONObject = new JSONObject();\n mJSONObject.put(\"app_icon\", Base64.encodeToString(byteArray, Base64.DEFAULT));\n mJSONObject.put(\"app_name\", mAPKFile.getName());\n mJSONObject.put(\"package_name\", sAPKUtils.getPackageName(mAPKFile.getAbsolutePath(), mContext));\n mJSONObject.put(\"smali_edited\", false);\n sFileUtils.create(mJSONObject.toString(), new File(mBackUpPath, \"appData\"));\n }\n } catch (JSONException ignored) {\n }\n APKEditorUtils.unzip(mPackageName != null ? sPackageUtils.getSourceDir(mPackageName, mContext) : mAPKFile.getAbsolutePath(), mExplorePath.getAbsolutePath());\n // (Don't) Decompile dex file(s)\n// for (File files : Objects.requireNonNull(mExplorePath.listFiles())) {\n// if (files.getName().startsWith(\"classes\") && files.getName().endsWith(\".dex\") && !Common.isCancelled()) {\n// sFileUtils.mkdir(mBackUpPath);\n// sFileUtils.copy(files, new File(mBackUpPath, files.getName()));\n// sFileUtils.delete(files);\n// File mDexExtractPath = new File(mExplorePath, files.getName());\n// sFileUtils.mkdir(mDexExtractPath);\n// Common.setStatus(mContext.getString(R.string.decompiling, files.getName()));\n// new DexToSmali(false, mPackageName != null ? new File(sPackageUtils.getSourceDir(mPackageName, mContext))\n// : mAPKFile, mDexExtractPath, 0, files.getName()).execute();\n// }\n// }\n }\n if (Common.isCancelled()) {\n sFileUtils.delete(mExplorePath);\n Common.isCancelled(false);\n Common.setFinishStatus(true);\n }\n }\n\n @Override\n public void onPostExecute() {\n if (!Common.isFinished()) {\n Common.setFinishStatus(true);\n Intent explorer = new Intent(mContext, APKExploreActivity.class);\n mContext.startActivity(explorer);\n }\n }\n\n}" } ]
import android.app.Activity; import android.app.ProgressDialog; import android.net.Uri; import android.os.Bundle; import android.view.View; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.AppCompatImageButton; import androidx.appcompat.widget.AppCompatImageView; import androidx.appcompat.widget.LinearLayoutCompat; import androidx.documentfile.provider.DocumentFile; import androidx.viewpager.widget.ViewPager; import com.apk.axml.APKParser; import com.threethan.questpatcher.R; import com.threethan.questpatcher.fragments.APKDetailsFragment; import com.threethan.questpatcher.fragments.CertificateFragment; import com.threethan.questpatcher.fragments.ManifestFragment; import com.threethan.questpatcher.fragments.PermissionsFragment; import com.threethan.questpatcher.utils.APKExplorer; import com.threethan.questpatcher.utils.Common; import com.threethan.questpatcher.utils.dialogs.InvalidFileDialog; import com.threethan.questpatcher.utils.dialogs.SelectBundleDialog; import com.threethan.questpatcher.utils.tasks.ExploreAPK; import com.google.android.material.card.MaterialCardView; import com.google.android.material.dialog.MaterialAlertDialogBuilder; import com.google.android.material.tabs.TabLayout; import com.google.android.material.textview.MaterialTextView; import java.io.File; import java.util.Objects; import in.sunilpaulmathew.sCommon.Adapters.sPagerAdapter; import in.sunilpaulmathew.sCommon.CommonUtils.sExecutor; import in.sunilpaulmathew.sCommon.FileUtils.sFileUtils; import in.sunilpaulmathew.sCommon.PackageUtils.sPackageUtils;
7,334
package com.threethan.questpatcher.activities; /* * Created by APK Explorer & Editor <[email protected]> on March 27, 2021 */ public class APKInstallerActivity extends AppCompatActivity { private AppCompatImageButton mExploreIcon; private AppCompatImageView mAppIcon; private APKParser mAPKParser; private File mFile = null; private LinearLayoutCompat mMainLayout, mIconsLayout; private MaterialCardView mCancel, mInstall; private MaterialTextView mAppName, mInstallText, mPackageID; private TabLayout mTabLayout; private ViewPager mViewPager; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_apkdetails); mExploreIcon = findViewById(R.id.explore); mAppIcon = findViewById(R.id.app_image); mAppName = findViewById(R.id.app_title); mPackageID = findViewById(R.id.package_id); mMainLayout = findViewById(R.id.main_layout); mIconsLayout = findViewById(R.id.icons_layout); mInstall = findViewById(R.id.install); mInstallText = findViewById(R.id.install_text); mCancel = findViewById(R.id.cancel); mTabLayout = findViewById(R.id.tab_Layout); mViewPager = findViewById(R.id.view_pager); Bundle bundle = getIntent().getExtras(); if (bundle != null && bundle.containsKey("apkFileUri") && bundle.getString("apkFileUri") != null) { manageInstallation(Uri.parse(bundle.getString("apkFileUri")), null, this).execute(); } else if (bundle != null && bundle.containsKey("apkFilePath") && bundle.getString("apkFilePath") != null) { manageInstallation(null, bundle.getString("apkFilePath"), this).execute(); } else if (getIntent().getData() != null) { manageInstallation(getIntent().getData(), null, this).execute(); } } private sExecutor manageInstallation(Uri uri, String filePath, Activity activity) { return new sExecutor() { private ProgressDialog mProgressDialog; @Override public void onPreExecute() { mProgressDialog = new ProgressDialog(activity); mProgressDialog.setMessage(activity.getString(R.string.loading)); mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); mProgressDialog.setIcon(R.mipmap.ic_launcher); mProgressDialog.setTitle(R.string.app_name); mProgressDialog.setIndeterminate(true); mProgressDialog.setCancelable(false); mProgressDialog.show(); sFileUtils.delete(getExternalFilesDir("APK")); if (filePath == null) { String fileName = Objects.requireNonNull(DocumentFile.fromSingleUri(activity, uri)).getName(); mFile = new File(getExternalFilesDir("APK"), Objects.requireNonNull(fileName)); }
package com.threethan.questpatcher.activities; /* * Created by APK Explorer & Editor <[email protected]> on March 27, 2021 */ public class APKInstallerActivity extends AppCompatActivity { private AppCompatImageButton mExploreIcon; private AppCompatImageView mAppIcon; private APKParser mAPKParser; private File mFile = null; private LinearLayoutCompat mMainLayout, mIconsLayout; private MaterialCardView mCancel, mInstall; private MaterialTextView mAppName, mInstallText, mPackageID; private TabLayout mTabLayout; private ViewPager mViewPager; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_apkdetails); mExploreIcon = findViewById(R.id.explore); mAppIcon = findViewById(R.id.app_image); mAppName = findViewById(R.id.app_title); mPackageID = findViewById(R.id.package_id); mMainLayout = findViewById(R.id.main_layout); mIconsLayout = findViewById(R.id.icons_layout); mInstall = findViewById(R.id.install); mInstallText = findViewById(R.id.install_text); mCancel = findViewById(R.id.cancel); mTabLayout = findViewById(R.id.tab_Layout); mViewPager = findViewById(R.id.view_pager); Bundle bundle = getIntent().getExtras(); if (bundle != null && bundle.containsKey("apkFileUri") && bundle.getString("apkFileUri") != null) { manageInstallation(Uri.parse(bundle.getString("apkFileUri")), null, this).execute(); } else if (bundle != null && bundle.containsKey("apkFilePath") && bundle.getString("apkFilePath") != null) { manageInstallation(null, bundle.getString("apkFilePath"), this).execute(); } else if (getIntent().getData() != null) { manageInstallation(getIntent().getData(), null, this).execute(); } } private sExecutor manageInstallation(Uri uri, String filePath, Activity activity) { return new sExecutor() { private ProgressDialog mProgressDialog; @Override public void onPreExecute() { mProgressDialog = new ProgressDialog(activity); mProgressDialog.setMessage(activity.getString(R.string.loading)); mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); mProgressDialog.setIcon(R.mipmap.ic_launcher); mProgressDialog.setTitle(R.string.app_name); mProgressDialog.setIndeterminate(true); mProgressDialog.setCancelable(false); mProgressDialog.show(); sFileUtils.delete(getExternalFilesDir("APK")); if (filePath == null) { String fileName = Objects.requireNonNull(DocumentFile.fromSingleUri(activity, uri)).getName(); mFile = new File(getExternalFilesDir("APK"), Objects.requireNonNull(fileName)); }
Common.getAPKList().clear();
5
2023-11-18 15:13:30+00:00
12k
jenkinsci/harbor-plugin
src/main/java/io/jenkins/plugins/harbor/steps/WaitForHarborWebhookExecution.java
[ { "identifier": "HarborException", "path": "src/main/java/io/jenkins/plugins/harbor/HarborException.java", "snippet": "public class HarborException extends RuntimeException {\n public HarborException(String message) {\n super(message);\n }\n\n public HarborException(String message, Throwable cause) {\n super(message, cause);\n }\n\n public HarborException(Throwable cause) {\n super(cause);\n }\n}" }, { "identifier": "HarborBuildBadgeAction", "path": "src/main/java/io/jenkins/plugins/harbor/action/HarborBuildBadgeAction.java", "snippet": "@ExportedBean\npublic class HarborBuildBadgeAction implements BuildBadgeAction {\n private final String urlName;\n\n public HarborBuildBadgeAction(String urlName) {\n this.urlName = urlName;\n }\n\n @Override\n public String getIconFileName() {\n return \"/plugin/harbor/images/harbor.svg\";\n }\n\n @Override\n public String getDisplayName() {\n return \"Harbor\";\n }\n\n @Override\n @Exported(visibility = 2)\n public String getUrlName() {\n return urlName;\n }\n}" }, { "identifier": "HarborWebHookAction", "path": "src/main/java/io/jenkins/plugins/harbor/action/HarborWebHookAction.java", "snippet": "@Extension\npublic class HarborWebHookAction extends CrumbExclusion implements UnprotectedRootAction {\n private static final Logger logger = Logger.getLogger(HarborWebHookAction.class.getName());\n private static final String URL_NAME = \"harbor-webhook\";\n private static final Cache<String, HarborWebhookEvent> eventCache = Caffeine.newBuilder()\n .expireAfterWrite(2, TimeUnit.HOURS)\n .recordStats()\n .build();\n List<Consumer<HarborWebhookEvent>> listeners = new CopyOnWriteArrayList<>();\n\n public static HarborWebHookAction get() {\n return Jenkins.get().getExtensionList(RootAction.class).get(HarborWebHookAction.class);\n }\n\n public static Cache<String, HarborWebhookEvent> getEventCache() {\n return eventCache;\n }\n\n /**\n * Harbor WebHook API\n *\n * @param req StaplerRequest\n * @param rsp StaplerResponse\n * @throws IOException Invalid JSON Payload\n * @see <a href=\"https://wiki.jenkins-ci.org/display/JENKINS/Web+Method\">Web+Method</a>\n */\n @RequirePOST\n @SuppressWarnings(\"lgtm[jenkins/no-permission-check]\")\n public void doIndex(StaplerRequest req, StaplerResponse rsp) throws IOException {\n String payload = IOUtils.toString(req.getReader());\n\n try {\n ObjectMapper objectMapper = new ObjectMapper();\n WebhookEventPayload webhookEventPayload = objectMapper.readValue(payload, WebhookEventPayload.class);\n HarborWebhookEvent harborWebhookEvent = new HarborWebhookEvent(webhookEventPayload);\n for (Consumer<HarborWebhookEvent> listener : listeners) {\n listener.accept(harborWebhookEvent);\n }\n } catch (JacksonException e) {\n logger.log(Level.FINE, String.format(\"Invalid JSON Payload(%s)%n\", payload), e);\n rsp.sendError(HttpServletResponse.SC_BAD_REQUEST, \"Invalid JSON Payload\");\n } finally {\n logger.info(\"Received POST from: \" + req.getRemoteHost() + \", Payload: \" + payload);\n }\n\n rsp.setStatus(HttpServletResponse.SC_OK);\n }\n\n public void addListener(Consumer<HarborWebhookEvent> harborWebhookEventConsumer) {\n listeners.add(harborWebhookEventConsumer);\n }\n\n public void removeListener(Consumer<HarborWebhookEvent> harborWebhookEventConsumer) {\n listeners.remove(harborWebhookEventConsumer);\n }\n\n @Override\n public String getIconFileName() {\n return null;\n }\n\n @Override\n public String getDisplayName() {\n return null;\n }\n\n @Override\n public String getUrlName() {\n return URL_NAME;\n }\n\n @Override\n public boolean process(HttpServletRequest request, HttpServletResponse response, FilterChain chain)\n throws IOException, ServletException {\n String pathInfo = request.getPathInfo();\n if (pathInfo != null && pathInfo.equals(\"/\" + URL_NAME + \"/\")) {\n chain.doFilter(request, response);\n return true;\n }\n\n return false;\n }\n\n public HarborWebhookEvent getWebhookEventForDigest(String digest) {\n return eventCache.getIfPresent(digest);\n }\n}" }, { "identifier": "HarborWebhookEvent", "path": "src/main/java/io/jenkins/plugins/harbor/action/HarborWebhookEvent.java", "snippet": "public class HarborWebhookEvent {\n private WebhookEventPayload webhookEventPayload;\n private String digest;\n private String name;\n private String namespace;\n private String tag;\n private String resourceUrl;\n\n public HarborWebhookEvent(\n WebhookEventPayload webhookEventPayload,\n String digest,\n String name,\n String namespace,\n String tag,\n String resourceUrl) {\n this.webhookEventPayload = webhookEventPayload;\n this.digest = digest;\n this.name = name;\n this.namespace = namespace;\n this.tag = tag;\n this.resourceUrl = resourceUrl;\n }\n\n public HarborWebhookEvent(WebhookEventPayload webhookEventPayload) {\n this.webhookEventPayload = webhookEventPayload;\n this.digest = webhookEventPayload.getEventData().getResources()[0].getDigest();\n this.name = webhookEventPayload.getEventData().getRepository().getName();\n this.namespace = webhookEventPayload.getEventData().getRepository().getNamespace();\n this.tag = webhookEventPayload.getEventData().getResources()[0].getTag();\n this.resourceUrl = webhookEventPayload.getEventData().getResources()[0].getResourceURL();\n }\n\n public WebhookEventPayload getWebhookEventPayload() {\n return webhookEventPayload;\n }\n\n public void setWebhookEventPayload(WebhookEventPayload webhookEventPayload) {\n this.webhookEventPayload = webhookEventPayload;\n }\n\n public String getDigest() {\n return digest;\n }\n\n public void setDigest(String digest) {\n this.digest = digest;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getNamespace() {\n return namespace;\n }\n\n public void setNamespace(String namespace) {\n this.namespace = namespace;\n }\n\n public String getTag() {\n return tag;\n }\n\n public void setTag(String tag) {\n this.tag = tag;\n }\n\n public String getResourceUrl() {\n return resourceUrl;\n }\n\n public void setResourceUrl(String resourceUrl) {\n this.resourceUrl = resourceUrl;\n }\n\n public String getImageName() {\n return String.format(\"%s/%s:%s@%s\", namespace, name, tag, digest);\n }\n}" }, { "identifier": "EventType", "path": "src/main/java/io/jenkins/plugins/harbor/action/model/EventType.java", "snippet": "public enum EventType {\n CREATE_PROJECT(\"CREATE_PROJECT\"),\n DELETE_PROJECT(\"DELETE_PROJECT\"),\n PUSH_ARTIFACT(\"PUSH_ARTIFACT\"),\n PULL_ARTIFACT(\"PULL_ARTIFACT\"),\n DELETE_ARTIFACT(\"DELETE_ARTIFACT\"),\n DELETE_REPOSITORY(\"DELETE_REPOSITORY\"),\n CREATE_TAG(\"CREATE_TAG\"),\n DELETE_TAG(\"DELETE_TAG\"),\n SCANNING_FAILED(\"SCANNING_FAILED\"),\n SCANNING_STOPPED(\"SCANNING_STOPPED\"),\n SCANNING_COMPLETED(\"SCANNING_COMPLETED\");\n\n @JsonValue\n private final String eventType;\n\n EventType(String eventType) {\n this.eventType = eventType;\n }\n\n public String getEventType() {\n return eventType;\n }\n}" }, { "identifier": "Resource", "path": "src/main/java/io/jenkins/plugins/harbor/action/model/Resource.java", "snippet": "@SuppressFBWarnings(\"EI_EXPOSE_REP\")\npublic class Resource {\n private String digest;\n private String tag;\n\n @JsonProperty(\"resource_url\")\n private String resourceURL;\n\n @JsonProperty(\"scan_overview\")\n private HashMap<String, NativeReportSummary> ScanOverview;\n\n public String getDigest() {\n return digest;\n }\n\n public void setDigest(String digest) {\n this.digest = digest;\n }\n\n public String getTag() {\n return tag;\n }\n\n public void setTag(String tag) {\n this.tag = tag;\n }\n\n public String getResourceURL() {\n return resourceURL;\n }\n\n public void setResourceURL(String resourceURL) {\n this.resourceURL = resourceURL;\n }\n\n public HashMap<String, NativeReportSummary> getScanOverview() {\n return ScanOverview;\n }\n\n public void setScanOverview(HashMap<String, NativeReportSummary> scanOverview) {\n ScanOverview = scanOverview;\n }\n}" }, { "identifier": "VulnerabilityScanStatus", "path": "src/main/java/io/jenkins/plugins/harbor/action/model/VulnerabilityScanStatus.java", "snippet": "public enum VulnerabilityScanStatus {\n NOT_SCANNED(\"Not Scanned\"),\n PENDING(\"Pending\"),\n RUNNING(\"Running\"),\n ERROR(\"Error\"),\n STOPPED(\"Stopped\"),\n SUCCESS(\"Success\"),\n SCHEDULED(\"Scheduled\");\n\n @JsonValue\n private final String scanStatus;\n\n VulnerabilityScanStatus(String scanStatus) {\n this.scanStatus = scanStatus;\n }\n\n public String getScanStatus() {\n return scanStatus;\n }\n}" }, { "identifier": "HarborClientImpl", "path": "src/main/java/io/jenkins/plugins/harbor/client/HarborClientImpl.java", "snippet": "public class HarborClientImpl implements HarborClient {\n private static final int DEFAULT_CONNECT_TIMEOUT_SECONDS = 30;\n private static final int DEFAULT_READ_TIMEOUT_SECONDS = 30;\n private static final int DEFAULT_WRITE_TIMEOUT_SECONDS = 30;\n private static final String API_PING_PATH = \"/ping\";\n private static final String API_LIST_ALL_REPOSITORIES_PATH = \"/repositories\";\n private static final String API_LIST_ARTIFACTS_PATH =\n \"/projects/{project_name}/repositories/{repository_name}/artifacts\";\n private static final String API_GET_ARTIFACT_PATH =\n \"/projects/{project_name}/repositories/{repository_name}/artifacts/{reference}\";\n private final String baseUrl;\n private final OkHttpClient httpClient;\n\n public HarborClientImpl(\n String baseUrl,\n StandardUsernamePasswordCredentials credentials,\n boolean isSkipTlsVerify,\n boolean debugLogging)\n throws NoSuchAlgorithmException, KeyManagementException {\n this.baseUrl = baseUrl;\n\n // Create Http client\n OkHttpClient.Builder httpClientBuilder = JenkinsOkHttpClient.newClientBuilder(new OkHttpClient());\n addTimeout(httpClientBuilder);\n skipTlsVerify(httpClientBuilder, isSkipTlsVerify);\n addAuthenticator(httpClientBuilder, credentials);\n enableDebugLogging(httpClientBuilder, debugLogging);\n this.httpClient = httpClientBuilder.build();\n }\n\n private OkHttpClient.Builder addTimeout(OkHttpClient.Builder httpClient) {\n httpClient.connectTimeout(DEFAULT_CONNECT_TIMEOUT_SECONDS, TimeUnit.SECONDS);\n httpClient.readTimeout(DEFAULT_READ_TIMEOUT_SECONDS, TimeUnit.SECONDS);\n httpClient.writeTimeout(DEFAULT_WRITE_TIMEOUT_SECONDS, TimeUnit.SECONDS);\n httpClient.setRetryOnConnectionFailure$okhttp(true);\n return httpClient;\n }\n\n @SuppressWarnings(\"lgtm[jenkins/unsafe-calls]\")\n private OkHttpClient.Builder skipTlsVerify(OkHttpClient.Builder httpClient, boolean isSkipTlsVerify)\n throws NoSuchAlgorithmException, KeyManagementException {\n if (isSkipTlsVerify) {\n SSLContext sslContext = SSLContext.getInstance(\"TLS\");\n TrustManager[] trustManagers = new TrustManager[] {new NoCheckTrustManager()};\n sslContext.init(null, trustManagers, new java.security.SecureRandom());\n httpClient.sslSocketFactory(sslContext.getSocketFactory(), (X509TrustManager) trustManagers[0]);\n httpClient.setHostnameVerifier$okhttp((hostname, session) -> true);\n }\n\n return httpClient;\n }\n\n private OkHttpClient.Builder addAuthenticator(\n OkHttpClient.Builder httpClientBuilder, StandardUsernamePasswordCredentials credentials) {\n if (credentials != null) {\n HarborInterceptor harborInterceptor = new HarborInterceptor(credentials);\n httpClientBuilder.addInterceptor(harborInterceptor);\n }\n\n return httpClientBuilder;\n }\n\n private OkHttpClient.Builder enableDebugLogging(OkHttpClient.Builder httpClient, boolean debugLogging) {\n if (debugLogging) {\n HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();\n loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);\n httpClient.addInterceptor(loggingInterceptor);\n }\n\n return httpClient;\n }\n\n private String getXAcceptVulnerabilities() {\n return String.format(\n \"%s, %s\",\n HarborConstants.HarborVulnerabilityReportV11MimeType, HarborConstants.HarborVulnReportv1MimeType);\n }\n\n @Override\n public NativeReportSummary getVulnerabilitiesAddition(String projectName, String repositoryName, String reference) {\n return null;\n }\n\n @Override\n public String getPing() throws IOException {\n UriTemplate template = UriTemplate.fromTemplate(baseUrl + API_PING_PATH);\n HttpUrl apiUrl = HttpUrl.parse(template.expand());\n if (apiUrl != null) {\n return httpGet(apiUrl);\n }\n\n throw new HarborException(String.format(\"httpUrl is null, UriTemplate is %s.\", template.expand()));\n }\n\n @Override\n public Repository[] listAllRepositories() throws IOException {\n HttpUrl apiUrl = addQueryParameter(\n UriTemplate.fromTemplate(baseUrl + API_LIST_ALL_REPOSITORIES_PATH), new HashMap<String, String>());\n return JsonParser.toJava(httpGet(apiUrl), Repository[].class);\n }\n\n @Override\n public Artifact[] listArtifacts(\n String projectName, String repositoryName, @Nullable Map<String, String> extraParams)\n throws HarborException, IOException {\n HttpUrl apiUrl = addQueryParameter(\n UriTemplate.fromTemplate(baseUrl + API_LIST_ARTIFACTS_PATH)\n .set(\"project_name\", projectName)\n .set(\"repository_name\", repositoryName),\n extraParams);\n return JsonParser.toJava(httpGet(apiUrl), Artifact[].class);\n }\n\n @Override\n public Artifact getArtifact(\n String projectName, String repositoryName, String reference, @Nullable Map<String, String> extraParams)\n throws IOException {\n HttpUrl apiUrl = addQueryParameter(\n UriTemplate.fromTemplate(baseUrl + API_GET_ARTIFACT_PATH)\n .set(\"project_name\", projectName)\n .set(\"repository_name\", repositoryName)\n .set(\"reference\", reference),\n extraParams);\n return JsonParser.toJava(httpGet(apiUrl), Artifact.class);\n }\n\n private HttpUrl addQueryParameter(UriTemplate template, @Nullable Map<String, String> extraParams) {\n HttpUrl httpUrl = HttpUrl.parse(template.expand());\n if (httpUrl != null) {\n HttpUrl.Builder httpBuilder = httpUrl.newBuilder();\n if (extraParams != null) {\n for (Map.Entry<String, String> param : extraParams.entrySet()) {\n httpBuilder.addQueryParameter(param.getKey(), param.getValue());\n }\n }\n return httpBuilder.build();\n } else {\n throw new HarborException(String.format(\"httpUrl is null, UriTemplate is %s.\", template.expand()));\n }\n }\n\n private String httpGet(HttpUrl httpUrl) throws IOException {\n Request request = new Request.Builder()\n .url(httpUrl.url())\n .header(\"X-Accept-Vulnerabilities\", getXAcceptVulnerabilities())\n .build();\n Response response = httpClient.newCall(request).execute();\n ResponseBody responseBody = response.body();\n if (responseBody != null) {\n if (response.isSuccessful()) {\n return responseBody.string();\n } else {\n throw new HarborRequestException(\n response.code(),\n String.format(\n \"The server(%s) api response failed, Response message is '%s'.\",\n httpUrl, responseBody.string()));\n }\n } else {\n throw new HarborRequestException(\n response.code(),\n String.format(\n \"httpGet method get responseBody failed, The request api is %s, Response message is '%s'\",\n httpUrl, response.message()));\n }\n }\n}" }, { "identifier": "Artifact", "path": "src/main/java/io/jenkins/plugins/harbor/client/models/Artifact.java", "snippet": "@SuppressFBWarnings(\n value = {\"EI_EXPOSE_REP\", \"EI_EXPOSE_REP2\"},\n justification = \"I prefer to suppress these FindBugs warnings\")\npublic class Artifact {\n private long id;\n private String type;\n private String mediaType;\n private String manifestMediaType;\n private String projectId;\n private String repositoryId;\n private String repositoryName;\n private String digest;\n private long size;\n private String icon;\n private Date pushTime;\n private Date pullTime;\n private HashMap<String, Object> extraAttrs;\n private String annotations;\n private String references;\n\n @JsonIgnore\n private String tags;\n\n @JsonIgnore\n private HashMap<String, AdditionLink> additionLinks;\n\n private String labels;\n\n @SuppressWarnings(\"lgtm[jenkins/plaintext-storage]\")\n private String accessories;\n\n private HashMap<String, NativeReportSummary> scanOverview;\n\n public String getMediaType() {\n return mediaType;\n }\n\n @JsonProperty(\"media_type\")\n public void setMediaType(String mediaType) {\n this.mediaType = mediaType;\n }\n\n public long getSize() {\n return size;\n }\n\n public void setSize(long size) {\n this.size = size;\n }\n\n public Date getPushTime() {\n return pushTime;\n }\n\n @JsonProperty(\"push_time\")\n public void setPushTime(Date pushTime) {\n this.pushTime = pushTime;\n }\n\n public String getTags() {\n return tags;\n }\n\n public void setTags(String tags) {\n this.tags = tags;\n }\n\n public HashMap<String, NativeReportSummary> getScanOverview() {\n return scanOverview;\n }\n\n @JsonProperty(\"scan_overview\")\n public void setScanOverview(HashMap<String, NativeReportSummary> scanOverview) {\n this.scanOverview = scanOverview;\n }\n\n public Date getPullTime() {\n return pullTime;\n }\n\n @JsonProperty(\"pull_time\")\n public void setPullTime(Date pullTime) {\n this.pullTime = pullTime;\n }\n\n public String getLabels() {\n return labels;\n }\n\n public void setLabels(String labels) {\n this.labels = labels;\n }\n\n public String getAccessories() {\n return accessories;\n }\n\n public void setAccessories(String accessories) {\n this.accessories = accessories;\n }\n\n public String getReferences() {\n return references;\n }\n\n public void setReferences(String references) {\n this.references = references;\n }\n\n public String getManifestMediaType() {\n return manifestMediaType;\n }\n\n @JsonProperty(\"manifest_media_type\")\n public void setManifestMediaType(String manifestMediaType) {\n this.manifestMediaType = manifestMediaType;\n }\n\n public long getId() {\n return id;\n }\n\n public void setId(long id) {\n this.id = id;\n }\n\n public String getDigest() {\n return digest;\n }\n\n public void setDigest(String digest) {\n this.digest = digest;\n }\n\n public String getIcon() {\n return icon;\n }\n\n public void setIcon(String icon) {\n this.icon = icon;\n }\n\n public String getRepositoryId() {\n return repositoryId;\n }\n\n @JsonProperty(\"repository_id\")\n public void setRepositoryId(String repositoryId) {\n this.repositoryId = repositoryId;\n }\n\n public HashMap<String, AdditionLink> getAdditionLinks() {\n return additionLinks;\n }\n\n @JsonProperty(\"addition_links\")\n public void setAdditionLinks(HashMap<String, AdditionLink> additionLinks) {\n this.additionLinks = additionLinks;\n }\n\n public String getProjectId() {\n return projectId;\n }\n\n @JsonProperty(\"project_id\")\n public void setProjectId(String projectId) {\n this.projectId = projectId;\n }\n\n public String getType() {\n return type;\n }\n\n public void setType(String type) {\n this.type = type;\n }\n\n public String getAnnotations() {\n return annotations;\n }\n\n public void setAnnotations(String annotations) {\n this.annotations = annotations;\n }\n\n public HashMap<String, Object> getExtraAttrs() {\n return extraAttrs;\n }\n\n @JsonProperty(\"extra_attrs\")\n public void setExtraAttrs(HashMap<String, Object> extraAttrs) {\n this.extraAttrs = extraAttrs;\n }\n\n public String getRepositoryName() {\n return repositoryName;\n }\n\n @JsonProperty(\"repository_name\")\n public void setRepositoryName(String repositoryName) {\n this.repositoryName = repositoryName;\n }\n}" }, { "identifier": "NativeReportSummary", "path": "src/main/java/io/jenkins/plugins/harbor/client/models/NativeReportSummary.java", "snippet": "@SuppressFBWarnings(\n value = {\"EI_EXPOSE_REP\", \"EI_EXPOSE_REP2\"},\n justification = \"I prefer to suppress these FindBugs warnings\")\npublic class NativeReportSummary {\n private String reportId;\n\n private VulnerabilityScanStatus ScanStatus;\n\n private Severity severity;\n\n private long duration;\n\n private VulnerabilitySummary summary;\n\n private ArrayList<String> cvebypassed;\n\n private Date StartTime;\n\n private Date EndTime;\n\n private Scanner scanner;\n\n private int completePercent;\n\n @JsonIgnore\n private int totalCount;\n\n @JsonIgnore\n private int completeCount;\n\n @JsonIgnore\n private VulnerabilityItemList vulnerabilityItemList;\n\n public String getReportId() {\n return reportId;\n }\n\n @JsonProperty(\"report_id\")\n public void setReportId(String reportId) {\n this.reportId = reportId;\n }\n\n public VulnerabilityScanStatus getScanStatus() {\n return ScanStatus;\n }\n\n @JsonProperty(\"scan_status\")\n public void setScanStatus(VulnerabilityScanStatus scanStatus) {\n ScanStatus = scanStatus;\n }\n\n public Severity getSeverity() {\n return severity;\n }\n\n public void setSeverity(Severity severity) {\n this.severity = severity;\n }\n\n public long getDuration() {\n return duration;\n }\n\n public void setDuration(long duration) {\n this.duration = duration;\n }\n\n public VulnerabilitySummary getSummary() {\n return summary;\n }\n\n public void setSummary(VulnerabilitySummary summary) {\n this.summary = summary;\n }\n\n public ArrayList<String> getCvebypassed() {\n return cvebypassed;\n }\n\n @JsonIgnore\n public void setCvebypassed(ArrayList<String> cvebypassed) {\n this.cvebypassed = cvebypassed;\n }\n\n public Date getStartTime() {\n return StartTime;\n }\n\n @JsonProperty(\"start_time\")\n public void setStartTime(Date startTime) {\n StartTime = startTime;\n }\n\n public Date getEndTime() {\n return EndTime;\n }\n\n @JsonProperty(\"end_time\")\n public void setEndTime(Date endTime) {\n EndTime = endTime;\n }\n\n public Scanner getScanner() {\n return scanner;\n }\n\n public void setScanner(Scanner scanner) {\n this.scanner = scanner;\n }\n\n public int getCompletePercent() {\n return completePercent;\n }\n\n @JsonProperty(\"complete_percent\")\n public void setCompletePercent(int completePercent) {\n this.completePercent = completePercent;\n }\n\n public int getTotalCount() {\n return totalCount;\n }\n\n public void setTotalCount(int totalCount) {\n this.totalCount = totalCount;\n }\n\n public int getCompleteCount() {\n return completeCount;\n }\n\n public void setCompleteCount(int completeCount) {\n this.completeCount = completeCount;\n }\n\n public VulnerabilityItemList getVulnerabilityItemList() {\n return vulnerabilityItemList;\n }\n\n public void setVulnerabilityItemList(VulnerabilityItemList vulnerabilityItemList) {\n this.vulnerabilityItemList = vulnerabilityItemList;\n }\n}" }, { "identifier": "Severity", "path": "src/main/java/io/jenkins/plugins/harbor/client/models/Severity.java", "snippet": "public enum Severity {\n None(\"None\"),\n Unknown(\"Unknown\"),\n Negligible(\"Negligible\"),\n Low(\"Low\"),\n Medium(\"Medium\"),\n High(\"High\"),\n Critical(\"Critical\");\n\n @JsonValue\n private final String severity;\n\n Severity(String severity) {\n this.severity = severity;\n }\n\n public String getSeverity() {\n return severity;\n }\n}" }, { "identifier": "HarborPluginGlobalConfiguration", "path": "src/main/java/io/jenkins/plugins/harbor/configuration/HarborPluginGlobalConfiguration.java", "snippet": "@Extension\npublic class HarborPluginGlobalConfiguration extends GlobalConfiguration implements Serializable {\n private static final Logger logger = Logger.getLogger(HarborPluginGlobalConfiguration.class.getName());\n\n private List<HarborServer> servers;\n\n public HarborPluginGlobalConfiguration() {\n load();\n }\n\n public static HarborPluginGlobalConfiguration get() {\n return GlobalConfiguration.all().get(HarborPluginGlobalConfiguration.class);\n }\n\n public static HarborServer getHarborServerByName(String name) {\n return get().getServers().stream()\n .filter(harborServer -> StringUtils.equals(name, harborServer.getName()))\n .findFirst()\n .orElseThrow(() -> new HarborException(\"The Harbor Server Name Is Invalid\"));\n }\n\n public List<HarborServer> getServers() {\n return servers;\n }\n\n public void setServers(List<HarborServer> servers) {\n this.servers = servers;\n }\n\n @Override\n public boolean configure(StaplerRequest req, JSONObject json) throws FormException {\n req.bindJSON(this, json);\n save();\n return true;\n }\n}" }, { "identifier": "HarborServer", "path": "src/main/java/io/jenkins/plugins/harbor/configuration/HarborServer.java", "snippet": "public class HarborServer extends AbstractDescribableImpl<HarborServer> implements Serializable {\n private static final long serialVersionUID = 1L;\n private static final Logger logger = Logger.getLogger(HarborServer.class.getName());\n private String name;\n private String baseUrl;\n private String webhookSecretId;\n private boolean skipTlsVerify = false;\n private boolean debugLogging = false;\n\n @DataBoundConstructor\n public HarborServer(\n String name, String baseUrl, String webhookSecretId, boolean skipTlsVerify, boolean debugLogging) {\n this.name = name;\n this.baseUrl = baseUrl;\n this.webhookSecretId = webhookSecretId;\n this.skipTlsVerify = skipTlsVerify;\n this.debugLogging = debugLogging;\n }\n\n public String getName() {\n return name;\n }\n\n @DataBoundSetter\n public void setName(String name) {\n this.name = name;\n }\n\n public String getBaseUrl() {\n return baseUrl;\n }\n\n @DataBoundSetter\n public void setBaseUrl(String baseUrl) {\n this.baseUrl = baseUrl;\n }\n\n public String getWebhookSecretId() {\n return webhookSecretId;\n }\n\n @DataBoundSetter\n public void setWebhookSecretId(String webhookSecretId) {\n this.webhookSecretId = webhookSecretId;\n }\n\n public boolean isSkipTlsVerify() {\n return skipTlsVerify;\n }\n\n @DataBoundSetter\n public void setSkipTlsVerify(boolean skipTlsVerify) {\n this.skipTlsVerify = skipTlsVerify;\n }\n\n public boolean isDebugLogging() {\n return debugLogging;\n }\n\n @DataBoundSetter\n public void setDebugLogging(boolean debugLogging) {\n this.debugLogging = debugLogging;\n }\n\n @Extension\n public static class DescriptorImpl extends Descriptor<HarborServer> {\n /**\n * Checks that the supplied URL is valid.\n *\n * @param value the URL to check.\n * @return the validation results.\n */\n @SuppressWarnings({\"unused\", \"lgtm[jenkins/csrf]\"})\n public static FormValidation doCheckBaseUrl(@QueryParameter String value) {\n if (!Jenkins.get().hasPermission(Jenkins.ADMINISTER)) {\n return FormValidation.error(\"You do not have sufficient permissions.\");\n }\n\n try {\n new URL(value);\n } catch (MalformedURLException e) {\n return FormValidation.error(\"Invalid URL: \" + e.getMessage());\n }\n return FormValidation.ok();\n }\n\n @SuppressWarnings({\"unused\", \"lgtm[jenkins/csrf]\"})\n public ListBoxModel doFillWebhookSecretIdItems(@QueryParameter String webhookSecretId) {\n if (!Jenkins.get().hasPermission(Jenkins.ADMINISTER)) {\n return new StandardListBoxModel().includeCurrentValue(webhookSecretId);\n }\n\n return new StandardListBoxModel()\n .includeEmptyValue()\n .includeMatchingAs(\n ACL.SYSTEM,\n Jenkins.get(),\n StringCredentials.class,\n Collections.emptyList(),\n CredentialsMatchers.always());\n }\n\n @Override\n public String getDisplayName() {\n return \"Harbor Server\";\n }\n }\n}" }, { "identifier": "HarborConstants", "path": "src/main/java/io/jenkins/plugins/harbor/util/HarborConstants.java", "snippet": "public class HarborConstants {\n public static final String HarborVulnerabilityReportV11MimeType =\n \"application/vnd.security.vulnerability.report; version=1.1\";\n public static final String HarborVulnReportv1MimeType =\n \"application/vnd.scanner.adapter.vuln.report.harbor+json; version=1.0\";\n}" } ]
import com.cloudbees.plugins.credentials.CredentialsProvider; import com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials; import edu.umd.cs.findbugs.annotations.NonNull; import hudson.AbortException; import hudson.EnvVars; import hudson.Launcher; import hudson.model.Run; import hudson.model.TaskListener; import hudson.util.ArgumentListBuilder; import io.jenkins.plugins.harbor.HarborException; import io.jenkins.plugins.harbor.action.HarborBuildBadgeAction; import io.jenkins.plugins.harbor.action.HarborWebHookAction; import io.jenkins.plugins.harbor.action.HarborWebhookEvent; import io.jenkins.plugins.harbor.action.model.EventType; import io.jenkins.plugins.harbor.action.model.Resource; import io.jenkins.plugins.harbor.action.model.VulnerabilityScanStatus; import io.jenkins.plugins.harbor.client.HarborClientImpl; import io.jenkins.plugins.harbor.client.models.Artifact; import io.jenkins.plugins.harbor.client.models.NativeReportSummary; import io.jenkins.plugins.harbor.client.models.Severity; import io.jenkins.plugins.harbor.configuration.HarborPluginGlobalConfiguration; import io.jenkins.plugins.harbor.configuration.HarborServer; import io.jenkins.plugins.harbor.util.HarborConstants; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.nio.charset.Charset; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.util.*; import java.util.function.Consumer; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.jenkinsci.plugins.workflow.graph.FlowNode; import org.jenkinsci.plugins.workflow.steps.StepContext; import org.jenkinsci.plugins.workflow.steps.StepExecution; import org.jenkinsci.plugins.workflow.support.actions.PauseAction;
9,019
List<String> lastConsoleLogLines = getContextClass(Run.class).getLog(MAX_LOG_LINES); Pattern namePattern = Pattern.compile(BUILD_IMAGE_NAME_PATTERN); Pattern digestPattern = Pattern.compile(BUILD_IMAGE_DIGEST_PATTERN); for (String line : lastConsoleLogLines) { Matcher nameMatcher = namePattern.matcher(line); Matcher digestMatcher = digestPattern.matcher(line); if (nameMatcher.find()) { foundImageName = nameMatcher.group(1); } if (digestMatcher.find()) { foundImageDigest = digestMatcher.group(2); } } } else { foundImageDigest = getDigestByFullImageName(foundImageName); } if (foundImageName == null || foundImageDigest == null) { throw new ImageInfoExtractionException(String.format( "Failed to extract image name(%s) or digest(%s). Image not found.", foundImageName, foundImageDigest)); } this.image = new Image(foundImageName, foundImageDigest); getContextClass(Run.class) .addAction(new HarborBuildBadgeAction(String.format( "https://%s/harbor/projects/%s/repositories/%s/artifacts-tab/artifacts/%s", image.getRegistry(), image.getProjects(), image.getRepository(), foundImageDigest))); } private String getDigestByFullImageName(String fullImageName) { ArgumentListBuilder argumentListBuilder = new ArgumentListBuilder(); argumentListBuilder.add("docker", "inspect", "-f", "{{.RepoDigests}}", fullImageName); ByteArrayOutputStream output = new ByteArrayOutputStream(); ByteArrayOutputStream error = new ByteArrayOutputStream(); try { int status = getContextClass(Launcher.class) .launch() .cmds(argumentListBuilder) .envs(getContextClass(EnvVars.class)) .quiet(true) .stdout(output) .stderr(error) .start() .join(); if (status == 0) { String charsetName = Charset.defaultCharset().name(); String repoDigests = output.toString(charsetName).trim(); for (String repoDigest : repoDigests.substring(1, repoDigests.length() - 1).split(" ")) { if (repoDigest.startsWith(fullImageName.split(":")[0])) { return repoDigest.split("@")[1]; } } throw new HarborException( String.format("Unable to get matching image digest. repoDigests: %s%n", repoDigests)); } else { throw new HarborException("Run docker command fail, Unable to get image digest."); } } catch (UnsupportedEncodingException e) { throw new HarborException("Encoding error, unable to read command result.", e); } catch (IOException | InterruptedException e) { throw new HarborException("Run command error, Unable to get command execution results", e); } } private boolean checkScanCompleted() { HarborWebHookAction.get().addListener(this); writeLogToConsole( "Checking scan status of Harbor artifact '%s' on server '%s'%n", image.getImageName(), image.getRegistry()); try { HarborServer harborServer = HarborPluginGlobalConfiguration.getHarborServerByName(waitForHarborWebhookStep.getServer()); HarborClientImpl harborAPIClient = new HarborClientImpl( harborServer.getBaseUrl(), getCredentials(waitForHarborWebhookStep.getCredentialsId()), harborServer.isSkipTlsVerify(), harborServer.isDebugLogging()); HashMap<String, String> extraParams = new HashMap<String, String>() { { put("with_scan_overview", "true"); put("page_size", "15"); put("page", "1"); } }; Artifact artifact = harborAPIClient.getArtifact( image.getProjects(), image.getRepository(), image.getImageDigest(), extraParams); logger.info(artifact.toString()); HashMap<String, NativeReportSummary> scanOverview = artifact.getScanOverview(); if (scanOverview != null && !scanOverview.isEmpty()) { NativeReportSummary nativeReportSummary = scanOverview.get(HarborConstants.HarborVulnerabilityReportV11MimeType); return checkScanStatus(nativeReportSummary.getScanStatus(), nativeReportSummary.getSeverity(), true); } writeLogToConsole( "The Artifact api cannot get scan overview, Please check whether you have enabled image scanning."); return false; } catch (NoSuchAlgorithmException | KeyManagementException e) { throw new HarborException("Connect to harbor server Failed.", e); } catch (IOException e) { throw new HarborException("Interrupted on checkScanCompleted.", e); } } private StandardUsernamePasswordCredentials getCredentials(String credentialsId) { return CredentialsProvider.findCredentialById( credentialsId, StandardUsernamePasswordCredentials.class, Objects.requireNonNull(getContextClass(Run.class)), Collections.emptyList()); }
package io.jenkins.plugins.harbor.steps; public class WaitForHarborWebhookExecution extends StepExecution implements Consumer<HarborWebhookEvent> { private static final long serialVersionUID = 1L; private static final Logger logger = Logger.getLogger(WaitForHarborWebhookExecution.class.getName()); private static final int MAX_LOG_LINES = 1000; private static final String BUILD_IMAGE_NAME_PATTERN = "#\\d+ naming to (\\S+/\\S+/\\S+:\\S+) .*done"; private static final String BUILD_IMAGE_DIGEST_PATTERN = "(\\d+): digest: (sha256:[a-f0-9]+) size: (\\d+)"; private final WaitForHarborWebhookStep waitForHarborWebhookStep; private Image image; public WaitForHarborWebhookExecution(StepContext context, WaitForHarborWebhookStep waitForHarborWebhookStep) { super(context); this.waitForHarborWebhookStep = waitForHarborWebhookStep; } @Override public boolean start() throws Exception { processStepParameters(); if (!checkScanCompleted()) { HarborWebhookEvent harborWebhookEvent = HarborWebHookAction.get().getWebhookEventForDigest(image.getImageDigest()); if (harborWebhookEvent != null) { validateWebhookAndCheckSeverityIfValid(harborWebhookEvent, true); return true; } else { getContextClass(FlowNode.class).addAction(new PauseAction("Harbor Scanner analysis")); return false; } } else { return true; } } private void processStepParameters() throws IOException { String foundImageName = waitForHarborWebhookStep.getFullImageName(); String foundImageDigest = null; if (foundImageName == null) { List<String> lastConsoleLogLines = getContextClass(Run.class).getLog(MAX_LOG_LINES); Pattern namePattern = Pattern.compile(BUILD_IMAGE_NAME_PATTERN); Pattern digestPattern = Pattern.compile(BUILD_IMAGE_DIGEST_PATTERN); for (String line : lastConsoleLogLines) { Matcher nameMatcher = namePattern.matcher(line); Matcher digestMatcher = digestPattern.matcher(line); if (nameMatcher.find()) { foundImageName = nameMatcher.group(1); } if (digestMatcher.find()) { foundImageDigest = digestMatcher.group(2); } } } else { foundImageDigest = getDigestByFullImageName(foundImageName); } if (foundImageName == null || foundImageDigest == null) { throw new ImageInfoExtractionException(String.format( "Failed to extract image name(%s) or digest(%s). Image not found.", foundImageName, foundImageDigest)); } this.image = new Image(foundImageName, foundImageDigest); getContextClass(Run.class) .addAction(new HarborBuildBadgeAction(String.format( "https://%s/harbor/projects/%s/repositories/%s/artifacts-tab/artifacts/%s", image.getRegistry(), image.getProjects(), image.getRepository(), foundImageDigest))); } private String getDigestByFullImageName(String fullImageName) { ArgumentListBuilder argumentListBuilder = new ArgumentListBuilder(); argumentListBuilder.add("docker", "inspect", "-f", "{{.RepoDigests}}", fullImageName); ByteArrayOutputStream output = new ByteArrayOutputStream(); ByteArrayOutputStream error = new ByteArrayOutputStream(); try { int status = getContextClass(Launcher.class) .launch() .cmds(argumentListBuilder) .envs(getContextClass(EnvVars.class)) .quiet(true) .stdout(output) .stderr(error) .start() .join(); if (status == 0) { String charsetName = Charset.defaultCharset().name(); String repoDigests = output.toString(charsetName).trim(); for (String repoDigest : repoDigests.substring(1, repoDigests.length() - 1).split(" ")) { if (repoDigest.startsWith(fullImageName.split(":")[0])) { return repoDigest.split("@")[1]; } } throw new HarborException( String.format("Unable to get matching image digest. repoDigests: %s%n", repoDigests)); } else { throw new HarborException("Run docker command fail, Unable to get image digest."); } } catch (UnsupportedEncodingException e) { throw new HarborException("Encoding error, unable to read command result.", e); } catch (IOException | InterruptedException e) { throw new HarborException("Run command error, Unable to get command execution results", e); } } private boolean checkScanCompleted() { HarborWebHookAction.get().addListener(this); writeLogToConsole( "Checking scan status of Harbor artifact '%s' on server '%s'%n", image.getImageName(), image.getRegistry()); try { HarborServer harborServer = HarborPluginGlobalConfiguration.getHarborServerByName(waitForHarborWebhookStep.getServer()); HarborClientImpl harborAPIClient = new HarborClientImpl( harborServer.getBaseUrl(), getCredentials(waitForHarborWebhookStep.getCredentialsId()), harborServer.isSkipTlsVerify(), harborServer.isDebugLogging()); HashMap<String, String> extraParams = new HashMap<String, String>() { { put("with_scan_overview", "true"); put("page_size", "15"); put("page", "1"); } }; Artifact artifact = harborAPIClient.getArtifact( image.getProjects(), image.getRepository(), image.getImageDigest(), extraParams); logger.info(artifact.toString()); HashMap<String, NativeReportSummary> scanOverview = artifact.getScanOverview(); if (scanOverview != null && !scanOverview.isEmpty()) { NativeReportSummary nativeReportSummary = scanOverview.get(HarborConstants.HarborVulnerabilityReportV11MimeType); return checkScanStatus(nativeReportSummary.getScanStatus(), nativeReportSummary.getSeverity(), true); } writeLogToConsole( "The Artifact api cannot get scan overview, Please check whether you have enabled image scanning."); return false; } catch (NoSuchAlgorithmException | KeyManagementException e) { throw new HarborException("Connect to harbor server Failed.", e); } catch (IOException e) { throw new HarborException("Interrupted on checkScanCompleted.", e); } } private StandardUsernamePasswordCredentials getCredentials(String credentialsId) { return CredentialsProvider.findCredentialById( credentialsId, StandardUsernamePasswordCredentials.class, Objects.requireNonNull(getContextClass(Run.class)), Collections.emptyList()); }
public boolean checkScanStatus(VulnerabilityScanStatus scanStatus, Severity severity, boolean onStart) {
6
2023-11-11 14:54:53+00:00
12k
Mapty231/SpawnFix
src/main/java/me/tye/spawnfix/SpawnFix.java
[ { "identifier": "Commands", "path": "src/main/java/me/tye/spawnfix/commands/Commands.java", "snippet": "public class Commands implements CommandExecutor {\n@Override\npublic boolean onCommand(@NotNull CommandSender commandSender, @NotNull Command command, @NotNull String label, @NotNull String[] args) {\n if (!commandSender.hasPermission(\"sf\")) return true;\n\n if (args.length != 1) return true;\n\n switch (args[0]) {\n\n //Sets the new spawn to the players position.\n case \"setSpawn\" -> {\n if (!(commandSender instanceof Player)) return true;\n\n Player player = (Player) commandSender;\n Location currentLocation = player.getLocation();\n\n String worldName = currentLocation.getWorld().getName();\n double x = currentLocation.getX();\n double y = currentLocation.getY();\n double z = currentLocation.getZ();\n float yaw = currentLocation.getYaw();\n float pitch = currentLocation.getPitch();\n\n try {\n writeYamlData(\"default.worldName\", worldName, configFile);\n writeYamlData(\"default.x\", String.valueOf(x), configFile);\n writeYamlData(\"default.y\", String.valueOf(y), configFile);\n writeYamlData(\"default.z\", String.valueOf(z), configFile);\n writeYamlData(\"default.yaw\", String.valueOf(yaw), configFile);\n writeYamlData(\"default.pitch\", String.valueOf(pitch), configFile);\n } catch (IOException e) {\n player.sendMessage(Lang.commands_unableToSet.getResponse(Key.filePath.replaceWith(configFile.getAbsolutePath())));\n log.log(Level.WARNING, \"\", e);\n return true;\n }\n\n //reloads the config values\n Config.load();\n player.sendMessage(Lang.commands_setSpawn.getResponse());\n }\n\n //Teleports the player to the set spawn.\n case \"tp\" -> {\n if (!(commandSender instanceof Player)) return true;\n Player player = (Player) commandSender;\n\n player.teleport(Util.getDefaultSpawn());\n\n player.sendMessage(Lang.commands_teleported.getResponse());\n }\n\n //Reloads the config values for SpawnFix.\n case \"reload\" -> {\n Config.load();\n Lang.load();\n\n commandSender.sendMessage(Lang.commands_reload.getResponse());\n }\n\n default -> {\n commandSender.sendMessage(Lang.commands_help_help.getResponse());\n commandSender.sendMessage(Lang.commands_help_setSpawn.getResponse());\n commandSender.sendMessage(Lang.commands_help_tp.getResponse());\n commandSender.sendMessage(Lang.commands_help_reload.getResponse());\n }\n\n }\n\n return true;\n}\n}" }, { "identifier": "TabComplete", "path": "src/main/java/me/tye/spawnfix/commands/TabComplete.java", "snippet": "public class TabComplete implements TabCompleter {\n@Nullable\n@Override\npublic List<String> onTabComplete(@NotNull CommandSender commandSender, @NotNull Command command, @NotNull String alias, @NotNull String[] args) {\n ArrayList<String> completions = new ArrayList<>();\n\n if (!commandSender.hasPermission(\"sf\")) {\n return completions;\n }\n\n String token = \"\";\n\n if (args.length == 1) {\n token = args[0];\n }\n\n StringUtil.copyPartialMatches(token, List.of(\"setSpawn\", \"tp\", \"reload\", \"help\"), completions);\n\n return completions;\n}\n}" }, { "identifier": "Config", "path": "src/main/java/me/tye/spawnfix/utils/Config.java", "snippet": "public enum Config {\n\n default_worldName(String.class),\n default_x(Double.class),\n default_y(Double.class),\n default_z(Double.class),\n default_yaw(Float.class),\n default_pitch(Float.class),\n\n teleport_times(Integer.class),\n teleport_retryInterval(Integer.class),\n\n login(Occurrence.class),\n onSpawn(Occurrence.class),\n lang(String.class);\n\n\n\n/**\n * @param type Should be set to the class of the object this enum will be parsed as. This checks that the config values entered are valid for the used key.\n */\nConfig(Class type) {\n this.type = type;\n}\n\n/**\n Stores the class this object should be parsed as.\n */\nprivate final Class type;\n\n/**\n * @return The class of the object this enum should be parsed as.\n */\nprivate Class getType() {\n return type;\n}\n\n\n/**\n Stores the configs for this plugin.\n */\nprivate static final HashMap<Config, Object> configs = new HashMap<>();\n\n\n/**\n * @return Gets the config response for the selected enum.\n */\npublic @NotNull Object getConfig() {\n Object response = configs.get(this);\n\n assert response != null;\n\n return response;\n}\n\n/**\n * @return Gets the config response for the selected enum wrapped with String.valueOf().\n */\npublic @NotNull String getStringConfig() {\n return String.valueOf(getConfig());\n}\n\n/**\n * @return Gets the config response for the selected enum wrapped with Integer.parseInt().\n */\npublic int getIntegerConfig() {\n return Integer.parseInt(getStringConfig());\n}\n\n/**\n * @return Gets the config response for the selected enum wrapped with Double.parseDouble().\n */\npublic double getDoubleConfig() {\n return Double.parseDouble(getStringConfig());\n}\n\n/**\n * @return Gets the config response for the selected enum wrapped with Float.parseFloat().\n */\npublic float getFloatConfig() {\n return Float.parseFloat(getStringConfig());\n}\n\n/**\n Enum for how often spawnFix should act for a certain feature.\n */\npublic enum Occurrence {\n NEVER,\n FIRST,\n EVERY;\n}\n\n/**\n * @return Gets the config response for the selected enum wrapped with Occurrence.valueOf().\n */\npublic @NotNull Occurrence getOccurrenceConfig() {\n return Occurrence.valueOf(getStringConfig().toUpperCase());\n}\n\n/**\n Loads the default configs.\n */\npublic static void init() {\n //Loads the default values into the config.\n HashMap<String,Object> internalConfig = Util.parseInternalYaml(\"config.yml\");\n\n internalConfig.forEach((String key, Object value) -> {\n String formattedKey = key.replace('.', '_');\n\n try {\n Config config = Config.valueOf(formattedKey);\n\n if (!validate(config, value)) {\n //Dev warning\n throw new RuntimeException(\"\\\"\"+config+\"\\\" cannot be parsed as given object. - Dev warning\");\n }\n\n configs.put(config, value);\n\n } catch (IllegalArgumentException e) {\n //Dev warning\n throw new RuntimeException(\"\\\"\"+formattedKey + \"\\\" isn't in default config file. - Dev warning\");\n }\n });\n\n //Checks if any default values are missing.\n for (Config config : Config.values()) {\n if (configs.containsKey(config)) continue;\n\n //Dev warning.\n throw new RuntimeException(\"\\\"\"+config+\"\\\" isn't in default config file. - Dev warning\");\n }\n}\n\n/**\n Puts the keys response specified by the user into the configs map.\n */\npublic static void load() {\n //Loads in the user-set configs.\n File externalConfigFile = new File(Util.dataFolder.toPath()+File.separator+\"config.yml\");\n HashMap<String,Object> externalConfigs = Util.parseAndRepairExternalYaml(externalConfigFile, \"config.yml\");\n\n HashMap<Config, Object> userConfigs = new HashMap<>();\n\n //Gets the default keys that the user has entered.\n for (Map.Entry<String, Object> entry : externalConfigs.entrySet()) {\n String key = entry.getKey();\n Object value = entry.getValue();\n\n String formattedKey = key.replace('.', '_');\n Config config = Config.valueOf(formattedKey);\n\n if (!validate(config, value)) {\n log.warning(Lang.excepts_invalidValue.getResponse(Key.key.replaceWith(key), Key.filePath.replaceWith(externalConfigFile.getAbsolutePath())));\n continue;\n }\n\n //logs an exception if the key doesn't exist.\n try {\n userConfigs.put(config, value);\n\n } catch (IllegalArgumentException e) {\n log.warning(Lang.excepts_invalidKey.getResponse(Key.key.replaceWith(key)));\n }\n }\n\n\n //Warns the user about any config keys they are missing.\n for (Config config : configs.keySet()) {\n if (userConfigs.containsKey(config)) continue;\n\n log.warning(Lang.excepts_missingKey.getResponse(Key.key.replaceWith(config.toString()), Key.filePath.replaceWith(externalConfigFile.getAbsolutePath())));\n }\n\n configs.putAll(userConfigs);\n}\n\n/**\n Checks if config can be parsed as its intended object.\n * @param config The config to check.\n * @param value The value of the config.\n * @return True if the config can be parsed as its intended object. False if it can't.\n */\nprivate static boolean validate(Config config, Object value) {\n Class configType = config.getType();\n\n //Strings can always be parsed.\n if (configType.equals(String.class)) return true;\n\n String stringValue = value.toString();\n\n if (configType.equals(Double.class)) {\n try {\n Double.parseDouble(stringValue);\n return true;\n } catch (Exception ignore) {\n return false;\n }\n }\n\n if (configType.equals(Occurrence.class)) {\n try {\n Occurrence.valueOf(stringValue.toUpperCase());\n return true;\n } catch (Exception ignore) {\n return false;\n }\n }\n\n if (configType.equals(Integer.class)) {\n try {\n Integer.parseInt(stringValue);\n return true;\n } catch (Exception ignore) {\n return false;\n }\n }\n\n if (configType.equals(Float.class)) {\n try {\n Float.parseFloat(stringValue);\n return true;\n } catch (Exception ignore) {\n return false;\n }\n }\n\n throw new RuntimeException(\"Validation for class \\\"\"+configType+\"\\\" does not exist! - Dev warning.\");\n}\n\n}" }, { "identifier": "Lang", "path": "src/main/java/me/tye/spawnfix/utils/Lang.java", "snippet": "public enum Lang {\n\n startUp_readMe,\n startUp_link,\n\n teleport_noLocation,\n teleport_noPlayer,\n\n commands_setSpawn,\n commands_unableToSet,\n commands_teleported,\n commands_reload,\n commands_help_help,\n commands_help_reload,\n commands_help_setSpawn,\n commands_help_tp,\n\n excepts_invalidKey,\n excepts_invalidValue,\n excepts_missingKey,\n excepts_fileCreation,\n excepts_fileRestore,\n excepts_parseYaml,\n excepts_noFile;\n\n/**\n Stores the lang values.\n */\nprivate static final HashMap<Lang, String> langs = new HashMap<>();\n\n\n/**\n Gets the string response for the selected enum.\n * @param keys The keys to modify the response with.\n * @return The modified string.\n */\npublic @NotNull String getResponse(@NotNull Key... keys) {\n String response = this.getResponse();\n\n for (Key key : keys) {\n String replaceString = key.getReplaceWith();\n\n //For windows file paths the \"\\\" wouldn't get logged so it's escaped.\n if (key.equals(Key.filePath)) {\n replaceString = replaceString.replaceAll(\"\\\\\\\\\", \"\\\\\\\\\\\\\\\\\");\n }\n\n response = response.replaceAll(\"\\\\{\"+key+\"}\", replaceString);\n }\n\n return response;\n}\n\n/**\n * @return The string response without any keys being modified. This is the same as getResponse();\n */\npublic @NotNull String getResponse() {\n String response = langs.get(this);\n\n assert response != null;\n\n return response;\n}\n\n/**\n Loads the default lang.\n */\npublic static void init() {\n //Falls back to english if default values can't be found.\n String resourcePath = \"lang/\"+Config.lang.getStringConfig()+\".yml\";\n if (plugin.getResource(resourcePath) == null) {\n resourcePath = \"lang/eng.yml\";\n }\n\n //Loads the default values into lang.\n HashMap<String,Object> internalYaml = Util.parseInternalYaml(resourcePath);\n internalYaml.forEach((String key, Object value) -> {\n String formattedKey = key.replace('.', '_');\n\n try {\n langs.put(Lang.valueOf(formattedKey), value.toString());\n\n } catch (IllegalArgumentException e) {\n //Dev warning\n throw new RuntimeException(formattedKey + \" isn't present in the lang enum.\");\n }\n });\n\n //Checks if any default values are missing.\n for (Lang lang : Lang.values()) {\n if (langs.containsKey(lang)) continue;\n\n //Dev warning.\n throw new RuntimeException(lang+\" isn't in default lang file.\");\n }\n}\n\n/**\n Loads the user - selected lang values into the lang map.<br>\n To see available languages for a version see the src/main/resources/lang/ for your version on GitHub.\n */\npublic static void load() {\n //No repair is attempted if the internal file can't be found.\n String resourcePath = \"lang/\"+Config.lang.getStringConfig()+\".yml\";\n if (plugin.getResource(resourcePath) == null) {\n resourcePath = null;\n }\n\n //Loads the external lang responses. No file repairing is done if an internal lang can't be found.\n File externalFile = new File(langFolder.toPath()+File.separator+Config.lang.getStringConfig()+\".yml\");\n HashMap<String,Object> externalYaml = Util.parseAndRepairExternalYaml(externalFile, resourcePath);\n\n HashMap<Lang, String> userLangs = new HashMap<>();\n\n //Gets the default keys that the user has entered.\n externalYaml.forEach((String key, Object value) -> {\n String formattedKey = key.replace('.', '_');\n\n //Logs an exception if the key doesn't exist.\n try {\n userLangs.put(Lang.valueOf(formattedKey), value.toString());\n } catch (IllegalArgumentException e) {\n Util.log.warning(Lang.excepts_invalidKey.getResponse(Key.key.replaceWith(key), Key.filePath.replaceWith(externalFile.getAbsolutePath())));\n }\n });\n\n //Warns the user about any lang keys they are missing.\n for (Lang lang : langs.keySet()) {\n if (userLangs.containsKey(lang)) continue;\n\n String formattedKey = lang.toString().replace('.', '_');\n log.warning(Lang.excepts_missingKey.getResponse(Key.key.replaceWith(formattedKey), Key.filePath.replaceWith(externalFile.getAbsolutePath())));\n }\n\n langs.putAll(userLangs);\n}\n\n}" }, { "identifier": "Util", "path": "src/main/java/me/tye/spawnfix/utils/Util.java", "snippet": "public class Util {\n\n/**\n This plugin.\n */\npublic static final JavaPlugin plugin = JavaPlugin.getPlugin(SpawnFix.class);\n\n\n/**\n The data folder.\n */\npublic static final File dataFolder = plugin.getDataFolder();\n\n/**\n The config file for this plugin.\n */\npublic static final File configFile = new File(dataFolder.toPath() + File.separator + \"config.yml\");\n\n/**\n The lang folder for this plugin.\n */\npublic static File langFolder = new File(dataFolder.toPath() + File.separator + \"langFiles\");\n\n/**\n The logger for this plugin.\n */\npublic static final Logger log = plugin.getLogger();\n\n\n/**\n * @return The default spawn location as set in the config.yml of this plugin.\n */\npublic static Location getDefaultSpawn() {\n return new Location(Bukkit.getWorld(Config.default_worldName.getStringConfig()),\n Config.default_x.getDoubleConfig(),\n Config.default_y.getDoubleConfig(),\n Config.default_z.getDoubleConfig(),\n Config.default_yaw.getFloatConfig(),\n Config.default_pitch.getFloatConfig()\n );\n}\n\n\n/**\n Formats the Map returned from Yaml.load() into a hashmap where the exact key corresponds to the value.<br>\n E.G: key: \"example.response\" value: \"test\".\n @param baseMap The Map from Yaml.load().\n @return The formatted Map. */\npublic static @NotNull HashMap<String,Object> getKeysRecursive(@Nullable Map<?,?> baseMap) {\n HashMap<String,Object> map = new HashMap<>();\n if (baseMap == null) return map;\n\n for (Object key : baseMap.keySet()) {\n Object value = baseMap.get(key);\n\n if (value instanceof Map<?,?> subMap) {\n map.putAll(getKeysRecursive(String.valueOf(key), subMap));\n } else {\n map.put(String.valueOf(key), String.valueOf(value));\n }\n\n }\n\n return map;\n}\n\n/**\n Formats the Map returned from Yaml.load() into a hashmap where the exact key corresponds to the value.\n @param keyPath The path to append to the starts of the key. (Should only be called internally).\n @param baseMap The Map from Yaml.load().\n @return The formatted Map. */\npublic static @NotNull HashMap<String,Object> getKeysRecursive(@NotNull String keyPath, @NotNull Map<?,?> baseMap) {\n if (!keyPath.isEmpty()) keyPath += \".\";\n\n HashMap<String,Object> map = new HashMap<>();\n for (Object key : baseMap.keySet()) {\n Object value = baseMap.get(key);\n\n if (value instanceof Map<?,?> subMap) {\n map.putAll(getKeysRecursive(keyPath+key, subMap));\n } else {\n map.put(keyPath+key, String.valueOf(value));\n }\n\n }\n\n return map;\n}\n\n/**\n Copies the content of an internal file to a new external one.\n @param file External file destination\n @param resource Input stream for the data to write, or null if target is an empty file/dir.\n @param isFile Set to true to create a file. Set to false to create a dir.*/\npublic static void makeRequiredFile(@NotNull File file, @Nullable InputStream resource, boolean isFile) throws IOException {\n if (file.exists())\n return;\n\n if (isFile) {\n if (!file.createNewFile())\n throw new IOException();\n }\n else {\n if (!file.mkdir())\n throw new IOException();\n }\n\n if (resource != null) {\n String text = new String(resource.readAllBytes());\n FileWriter fw = new FileWriter(file);\n fw.write(text);\n fw.close();\n }\n}\n\n/**\n Copies the content of an internal file to a new external one.\n @param file External file destination\n @param resource Input stream for the data to write, or null if target is an empty file/dir.\n @param isFile Set to true to create a file. Set to false to create a dir.*/\npublic static void createFile(@NotNull File file, @Nullable InputStream resource, boolean isFile) {\n try {\n makeRequiredFile(file, resource, isFile);\n } catch (IOException e) {\n log.log(Level.WARNING, Lang.excepts_fileCreation.getResponse(Key.filePath.replaceWith(file.getAbsolutePath())), e);\n }\n}\n\n\n/**\n Parses & formats data from the given inputStream to a Yaml resource.\n * @param yamlInputStream The given inputStream to a Yaml resource.\n * @return The parsed values in the format key: \"test1.log\" value: \"works!\"<br>\n * Or an empty hashMap if the given inputStream is null.\n * @throws IOException If the data couldn't be read from the given inputStream.\n */\nprivate static @NotNull HashMap<String, Object> parseYaml(@Nullable InputStream yamlInputStream) throws IOException {\n if (yamlInputStream == null) return new HashMap<>();\n\n byte[] resourceBytes = yamlInputStream.readAllBytes();\n\n String resourceContent = new String(resourceBytes, Charset.defaultCharset());\n\n return getKeysRecursive(new Yaml().load(resourceContent));\n}\n\n/**\n Parses the data from an internal YAML file.\n * @param resourcePath The path to the file from /src/main/resource/\n * @return The parsed values in the format key: \"test1.log\" value: \"works!\" <br>\n * Or an empty hashMap if the file couldn't be found or read.\n */\npublic static @NotNull HashMap<String, Object> parseInternalYaml(@NotNull String resourcePath) {\n try (InputStream resourceInputStream = plugin.getResource(resourcePath)) {\n return parseYaml(resourceInputStream);\n\n } catch (IOException e) {\n log.log(Level.SEVERE, \"Unable to parse internal YAML files.\\nConfig & lang might break.\\n\", e);\n return new HashMap<>();\n }\n\n}\n\n\n/**\n Parses the given external file into a hashMap. If the internal file contained keys that the external file didn't then the key-value pare is added to the external file.\n * @param externalFile The external file to parse.\n * @param pathToInternalResource The path to the internal resource to repair it with or fallback on if the external file is broken.\n * @return The key-value pairs from the external file. If any keys were missing from the external file then they are put into the hashMap with their default value.\n */\npublic static @NotNull HashMap<String, Object> parseAndRepairExternalYaml(@NotNull File externalFile, @Nullable String pathToInternalResource) {\n HashMap<String,Object> externalYaml;\n\n //tries to parse the external file.\n try (InputStream externalInputStream = new FileInputStream(externalFile)) {\n externalYaml = parseYaml(externalInputStream);\n\n } catch (FileNotFoundException e) {\n log.log(Level.SEVERE, Lang.excepts_noFile.getResponse(Key.filePath.replaceWith(externalFile.getAbsolutePath())), e);\n\n //returns an empty hashMap or the internal values if present.\n return pathToInternalResource == null ? new HashMap<>() : parseInternalYaml(pathToInternalResource);\n\n } catch (IOException e) {\n log.log(Level.SEVERE, Lang.excepts_parseYaml.getResponse(Key.filePath.replaceWith(externalFile.getAbsolutePath())), e);\n\n //returns an empty hashMap or the internal values if present.\n return pathToInternalResource == null ? new HashMap<>() : parseInternalYaml(pathToInternalResource);\n }\n\n\n //if there is no internal resource to compare against then only the external file data is returned.\n if (pathToInternalResource == null)\n return externalYaml;\n\n HashMap<String,Object> internalYaml = parseInternalYaml(pathToInternalResource);\n\n //gets the values that the external file is missing;\n HashMap<String,Object> missingPairsMap = new HashMap<>();\n internalYaml.forEach((String key, Object value) -> {\n if (externalYaml.containsKey(key))\n return;\n\n missingPairsMap.put(key, value);\n });\n\n //if no values are missing return\n if (missingPairsMap.keySet().isEmpty())\n return externalYaml;\n\n //Adds all the missing key-value pairs to a stringBuilder.\n StringBuilder missingPairs = new StringBuilder(\"\\n\");\n missingPairsMap.forEach((String key, Object value) -> {\n missingPairs.append(key)\n .append(\": \\\"\")\n .append(preserveEscapedQuotes(value))\n .append(\"\\\"\\n\");\n });\n\n //Adds al the missing pairs to the external Yaml.\n externalYaml.putAll(missingPairsMap);\n\n\n //Writes the missing pairs to the external file.\n try (FileWriter externalFileWriter = new FileWriter(externalFile, true)) {\n externalFileWriter.append(missingPairs.toString());\n\n }catch (IOException e) {\n //Logs a warning\n log.log(Level.WARNING, Lang.excepts_fileRestore.getResponse(Key.filePath.replaceWith(externalFile.getAbsolutePath())), e);\n\n //Logs the keys that couldn't be appended.\n missingPairsMap.forEach((String key, Object value) -> {\n log.log(Level.WARNING, key + \": \" + value);\n });\n }\n\n return externalYaml;\n}\n\n/**\n Object.toString() changes \\\" to \". This method resolves this problem.\n * @param value The object to get the string from.\n * @return The correct string from the given object.\n */\nprivate static String preserveEscapedQuotes(Object value) {\n char[] valueCharArray = value.toString().toCharArray();\n StringBuilder correctString = new StringBuilder();\n\n\n for (char character : valueCharArray) {\n if (character != '\"') {\n correctString.append(character);\n continue;\n }\n\n correctString.append('\\\\');\n correctString.append('\"');\n }\n\n return correctString.toString();\n}\n\n/**\n Writes the new value to the key in the specified external yaml file.\n * @param key The key to replace the value of.\n * @param value The new string to overwrite the old value with.\n * @param externalYaml The external yaml to perform this operation on.\n * @throws IOException If there was an error reading or writing data to the Yaml file.\n */\npublic static void writeYamlData(@NotNull String key, @NotNull String value, @NotNull File externalYaml) throws IOException {\n String fileContent;\n\n //Reads the content from the file.\n try (FileInputStream externalYamlInputStream = new FileInputStream(externalYaml)) {\n fileContent = new String(externalYamlInputStream.readAllBytes());\n }\n\n //Ensures that every key ends with \":\".\n //This avoids false matches where one key contains the starting chars of another.\n String[] keys = key.split(\"\\\\.\");\n for (int i = 0; i < keys.length; i++) {\n String k = keys[i];\n\n if (k.endsWith(\":\")) continue;\n\n k+=\":\";\n keys[i] = k;\n }\n\n\n Integer valueStartPosition = findKeyPosition(keys, fileContent);\n if (valueStartPosition == null) throw new IOException(\"Unable to find \"+key+\" in external Yaml file.\");\n\n int valueLineEnd = valueStartPosition;\n //Finds the index of the end of the line that the key is on.\n while (fileContent.charAt(valueLineEnd) != '\\n') {\n valueLineEnd++;\n }\n\n String firstPart = fileContent.substring(0, valueStartPosition);\n String secondPart = fileContent.substring(valueLineEnd, fileContent.length()-1);\n\n String newFileContent = firstPart.concat(value).concat(secondPart);\n\n try (FileWriter externalYamlWriter = new FileWriter(externalYaml)) {\n externalYamlWriter.write(newFileContent);\n }\n}\n\n/**\n Finds the given key index in the given file content split on each new line.<br>\n The key should be given in the format \"example.key1\".\n * @param keys The given keys.\n * @param fileContent The given file content.\n * @return The index of the char a space after the end of the last key.<br>\n * Example: \"key1: !\" the char index that the '!' is on.<br>\n * Or null if the key couldn't be found.\n */\nprivate static @Nullable Integer findKeyPosition(@NotNull String[] keys, @NotNull String fileContent) {\n\n //Iterates over each line in the file content.\n String[] split = fileContent.split(\"\\n\");\n\n for (int keyLine = 0, splitLength = split.length; keyLine < splitLength; keyLine++) {\n String strippedLine = split[keyLine].stripLeading();\n\n //if it doesn't start with the key value then continue\n if (!strippedLine.startsWith(keys[0])) {\n continue;\n }\n\n return findKeyPosition(keys, keyLine+1, 1, fileContent);\n\n }\n\n return null;\n}\n\n/**\n Gets the index for the line of the last sub-key given in the given fileContent.<br>\n This method executes recursively.\n * @param keys The keys to find in the file.\n * @param startLine The index of the line to start the search from.\n * @param keyIndex The index of the sub-key that is searched for.\n * @param fileContent The content of the file to search through.\n * @return The index of the char a space after the end of the last key.<br>\n * Example: \"key1: !\" the char index that the '!' is on.<br>\n * Or null if the key couldn't be found.\n */\nprivate static @Nullable Integer findKeyPosition(@NotNull String[] keys, int startLine, int keyIndex, @NotNull String fileContent) {\n //Iterates over each line in the file content.\n String[] split = fileContent.split(\"\\n\");\n\n for (int lineIndex = startLine, splitLength = split.length; lineIndex < splitLength; lineIndex++) {\n\n String line = split[lineIndex];\n\n //returns null if the key doesn't exist as a sub-key of the base key.\n if (!(line.startsWith(\" \") || line.startsWith(\"\\t\"))) {\n return null;\n }\n\n String strippedLine = line.stripLeading();\n\n //if it doesn't start with the key value then continue\n if (!strippedLine.startsWith(keys[keyIndex])) {\n continue;\n }\n\n keyIndex++;\n\n //returns the char position that the key ends on if it is the last key in the sequence.\n if (keyIndex == keys.length) {\n\n int currentLinePosition = 0;\n //Gets the char position of the current line within the string.\n for (int i = 0; i < lineIndex; i++) {\n currentLinePosition+=split[i].length()+1;\n }\n\n //Finds the char position a space after the key ends.\n for (int i = currentLinePosition; i < fileContent.length(); i++) {\n char character = fileContent.charAt(i);\n\n if (character != ':') continue;\n\n return i+2;\n\n }\n }\n\n return findKeyPosition(keys, startLine, keyIndex, fileContent);\n }\n\n return null;\n}\n\n}" } ]
import me.tye.spawnfix.commands.Commands; import me.tye.spawnfix.commands.TabComplete; import me.tye.spawnfix.utils.Config; import me.tye.spawnfix.utils.Lang; import org.bukkit.plugin.java.JavaPlugin; import java.io.File; import java.io.IOException; import java.util.Objects; import java.util.logging.Level; import static me.tye.spawnfix.utils.Util.*;
7,202
package me.tye.spawnfix; public final class SpawnFix extends JavaPlugin { @Override public void onEnable() { createRequiredFiles(); Config.init();
package me.tye.spawnfix; public final class SpawnFix extends JavaPlugin { @Override public void onEnable() { createRequiredFiles(); Config.init();
Lang.init();
3
2023-11-13 23:53:25+00:00
12k
wangxianhui111/xuechengzaixian
xuecheng-plus-content/xuecheng-plus-content-service/src/main/java/com/xuecheng/content/service/impl/CoursePublishServiceImpl.java
[ { "identifier": "XueChengPlusException", "path": "xuecheng-plus-base/src/main/java/com/xuecheng/base/exception/XueChengPlusException.java", "snippet": "public class XueChengPlusException extends RuntimeException {\n private static final long serialVersionUID = 5565760508056698922L;\n private String errMessage;\n\n public XueChengPlusException() {\n super();\n }\n\n public XueChengPlusException(String errMessage) {\n super(errMessage);\n this.errMessage = errMessage;\n }\n\n public String getErrMessage() {\n return errMessage;\n }\n\n public static void cast(CommonError commonError) {\n throw new XueChengPlusException(commonError.getErrMessage());\n }\n\n public static void cast(String errMessage) {\n throw new XueChengPlusException(errMessage);\n }\n}" }, { "identifier": "MultipartSupportConfig", "path": "xuecheng-plus-content/xuecheng-plus-content-service/src/main/java/com/xuecheng/content/config/MultipartSupportConfig.java", "snippet": "@Configuration\npublic class MultipartSupportConfig {\n @Autowired\n private ObjectFactory<HttpMessageConverters> messageConverters;\n\n @Bean\n @Primary// 注入相同类型的bean时优先使用\n @Scope(\"prototype\")\n public Encoder feignEncoder() {\n return new SpringFormEncoder(new SpringEncoder(messageConverters));\n }\n\n // 将file转为Multipart\n public static MultipartFile getMultipartFile(File file) {\n FileItem item = new DiskFileItemFactory()\n .createItem(\"file\", MediaType.MULTIPART_FORM_DATA_VALUE, true, file.getName());\n try (FileInputStream inputStream = new FileInputStream(file);\n\n OutputStream outputStream = item.getOutputStream();) {\n IOUtils.copy(inputStream, outputStream);\n } catch (Exception e) {\n e.printStackTrace();\n }\n return new CommonsMultipartFile(item);\n }\n}" }, { "identifier": "MediaServiceClient", "path": "xuecheng-plus-content/xuecheng-plus-content-service/src/main/java/com/xuecheng/content/feignclient/MediaServiceClient.java", "snippet": "@FeignClient(value = \"media-api\",\n configuration = MultipartSupportConfig.class,\n fallbackFactory = MediaServiceClient.MediaServiceClientFallbackFactory.class)\npublic interface MediaServiceClient {\n\n /**\n * 上传文件\n */\n @RequestMapping(value = \"/media/upload/coursefile\", consumes = {MediaType.MULTIPART_FORM_DATA_VALUE})\n String uploadFile(@RequestPart(\"filedata\") MultipartFile filedata,\n @RequestParam(value = \"folder\", required = false) String folder,\n @RequestParam(value = \"objectName\", required = false) String objectName);\n\n // 服务降级处理,可以获取异常信息\n @Slf4j\n class MediaServiceClientFallbackFactory implements FallbackFactory<MediaServiceClient> {\n // 降级方法\n @Override\n public MediaServiceClient create(Throwable cause) {\n log.error(\"远程调用媒资管理服务上传文件时发生熔断,熔断异常是:{}\", cause.getMessage());\n return null;\n }\n }\n}" }, { "identifier": "SearchServiceClient", "path": "xuecheng-plus-content/xuecheng-plus-content-service/src/main/java/com/xuecheng/content/feignclient/SearchServiceClient.java", "snippet": "@FeignClient(value = \"search\",\n fallbackFactory = SearchServiceClient.SearchServiceClientFallbackFactory.class)\npublic interface SearchServiceClient {\n\n /**\n * 添加课程\n */\n @PostMapping(\"/search/index/course\")\n Boolean add(@RequestBody CourseIndex courseIndex);\n\n @Slf4j\n class SearchServiceClientFallbackFactory implements FallbackFactory<SearchServiceClient> {\n\n @Override\n public SearchServiceClient create(Throwable cause) {\n log.error(\"远程调用课程索引添加服务时发生熔断,熔断异常是:{}\", cause.getMessage());\n return null;\n }\n }\n\n}" }, { "identifier": "CourseIndex", "path": "xuecheng-plus-content/xuecheng-plus-content-service/src/main/java/com/xuecheng/content/feignclient/po/CourseIndex.java", "snippet": "@Data\npublic class CourseIndex implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n /**\n * 主键\n */\n private Long id;\n\n /**\n * 机构ID\n */\n private Long companyId;\n\n /**\n * 公司名称\n */\n private String companyName;\n\n /**\n * 课程名称\n */\n private String name;\n\n /**\n * 适用人群\n */\n private String users;\n\n /**\n * 标签\n */\n private String tags;\n\n\n /**\n * 大分类\n */\n private String mt;\n\n /**\n * 大分类名称\n */\n private String mtName;\n\n /**\n * 小分类\n */\n private String st;\n\n /**\n * 小分类名称\n */\n private String stName;\n\n\n /**\n * 课程等级\n */\n private String grade;\n\n /**\n * 教育模式\n */\n private String teachmode;\n /**\n * 课程图片\n */\n private String pic;\n\n /**\n * 课程介绍\n */\n private String description;\n\n\n /**\n * 发布时间\n */\n @JSONField(format = \"yyyy-MM-dd HH:mm:ss\")\n @JsonFormat(pattern = \"yyyy-MM-dd HH:mm:ss\")\n private LocalDateTime createDate;\n\n /**\n * 状态\n */\n private String status;\n\n /**\n * 备注\n */\n private String remark;\n\n /**\n * 收费规则,对应数据字典--203\n */\n private String charge;\n\n /**\n * 现价\n */\n private Float price;\n /**\n * 原价\n */\n private Float originalPrice;\n\n /**\n * 课程有效期天数\n */\n private Integer validDays;\n\n}" }, { "identifier": "CourseBaseMapper", "path": "xuecheng-plus-content/xuecheng-plus-content-service/src/main/java/com/xuecheng/content/mapper/CourseBaseMapper.java", "snippet": "public interface CourseBaseMapper extends BaseMapper<CourseBase> {\n\n}" }, { "identifier": "CourseMarketMapper", "path": "xuecheng-plus-content/xuecheng-plus-content-service/src/main/java/com/xuecheng/content/mapper/CourseMarketMapper.java", "snippet": "public interface CourseMarketMapper extends BaseMapper<CourseMarket> {\n\n}" }, { "identifier": "CoursePublishMapper", "path": "xuecheng-plus-content/xuecheng-plus-content-service/src/main/java/com/xuecheng/content/mapper/CoursePublishMapper.java", "snippet": "public interface CoursePublishMapper extends BaseMapper<CoursePublish> {\n\n}" }, { "identifier": "CoursePublishPreMapper", "path": "xuecheng-plus-content/xuecheng-plus-content-service/src/main/java/com/xuecheng/content/mapper/CoursePublishPreMapper.java", "snippet": "public interface CoursePublishPreMapper extends BaseMapper<CoursePublishPre> {\n\n}" }, { "identifier": "CourseBaseInfoDto", "path": "xuecheng-plus-content/xuecheng-plus-content-model/src/main/java/com/xuecheng/content/model/dto/CourseBaseInfoDto.java", "snippet": "@EqualsAndHashCode(callSuper = true)\n@Data\npublic class CourseBaseInfoDto extends CourseBase {\n\n /**\n * 收费规则,对应数据字典\n */\n private String charge;\n\n /**\n * 价格\n */\n private Float price;\n\n /**\n * 原价\n */\n private Float originalPrice;\n\n /**\n * 咨询qq\n */\n private String qq;\n\n /**\n * 微信\n */\n private String wechat;\n\n /**\n * 电话\n */\n private String phone;\n\n /**\n * 有效期天数\n */\n private Integer validDays;\n\n /**\n * 大分类名称\n */\n private String mtName;\n\n /**\n * 小分类名称\n */\n private String stName;\n\n}" }, { "identifier": "CoursePreviewDto", "path": "xuecheng-plus-content/xuecheng-plus-content-model/src/main/java/com/xuecheng/content/model/dto/CoursePreviewDto.java", "snippet": "@Data\npublic class CoursePreviewDto {\n\n /**\n * 课程基本信息,课程营销信息\n */\n CourseBaseInfoDto courseBase;\n\n /**\n * 课程计划信息\n */\n List<TeachplanDto> teachplans;\n\n // 师资信息暂时不加...\n\n}" }, { "identifier": "TeachplanDto", "path": "xuecheng-plus-content/xuecheng-plus-content-model/src/main/java/com/xuecheng/content/model/dto/TeachplanDto.java", "snippet": "@EqualsAndHashCode(callSuper = true)\n@Slf4j\n@Data\npublic class TeachplanDto extends Teachplan {\n\n /**\n * 关联的媒资信息\n */\n TeachplanMedia teachplanMedia;\n\n /**\n * 子目录\n */\n List<TeachplanDto> teachPlanTreeNodes;\n\n}" }, { "identifier": "CourseBase", "path": "xuecheng-plus-content/xuecheng-plus-content-model/src/main/java/com/xuecheng/content/model/po/CourseBase.java", "snippet": "@Data\n@TableName(\"course_base\")\npublic class CourseBase implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n /**\n * 主键\n */\n @TableId(value = \"id\", type = IdType.AUTO)\n private Long id;\n\n /**\n * 机构ID\n */\n private Long companyId;\n\n /**\n * 机构名称\n */\n private String companyName;\n\n /**\n * 课程名称\n */\n private String name;\n\n /**\n * 适用人群\n */\n private String users;\n\n /**\n * 课程标签\n */\n private String tags;\n\n /**\n * 大分类\n */\n private String mt;\n\n /**\n * 小分类\n */\n private String st;\n\n /**\n * 课程等级\n */\n private String grade;\n\n /**\n * 教育模式(common普通,record 录播,live直播等)\n */\n private String teachmode;\n\n /**\n * 课程介绍\n */\n private String description;\n\n /**\n * 课程图片\n */\n private String pic;\n\n /**\n * 创建时间\n */\n @TableField(fill = FieldFill.INSERT)\n private LocalDateTime createDate;\n\n /**\n * 修改时间\n */\n @TableField(fill = FieldFill.INSERT_UPDATE)\n private LocalDateTime changeDate;\n\n /**\n * 创建人\n */\n private String createPeople;\n\n /**\n * 更新人\n */\n private String changePeople;\n\n /**\n * 审核状态<p>\n * {\"202001\":\"审核未通过\"},{\"202002\":\"未提交\"},{\"202003\":\"已提交\"},{\"202004\":\"审核通过\"}\n */\n private String auditStatus;\n\n /**\n * 课程发布状态 未发布 已发布 下线<p>\n * {\"203001\":\"未发布\"},{\"203002\":\"已发布\"},{\"203003\":\"下线\"}\n * </p>\n */\n private String status;\n\n}" }, { "identifier": "CourseMarket", "path": "xuecheng-plus-content/xuecheng-plus-content-model/src/main/java/com/xuecheng/content/model/po/CourseMarket.java", "snippet": "@Data\n@TableName(\"course_market\")\npublic class CourseMarket implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n /**\n * 主键,课程id\n */\n private Long id;\n\n /**\n * 收费规则,对应数据字典\n */\n private String charge;\n\n /**\n * 现价\n */\n private Float price;\n\n /**\n * 原价\n */\n private Float originalPrice;\n\n /**\n * 咨询qq\n */\n private String qq;\n\n /**\n * 微信\n */\n private String wechat;\n\n /**\n * 电话\n */\n private String phone;\n\n /**\n * 有效期天数\n */\n private Integer validDays;\n\n}" }, { "identifier": "CoursePublish", "path": "xuecheng-plus-content/xuecheng-plus-content-model/src/main/java/com/xuecheng/content/model/po/CoursePublish.java", "snippet": "@Data\n@TableName(\"course_publish\")\npublic class CoursePublish implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n /**\n * 主键(课程id)\n */\n private Long id;\n\n /**\n * 机构ID\n */\n private Long companyId;\n\n /**\n * 公司名称\n */\n private String companyName;\n\n /**\n * 课程名称\n */\n private String name;\n\n /**\n * 适用人群\n */\n private String users;\n\n /**\n * 标签\n */\n private String tags;\n\n /**\n * 创建人\n */\n private String username;\n\n /**\n * 大分类\n */\n private String mt;\n\n /**\n * 大分类名称\n */\n private String mtName;\n\n /**\n * 小分类\n */\n private String st;\n\n /**\n * 小分类名称\n */\n private String stName;\n\n /**\n * 课程等级\n */\n private String grade;\n\n /**\n * 教育模式\n */\n private String teachmode;\n\n /**\n * 课程图片\n */\n private String pic;\n\n /**\n * 课程介绍\n */\n private String description;\n\n /**\n * 课程营销信息,json格式\n */\n private String market;\n\n /**\n * 所有课程计划,json格式\n */\n private String teachplan;\n\n /**\n * 教师信息,json格式\n */\n private String teachers;\n\n /**\n * 发布时间\n */\n @TableField(fill = FieldFill.INSERT)\n private LocalDateTime createDate;\n\n /**\n * 上架时间\n */\n private LocalDateTime onlineDate;\n\n /**\n * 下架时间\n */\n private LocalDateTime offlineDate;\n\n /**\n * 发布状态<p>\n * {\"203001\":\"未发布\"},{\"203002\":\"已发布\"},{\"203003\":\"下线\"}\n * </p>\n */\n private String status;\n\n /**\n * 备注\n */\n private String remark;\n\n /**\n * 收费规则,对应数据字典--203\n */\n private String charge;\n\n /**\n * 现价\n */\n private Float price;\n\n /**\n * 原价\n */\n private Float originalPrice;\n\n /**\n * 课程有效期天数\n */\n private Integer validDays;\n\n\n}" }, { "identifier": "CoursePublishPre", "path": "xuecheng-plus-content/xuecheng-plus-content-model/src/main/java/com/xuecheng/content/model/po/CoursePublishPre.java", "snippet": "@Data\n@TableName(\"course_publish_pre\")\npublic class CoursePublishPre implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n /**\n * 主键\n */\n private Long id;\n\n /**\n * 机构ID\n */\n private Long companyId;\n\n /**\n * 公司名称\n */\n private String companyName;\n\n /**\n * 课程名称\n */\n private String name;\n\n /**\n * 适用人群\n */\n private String users;\n\n /**\n * 标签\n */\n private String tags;\n\n /**\n * 创建人\n */\n private String username;\n\n /**\n * 大分类\n */\n private String mt;\n\n /**\n * 大分类名称\n */\n private String mtName;\n\n /**\n * 小分类\n */\n private String st;\n\n /**\n * 小分类名称\n */\n private String stName;\n\n /**\n * 课程等级\n */\n private String grade;\n\n /**\n * 教育模式\n */\n private String teachmode;\n\n /**\n * 课程图片\n */\n private String pic;\n\n /**\n * 课程介绍\n */\n private String description;\n\n /**\n * 课程营销信息,json格式\n */\n private String market;\n\n /**\n * 所有课程计划,json格式\n */\n private String teachplan;\n\n /**\n * 教师信息,json格式\n */\n private String teachers;\n\n /**\n * 提交时间\n */\n @TableField(fill = FieldFill.INSERT)\n private LocalDateTime createDate;\n\n /**\n * 审核时间\n */\n private LocalDateTime auditDate;\n\n /**\n * 状态\n */\n private String status;\n\n /**\n * 备注\n */\n private String remark;\n\n /**\n * 收费规则,对应数据字典--203\n */\n private String charge;\n\n /**\n * 现价\n */\n private Float price;\n\n /**\n * 原价\n */\n private Float originalPrice;\n\n /**\n * 课程有效期天数\n */\n private Integer validDays;\n\n\n}" }, { "identifier": "CourseBaseInfoService", "path": "xuecheng-plus-content/xuecheng-plus-content-service/src/main/java/com/xuecheng/content/service/CourseBaseInfoService.java", "snippet": "public interface CourseBaseInfoService {\n\n /**\n * 课程查询\n *\n * @param companyId 机构id\n * @param params 分页参数\n * @param queryCourseParams 查询条件\n * @return 分页结果\n */\n PageResult<CourseBase> queryCourseBaseList(Long companyId, PageParams params, QueryCourseParamsDto queryCourseParams);\n\n /**\n * 新增课程\n *\n * @param companyId 培训机构 id\n * @param addCourseDto 新增课程的信息\n * @return 课程信息包括基本信息,营销信息\n */\n CourseBaseInfoDto createCourseBase(Long companyId, AddCourseDto addCourseDto);\n\n /**\n * 根据课程id查询课程基本信息,包括基本信息和营销信息\n *\n * @param courseId 课程id\n * @return 返回对应的课程信息\n */\n CourseBaseInfoDto queryCourseBaseById(Long courseId);\n\n /**\n * 修改课程信息\n *\n * @param companyId 机构id(校验:本机构只能修改本机构的课程)\n * @param dto 课程信息\n * @return 返回修改后的课程信息\n */\n CourseBaseInfoDto updateCourseBase(Long companyId, EditCourseDto dto);\n\n /**\n * 删除课程\n *\n * @param courseId 课程 id\n * @return 删除结果\n */\n RestResponse<Boolean> deleteCourseBase(Long courseId);\n\n}" }, { "identifier": "CoursePublishService", "path": "xuecheng-plus-content/xuecheng-plus-content-service/src/main/java/com/xuecheng/content/service/CoursePublishService.java", "snippet": "public interface CoursePublishService {\n\n /**\n * 获取课程预览信息\n *\n * @param courseId 课程 id\n * @return {@link com.xuecheng.content.model.dto.CoursePreviewDto}\n * @author Wuxy\n * @since 2022/9/16 15:36\n */\n CoursePreviewDto getCoursePreviewInfo(Long courseId);\n\n /**\n * 通过 /open 接口获取课程预览信息\n *\n * @param courseId 课程 id\n * @return {@link com.xuecheng.content.model.dto.CoursePreviewDto}\n * @author Wuxy\n * @since 2022/9/16 15:36\n */\n CoursePreviewDto getOpenCoursePreviewInfo(Long courseId);\n\n /**\n * 提交审核\n *\n * @param courseId 课程 id\n * @author Wuxy\n * @since 2022/9/18 10:31\n */\n void commitAudit(Long companyId, Long courseId);\n\n /**\n * 课程发布接口\n *\n * @param companyId 机构 id\n * @param courseId 课程 id\n * @author Wuxy\n * @since 2022/9/20 16:23\n */\n void publish(Long companyId, Long courseId);\n\n /**\n * 课程静态化\n *\n * @param courseId 课程 id\n * @return {@link File} 静态化文件\n * @author Wuxy\n * @since 2022/9/23 16:59\n */\n File generateCourseHtml(Long courseId);\n\n /**\n * 上传课程静态化页面\n *\n * @param courseId 课程 id\n * @param file 静态化文件\n * @author Wuxy\n * @since 2022/9/23 16:59\n */\n void uploadCourseHtml(Long courseId, File file);\n\n /**\n * 新增课程索引\n *\n * @param courseId 课程id\n * @return 新增成功返回 true,否则 false\n */\n Boolean saveCourseIndex(Long courseId);\n\n /**\n * 根据课程id查询课程发布信息\n *\n * @param courseId 课程id\n * @return 课程发布信息\n */\n CoursePublish getCoursePublish(Long courseId);\n\n /**\n * 根据课程 id 查询缓存(Redis等)中的课程发布信息\n * <ol>\n * <li>基于缓存空值解决缓存穿透问题</li>\n * <li>基于redisson分布式锁解决缓存击穿问题</li>\n * </ol>\n *\n * @param courseId 课程id\n * @return 课程发布信息\n */\n CoursePublish getCoursePublishCache(Long courseId);\n\n}" }, { "identifier": "TeachplanService", "path": "xuecheng-plus-content/xuecheng-plus-content-service/src/main/java/com/xuecheng/content/service/TeachplanService.java", "snippet": "public interface TeachplanService {\n\n /**\n * 查询课程计划树形结构\n *\n * @param courseId 课程id\n * @return 课程计划树形结构\n */\n List<TeachplanDto> findTeachplanTree(Long courseId);\n\n /**\n * 保存课程计划(新增/修改)\n *\n * @param teachplan 课程计划\n */\n void saveTeachplan(SaveTeachplanDto teachplan);\n\n /**\n * 教学计划绑定媒资\n *\n * @param bindTeachplanMediaDto 教学计划-媒资管理绑定数据\n * @return {@link com.xuecheng.content.model.po.TeachplanMedia}\n * @author Mr.M\n * @since 2022/9/14 22:20\n */\n TeachplanMedia associationMedia(BindTeachplanMediaDto bindTeachplanMediaDto);\n\n /**\n * 删除指定教学计划-媒资绑定信息\n *\n * @param teachplanId 教学计划id\n * @param mediaId 媒资id\n */\n void deleteTeachplanMedia(Long teachplanId, String mediaId);\n\n}" }, { "identifier": "MqMessage", "path": "xuecheng-plus-message-sdk/src/main/java/com/xuecheng/messagesdk/model/po/MqMessage.java", "snippet": "@Data\n@ToString\n@TableName(\"mq_message\")\npublic class MqMessage implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n /**\n * 消息id\n */\n @TableId(value = \"id\", type = IdType.AUTO)\n private Long id;\n\n /**\n * 消息类型代码: course_publish , media_test,\n */\n private String messageType;\n\n /**\n * 关联业务信息\n */\n private String businessKey1;\n\n /**\n * 关联业务信息\n */\n private String businessKey2;\n\n /**\n * 关联业务信息\n */\n private String businessKey3;\n\n /**\n * 执行次数\n */\n private Integer executeNum;\n\n /**\n * 处理状态,0:初始,1:成功\n */\n private String state;\n\n /**\n * 回复失败时间\n */\n private LocalDateTime returnfailureDate;\n\n /**\n * 回复成功时间\n */\n private LocalDateTime returnsuccessDate;\n\n /**\n * 回复失败内容\n */\n private String returnfailureMsg;\n\n /**\n * 最近执行时间\n */\n private LocalDateTime executeDate;\n\n /**\n * 阶段1处理状态, 0:初始,1:成功\n */\n private String stageState1;\n\n /**\n * 阶段2处理状态, 0:初始,1:成功\n */\n private String stageState2;\n\n /**\n * 阶段3处理状态, 0:初始,1:成功\n */\n private String stageState3;\n\n /**\n * 阶段4处理状态, 0:初始,1:成功\n */\n private String stageState4;\n\n\n}" }, { "identifier": "MqMessageService", "path": "xuecheng-plus-message-sdk/src/main/java/com/xuecheng/messagesdk/service/MqMessageService.java", "snippet": "public interface MqMessageService extends IService<MqMessage> {\n\n /**\n * 扫描消息表记录,采用与扫描视频处理表相同的思路\n *\n * @param shardIndex 分片序号\n * @param shardTotal 分片总数\n * @param count 扫描记录数\n * @return {@link java.util.List}<{@link MqMessage}> 消息记录\n * @author Wuxy\n * @since 2022/9/21 18:55\n */\n List<MqMessage> getMessageList(int shardIndex, int shardTotal, String messageType, int count);\n\n /**\n * 添加消息\n *\n * @param messageType 消息类型(例如:支付结果、课程发布等)\n * @param businessKey1 业务id\n * @param businessKey2 业务id\n * @param businessKey3 业务id\n * @return {@link com.xuecheng.messagesdk.model.po.MqMessage} 消息内容\n * @author Wuxy\n * @since 2022/9/23 13:45\n */\n MqMessage addMessage(String messageType, String businessKey1, String businessKey2, String businessKey3);\n\n /**\n * 完成任务\n *\n * @param id 消息id\n * @return int 更新成功:1\n * @author Wuxy\n * @since 2022/9/21 20:49\n */\n int completed(long id);\n\n /**\n * 完成阶段一任务\n *\n * @param id 消息id\n * @return int 更新成功:1\n * @author Wuxy\n * @since 2022/9/21 20:49\n */\n int completedStageOne(long id);\n\n /**\n * 完成阶段二任务\n *\n * @param id 消息id\n * @return int 更新成功:1\n * @author Wuxy\n * @since 2022/9/21 20:49\n */\n int completedStageTwo(long id);\n\n /**\n * 完成阶段三任务\n *\n * @param id 消息id\n * @return int 更新成功:1\n * @author Wuxy\n * @since 2022/9/21 20:49\n */\n int completedStageThree(long id);\n\n /**\n * 完成阶段四任务\n *\n * @param id 消息id\n * @return int 更新成功:1\n * @author Wuxy\n * @since 2022/9/21 20:49\n */\n int completedStageFour(long id);\n\n /**\n * 查询阶段一状态\n *\n * @param id 消息id\n * @return int\n * @author Wuxy\n * @since 2022/9/21 20:54\n */\n public int getStageOne(long id);\n\n /**\n * 查询阶段二状态\n *\n * @param id 消息id\n * @return int\n * @author Wuxy\n * @since 2022/9/21 20:54\n */\n int getStageTwo(long id);\n\n /**\n * 查询阶段三状态\n *\n * @param id 消息id\n * @return int\n * @author Wuxy\n * @since 2022/9/21 20:54\n */\n int getStageThree(long id);\n\n /**\n * 查询阶段四状态\n *\n * @param id 消息id\n * @return int\n * @author Wuxy\n * @since 2022/9/21 20:54\n */\n int getStageFour(long id);\n\n}" } ]
import com.alibaba.fastjson.JSON; import com.xuecheng.base.exception.XueChengPlusException; import com.xuecheng.content.config.MultipartSupportConfig; import com.xuecheng.content.feignclient.MediaServiceClient; import com.xuecheng.content.feignclient.SearchServiceClient; import com.xuecheng.content.feignclient.po.CourseIndex; import com.xuecheng.content.mapper.CourseBaseMapper; import com.xuecheng.content.mapper.CourseMarketMapper; import com.xuecheng.content.mapper.CoursePublishMapper; import com.xuecheng.content.mapper.CoursePublishPreMapper; import com.xuecheng.content.model.dto.CourseBaseInfoDto; import com.xuecheng.content.model.dto.CoursePreviewDto; import com.xuecheng.content.model.dto.TeachplanDto; import com.xuecheng.content.model.po.CourseBase; import com.xuecheng.content.model.po.CourseMarket; import com.xuecheng.content.model.po.CoursePublish; import com.xuecheng.content.model.po.CoursePublishPre; import com.xuecheng.content.service.CourseBaseInfoService; import com.xuecheng.content.service.CoursePublishService; import com.xuecheng.content.service.TeachplanService; import com.xuecheng.messagesdk.model.po.MqMessage; import com.xuecheng.messagesdk.service.MqMessageService; import freemarker.template.Configuration; import freemarker.template.Template; import lombok.extern.slf4j.Slf4j; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.redisson.api.RLock; import org.redisson.api.RedissonClient; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.ui.freemarker.FreeMarkerTemplateUtils; import org.springframework.web.multipart.MultipartFile; import javax.annotation.Resource; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.time.LocalDateTime; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit;
8,273
package com.xuecheng.content.service.impl; /** * @author Wuxy * @version 1.0 * @ClassName CoursePublishServiceImpl * @since 2023/1/30 15:45 */ @Slf4j @Service public class CoursePublishServiceImpl implements CoursePublishService { @Resource private CourseBaseMapper courseBaseMapper; @Resource private CourseMarketMapper courseMarketMapper; @Resource private CoursePublishMapper coursePublishMapper; @Resource private CoursePublishPreMapper coursePublishPreMapper; @Autowired
package com.xuecheng.content.service.impl; /** * @author Wuxy * @version 1.0 * @ClassName CoursePublishServiceImpl * @since 2023/1/30 15:45 */ @Slf4j @Service public class CoursePublishServiceImpl implements CoursePublishService { @Resource private CourseBaseMapper courseBaseMapper; @Resource private CourseMarketMapper courseMarketMapper; @Resource private CoursePublishMapper coursePublishMapper; @Resource private CoursePublishPreMapper coursePublishPreMapper; @Autowired
private CourseBaseInfoService courseBaseInfoService;
16
2023-11-13 11:39:35+00:00
12k
jensjeflensje/minecraft_typewriter
src/main/java/dev/jensderuiter/minecrafttypewriter/command/SpawnCommand.java
[ { "identifier": "TypewriterPlugin", "path": "src/main/java/dev/jensderuiter/minecrafttypewriter/TypewriterPlugin.java", "snippet": "public final class TypewriterPlugin extends JavaPlugin {\n\n public static HashMap<Player, TypeWriter> playerWriters;\n\n @Getter\n private static TypewriterPlugin instance;\n\n @Override\n public void onEnable() {\n instance = this;\n\n getCommand(\"typewriter\").setExecutor(new SpawnCommand());\n getCommand(\"wc\").setExecutor(new CompleteCommand());\n getCommand(\"wr\").setExecutor(new RemoveCommand());\n getCommand(\"w\").setExecutor(new WriteCommand());\n getCommand(\"w\").setTabCompleter(new WriteTabCompleter());\n\n playerWriters = new HashMap<>();\n\n }\n\n @Override\n public void onDisable() {\n playerWriters.values().forEach(TypeWriter::destroy);\n }\n}" }, { "identifier": "TypeWriter", "path": "src/main/java/dev/jensderuiter/minecrafttypewriter/typewriter/TypeWriter.java", "snippet": "public interface TypeWriter {\n\n void setUp(Location location);\n void newData(String data);\n void newLine();\n void destroy();\n void complete();\n void giveLetter();\n HashMap<String, String> getKeyboardTextures();\n HashMap<String, Vector> getKeyboardLayout();\n\n\n}" }, { "identifier": "WoodenTypeWriter", "path": "src/main/java/dev/jensderuiter/minecrafttypewriter/typewriter/type/WoodenTypeWriter.java", "snippet": "public class WoodenTypeWriter extends BaseTypeWriter {\n\n public WoodenTypeWriter(Player player) {\n super(player);\n }\n\n @Override\n public void setUp(Location location) {\n super.setUp(location);\n }\n\n @Override\n public HashMap<String, String> getKeyboardTextures() {\n HashMap<String, String> textures = new HashMap<>();\n textures.put(\"back\", \"eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvODY1MmUyYjkzNmNhODAyNmJkMjg2NTFkN2M5ZjI4MTlkMmU5MjM2OTc3MzRkMThkZmRiMTM1NTBmOGZkYWQ1ZiJ9fX0=\");\n textures.put(\"enter\", \"eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvYmQ2OWUwNmU1ZGFkZmQ4NGU1ZjNkMWMyMTA2M2YyNTUzYjJmYTk0NWVlMWQ0ZDcxNTJmZGM1NDI1YmMxMmE5In19fQ==\");\n textures.put(\" \", \"eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvOTQzYWFjMDllZTgxYzExYWQ2MmM2NzIwOTVkMGUxZmNjMjZjNDM3ZWQ1YzUwNzUzOGY5YmYzNmRiMDRmZTRmMSJ9fX0=\");\n textures.put(\"1\", \"eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvNzFiYzJiY2ZiMmJkMzc1OWU2YjFlODZmYzdhNzk1ODVlMTEyN2RkMzU3ZmMyMDI4OTNmOWRlMjQxYmM5ZTUzMCJ9fX0=\");\n textures.put(\"2\", \"eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvNGNkOWVlZWU4ODM0Njg4ODFkODM4NDhhNDZiZjMwMTI0ODVjMjNmNzU3NTNiOGZiZTg0ODczNDE0MTk4NDcifX19\");\n textures.put(\"3\", \"eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvMWQ0ZWFlMTM5MzM4NjBhNmRmNWU4ZTk1NTY5M2I5NWE4YzNiMTVjMzZiOGI1ODc1MzJhYzA5OTZiYzM3ZTUifX19\");\n textures.put(\"4\", \"eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvZDJlNzhmYjIyNDI0MjMyZGMyN2I4MWZiY2I0N2ZkMjRjMWFjZjc2MDk4NzUzZjJkOWMyODU5ODI4N2RiNSJ9fX0=\");\n textures.put(\"5\", \"eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvNmQ1N2UzYmM4OGE2NTczMGUzMWExNGUzZjQxZTAzOGE1ZWNmMDg5MWE2YzI0MzY0M2I4ZTU0NzZhZTIifX19\");\n textures.put(\"6\", \"eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvMzM0YjM2ZGU3ZDY3OWI4YmJjNzI1NDk5YWRhZWYyNGRjNTE4ZjVhZTIzZTcxNjk4MWUxZGNjNmIyNzIwYWIifX19\");\n textures.put(\"7\", \"eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvNmRiNmViMjVkMWZhYWJlMzBjZjQ0NGRjNjMzYjU4MzI0NzVlMzgwOTZiN2UyNDAyYTNlYzQ3NmRkN2I5In19fQ==\");\n textures.put(\"8\", \"eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvNTkxOTQ5NzNhM2YxN2JkYTk5NzhlZDYyNzMzODM5OTcyMjI3NzRiNDU0Mzg2YzgzMTljMDRmMWY0Zjc0YzJiNSJ9fX0=\");\n textures.put(\"9\", \"eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvZTY3Y2FmNzU5MWIzOGUxMjVhODAxN2Q1OGNmYzY0MzNiZmFmODRjZDQ5OWQ3OTRmNDFkMTBiZmYyZTViODQwIn19fQ==\");\n textures.put(\"0\", \"eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvMGViZTdlNTIxNTE2OWE2OTlhY2M2Y2VmYTdiNzNmZGIxMDhkYjg3YmI2ZGFlMjg0OWZiZTI0NzE0YjI3In19fQ==\");\n textures.put(\"a\", \"eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvYTY3ZDgxM2FlN2ZmZTViZTk1MWE0ZjQxZjJhYTYxOWE1ZTM4OTRlODVlYTVkNDk4NmY4NDk0OWM2M2Q3NjcyZSJ9fX0=\");\n textures.put(\"b\", \"eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvNTBjMWI1ODRmMTM5ODdiNDY2MTM5Mjg1YjJmM2YyOGRmNjc4NzEyM2QwYjMyMjgzZDg3OTRlMzM3NGUyMyJ9fX0=\");\n textures.put(\"c\", \"eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvYWJlOTgzZWM0NzgwMjRlYzZmZDA0NmZjZGZhNDg0MjY3NjkzOTU1MWI0NzM1MDQ0N2M3N2MxM2FmMThlNmYifX19\");\n textures.put(\"d\", \"eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvMzE5M2RjMGQ0YzVlODBmZjlhOGEwNWQyZmNmZTI2OTUzOWNiMzkyNzE5MGJhYzE5ZGEyZmNlNjFkNzEifX19\");\n textures.put(\"e\", \"eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvZGJiMjczN2VjYmY5MTBlZmUzYjI2N2RiN2Q0YjMyN2YzNjBhYmM3MzJjNzdiZDBlNGVmZjFkNTEwY2RlZiJ9fX0=\");\n textures.put(\"f\", \"eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvYjE4M2JhYjUwYTMyMjQwMjQ4ODZmMjUyNTFkMjRiNmRiOTNkNzNjMjQzMjU1OWZmNDllNDU5YjRjZDZhIn19fQ==\");\n textures.put(\"g\", \"eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvMWNhM2YzMjRiZWVlZmI2YTBlMmM1YjNjNDZhYmM5MWNhOTFjMTRlYmE0MTlmYTQ3NjhhYzMwMjNkYmI0YjIifX19\");\n textures.put(\"h\", \"eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvMzFmMzQ2MmE0NzM1NDlmMTQ2OWY4OTdmODRhOGQ0MTE5YmM3MWQ0YTVkODUyZTg1YzI2YjU4OGE1YzBjNzJmIn19fQ==\");\n textures.put(\"i\", \"eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvNDYxNzhhZDUxZmQ1MmIxOWQwYTM4ODg3MTBiZDkyMDY4ZTkzMzI1MmFhYzZiMTNjNzZlN2U2ZWE1ZDMyMjYifX19\");\n textures.put(\"j\", \"eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvM2E3OWRiOTkyMzg2N2U2OWMxZGJmMTcxNTFlNmY0YWQ5MmNlNjgxYmNlZGQzOTc3ZWViYmM0NGMyMDZmNDkifX19\");\n textures.put(\"k\", \"eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvOTQ2MWIzOGM4ZTQ1NzgyYWRhNTlkMTYxMzJhNDIyMmMxOTM3NzhlN2Q3MGM0NTQyYzk1MzYzNzZmMzdiZTQyIn19fQ==\");\n textures.put(\"l\", \"eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvMzE5ZjUwYjQzMmQ4NjhhZTM1OGUxNmY2MmVjMjZmMzU0MzdhZWI5NDkyYmNlMTM1NmM5YWE2YmIxOWEzODYifX19\");\n textures.put(\"m\", \"eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvNDljNDVhMjRhYWFiZjQ5ZTIxN2MxNTQ4MzIwNDg0OGE3MzU4MmFiYTdmYWUxMGVlMmM1N2JkYjc2NDgyZiJ9fX0=\");\n textures.put(\"n\", \"eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvMzViOGIzZDhjNzdkZmI4ZmJkMjQ5NWM4NDJlYWM5NGZmZmE2ZjU5M2JmMTVhMjU3NGQ4NTRkZmYzOTI4In19fQ==\");\n textures.put(\"o\", \"eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvZDExZGUxY2FkYjJhZGU2MTE0OWU1ZGVkMWJkODg1ZWRmMGRmNjI1OTI1NWIzM2I1ODdhOTZmOTgzYjJhMSJ9fX0=\");\n textures.put(\"p\", \"eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvYTBhNzk4OWI1ZDZlNjIxYTEyMWVlZGFlNmY0NzZkMzUxOTNjOTdjMWE3Y2I4ZWNkNDM2MjJhNDg1ZGMyZTkxMiJ9fX0=\");\n textures.put(\"q\", \"eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvNDM2MDlmMWZhZjgxZWQ0OWM1ODk0YWMxNGM5NGJhNTI5ODlmZGE0ZTFkMmE1MmZkOTQ1YTU1ZWQ3MTllZDQifX19\");\n textures.put(\"r\", \"eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvYTVjZWQ5OTMxYWNlMjNhZmMzNTEzNzEzNzliZjA1YzYzNWFkMTg2OTQzYmMxMzY0NzRlNGU1MTU2YzRjMzcifX19\");\n textures.put(\"s\", \"eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvM2U0MWM2MDU3MmM1MzNlOTNjYTQyMTIyODkyOWU1NGQ2Yzg1NjUyOTQ1OTI0OWMyNWMzMmJhMzNhMWIxNTE3In19fQ==\");\n textures.put(\"t\", \"eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvMTU2MmU4YzFkNjZiMjFlNDU5YmU5YTI0ZTVjMDI3YTM0ZDI2OWJkY2U0ZmJlZTJmNzY3OGQyZDNlZTQ3MTgifX19\");\n textures.put(\"u\", \"eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvNjA3ZmJjMzM5ZmYyNDFhYzNkNjYxOWJjYjY4MjUzZGZjM2M5ODc4MmJhZjNmMWY0ZWZkYjk1NGY5YzI2In19fQ==\");\n textures.put(\"v\", \"eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvY2M5YTEzODYzOGZlZGI1MzRkNzk5Mjg4NzZiYWJhMjYxYzdhNjRiYTc5YzQyNGRjYmFmY2M5YmFjNzAxMGI4In19fQ==\");\n textures.put(\"w\", \"eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvMjY5YWQxYTg4ZWQyYjA3NGUxMzAzYTEyOWY5NGU0YjcxMGNmM2U1YjRkOTk1MTYzNTY3ZjY4NzE5YzNkOTc5MiJ9fX0=\");\n textures.put(\"x\", \"eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvNWE2Nzg3YmEzMjU2NGU3YzJmM2EwY2U2NDQ5OGVjYmIyM2I4OTg0NWU1YTY2YjVjZWM3NzM2ZjcyOWVkMzcifX19\");\n textures.put(\"y\", \"eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvYzUyZmIzODhlMzMyMTJhMjQ3OGI1ZTE1YTk2ZjI3YWNhNmM2MmFjNzE5ZTFlNWY4N2ExY2YwZGU3YjE1ZTkxOCJ9fX0=\");\n textures.put(\"z\", \"eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvOTA1ODJiOWI1ZDk3OTc0YjExNDYxZDYzZWNlZDg1ZjQzOGEzZWVmNWRjMzI3OWY5YzQ3ZTFlMzhlYTU0YWU4ZCJ9fX0=\");\n textures.put(\".\", \"eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvNzQ1NjQ4NWFhMjM2MTQzNGNiM2JlNTMxYmMxMjE2NTlmNTU1YTRhYWYyNjFkMjFhMDZkN2FmZGU1YWE2MGIyIn19fQ==\");\n textures.put(\",\", \"eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvNzg0MGI0ZTdhNjgwNDM0ODU3NDI3MTExYmRhZjY0ZTdmYmE5MTJlYTU3MDcxODJlOThiYzU4NWNjYjUzIn19fQ==\");\n return textures;\n }\n\n @Override\n public HashMap<String, Vector> getKeyboardLayout() {\n HashMap<String, Vector> textures = new HashMap<>();\n textures.put(\"1\", new Vector(-0.95, 0, -0.4));\n textures.put(\"2\", new Vector(-0.75, 0, -0.4));\n textures.put(\"3\", new Vector(-0.55, 0, -0.4));\n textures.put(\"4\", new Vector(-0.35, 0, -0.4));\n textures.put(\"5\", new Vector(-0.15, 0, -0.4));\n textures.put(\"6\", new Vector(0.05, 0, -0.4));\n textures.put(\"7\", new Vector(0.25, 0, -0.4));\n textures.put(\"8\", new Vector(0.45, 0, -0.4));\n textures.put(\"9\", new Vector(0.65, 0, -0.4));\n textures.put(\"0\", new Vector(0.85, 0, -0.4));\n textures.put(\"back\", new Vector(1.05, 0, -0.4));\n textures.put(\" \", new Vector(0, 0, 0.4));\n textures.put(\"enter\", new Vector(1, -0.1, 0));\n textures.put(\"a\", new Vector(-0.80, -0.1, 0));\n textures.put(\"b\", new Vector(0.10, -0.15, 0.2));\n textures.put(\"c\", new Vector(-0.30, -0.15, 0.2));\n textures.put(\"d\", new Vector(-0.40, -0.1, 0));\n textures.put(\"e\", new Vector(-0.45, -0.05, -0.2));\n textures.put(\"f\", new Vector(-0.20, -0.1, 0));\n textures.put(\"g\", new Vector(0, -0.1, 0));\n textures.put(\"h\", new Vector(0.20, -0.1, 0));\n textures.put(\"i\", new Vector(0.55, -0.05, -0.2));\n textures.put(\"j\", new Vector(0.40, -0.1, 0));\n textures.put(\"k\", new Vector(0.60, -0.1, 0));\n textures.put(\"l\", new Vector(0.80, -0.1, 0));\n textures.put(\"m\", new Vector(0.50, -0.15, 0.2));\n textures.put(\"n\", new Vector(0.30, -0.15, 0.2));\n textures.put(\"o\", new Vector(0.75, -0.05, -0.2));\n textures.put(\"p\", new Vector(0.95, -0.05, -0.2));\n textures.put(\"q\", new Vector(-0.85, -0.05, -0.2));\n textures.put(\"r\", new Vector(-0.25, -0.05, -0.2));\n textures.put(\"s\", new Vector(-0.60, -0.1, 0));\n textures.put(\"t\", new Vector(-0.05, -0.05, -0.2));\n textures.put(\"u\", new Vector(0.35, -0.05, -0.2));\n textures.put(\"v\", new Vector(-0.10, -0.15, 0.2));\n textures.put(\"w\", new Vector(-0.65, -0.05, -0.2));\n textures.put(\"x\", new Vector(-0.50, -0.15, 0.2));\n textures.put(\"y\", new Vector(0.15, -0.05, -0.2));\n textures.put(\"z\", new Vector(-0.70, -0.15, 0.2));\n textures.put(\".\", new Vector(0.90, -0.15, 0.2));\n textures.put(\",\", new Vector(0.70, -0.15, 0.2));\n return textures;\n }\n\n}" } ]
import dev.jensderuiter.minecrafttypewriter.TypewriterPlugin; import dev.jensderuiter.minecrafttypewriter.typewriter.TypeWriter; import dev.jensderuiter.minecrafttypewriter.typewriter.type.WoodenTypeWriter; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player;
7,543
package dev.jensderuiter.minecrafttypewriter.command; public class SpawnCommand implements CommandExecutor { @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { if (!(sender instanceof Player)) return true; Player player = (Player) sender; if (TypewriterPlugin.playerWriters.get(player) != null) return true;
package dev.jensderuiter.minecrafttypewriter.command; public class SpawnCommand implements CommandExecutor { @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { if (!(sender instanceof Player)) return true; Player player = (Player) sender; if (TypewriterPlugin.playerWriters.get(player) != null) return true;
TypeWriter typeWriter = new WoodenTypeWriter(player);
1
2023-11-18 20:44:30+00:00
12k
ZhiQinIsZhen/dubbo-springboot3
dubbo-service/dubbo-service-auth/auth-biz/src/main/java/com/liyz/boot3/service/auth/provider/RemoteJwtParseServiceImpl.java
[ { "identifier": "CommonServiceConstant", "path": "dubbo-common/dubbo-common-service/src/main/java/com/liyz/boot3/common/service/constant/CommonServiceConstant.java", "snippet": "public interface CommonServiceConstant {\n\n /**\n * 默认连接符\n */\n String DEFAULT_JOINER = \":\";\n\n String DEFAULT_PADDING = \"================================================================\";\n}" }, { "identifier": "DateUtil", "path": "dubbo-common/dubbo-common-util/src/main/java/com/liyz/boot3/common/util/DateUtil.java", "snippet": "@Slf4j\n@UtilityClass\npublic class DateUtil {\n\n /**\n * 年月日格式匹配符(预置),详情请参阅{@link SimpleDateFormat}\n */\n public static final String PATTERN_YEAR_MONTH_DAY = \"yyyyMMdd\";\n public static final String PATTERN_YEAR_MONTH = \"yyyyMM\";\n public static final String TIME_BEGIN = \"00:00:00\";\n public static final String TIME_END = \"23:59:59\";\n public static final String PATTERN_DATE = \"yyyy-MM-dd\";\n public static final String PATTERN_DATE_TIME = \"yyyy-MM-dd HH:mm:ss\";\n public static final String PATTERN_DATE_1 = \"yyyy/MM/dd\";\n public static final String TIME_ZONE_GMT8 = \"GMT+8\";\n\n /**\n * 获取目标日期的时间戳\n *\n * @param date\n * @return\n */\n public static long getTimeMillis(Date date) {\n if (date == null) {\n throw new NullPointerException(\"date is not null\");\n }\n return date.getTime();\n }\n\n /**\n * 获取当前时间\n *\n * @return\n */\n public static Date currentDate() {\n Calendar calendar = Calendar.getInstance();\n return calendar.getTime();\n }\n\n /**\n * 将目标时间设置为开始时间\n *\n * @param date\n * @return\n */\n public static Date formatBegin(Date date) {\n return formatTime(date, TIME_BEGIN);\n }\n\n /**\n * 将目标时间设置为结束时间\n *\n * @param date\n * @return\n */\n public static Date formatEnd(Date date) {\n return formatTime(date, TIME_END);\n }\n\n /**\n * 将日期设置为固定时间\n *\n * @param date 指定日期\n * @param timePatten 时间10:00:00\n * @return\n */\n public static Date formatTime(Date date, String timePatten) {\n if (date == null) {\n return null;\n }\n if (StringUtils.isBlank(timePatten)) {\n return date;\n }\n SimpleDateFormat sdf = new SimpleDateFormat(PATTERN_DATE);\n String formatDate = sdf.format(date).concat(\" \").concat(timePatten);\n sdf.applyPattern(PATTERN_DATE_TIME);\n try {\n return sdf.parse(formatDate);\n } catch (ParseException e) {\n log.error(\"formatTime error\", e);\n }\n return null;\n }\n\n /**\n * 将字符串格式日期,转化为日期\n *\n * @param date\n * @param format\n * @return\n */\n public static Date parse(String date, String format) {\n SimpleDateFormat sdf = new SimpleDateFormat(format);\n try {\n return sdf.parse(date);\n } catch (ParseException e) {\n log.error(\"parse error\", e);\n }\n return null;\n }\n\n /**\n * 目标时间增肌天数\n *\n * @param date\n * @param day\n * @return\n */\n public static Date addDay(Date date, int day) {\n return add(date, day, Calendar.DAY_OF_YEAR);\n }\n\n /**\n * 目标时间增加时间\n *\n * @param date\n * @param amount\n * @param field 详情请参阅{@link Calendar}\n * @return\n */\n public static Date add(Date date, int amount, int field) {\n if (date == null) {\n return null;\n }\n Calendar calendar = Calendar.getInstance();\n calendar.setTime(date);\n calendar.add(field, amount);\n return calendar.getTime();\n }\n\n /**\n * 格式化时间(yyyy-MM-dd HH:mm:ss)\n *\n * @param date\n * @return\n */\n public static String formatDate(Date date) {\n return formatDate(date, null);\n }\n\n /**\n * 获取当前时间格式化\n *\n * @param pattern 格式匹配符\n * @return 处理结果\n */\n public static String formatDate(String pattern) {\n return formatDate(currentDate(), pattern);\n }\n\n /**\n * 格式化时间\n *\n * @param date\n * @param pattern\n * @return\n */\n public static String formatDate(Date date, String pattern) {\n if (Objects.isNull(date)) {\n return null;\n }\n if (StringUtils.isBlank(pattern)) {\n pattern = PATTERN_DATE_TIME;\n }\n SimpleDateFormat sdf = new SimpleDateFormat(pattern);\n return sdf.format(date);\n }\n\n /**\n * 格式化时间\n *\n * @param time\n * @return\n */\n public static String formatDate(LocalDateTime time) {\n return formatDate(time, null);\n }\n\n /**\n * 格式化时间\n *\n * @param time\n * @param pattern\n * @return\n */\n public static String formatDate(LocalDateTime time, String pattern) {\n if (time == null) {\n return null;\n }\n if (StringUtils.isBlank(pattern)) {\n pattern = PATTERN_DATE_TIME;\n }\n return time.format(DateTimeFormatter.ofPattern(pattern));\n }\n\n /**\n * 获取两个时间的间隔天数\n *\n * @param sourceDate\n * @param targetDate\n * @return\n */\n public static long between(Date sourceDate, Date targetDate) {\n return between(sourceDate, targetDate, ChronoUnit.DAYS);\n }\n\n /**\n * 计算两个日期的时间差\n *\n * @param sourceDate\n * @param targetDate\n * @param field 详情请参阅{@link ChronoUnit}\n * @return\n */\n public static long between(Date sourceDate, Date targetDate, ChronoUnit field) {\n if (sourceDate == null || targetDate == null) {\n return 0L;\n }\n if (field == null) {\n field = ChronoUnit.DAYS;\n }\n return field.between(convertDateToLocalDateTime(sourceDate),\n convertDateToLocalDateTime(targetDate));\n }\n\n /**\n * 日期差值的绝对值\n *\n * @param sourceDate\n * @param targetDate\n * @return\n */\n public static long betweenAbs(Date sourceDate, Date targetDate) {\n return Math.abs(between(sourceDate, targetDate, ChronoUnit.DAYS));\n }\n\n /**\n * 日期差值的绝对值\n *\n * @param sourceDate\n * @param targetDate\n * @param field\n * @return\n */\n public static long betweenAbs(Date sourceDate, Date targetDate, ChronoUnit field) {\n return Math.abs(between(sourceDate, targetDate, field));\n }\n\n /**\n * 目标时间月份的第一天\n *\n * @param date\n * @return\n */\n public static Date firstDayOfMonth(Date date) {\n if (date == null) {\n return null;\n }\n Calendar calendar = Calendar.getInstance();\n calendar.setTime(date);\n calendar.set(Calendar.DAY_OF_MONTH, 1);\n return calendar.getTime();\n }\n\n /**\n * 目标时间月份的最后一天\n *\n * @param date\n * @return\n */\n public static Date lastDayOfMonth(Date date) {\n if (date == null) {\n return null;\n }\n Calendar calendar = Calendar.getInstance();\n calendar.setTime(date);\n calendar.add(Calendar.MONTH, 1);\n calendar.set(Calendar.DAY_OF_MONTH, 0);\n return calendar.getTime();\n }\n\n /**\n * 目标时间前一个月份的第一天\n *\n * @param date\n * @return\n */\n public static Date firstDayOfPreMonth(Date date) {\n if (date == null) {\n return null;\n }\n Calendar calendar = Calendar.getInstance();\n calendar.setTime(date);\n calendar.add(Calendar.MONTH, -1);\n calendar.set(Calendar.DAY_OF_MONTH, 1);\n return calendar.getTime();\n }\n\n /**\n * 目标时间前一个月份的最后一天\n *\n * @param date\n * @return\n */\n public static Date lastDayOfPreMonth(Date date) {\n if (date == null) {\n return null;\n }\n Calendar calendar = Calendar.getInstance();\n calendar.setTime(date);\n calendar.set(Calendar.DAY_OF_MONTH, 0);\n return calendar.getTime();\n }\n\n /**\n * 目标时间后一个月份的第一天\n *\n * @param date\n * @return\n */\n public static Date firstDayOfNextMonth(Date date) {\n if (date == null) {\n return null;\n }\n Calendar calendar = Calendar.getInstance();\n calendar.setTime(date);\n calendar.add(Calendar.MONTH, 1);\n calendar.set(Calendar.DAY_OF_MONTH, 1);\n return calendar.getTime();\n }\n\n /**\n * 目标时间后一个月份的最后一天\n *\n * @param date\n * @return\n */\n public static Date lastDayOfNextMonth(Date date) {\n if (date == null) {\n return null;\n }\n Calendar calendar = Calendar.getInstance();\n calendar.setTime(date);\n calendar.add(Calendar.MONTH, 2);\n calendar.set(Calendar.DAY_OF_MONTH, 0);\n return calendar.getTime();\n }\n\n /**\n * 目标时间 季度的第一天\n *\n * @param date\n * @return\n */\n public static Date firstDayOfQuarter(Date date) {\n if (date == null) {\n return null;\n }\n Calendar calendar = Calendar.getInstance();\n calendar.setTime(date);\n int month = calendar.get(Calendar.MONTH);\n if (month <=2) {\n calendar.set(Calendar.MONTH, 0);\n } else if (month <= 5) {\n calendar.set(Calendar.MONTH, 3);\n } else if (month <= 8) {\n calendar.set(Calendar.MONTH, 6);\n } else {\n calendar.set(Calendar.MONTH, 9);\n }\n calendar.set(Calendar.DAY_OF_MONTH, 1);\n return calendar.getTime();\n }\n\n /**\n * 目标时间 季度的最后一天\n *\n * @param date\n * @return\n */\n public static Date lastDayOfQuarter(Date date) {\n if (date == null) {\n return null;\n }\n Calendar calendar = Calendar.getInstance();\n calendar.setTime(firstDayOfQuarter(date));\n calendar.add(Calendar.MONTH, 3);\n calendar.set(Calendar.DAY_OF_MONTH, 0);\n return calendar.getTime();\n }\n\n /**\n * 目标时间 上一个季度的第一天\n *\n * @param date\n * @return\n */\n public static Date firstDayOfPreQuarter(Date date) {\n if (date == null) {\n return null;\n }\n Calendar calendar = Calendar.getInstance();\n calendar.setTime(firstDayOfQuarter(date));\n calendar.add(Calendar.MONTH, -3);\n return calendar.getTime();\n }\n\n /**\n * 目标时间 上个季度的最后一天\n *\n * @param date\n * @return\n */\n public static Date lastDayOfPreQuarter(Date date) {\n if (date == null) {\n return null;\n }\n Calendar calendar = Calendar.getInstance();\n calendar.setTime(lastDayOfQuarter(date));\n calendar.add(Calendar.MONTH, -3);\n return calendar.getTime();\n }\n\n /**\n * 目标时间 下一个季度的第一天\n *\n * @param date\n * @return\n */\n public static Date firstDayOfNextQuarter(Date date) {\n if (date == null) {\n return null;\n }\n Calendar calendar = Calendar.getInstance();\n calendar.setTime(firstDayOfQuarter(date));\n calendar.add(Calendar.MONTH, 3);\n return calendar.getTime();\n }\n\n /**\n * 目标时间 下一个季度的最后一天\n *\n * @param date\n * @return\n */\n public static Date lastDayOfNextQuarter(Date date) {\n if (date == null) {\n return null;\n }\n Calendar calendar = Calendar.getInstance();\n calendar.setTime(lastDayOfQuarter(date));\n calendar.add(Calendar.MONTH, 3);\n return calendar.getTime();\n }\n\n /**\n * 目标时间 年度的第一天\n *\n * @param date\n * @return\n */\n public static Date firstDayOfYear(Date date) {\n if (date == null) {\n return null;\n }\n Calendar calendar = Calendar.getInstance();\n calendar.setTime(date);\n calendar.set(Calendar.DAY_OF_YEAR, 1);\n return calendar.getTime();\n }\n\n /**\n * 目标时间 年度的最后一天\n *\n * @param date\n * @return\n */\n public static Date lastDayOfYear(Date date) {\n if (date == null) {\n return null;\n }\n Calendar calendar = Calendar.getInstance();\n calendar.setTime(date);\n calendar.add(Calendar.YEAR, 1);\n calendar.set(Calendar.DAY_OF_YEAR, 0);\n return calendar.getTime();\n }\n\n /**\n * 目标时间 上一年度的第一天\n *\n * @param date\n * @return\n */\n public static Date firstDayOfPreYear(Date date) {\n if (date == null) {\n return null;\n }\n Calendar calendar = Calendar.getInstance();\n calendar.setTime(date);\n calendar.add(Calendar.YEAR, -1);\n calendar.set(Calendar.DAY_OF_YEAR, 1);\n return calendar.getTime();\n }\n\n /**\n * 目标时间 上一年度的最后一天\n *\n * @param date\n * @return\n */\n public static Date lastDayOfPreYear(Date date) {\n if (date == null) {\n return null;\n }\n Calendar calendar = Calendar.getInstance();\n calendar.setTime(date);\n calendar.set(Calendar.DAY_OF_YEAR, 0);\n return calendar.getTime();\n }\n\n /**\n * 目标时间 下一年度的第一天\n *\n * @param date\n * @return\n */\n public static Date firstDayOfNextYear(Date date) {\n if (date == null) {\n return null;\n }\n Calendar calendar = Calendar.getInstance();\n calendar.setTime(date);\n calendar.add(Calendar.YEAR, 1);\n calendar.set(Calendar.DAY_OF_YEAR, 1);\n return calendar.getTime();\n }\n\n /**\n * 目标时间 下一年度的最后一天\n *\n * @param date\n * @return\n */\n public static Date lastDayOfNextYear(Date date) {\n if (date == null) {\n return null;\n }\n Calendar calendar = Calendar.getInstance();\n calendar.setTime(date);\n calendar.add(Calendar.YEAR, 2);\n calendar.set(Calendar.DAY_OF_YEAR, 0);\n return calendar.getTime();\n }\n\n /**\n * date转换为LocalDateTime\n *\n * @param date\n * @return\n */\n public static LocalDateTime convertDateToLocalDateTime(Date date) {\n return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());\n }\n\n /**\n * LocalDateTime转date\n *\n * @param time\n * @return\n */\n public static Date convertLocalDateTimeToDate(LocalDateTime time) {\n return Date.from(time.atZone(ZoneId.systemDefault()).toInstant());\n }\n\n /**\n * 加日期\n *\n * @param time\n * @param number\n * @param field\n * @return\n */\n public static LocalDateTime plusTime(LocalDateTime time, long number, TemporalUnit field) {\n return time.plus(number, field);\n }\n\n /**\n * 减日期\n *\n * @param time\n * @param number\n * @param field\n * @return\n */\n public static LocalDateTime minusTime(LocalDateTime time, long number, TemporalUnit field) {\n return time.minus(number, field);\n }\n\n /**\n * 获取两个时间差\n *\n * @param startTime\n * @param endTime\n * @param field\n * @return\n */\n public static long between(LocalDateTime startTime, LocalDateTime endTime,\n ChronoUnit field) {\n Period period = Period.between(LocalDate.from(startTime), LocalDate.from(endTime));\n if (field == ChronoUnit.YEARS) {\n return period.getYears();\n }\n if (field == ChronoUnit.MONTHS) {\n return period.getYears() * 12 + period.getMonths();\n }\n return field.between(startTime, endTime);\n }\n\n /**\n * 获取下周一\n *\n * @param date\n * @return\n */\n public static Date getNextWeekMonday(Date date) {\n Calendar cal = Calendar.getInstance();\n cal.setTime(getThisWeekMonday(date));\n cal.add(Calendar.DATE, 7);\n return cal.getTime();\n }\n\n /**\n * 获取这周一\n *\n * @param date\n * @return\n */\n public static Date getThisWeekMonday(Date date) {\n Calendar cal = Calendar.getInstance();\n cal.setTime(date);\n // 获得当前日期是一个星期的第几天\n int dayWeek = cal.get(Calendar.DAY_OF_WEEK);\n if (1 == dayWeek) {\n cal.add(Calendar.DAY_OF_MONTH, -1);\n }\n // 设置一个星期的第一天,按中国的习惯一个星期的第一天是星期一\n cal.setFirstDayOfWeek(Calendar.MONDAY);\n // 获得当前日期是一个星期的第几天\n int day = cal.get(Calendar.DAY_OF_WEEK);\n // 根据日历的规则,给当前日期减去星期几与一个星期第一天的差值\n cal.add(Calendar.DATE, cal.getFirstDayOfWeek() - day);\n return cal.getTime();\n }\n}" }, { "identifier": "PatternUtil", "path": "dubbo-common/dubbo-common-util/src/main/java/com/liyz/boot3/common/util/PatternUtil.java", "snippet": "@UtilityClass\npublic class PatternUtil {\n\n /**\n * 邮箱正则表达式\n */\n public static final String EMAIL_REG = \"^([a-zA-Z0-9_\\\\-\\\\.\\\\+]+)@((\\\\[[0-9]{1,3}\\\\.[0-9]{1,3}\\\\.[0-9]{1,3}\\\\.)|(([a-zA-Z0-9\\\\-]+\\\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\\\]?)$\";\n\n /**\n * 手机正则表达式\n */\n public static final String PHONE_REG = \"^1(3|4|5|7|8|9)\\\\d{9}$\";\n\n /**\n * 密码强度校验\n */\n public static final String PASSWORD_STRONG = \"^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,20}$\";\n\n /**\n * 匹配手机\n *\n * @param mobile\n * @return\n */\n public static boolean matchMobile(String mobile) {\n if (StringUtils.isBlank(mobile)) {\n return false;\n }\n Pattern p = Pattern.compile(PHONE_REG);\n Matcher m = p.matcher(mobile);\n return m.matches();\n }\n\n /**\n * 匹配邮箱\n *\n * @param email\n * @return\n */\n public static boolean matchEmail(String email) {\n if (StringUtils.isBlank(email)) {\n return false;\n }\n Pattern p = Pattern.compile(EMAIL_REG);\n Matcher m = p.matcher(email);\n return m.matches();\n }\n\n /**\n * 校验地址是否是邮件或者手机号码格式,如果不是,则抛出异常\n *\n * @param address\n * @return 1:手机号码;2:邮件;-1:无法判断\n */\n public static int checkMobileEmail(String address) {\n int type = -1;\n if (matchMobile(address)) {\n type = 1;\n } else if (matchEmail(address)){\n type = 2;\n }\n return type;\n }\n}" }, { "identifier": "AuthUserBO", "path": "dubbo-service/dubbo-service-auth/auth-remote/src/main/java/com/liyz/boot3/service/auth/bo/AuthUserBO.java", "snippet": "@Getter\n@Setter\n@Builder\n@NoArgsConstructor\n@AllArgsConstructor\npublic class AuthUserBO implements Serializable {\n @Serial\n private static final long serialVersionUID = 6046110472442516409L;\n\n /**\n * 用户id\n */\n private Long authId;\n\n /**\n * 用户名\n */\n private String username;\n\n /**\n * 密码\n */\n private String password;\n\n /**\n * 加密盐\n */\n private String salt;\n\n /**\n * 客户端ID\n */\n private String clientId;\n\n /**\n * token\n */\n private String token;\n\n /**\n * 登录类型\n * @see com.liyz.boot3.service.auth.enums.LoginType\n */\n private LoginType loginType;\n\n /**\n * 登录设备\n * @see com.liyz.boot3.service.auth.enums.Device\n */\n private Device device;\n\n /**\n * 检查时间\n * 用于是否但设备登录的\n */\n private Date checkTime;\n\n /**\n * 用户角色\n */\n private List<Integer> roleIds;\n\n /**\n * 权限列表\n */\n private List<AuthGrantedAuthorityBO> authorities = new ArrayList<>();\n\n @Getter\n @Setter\n public static class AuthGrantedAuthorityBO implements Serializable {\n @Serial\n private static final long serialVersionUID = 1L;\n\n /**\n * 客户端ID\n */\n private String clientId;\n\n /**\n * 权限码\n */\n private String authorityCode;\n }\n}" }, { "identifier": "Device", "path": "dubbo-service/dubbo-service-auth/auth-remote/src/main/java/com/liyz/boot3/service/auth/enums/Device.java", "snippet": "@Getter\n@AllArgsConstructor\npublic enum Device {\n MOBILE(1, \"移动端\"),\n WEB(2, \"网页端\"),\n ;\n\n private final int type;\n private final String desc;\n\n public static Device getByType(int type) {\n for (Device device : Device.values()) {\n if (type == device.type) {\n return device;\n }\n }\n return null;\n }\n\n @Override\n public String toString() {\n return type + \":\" + desc;\n }\n}" }, { "identifier": "LoginType", "path": "dubbo-service/dubbo-service-auth/auth-remote/src/main/java/com/liyz/boot3/service/auth/enums/LoginType.java", "snippet": "@Getter\n@AllArgsConstructor\npublic enum LoginType {\n\n MOBILE(1, \"手机号码登录\"),\n EMAIL(2, \"邮箱登录\"),\n ;\n\n private final int type;\n private final String desc;\n\n public static LoginType getByType(int type) {\n for (LoginType loginType : LoginType.values()) {\n if (type == loginType.type) {\n return loginType;\n }\n }\n return null;\n }\n}" }, { "identifier": "AuthExceptionCodeEnum", "path": "dubbo-service/dubbo-service-auth/auth-remote/src/main/java/com/liyz/boot3/service/auth/exception/AuthExceptionCodeEnum.java", "snippet": "@AllArgsConstructor\npublic enum AuthExceptionCodeEnum implements IExceptionService {\n FORBIDDEN(\"401\", \"登录后进行操作\"),\n NO_RIGHT(\"403\", \"暂无权限\"),\n LOGIN_FAIL(\"20001\", \"用户名或者密码错误\"),\n AUTHORIZATION_FAIL(\"20002\", \"认证失败\"),\n AUTHORIZATION_TIMEOUT(\"20003\", \"认证过期\"),\n REGISTRY_ERROR(\"20004\", \"注册错误\"),\n LACK_SOURCE_ID(\"20005\", \"注册错误: 缺少资源客户端ID\"),\n NON_SET_SOURCE_ID(\"20006\", \"注册错误: 资源服务未配置该资源客户端ID\"),\n LOGIN_ERROR(\"20007\", \"登录错误\"),\n OTHERS_LOGIN(\"20008\", \"该账号已在其他地方登录\"),\n MOBILE_EXIST(\"20009\", \"该手机号码已注册\"),\n EMAIL_EXIST(\"20010\", \"该邮箱地址已注册\"),\n ;\n\n private final String code;\n\n private final String message;\n\n @Override\n public String getCode() {\n return code;\n }\n\n @Override\n public String getMessage() {\n return message;\n }\n\n @Override\n public String getName() {\n return name();\n }\n}" }, { "identifier": "RemoteAuthServiceException", "path": "dubbo-service/dubbo-service-auth/auth-remote/src/main/java/com/liyz/boot3/service/auth/exception/RemoteAuthServiceException.java", "snippet": "public class RemoteAuthServiceException extends RemoteServiceException {\n @Serial\n private static final long serialVersionUID = -7199913728327633511L;\n\n public RemoteAuthServiceException() {\n super();\n }\n\n public RemoteAuthServiceException(IExceptionService codeService) {\n super(codeService);\n }\n}" }, { "identifier": "AuthJwtDO", "path": "dubbo-service/dubbo-service-auth/auth-dao/src/main/java/com/liyz/boot3/service/auth/model/AuthJwtDO.java", "snippet": "@Getter\n@Setter\n@TableName(\"auth_jwt1\")\npublic class AuthJwtDO extends BaseDO implements Serializable {\n @Serial\n private static final long serialVersionUID = 4949126727508321753L;\n\n @TableId(type = IdType.AUTO)\n private Long id;\n\n /**\n * 应用名\n */\n private String clientId;\n\n /**\n * jwt前缀\n */\n private String jwtPrefix;\n\n /**\n * 签名key\n */\n private String signingKey;\n\n /**\n * 是否权限控制(0:没有;1:有)\n */\n private Boolean isAuthority;\n\n /**\n * token失效时间\n */\n private Long expiration;\n\n /**\n * 签名算法\n */\n private String signatureAlgorithm;\n\n /**\n * 是否同设备一个在线(0:没有限制;1:同设备只有一个)\n */\n private Boolean oneOnline;\n}" }, { "identifier": "RemoteAuthService", "path": "dubbo-service/dubbo-service-auth/auth-remote/src/main/java/com/liyz/boot3/service/auth/remote/RemoteAuthService.java", "snippet": "public interface RemoteAuthService {\n\n /**\n * 用户注册\n *\n * @param authUserRegister 注册参数\n * @return True:注册成功;false:注册失败\n */\n Boolean registry(@NotNull AuthUserRegisterBO authUserRegister);\n\n /**\n * 根据用户名查询用户信息\n *\n * @param username 用户名\n * @param device 登录设备\n * @return 登录用户信息\n */\n AuthUserBO loadByUsername(@NotBlank String username, @NotNull Device device);\n\n /**\n * 登录\n *\n * @param authUserLogin 登录参数\n * @return 当前登录时间\n */\n Date login(@NotNull AuthUserLoginBO authUserLogin);\n\n /**\n * 登出\n *\n * @param authUserLogout 登出参数\n * @return True:登出成功;false:登出失败\n */\n Boolean logout(@NotNull AuthUserLogoutBO authUserLogout);\n\n /**\n * 获取权限列表\n *\n * @param authUser 认证用户信息\n * @return 权限列表\n */\n default List<AuthUserBO.AuthGrantedAuthorityBO> authorities(@NotNull AuthUserBO authUser) {\n return new ArrayList<>();\n }\n}" }, { "identifier": "RemoteJwtParseService", "path": "dubbo-service/dubbo-service-auth/auth-remote/src/main/java/com/liyz/boot3/service/auth/remote/RemoteJwtParseService.java", "snippet": "public interface RemoteJwtParseService {\n\n /**\n * 解析token\n *\n * @param token jwt token\n * @param clientId 应用名称\n * @return 用户信息\n */\n AuthUserBO parseToken(final String token, final String clientId);\n\n /**\n * 生成token\n *\n * @param authUser 用户信息\n * @return jwt token\n */\n String generateToken(final AuthUserBO authUser);\n\n /**\n * 获取失效时间\n *\n * @param token jwt token\n * @return 失效时间\n */\n Long getExpiration(final String token);\n}" }, { "identifier": "AuthJwtService", "path": "dubbo-service/dubbo-service-auth/auth-biz/src/main/java/com/liyz/boot3/service/auth/service/AuthJwtService.java", "snippet": "public interface AuthJwtService extends IService<AuthJwtDO> {\n\n /**\n * 根据资源ID获取JWT配置信息\n *\n * @param clientId 资源ID\n * @return JWT配置信息\n */\n AuthJwtDO getByClientId(String clientId);\n}" }, { "identifier": "JwtUtil", "path": "dubbo-service/dubbo-service-auth/auth-biz/src/main/java/com/liyz/boot3/service/auth/util/JwtUtil.java", "snippet": "@UtilityClass\npublic class JwtUtil {\n\n /**\n * 构建jwt\n *\n * @return JwtBuilder\n */\n public static JwtBuilder builder() {\n return Jwts.builder();\n }\n\n /**\n * 构建jwt解析\n *\n * @return JwtParserBuilder\n */\n public static JwtParserBuilder parser() {\n return Jwts.parser();\n }\n\n /**\n * 解码\n *\n * @param jwt token\n * @param tClass 转化的实体类\n * @return 实体类\n * @param <T> 实体类泛型\n */\n public static <T> T decode(final String jwt, Class<T> tClass) {\n return JWT.of(jwt).getPayloads().toBean(tClass);\n }\n}" } ]
import com.google.common.base.Joiner; import com.google.common.collect.Lists; import com.liyz.boot3.common.service.constant.CommonServiceConstant; import com.liyz.boot3.common.util.DateUtil; import com.liyz.boot3.common.util.PatternUtil; import com.liyz.boot3.service.auth.bo.AuthUserBO; import com.liyz.boot3.service.auth.enums.Device; import com.liyz.boot3.service.auth.enums.LoginType; import com.liyz.boot3.service.auth.exception.AuthExceptionCodeEnum; import com.liyz.boot3.service.auth.exception.RemoteAuthServiceException; import com.liyz.boot3.service.auth.model.AuthJwtDO; import com.liyz.boot3.service.auth.remote.RemoteAuthService; import com.liyz.boot3.service.auth.remote.RemoteJwtParseService; import com.liyz.boot3.service.auth.service.AuthJwtService; import com.liyz.boot3.service.auth.util.JwtUtil; import io.jsonwebtoken.Claims; import io.jsonwebtoken.SignatureAlgorithm; import io.jsonwebtoken.impl.DefaultClaims; import io.jsonwebtoken.io.Decoders; import io.jsonwebtoken.security.Keys; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.apache.dubbo.config.annotation.DubboService; import javax.annotation.Resource; import java.util.Date; import java.util.Objects;
8,517
package com.liyz.boot3.service.auth.provider; /** * Desc: * * @author lyz * @version 1.0.0 * @date 2023/6/15 9:27 */ @Slf4j @DubboService public class RemoteJwtParseServiceImpl implements RemoteJwtParseService { private final static String CLAIM_DEVICE = "device"; @Resource private AuthJwtService authJwtService; @Resource private RemoteAuthService remoteAuthService; /** * 解析token * * @param token jwt token * @param clientId 应用名称 * @return 用户信息 */ @Override public AuthUserBO parseToken(String token, String clientId) { AuthJwtDO authJwtDO = authJwtService.getByClientId(clientId); if (Objects.isNull(authJwtDO)) { log.warn("解析token失败, 没有找到该应用下jwt配置信息,clientId:{}", clientId); throw new RemoteAuthServiceException(AuthExceptionCodeEnum.AUTHORIZATION_FAIL); } if (StringUtils.isBlank(token) || !token.startsWith(authJwtDO.getJwtPrefix())) { throw new RemoteAuthServiceException(AuthExceptionCodeEnum.AUTHORIZATION_FAIL); } final String authToken = token.substring(authJwtDO.getJwtPrefix().length()).trim(); Claims unSignClaims = parseClaimsJws(authToken); AuthUserBO authUser = remoteAuthService.loadByUsername(Joiner.on(CommonServiceConstant.DEFAULT_JOINER) .join(clientId, unSignClaims.getSubject()), Device.getByType(unSignClaims.get(CLAIM_DEVICE, Integer.class))); if (Objects.isNull(authUser)) { throw new RemoteAuthServiceException(AuthExceptionCodeEnum.AUTHORIZATION_FAIL); } Claims claims = this.parseClaimsJws(authToken, Joiner.on(CommonServiceConstant.DEFAULT_PADDING).join(authJwtDO.getSigningKey(), authUser.getSalt())); if (authJwtDO.getOneOnline() && Objects.nonNull(authUser.getCheckTime()) && claims.getNotBefore().compareTo(authUser.getCheckTime()) < 0) { throw new RemoteAuthServiceException(AuthExceptionCodeEnum.OTHERS_LOGIN); } if (!clientId.equals(claims.getAudience().stream().findFirst().orElse(StringUtils.EMPTY))) { throw new RemoteAuthServiceException(AuthExceptionCodeEnum.AUTHORIZATION_FAIL); } if (DateUtil.currentDate().compareTo(claims.getExpiration()) > 0) { throw new RemoteAuthServiceException(AuthExceptionCodeEnum.AUTHORIZATION_TIMEOUT); } return AuthUserBO.builder() .username(claims.getSubject()) .password(StringUtils.EMPTY) .salt(StringUtils.EMPTY)
package com.liyz.boot3.service.auth.provider; /** * Desc: * * @author lyz * @version 1.0.0 * @date 2023/6/15 9:27 */ @Slf4j @DubboService public class RemoteJwtParseServiceImpl implements RemoteJwtParseService { private final static String CLAIM_DEVICE = "device"; @Resource private AuthJwtService authJwtService; @Resource private RemoteAuthService remoteAuthService; /** * 解析token * * @param token jwt token * @param clientId 应用名称 * @return 用户信息 */ @Override public AuthUserBO parseToken(String token, String clientId) { AuthJwtDO authJwtDO = authJwtService.getByClientId(clientId); if (Objects.isNull(authJwtDO)) { log.warn("解析token失败, 没有找到该应用下jwt配置信息,clientId:{}", clientId); throw new RemoteAuthServiceException(AuthExceptionCodeEnum.AUTHORIZATION_FAIL); } if (StringUtils.isBlank(token) || !token.startsWith(authJwtDO.getJwtPrefix())) { throw new RemoteAuthServiceException(AuthExceptionCodeEnum.AUTHORIZATION_FAIL); } final String authToken = token.substring(authJwtDO.getJwtPrefix().length()).trim(); Claims unSignClaims = parseClaimsJws(authToken); AuthUserBO authUser = remoteAuthService.loadByUsername(Joiner.on(CommonServiceConstant.DEFAULT_JOINER) .join(clientId, unSignClaims.getSubject()), Device.getByType(unSignClaims.get(CLAIM_DEVICE, Integer.class))); if (Objects.isNull(authUser)) { throw new RemoteAuthServiceException(AuthExceptionCodeEnum.AUTHORIZATION_FAIL); } Claims claims = this.parseClaimsJws(authToken, Joiner.on(CommonServiceConstant.DEFAULT_PADDING).join(authJwtDO.getSigningKey(), authUser.getSalt())); if (authJwtDO.getOneOnline() && Objects.nonNull(authUser.getCheckTime()) && claims.getNotBefore().compareTo(authUser.getCheckTime()) < 0) { throw new RemoteAuthServiceException(AuthExceptionCodeEnum.OTHERS_LOGIN); } if (!clientId.equals(claims.getAudience().stream().findFirst().orElse(StringUtils.EMPTY))) { throw new RemoteAuthServiceException(AuthExceptionCodeEnum.AUTHORIZATION_FAIL); } if (DateUtil.currentDate().compareTo(claims.getExpiration()) > 0) { throw new RemoteAuthServiceException(AuthExceptionCodeEnum.AUTHORIZATION_TIMEOUT); } return AuthUserBO.builder() .username(claims.getSubject()) .password(StringUtils.EMPTY) .salt(StringUtils.EMPTY)
.loginType(LoginType.getByType(PatternUtil.checkMobileEmail(claims.getSubject())))
5
2023-11-13 01:28:21+00:00
12k
martin-bian/DimpleBlog
dimple-blog/src/main/java/com/dimple/service/impl/BlogServiceImpl.java
[ { "identifier": "Blog", "path": "dimple-blog/src/main/java/com/dimple/domain/Blog.java", "snippet": "@Data\n@Entity\n@Table(name = \"bg_blog\")\npublic class Blog extends BaseEntity implements Serializable {\n\n @Id\n @Column(name = \"blog_id\")\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n @NotNull(groups = {Update.class})\n @ApiModelProperty(value = \"ID\", hidden = true)\n private Long id;\n\n// private Long categoryId;\n\n @ApiModelProperty(\"文章标题\")\n @Length(min = 3, max = 100, message = \"文章标题不能为空,且长度为{min}~{max}个字符\", groups = {Create.class, Update.class})\n private String title;\n\n @ApiModelProperty(\"摘要\")\n @NotNull(message = \"摘要不能为空\", groups = {Create.class})\n @Length(min = 10, max = 250, message = \"摘要长度为{min}~{max}个字符\", groups = {Create.class})\n private String summary;\n\n @ApiModelProperty(\"封面图片地址\")\n @NotNull(message = \"封面不能为空\", groups = {Create.class})\n @Length(max = 256, message = \"封面地址不能超过256个字符\", groups = {Create.class})\n private String headerImg;\n\n @ApiModelProperty(\"封面类型(1表示普通,0表示没有,2表示大图)\")\n private Integer headerImgType;\n\n @ApiModelProperty(\"正文内容\")\n @NotNull(message = \"正文内容不能为空\", groups = {Create.class, Update.class})\n @Basic(fetch = FetchType.LAZY)\n private String content;\n\n @ApiModelProperty(\"HTML 格式化后的内容\")\n @Basic(fetch = FetchType.LAZY)\n @NotNull(message = \"正文内容不能为空\", groups = {Create.class, Update.class})\n private String htmlContent;\n\n @ApiModelProperty(\"文章状态,1表示已经发表,0表示草稿箱\")\n @NotNull(message = \"状态设置不能为空\", groups = {Create.class, Update.class})\n private Boolean status;\n\n @ApiModelProperty(\"是否允许评论,1表示允许,0表示不允许\")\n @NotNull(message = \"评论设置不能为空\", groups = {Create.class})\n private Boolean comment;\n\n @ApiModelProperty(\"是否允许推荐,1表示推荐,0表示不推荐\")\n @NotNull(message = \"推荐设置不能为空\", groups = {Create.class})\n private Boolean support;\n\n @ApiModelProperty(\"权重\")\n @Range(min = 1, max = 5, message = \"权重长度为{min}~{max}个字符\", groups = {Create.class})\n private Long weight;\n\n @ApiModelProperty(\"点赞数\")\n private Long like;\n\n @ApiModelProperty(\"点击数\")\n private Long click;\n\n @ApiModelProperty(\"分类\")\n @ManyToOne(fetch = FetchType.LAZY)\n @JoinColumn(name = \"category_id\")\n private Category category;\n\n// @ApiModelProperty(\"标签集合\")\n// private List<Tag> tagList;\n//\n// @ApiModelProperty(\"标签名集合\")\n// private List<String> tagTitleList;\n//\n// @ApiModelProperty(\"评论集合\")\n// private List<Comment> commentList;\n//\n// @ApiModelProperty(\"评论数量\")\n// private Long commentCount;\n\n}" }, { "identifier": "BlogMapper", "path": "dimple-blog/src/main/java/com/dimple/mapstruct/BlogMapper.java", "snippet": "@Mapper(componentModel = \"spring\", unmappedTargetPolicy = ReportingPolicy.IGNORE)\npublic interface BlogMapper extends BaseMapper<BlogDTO, Blog> {\n}" }, { "identifier": "BlogSmallMapper", "path": "dimple-blog/src/main/java/com/dimple/mapstruct/BlogSmallMapper.java", "snippet": "@Mapper(componentModel = \"spring\", unmappedTargetPolicy = ReportingPolicy.IGNORE)\npublic interface BlogSmallMapper extends BaseMapper<BlogSmallDTO, Blog> {\n}" }, { "identifier": "BlogRepository", "path": "dimple-blog/src/main/java/com/dimple/repository/BlogRepository.java", "snippet": "@Repository\npublic interface BlogRepository extends JpaRepository<Blog, Long>, JpaSpecificationExecutor<Blog> {\n\n void deleteAllByIdIn(Set<Long> ids);\n\n List<Blog> findAllByCategoryIdIn(Set<Long> ids);\n\n}" }, { "identifier": "BlogService", "path": "dimple-blog/src/main/java/com/dimple/service/BlogService.java", "snippet": "public interface BlogService {\n\n Map<String, Object> queryAll(BlogCriteria criteria, Pageable pageable);\n\n BlogDTO findById(Long id);\n\n void create(Blog blog);\n\n void update(Blog blog);\n\n void delete(Set<Long> ids);\n}" }, { "identifier": "BlogCriteria", "path": "dimple-blog/src/main/java/com/dimple/service/Dto/BlogCriteria.java", "snippet": "@Data\npublic class BlogCriteria {\n @Query(blurry = \"title,summary\")\n private String blurry;\n}" }, { "identifier": "BlogDTO", "path": "dimple-blog/src/main/java/com/dimple/service/Dto/BlogDTO.java", "snippet": "@Data\n@ToString(callSuper = true)\npublic class BlogDTO extends BaseDTO implements Serializable {\n private Long id;\n private String title;\n private String summary;\n private String headerImg;\n private Integer headerImgType;\n private String content;\n private String htmlContent;\n private Boolean status;\n private Boolean comment;\n private Boolean support;\n private Long weight;\n private Long like;\n private Long click;\n private Category category;\n}" }, { "identifier": "BadRequestException", "path": "dimple-common/src/main/java/com/dimple/exception/BadRequestException.java", "snippet": "@Getter\npublic class BadRequestException extends RuntimeException {\n\n private Integer status = BAD_REQUEST.value();\n\n public BadRequestException(String msg) {\n super(msg);\n }\n\n public BadRequestException(HttpStatus status, String msg) {\n super(msg);\n this.status = status.value();\n }\n}" }, { "identifier": "PageUtil", "path": "dimple-common/src/main/java/com/dimple/utils/PageUtil.java", "snippet": "public class PageUtil extends cn.hutool.core.util.PageUtil {\n\n /**\n * List 分页\n */\n public static List toPage(int page, int size, List list) {\n int fromIndex = page * size;\n int toIndex = page * size + size;\n if (fromIndex > list.size()) {\n return new ArrayList();\n } else if (toIndex >= list.size()) {\n return list.subList(fromIndex, list.size());\n } else {\n return list.subList(fromIndex, toIndex);\n }\n }\n\n /**\n * Page 数据处理,预防redis反序列化报错\n */\n public static Map<String, Object> toPage(Page page) {\n Map<String, Object> map = new LinkedHashMap<>(2);\n map.put(\"content\", page.getContent());\n map.put(\"totalElements\", page.getTotalElements());\n return map;\n }\n\n /**\n * 自定义分页\n */\n public static Map<String, Object> toPage(Object object, Object totalElements) {\n Map<String, Object> map = new LinkedHashMap<>(2);\n map.put(\"content\", object);\n map.put(\"totalElements\", totalElements);\n return map;\n }\n\n}" }, { "identifier": "QueryHelp", "path": "dimple-common/src/main/java/com/dimple/utils/QueryHelp.java", "snippet": "@Slf4j\n@SuppressWarnings({\"unchecked\", \"all\"})\npublic class QueryHelp {\n\n public static <R, Q> Predicate getPredicate(Root<R> root, Q query, CriteriaBuilder cb) {\n List<Predicate> list = new ArrayList<>();\n if (query == null) {\n return cb.and(list.toArray(new Predicate[0]));\n }\n try {\n List<Field> fields = getAllFields(query.getClass(), new ArrayList<>());\n for (Field field : fields) {\n boolean accessible = field.isAccessible();\n // 设置对象的访问权限,保证对private的属性的访\n field.setAccessible(true);\n Query q = field.getAnnotation(Query.class);\n if (q != null) {\n String propName = q.propName();\n String joinName = q.joinName();\n String blurry = q.blurry();\n String attributeName = isBlank(propName) ? field.getName() : propName;\n Class<?> fieldType = field.getType();\n Object val = field.get(query);\n if (ObjectUtil.isNull(val) || \"\".equals(val)) {\n continue;\n }\n Join join = null;\n // 模糊多字段\n if (ObjectUtil.isNotEmpty(blurry)) {\n String[] blurrys = blurry.split(\",\");\n List<Predicate> orPredicate = new ArrayList<>();\n for (String s : blurrys) {\n orPredicate.add(cb.like(root.get(s)\n .as(String.class), \"%\" + val.toString() + \"%\"));\n }\n Predicate[] p = new Predicate[orPredicate.size()];\n list.add(cb.or(orPredicate.toArray(p)));\n continue;\n }\n if (ObjectUtil.isNotEmpty(joinName)) {\n String[] joinNames = joinName.split(\">\");\n for (String name : joinNames) {\n switch (q.join()) {\n case LEFT:\n if (ObjectUtil.isNotNull(join) && ObjectUtil.isNotNull(val)) {\n join = join.join(name, JoinType.LEFT);\n } else {\n join = root.join(name, JoinType.LEFT);\n }\n break;\n case RIGHT:\n if (ObjectUtil.isNotNull(join) && ObjectUtil.isNotNull(val)) {\n join = join.join(name, JoinType.RIGHT);\n } else {\n join = root.join(name, JoinType.RIGHT);\n }\n break;\n default:\n break;\n }\n }\n }\n switch (q.type()) {\n case EQUAL:\n list.add(cb.equal(getExpression(attributeName, join, root)\n .as((Class<? extends Comparable>) fieldType), val));\n break;\n case GREATER_THAN:\n list.add(cb.greaterThanOrEqualTo(getExpression(attributeName, join, root)\n .as((Class<? extends Comparable>) fieldType), (Comparable) val));\n break;\n case LESS_THAN:\n list.add(cb.lessThanOrEqualTo(getExpression(attributeName, join, root)\n .as((Class<? extends Comparable>) fieldType), (Comparable) val));\n break;\n case LESS_THAN_NQ:\n list.add(cb.lessThan(getExpression(attributeName, join, root)\n .as((Class<? extends Comparable>) fieldType), (Comparable) val));\n break;\n case INNER_LIKE:\n list.add(cb.like(getExpression(attributeName, join, root)\n .as(String.class), \"%\" + val.toString() + \"%\"));\n break;\n case LEFT_LIKE:\n list.add(cb.like(getExpression(attributeName, join, root)\n .as(String.class), \"%\" + val.toString()));\n break;\n case RIGHT_LIKE:\n list.add(cb.like(getExpression(attributeName, join, root)\n .as(String.class), val.toString() + \"%\"));\n break;\n case IN:\n if (CollUtil.isNotEmpty((Collection<Long>) val)) {\n list.add(getExpression(attributeName, join, root).in((Collection<Long>) val));\n }\n break;\n case NOT_EQUAL:\n list.add(cb.notEqual(getExpression(attributeName, join, root), val));\n break;\n case NOT_NULL:\n list.add(cb.isNotNull(getExpression(attributeName, join, root)));\n break;\n case IS_NULL:\n list.add(cb.isNull(getExpression(attributeName, join, root)));\n break;\n case BETWEEN:\n List<Object> between = new ArrayList<>((List<Object>) val);\n list.add(cb.between(getExpression(attributeName, join, root).as((Class<? extends Comparable>) between.get(0).getClass()),\n (Comparable) between.get(0), (Comparable) between.get(1)));\n break;\n default:\n break;\n }\n }\n field.setAccessible(accessible);\n }\n } catch (Exception e) {\n log.error(e.getMessage(), e);\n }\n int size = list.size();\n return cb.and(list.toArray(new Predicate[size]));\n }\n\n @SuppressWarnings(\"unchecked\")\n private static <T, R> Expression<T> getExpression(String attributeName, Join join, Root<R> root) {\n if (ObjectUtil.isNotEmpty(join)) {\n return join.get(attributeName);\n } else {\n return root.get(attributeName);\n }\n }\n\n private static boolean isBlank(final CharSequence cs) {\n int strLen;\n if (cs == null || (strLen = cs.length()) == 0) {\n return true;\n }\n for (int i = 0; i < strLen; i++) {\n if (!Character.isWhitespace(cs.charAt(i))) {\n return false;\n }\n }\n return true;\n }\n\n public static List<Field> getAllFields(Class clazz, List<Field> fields) {\n if (clazz != null) {\n fields.addAll(Arrays.asList(clazz.getDeclaredFields()));\n getAllFields(clazz.getSuperclass(), fields);\n }\n return fields;\n }\n}" }, { "identifier": "RedisUtils", "path": "dimple-common/src/main/java/com/dimple/utils/RedisUtils.java", "snippet": "@Component\n@SuppressWarnings({\"unchecked\", \"all\"})\npublic class RedisUtils {\n private static final Logger log = LoggerFactory.getLogger(RedisUtils.class);\n private RedisTemplate<Object, Object> redisTemplate;\n @Value(\"${jwt.online-key}\")\n private String onlineKey;\n\n public RedisUtils(RedisTemplate<Object, Object> redisTemplate) {\n this.redisTemplate = redisTemplate;\n }\n\n /**\n * 指定缓存失效时间\n *\n * @param key 键\n * @param time 时间(秒)\n */\n public boolean expire(String key, long time) {\n try {\n if (time > 0) {\n redisTemplate.expire(key, time, TimeUnit.SECONDS);\n }\n } catch (Exception e) {\n log.error(e.getMessage(), e);\n return false;\n }\n return true;\n }\n\n /**\n * 指定缓存失效时间\n *\n * @param key 键\n * @param time 时间(秒)\n * @param timeUnit 单位\n */\n public boolean expire(String key, long time, TimeUnit timeUnit) {\n try {\n if (time > 0) {\n redisTemplate.expire(key, time, timeUnit);\n }\n } catch (Exception e) {\n log.error(e.getMessage(), e);\n return false;\n }\n return true;\n }\n\n /**\n * 根据 key 获取过期时间\n *\n * @param key 键 不能为null\n * @return 时间(秒) 返回0代表为永久有效\n */\n public long getExpire(Object key) {\n return redisTemplate.getExpire(key, TimeUnit.SECONDS);\n }\n\n /**\n * 查找匹配key\n *\n * @param pattern key\n * @return /\n */\n public List<String> scan(String pattern) {\n ScanOptions options = ScanOptions.scanOptions().match(pattern).build();\n RedisConnectionFactory factory = redisTemplate.getConnectionFactory();\n RedisConnection rc = Objects.requireNonNull(factory).getConnection();\n Cursor<byte[]> cursor = rc.scan(options);\n List<String> result = new ArrayList<>();\n while (cursor.hasNext()) {\n result.add(new String(cursor.next()));\n }\n try {\n RedisConnectionUtils.releaseConnection(rc, factory);\n } catch (Exception e) {\n log.error(e.getMessage(), e);\n }\n return result;\n }\n\n /**\n * 分页查询 key\n *\n * @param patternKey key\n * @param page 页码\n * @param size 每页数目\n * @return /\n */\n public List<String> findKeysForPage(String patternKey, int page, int size) {\n ScanOptions options = ScanOptions.scanOptions().match(patternKey).build();\n RedisConnectionFactory factory = redisTemplate.getConnectionFactory();\n RedisConnection rc = Objects.requireNonNull(factory).getConnection();\n Cursor<byte[]> cursor = rc.scan(options);\n List<String> result = new ArrayList<>(size);\n int tmpIndex = 0;\n int fromIndex = page * size;\n int toIndex = page * size + size;\n while (cursor.hasNext()) {\n if (tmpIndex >= fromIndex && tmpIndex < toIndex) {\n result.add(new String(cursor.next()));\n tmpIndex++;\n continue;\n }\n // 获取到满足条件的数据后,就可以退出了\n if (tmpIndex >= toIndex) {\n break;\n }\n tmpIndex++;\n cursor.next();\n }\n try {\n RedisConnectionUtils.releaseConnection(rc, factory);\n } catch (Exception e) {\n log.error(e.getMessage(), e);\n }\n return result;\n }\n\n /**\n * 判断key是否存在\n *\n * @param key 键\n * @return true 存在 false不存在\n */\n public boolean hasKey(String key) {\n try {\n return redisTemplate.hasKey(key);\n } catch (Exception e) {\n log.error(e.getMessage(), e);\n return false;\n }\n }\n\n /**\n * 删除缓存\n *\n * @param key 可以传一个值 或多个\n */\n public void del(String... keys) {\n if (keys != null && keys.length > 0) {\n if (keys.length == 1) {\n boolean result = redisTemplate.delete(keys[0]);\n System.out.println(\"--------------------------------------------\");\n System.out.println(new StringBuilder(\"删除缓存:\").append(keys[0]).append(\",结果:\").append(result));\n System.out.println(\"--------------------------------------------\");\n } else {\n Set<Object> keySet = new HashSet<>();\n for (String key : keys) {\n keySet.addAll(redisTemplate.keys(key));\n }\n long count = redisTemplate.delete(keySet);\n System.out.println(\"--------------------------------------------\");\n System.out.println(\"成功删除缓存:\" + keySet.toString());\n System.out.println(\"缓存删除数量:\" + count + \"个\");\n System.out.println(\"--------------------------------------------\");\n }\n }\n }\n\n // ============================String=============================\n\n /**\n * 普通缓存获取\n *\n * @param key 键\n * @return 值\n */\n public Object get(String key) {\n return key == null ? null : redisTemplate.opsForValue().get(key);\n }\n\n /**\n * 批量获取\n *\n * @param keys\n * @return\n */\n public List<Object> multiGet(List<String> keys) {\n Object obj = redisTemplate.opsForValue().multiGet(Collections.singleton(keys));\n return null;\n }\n\n /**\n * 普通缓存放入\n *\n * @param key 键\n * @param value 值\n * @return true成功 false失败\n */\n public boolean set(String key, Object value) {\n try {\n redisTemplate.opsForValue().set(key, value);\n return true;\n } catch (Exception e) {\n log.error(e.getMessage(), e);\n return false;\n }\n }\n\n /**\n * 普通缓存放入并设置时间\n *\n * @param key 键\n * @param value 值\n * @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期\n * @return true成功 false 失败\n */\n public boolean set(String key, Object value, long time) {\n try {\n if (time > 0) {\n redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);\n } else {\n set(key, value);\n }\n return true;\n } catch (Exception e) {\n log.error(e.getMessage(), e);\n return false;\n }\n }\n\n /**\n * 普通缓存放入并设置时间\n *\n * @param key 键\n * @param value 值\n * @param time 时间\n * @param timeUnit 类型\n * @return true成功 false 失败\n */\n public boolean set(String key, Object value, long time, TimeUnit timeUnit) {\n try {\n if (time > 0) {\n redisTemplate.opsForValue().set(key, value, time, timeUnit);\n } else {\n set(key, value);\n }\n return true;\n } catch (Exception e) {\n log.error(e.getMessage(), e);\n return false;\n }\n }\n\n // ================================Map=================================\n\n /**\n * HashGet\n *\n * @param key 键 不能为null\n * @param item 项 不能为null\n * @return 值\n */\n public Object hget(String key, String item) {\n return redisTemplate.opsForHash().get(key, item);\n }\n\n /**\n * 获取hashKey对应的所有键值\n *\n * @param key 键\n * @return 对应的多个键值\n */\n public Map<Object, Object> hmget(String key) {\n return redisTemplate.opsForHash().entries(key);\n\n }\n\n /**\n * HashSet\n *\n * @param key 键\n * @param map 对应多个键值\n * @return true 成功 false 失败\n */\n public boolean hmset(String key, Map<String, Object> map) {\n try {\n redisTemplate.opsForHash().putAll(key, map);\n return true;\n } catch (Exception e) {\n log.error(e.getMessage(), e);\n return false;\n }\n }\n\n /**\n * HashSet 并设置时间\n *\n * @param key 键\n * @param map 对应多个键值\n * @param time 时间(秒)\n * @return true成功 false失败\n */\n public boolean hmset(String key, Map<String, Object> map, long time) {\n try {\n redisTemplate.opsForHash().putAll(key, map);\n if (time > 0) {\n expire(key, time);\n }\n return true;\n } catch (Exception e) {\n log.error(e.getMessage(), e);\n return false;\n }\n }\n\n /**\n * 向一张hash表中放入数据,如果不存在将创建\n *\n * @param key 键\n * @param item 项\n * @param value 值\n * @return true 成功 false失败\n */\n public boolean hset(String key, String item, Object value) {\n try {\n redisTemplate.opsForHash().put(key, item, value);\n return true;\n } catch (Exception e) {\n log.error(e.getMessage(), e);\n return false;\n }\n }\n\n /**\n * 向一张hash表中放入数据,如果不存在将创建\n *\n * @param key 键\n * @param item 项\n * @param value 值\n * @param time 时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间\n * @return true 成功 false失败\n */\n public boolean hset(String key, String item, Object value, long time) {\n try {\n redisTemplate.opsForHash().put(key, item, value);\n if (time > 0) {\n expire(key, time);\n }\n return true;\n } catch (Exception e) {\n log.error(e.getMessage(), e);\n return false;\n }\n }\n\n /**\n * 删除hash表中的值\n *\n * @param key 键 不能为null\n * @param item 项 可以使多个 不能为null\n */\n public void hdel(String key, Object... item) {\n redisTemplate.opsForHash().delete(key, item);\n }\n\n /**\n * 判断hash表中是否有该项的值\n *\n * @param key 键 不能为null\n * @param item 项 不能为null\n * @return true 存在 false不存在\n */\n public boolean hHasKey(String key, String item) {\n return redisTemplate.opsForHash().hasKey(key, item);\n }\n\n /**\n * hash递增 如果不存在,就会创建一个 并把新增后的值返回\n *\n * @param key 键\n * @param item 项\n * @param by 要增加几(大于0)\n * @return\n */\n public double hincr(String key, String item, double by) {\n return redisTemplate.opsForHash().increment(key, item, by);\n }\n\n /**\n * hash递减\n *\n * @param key 键\n * @param item 项\n * @param by 要减少记(小于0)\n * @return\n */\n public double hdecr(String key, String item, double by) {\n return redisTemplate.opsForHash().increment(key, item, -by);\n }\n\n // ============================set=============================\n\n /**\n * 根据key获取Set中的所有值\n *\n * @param key 键\n * @return\n */\n public Set<Object> sGet(String key) {\n try {\n return redisTemplate.opsForSet().members(key);\n } catch (Exception e) {\n log.error(e.getMessage(), e);\n return null;\n }\n }\n\n /**\n * 根据value从一个set中查询,是否存在\n *\n * @param key 键\n * @param value 值\n * @return true 存在 false不存在\n */\n public boolean sHasKey(String key, Object value) {\n try {\n return redisTemplate.opsForSet().isMember(key, value);\n } catch (Exception e) {\n log.error(e.getMessage(), e);\n return false;\n }\n }\n\n /**\n * 将数据放入set缓存\n *\n * @param key 键\n * @param values 值 可以是多个\n * @return 成功个数\n */\n public long sSet(String key, Object... values) {\n try {\n return redisTemplate.opsForSet().add(key, values);\n } catch (Exception e) {\n log.error(e.getMessage(), e);\n return 0;\n }\n }\n\n /**\n * 将set数据放入缓存\n *\n * @param key 键\n * @param time 时间(秒)\n * @param values 值 可以是多个\n * @return 成功个数\n */\n public long sSetAndTime(String key, long time, Object... values) {\n try {\n Long count = redisTemplate.opsForSet().add(key, values);\n if (time > 0) {\n expire(key, time);\n }\n return count;\n } catch (Exception e) {\n log.error(e.getMessage(), e);\n return 0;\n }\n }\n\n /**\n * 获取set缓存的长度\n *\n * @param key 键\n * @return\n */\n public long sGetSetSize(String key) {\n try {\n return redisTemplate.opsForSet().size(key);\n } catch (Exception e) {\n log.error(e.getMessage(), e);\n return 0;\n }\n }\n\n /**\n * 移除值为value的\n *\n * @param key 键\n * @param values 值 可以是多个\n * @return 移除的个数\n */\n public long setRemove(String key, Object... values) {\n try {\n Long count = redisTemplate.opsForSet().remove(key, values);\n return count;\n } catch (Exception e) {\n log.error(e.getMessage(), e);\n return 0;\n }\n }\n\n // ===============================list=================================\n\n /**\n * 获取list缓存的内容\n *\n * @param key 键\n * @param start 开始\n * @param end 结束 0 到 -1代表所有值\n * @return\n */\n public List<Object> lGet(String key, long start, long end) {\n try {\n return redisTemplate.opsForList().range(key, start, end);\n } catch (Exception e) {\n log.error(e.getMessage(), e);\n return null;\n }\n }\n\n /**\n * 获取list缓存的长度\n *\n * @param key 键\n * @return\n */\n public long lGetListSize(String key) {\n try {\n return redisTemplate.opsForList().size(key);\n } catch (Exception e) {\n log.error(e.getMessage(), e);\n return 0;\n }\n }\n\n /**\n * 通过索引 获取list中的值\n *\n * @param key 键\n * @param index 索引 index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推\n * @return\n */\n public Object lGetIndex(String key, long index) {\n try {\n return redisTemplate.opsForList().index(key, index);\n } catch (Exception e) {\n log.error(e.getMessage(), e);\n return null;\n }\n }\n\n /**\n * 将list放入缓存\n *\n * @param key 键\n * @param value 值\n * @return\n */\n public boolean lSet(String key, Object value) {\n try {\n redisTemplate.opsForList().rightPush(key, value);\n return true;\n } catch (Exception e) {\n log.error(e.getMessage(), e);\n return false;\n }\n }\n\n /**\n * 将list放入缓存\n *\n * @param key 键\n * @param value 值\n * @param time 时间(秒)\n * @return\n */\n public boolean lSet(String key, Object value, long time) {\n try {\n redisTemplate.opsForList().rightPush(key, value);\n if (time > 0) {\n expire(key, time);\n }\n return true;\n } catch (Exception e) {\n log.error(e.getMessage(), e);\n return false;\n }\n }\n\n /**\n * 将list放入缓存\n *\n * @param key 键\n * @param value 值\n * @return\n */\n public boolean lSet(String key, List<Object> value) {\n try {\n redisTemplate.opsForList().rightPushAll(key, value);\n return true;\n } catch (Exception e) {\n log.error(e.getMessage(), e);\n return false;\n }\n }\n\n /**\n * 将list放入缓存\n *\n * @param key 键\n * @param value 值\n * @param time 时间(秒)\n * @return\n */\n public boolean lSet(String key, List<Object> value, long time) {\n try {\n redisTemplate.opsForList().rightPushAll(key, value);\n if (time > 0) {\n expire(key, time);\n }\n return true;\n } catch (Exception e) {\n log.error(e.getMessage(), e);\n return false;\n }\n }\n\n /**\n * 根据索引修改list中的某条数据\n *\n * @param key 键\n * @param index 索引\n * @param value 值\n * @return /\n */\n public boolean lUpdateIndex(String key, long index, Object value) {\n try {\n redisTemplate.opsForList().set(key, index, value);\n return true;\n } catch (Exception e) {\n log.error(e.getMessage(), e);\n return false;\n }\n }\n\n /**\n * 移除N个值为value\n *\n * @param key 键\n * @param count 移除多少个\n * @param value 值\n * @return 移除的个数\n */\n public long lRemove(String key, long count, Object value) {\n try {\n return redisTemplate.opsForList().remove(key, count, value);\n } catch (Exception e) {\n log.error(e.getMessage(), e);\n return 0;\n }\n }\n\n /**\n * @param prefix 前缀\n * @param ids id\n */\n public void delByKeys(String prefix, Set<Long> ids) {\n Set<Object> keys = new HashSet<>();\n for (Long id : ids) {\n keys.addAll(redisTemplate.keys(new StringBuffer(prefix).append(id).toString()));\n }\n long count = redisTemplate.delete(keys);\n // 此处提示可自行删除\n System.out.println(\"--------------------------------------------\");\n System.out.println(\"成功删除缓存:\" + keys.toString());\n System.out.println(\"缓存删除数量:\" + count + \"个\");\n System.out.println(\"--------------------------------------------\");\n }\n}" } ]
import com.dimple.domain.Blog; import com.dimple.mapstruct.BlogMapper; import com.dimple.mapstruct.BlogSmallMapper; import com.dimple.repository.BlogRepository; import com.dimple.service.BlogService; import com.dimple.service.Dto.BlogCriteria; import com.dimple.service.Dto.BlogDTO; import com.dimple.exception.BadRequestException; import com.dimple.utils.PageUtil; import com.dimple.utils.QueryHelp; import com.dimple.utils.RedisUtils; import lombok.RequiredArgsConstructor; import org.springframework.cache.annotation.CacheConfig; import org.springframework.cache.annotation.Cacheable; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.Map; import java.util.Set;
8,556
package com.dimple.service.impl; /** * @className: BlogServiceImpl * @description: * @author: Dimple * @date: 06/17/20 */ @Service @RequiredArgsConstructor @CacheConfig(cacheNames = "blog") public class BlogServiceImpl implements BlogService { private final BlogRepository blogRepository; private final BlogSmallMapper blogSmallMapper; private final BlogMapper blogMapper; private final RedisUtils redisUtils; @Override public Map<String, Object> queryAll(BlogCriteria criteria, Pageable pageable) { Page<Blog> blogPage = blogRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
package com.dimple.service.impl; /** * @className: BlogServiceImpl * @description: * @author: Dimple * @date: 06/17/20 */ @Service @RequiredArgsConstructor @CacheConfig(cacheNames = "blog") public class BlogServiceImpl implements BlogService { private final BlogRepository blogRepository; private final BlogSmallMapper blogSmallMapper; private final BlogMapper blogMapper; private final RedisUtils redisUtils; @Override public Map<String, Object> queryAll(BlogCriteria criteria, Pageable pageable) { Page<Blog> blogPage = blogRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
return PageUtil.toPage(blogPage.map(blogSmallMapper::toDto));
8
2023-11-10 03:30:36+00:00
12k
LazyCoder0101/LazyCoder
ui-code-generation/src/main/java/com/lazycoder/uicodegeneration/component/operation/component/typeset/module/SettingContainer.java
[ { "identifier": "MarkElementName", "path": "database/src/main/java/com/lazycoder/database/common/MarkElementName.java", "snippet": "public class MarkElementName {\n\n\t/**\n\t * 引入标记\n\t */\n\tpublic static final String IMPORT_MARK = \"importMark\";\n\n\t/**\n\t * 初始化标记\n\t */\n\tpublic static final String INIT_MARK = \"initMark\";\n\n\t/**\n\t * 设置标记\n\t */\n\tpublic static final String SET_MARK = \"setMark\";\n\n\t/**\n\t * 方法标记\n\t */\n\tpublic static final String FUNCTION_MARK = \"functionMark\";\n\n\t/**\n\t * 可选模板的功能的标记\n\t */\n\tpublic static final String ADDITIONAL_FUNCTION_MARK = \"additionalFunctionMark\";\n\n\t/**\n\t * 必填模板格式标记\n\t */\n\tpublic static final String MAIN_FORMAT_MARK = \"mainFormatMark\";\n\n\t/**\n\t * 必填模板设置类型\n\t */\n\tpublic static final String MAIN_SET_TYPE_MARK = \"mainSetTypeMark\";\n\n\t/**\n\t * 可选模板标记\n\t */\n\tpublic static final String ADDITIONAL_FORMAT_MARK = \"additionalFormatMark\";\n\n\t/**\n\t * 可选模板设置类型\n\t */\n\tpublic static final String ADDITIONAL_SET_TYPE_MARK = \"additionalSetTypeMark\";\n\n\t/**\n\t * 模块控制\n\t */\n\tpublic static final String MODULE_CONTROL = \"moduleControl\";\n\n\t/**\n\t * 标记为空,即不写\n\t */\n\tpublic static final int MARK_NULL = -1;\n\n}" }, { "identifier": "ModuleInfo", "path": "database/src/main/java/com/lazycoder/database/model/ModuleInfo.java", "snippet": "@NoArgsConstructor\n@Data\npublic class ModuleInfo implements BaseModel {\n\n\tprivate String moduleId;\n\n\t/**\n\t * 分类名\n\t */\n\tprivate String className = \"\";\n\n\t/**\n\t * 模块名\n\t */\n\tprivate String moduleName = \"\";\n\n\t/**\n\t * 引入代码的数量\n\t */\n\tprivate int numOfImport = 0;\n\n\t/**\n\t * 初始化代码的数量\n\t */\n\tprivate int numOfInit = 0;\n\n\t/**\n\t * 模块变量的数量\n\t */\n\tprivate int numOfVariable = 0;\n\n\t/**\n\t * 模块方法名的数量\n\t */\n\tprivate int numOfFunctionName=0;\n\n\t/**\n\t * 是否需要模块控制\n\t */\n\tprivate int whetherModuleControlIsRequired = FALSE_;\n\n\t/**\n\t * 添加文件数量\n\t */\n\tprivate int numOfAddFile = 0;\n\n\t/**\n\t * 添加文件参数\n\t */\n\tprivate String addFileParam = \"[]\";\n\n\t/**\n\t * 附带文件数量\n\t */\n\tprivate int numOfAttachedFile = 0;\n\n\t/**\n\t * 附带文件参数\n\t */\n\tprivate String attachedFileParam = \"[]\";\n\n\t/**\n\t * 设置代码种类数量\n\t */\n\tprivate int numOfSetCodeType = 0;\n\n\t/**\n\t * 设置代码类型列表\n\t */\n\tprivate String setTheTypeOfSetCodeParam = \"[]\";\n\n\t/**\n\t * 功能源码数量\n\t */\n\tprivate int numOfFunctionCodeType = 0;\n\n\t/**\n\t * 功能源码种类列表\n\t */\n\tprivate String functionTheTypeOfSourceCodeParam = \"[]\";\n\n\t/**\n\t * 需要使用的其他代码文件数量\n\t */\n\tprivate int theNumOfAdditionalCodeFilesParamsThatNeedToBeUsed = 0;\n\n\t/**\n\t * 需要使用到的其他代码文件\n\t */\n\tprivate String additionalCodeFilesParamsThatNeedToBeUsed = \"[]\";\n\n}" }, { "identifier": "ModuleInfoStaticMethod", "path": "database/src/main/java/com/lazycoder/database/model/formodule/ModuleInfoStaticMethod.java", "snippet": "public class ModuleInfoStaticMethod {\n\n /**\n * 记录设置类型参数\n *\n * @param moduleInfo\n * @param ModuleSetTypeList\n */\n public static void setModuleSetTypeListParam(ModuleInfo moduleInfo, ArrayList<String> ModuleSetTypeList) {\n moduleInfo.setSetTheTypeOfSetCodeParam(JsonUtil.getJsonStr(ModuleSetTypeList));\n }\n\n /**\n * 获取所有设置类型\n *\n * @return\n */\n public static ArrayList<String> getModuleSetTypeListParam(ModuleInfo moduleInfo) {\n ArrayList<String> list = JSON.parseObject(moduleInfo.getSetTheTypeOfSetCodeParam(),\n new TypeReference<ArrayList<String>>() {\n });\n return list;\n }\n\n /**\n * 设置方法类型参数\n *\n * @param moduleInfo\n * @param FunctionTypeList\n */\n public static void setFunctionTypeListParam(ModuleInfo moduleInfo, ArrayList<String> FunctionTypeList) {\n moduleInfo.setFunctionTheTypeOfSourceCodeParam(JsonUtil.getJsonStr(FunctionTypeList));\n }\n\n /**\n * 获取方法类型参数\n *\n * @param moduleInfo\n * @return\n */\n public static ArrayList<String> getFunctionTypeListParam(ModuleInfo moduleInfo) {\n ArrayList<String> list = JSON.parseObject(moduleInfo.getFunctionTheTypeOfSourceCodeParam(),\n new TypeReference<ArrayList<String>>() {\n });\n return list;\n }\n\n\n /**\n * 设置添加文件的参数\n *\n * @param moduleInfo\n * @param AddFileParamList\n */\n public static void setAddFileParam(ModuleInfo moduleInfo, ArrayList<String> AddFileParamList) {\n moduleInfo.setAddFileParam(JsonUtil.getJsonStr(AddFileParamList));\n }\n\n\n /**\n * 获取需要使用的代码文件参数\n *\n * @return\n */\n public static ArrayList<CodeFormatFlagParam> getAdditionalCodeFilesParamsThatNeedToBeUsed(\n ModuleInfo moduleInfo) {\n ArrayList<CodeFormatFlagParam> list = JSON.parseObject(\n moduleInfo.getAdditionalCodeFilesParamsThatNeedToBeUsed(),\n new TypeReference<ArrayList<CodeFormatFlagParam>>() {\n });\n return list;\n }\n\n\n\n}" }, { "identifier": "ModuleControlContainer", "path": "ui-code-generation/src/main/java/com/lazycoder/uicodegeneration/component/operation/container/ModuleControlContainer.java", "snippet": "public class ModuleControlContainer extends AbstractFormatContainer {\n\n /**\n *\n */\n private static final long serialVersionUID = -4295431847007760024L;\n\n private ModuleTypeOperatingContainerParam moduleTypeContainerParam;\n\n public ModuleControlContainer() {\n super();\n // TODO Auto-generated constructor stub\n init(false, true, \"模块控制\", ModuleTypeContainer.THE_PROPORTION);\n }\n\n /**\n * 还原\n *\n * @param model\n * @param moduleTypeContainerParam\n * @param codeControlPane\n */\n public void restore(ModuleControlContainerModel model, ModuleTypeOperatingContainerParam moduleTypeContainerParam,\n AbstractCodeControlPane codeControlPane) {\n this.moduleTypeContainerParam = moduleTypeContainerParam;\n FormatOpratingContainerParam codeGenerationalOpratingContainerParam = new FormatOpratingContainerParam();\n codeGenerationalOpratingContainerParam.setFormatControlPane(moduleTypeContainerParam.getFormatControlPane());\n codeGenerationalOpratingContainerParam.setCodeControlPane(codeControlPane);\n codeGenerationalOpratingContainerParam.setModule(moduleTypeContainerParam.getModule());\n codeGenerationalOpratingContainerParam.setModuleInfo(moduleTypeContainerParam.getModuleInfo());\n codeGenerationalOpratingContainerParam.setCodeSerialNumber(0);\n PathFind pathFind = new PathFind(MarkElementName.MODULE_CONTROL, PathFind.FORMAT_TYPE);\n codeGenerationalOpratingContainerParam.setParentPathFind(pathFind);\n codeGenerationalOpratingContainerParam.setFormatControlPane(moduleTypeContainerParam.getFormatControlPane());\n\n restoreContent(model, codeGenerationalOpratingContainerParam);\n setAppropriateSize();\n }\n\n /**\n * 新建\n *\n * @param moduleTypeContainerParam\n * @param codeControlPane\n * @return\n */\n public void build(ModuleTypeOperatingContainerParam moduleTypeContainerParam,\n AbstractCodeControlPane codeControlPane) {\n this.moduleTypeContainerParam = moduleTypeContainerParam;\n\n ModuleControl moduleControl = SysService.MODULE_CONTROL_SERVICE.getModuleControl(moduleTypeContainerParam.getModule().getModuleId());\n if (moduleControl != null) {\n FormatOpratingContainerParam codeGenerationalOpratingContainerParam = new FormatOpratingContainerParam();\n codeGenerationalOpratingContainerParam\n .setFormatControlPane(moduleTypeContainerParam.getFormatControlPane());\n codeGenerationalOpratingContainerParam.setCodeControlPane(codeControlPane);\n codeGenerationalOpratingContainerParam.setModule(moduleTypeContainerParam.getModule());\n codeGenerationalOpratingContainerParam.setModuleInfo(moduleTypeContainerParam.getModuleInfo());\n codeGenerationalOpratingContainerParam.setCodeSerialNumber(0);\n PathFind pathFind = new PathFind(MarkElementName.MODULE_CONTROL, PathFind.FORMAT_TYPE);\n codeGenerationalOpratingContainerParam.setParentPathFind(pathFind);\n codeGenerationalOpratingContainerParam\n .setControlStatementFormat(moduleControl.getDefaultControlStatementFormat());\n\n generateOperationalContent(codeGenerationalOpratingContainerParam);\n\n codeGenerationalOpratingContainerParam.setControlStatementFormat(null);\n setAppropriateSize();\n }\n }\n\n @Override\n public ArrayList<CodeShowPane> getCodePaneList() {\n // TODO Auto-generated method stub\n return CodeGenerationFrameHolder.codeShowPanel.getModulePaneList(moduleTypeContainerParam.getModule().getModuleId());\n }\n\n @Override\n public ArrayList<CodeFormatFlagParam> getCodePaneRelatedInfoList() {\n ArrayList<CodeFormatFlagParam> list = new ArrayList<>();\n ArrayList<CodeShowPane> codeShowPaneList = CodeGenerationFrameHolder.codeShowPanel.getModulePaneList(moduleTypeContainerParam.getModule().getModuleId());\n for (CodeShowPane codeShowPane : codeShowPaneList) {\n list.add(codeShowPane.getCodeFormatFlagParam());\n }\n return list;\n }\n\n @Override\n public File getImageRootPath() {\n File file = SourceGenerateFileStructure.getModulePictureFilePutPath(CodeGenerationFrameHolder.projectParentPath, CodeGenerationFrameHolder.projectName, moduleTypeContainerParam.getModule().getModuleId());\n return file;\n }\n\n @Override\n public File getFileSelectorRootPath() {\n File file = SourceGenerateFileStructure.getModuleNeedFilePutPath(CodeGenerationFrameHolder.projectParentPath, CodeGenerationFrameHolder.projectName, moduleTypeContainerParam.getModule().getModuleId());\n return file;\n }\n\n @Override\n public void setParam(AbstractOperatingContainerModel model) {\n // TODO Auto-generated method stub\n ModuleControlContainerModel theModel = (ModuleControlContainerModel) model;\n super.setParam(theModel);\n }\n\n @Override\n public ModuleControlContainerModel getFormatStructureModel() {\n // TODO Auto-generated method stub\n ModuleControlContainerModel model = new ModuleControlContainerModel();\n setParam(model);\n return model;\n }\n\n @Override\n public String getPaneType() {\n // TODO Auto-generated method stub\n return MarkElementName.MODULE_CONTROL;\n }\n\n @Override\n public String getClassName() {\n // TODO Auto-generated method stub\n return moduleTypeContainerParam.getModule().getClassName();\n }\n\n @Override\n public String getModuleName() {\n // TODO Auto-generated method stub\n return moduleTypeContainerParam.getModule().getModuleName();\n }\n\n @Override\n public String getModuleId() {\n return moduleTypeContainerParam.getModule().getModuleId();\n }\n\n @Override\n public int getAdditionalSerialNumber() {\n // TODO Auto-generated method stub\n return 0;\n }\n\n @Override\n public AbstractCommandOpratingContainer getFirstCommandOpratingContainer() {\n return null;\n }\n\n @Override\n public AbstractFormatContainer getFormatContainer() {\n return this;\n }\n\n @Override\n public Dimension getRequiredDimension() {\n return super.getRequiredDimension();\n }\n\n}" }, { "identifier": "OpratingContainerInterface", "path": "ui-code-generation/src/main/java/com/lazycoder/uicodegeneration/component/operation/container/OpratingContainerInterface.java", "snippet": "public interface OpratingContainerInterface\n extends OpratingContainerBusinessTraverse {\n\n /**\n * 获取该功能容器组件的内部的控制组件放置面板类型\n *\n * @return\n */\n public String getPaneType();\n\n /**\n * 分类名\n *\n * @return\n */\n public String getClassName();\n\n /**\n * 模块名\n *\n * @return\n */\n public String getModuleName();\n\n /**\n * 获取模块id\n *\n * @return\n */\n public String getModuleId();\n\n /**\n * 其他代码序号\n *\n * @return\n */\n public int getAdditionalSerialNumber();\n\n /**\n * 更新对应代码值(该方法只能提供给所在功能)\n * @param codeGenerationComponent\n * @param paneType\n * @param updateParam\n */\n public void updateValue(CodeGenerationComponentInterface codeGenerationComponent,int paneType, Object updateParam);\n\n\n// @Override\n// public void delThis();\n\n /**\n * 获取图片路径(供该面板上的图片组件调用,继承该面板都要重写)\n *\n * @return\n */\n public File getImageRootPath();\n\n /**\n * 获取文件选择路径(供该面板的文件选择组件调用,继承该面板都要重写)\n *\n * @return\n */\n public File getFileSelectorRootPath();\n\n /**\n * 返回对应的变量列表\n *\n * @return\n */\n public CustomVariableHolder getThisCustomVariableHolder();\n\n /**\n * 返回对应的方法名列表\n *\n * @return\n */\n public CustomFunctionNameHolder getThisCustomMethodNameHolder();\n\n public PathFind getPathFind();\n\n public int getCodeSerialNumber();\n\n public AbstractOperatingContainerModel getFormatStructureModel();\n\n public void setParam(AbstractOperatingContainerModel model);\n\n /**\n * 获取放置该容器的首个命令容器\n *\n * @return\n */\n public AbstractCommandOpratingContainer getFirstCommandOpratingContainer();\n\n /**\n * 获取放置该容器的首个格式容器\n *\n * @return\n */\n public AbstractFormatContainer getFormatContainer();\n\n /**\n * 是否是同一层级\n *\n * @return\n */\n public boolean isItTheSameLevel(OpratingContainerInterface opratingContainer);\n\n /**\n * 设置变量组件里面自动选择的值(仅在第一次创建代码生成界面的时候使用)\n */\n public void setNoUserSelectionIsRequiredValue();\n\n /**\n * 打开项目文件的时候才用,选择之前选好的值\n */\n public void showSelectedValue();\n\n}" }, { "identifier": "ModuleTypeOperatingContainerParam", "path": "ui-code-generation/src/main/java/com/lazycoder/uicodegeneration/component/operation/container/sendparam/ModuleTypeOperatingContainerParam.java", "snippet": "@Data\n@NoArgsConstructor\npublic class ModuleTypeOperatingContainerParam extends GeneralOperatingContainerParam {\n\n private ModuleSetFeatureSelectionModel moduleSetFeatureSelectionModel;\n\n private String moduleSetType = \"\";\n\n private SetButton setButton = null;\n\n}" }, { "identifier": "AbstractCodeControlPane", "path": "ui-code-generation/src/main/java/com/lazycoder/uicodegeneration/generalframe/operation/component/AbstractCodeControlPane.java", "snippet": "public abstract class AbstractCodeControlPane extends FolderPane\n implements GeneralCodeControlPaneInterface, CodeControlPaneBusinessTraverse {\n\n /**\n *\n */\n private static final long serialVersionUID = 5791773657249060168L;\n\n @Getter\n @Setter\n private PathFind pathFind = null;\n\n /**\n *\n */\n @Getter\n private AbstractFormatControlPane formatControlPane = null;\n\n /**\n * 放置该面板的滑动面板,用来设置滑到底部的方法\n */\n @Getter\n @Setter\n protected JScrollPane parentScrollPane = null;\n\n public AbstractCodeControlPane(AbstractFormatControlPane formatControlPane, int intterTabPadding) {\n super(intterTabPadding);\n this.formatControlPane = formatControlPane;\n // TODO Auto-generated constructor stub\n parentScrollPaneInit();\n }\n\n protected void parentScrollPaneInit() {\n parentScrollPane = new JScrollPane(this);\n parentScrollPane.setUI(new BEScrollPaneUI());\n }\n\n public void delCodeControlCommand(Folder delCodeControlCommand) {\n if (delCodeControlCommand.getHiddenButton() != null) {\n delCodeControlCommand.getHiddenButton().removeAll();\n }\n this.remove(delCodeControlCommand);\n tabs.remove(delCodeControlCommand);\n if (getParent() != null) {\n getParent().doLayout();\n }\n }\n\n /**\n * 滑到底部\n */\n public void scrollToBottom() {\n if (parentScrollPane != null) {\n SysUtil.scrollToBottom(parentScrollPane);\n }\n }\n\n\n @Override\n public void setParam(AbstractCodeControlPaneModel model) {\n // TODO Auto-generated method stub\n model.setContainerList(getOperatingContainerListParam());\n }\n\n /**\n * 把所有功能容器的信息转成参数\n *\n * @return\n */\n protected ArrayList<AbstractOperatingContainerModel> getOperatingContainerListParam() {\n ArrayList<AbstractOperatingContainerModel> list = new ArrayList<>();\n OpratingContainerInterface opratingContainer;\n Component component;\n for (int i = 0; i < getComponentCount(); i++) {\n component = getComponent(i);\n if (component instanceof OpratingContainerInterface) {\n opratingContainer = (OpratingContainerInterface) component;\n list.add(opratingContainer.getFormatStructureModel());\n }\n }\n return list;\n }\n\n @Override\n public ArrayList<OpratingContainerInterface> getAllOpratingContainer() {\n ArrayList<OpratingContainerInterface> opratingContainerList = new ArrayList<OpratingContainerInterface>();\n ArrayList<OpratingContainerInterface> containerList = getAllOpratingContainerListInThisPane();\n for (OpratingContainerInterface container : containerList) {\n opratingContainerList.add(container);\n opratingContainerList.addAll(container.getAllOpratingContainerListInThis());\n }\n return opratingContainerList;\n }\n\n /**\n * 获取添加在这个面板上的所有的功能容器(不包括容器里面的容器)\n *\n * @return\n */\n public ArrayList<OpratingContainerInterface> getAllOpratingContainerListInThisPane() {\n ArrayList<OpratingContainerInterface> opratingContainerList = new ArrayList<OpratingContainerInterface>();\n OpratingContainerInterface opratingContainer;\n for (int i = 0; i < getComponentCount(); i++) {\n if (getComponent(i) instanceof OpratingContainerInterface) {\n opratingContainer = (OpratingContainerInterface) getComponent(i);\n opratingContainerList.add(opratingContainer);\n }\n }\n return opratingContainerList;\n }\n\n @Override\n public void delModuleOpratingContainerFromComponent(String moduleId) {\n ArrayList<OpratingContainerInterface> containerList = getAllOpratingContainerListInThisPane();\n for (OpratingContainerInterface container : containerList) {\n container.delModuleOpratingContainerFromComponent(moduleId);\n }\n }\n\n @Override\n public void delThis() {\n ArrayList<OpratingContainerInterface> containerList = getAllOpratingContainerListInThisPane();\n for (OpratingContainerInterface container : containerList) {\n container.delThis();\n }\n }\n\n @Override\n public void collapseThis() {\n ArrayList<OpratingContainerInterface> containerList = getAllOpratingContainerListInThisPane();\n for (OpratingContainerInterface container : containerList) {\n container.collapseThis();\n }\n }\n\n /**\n * 收起隐藏面板\n *\n * @param currentOpratingContainer\n */\n public void autoCollapse(OpratingContainerInterface currentOpratingContainer) {\n// if (currentOpratingContainer != null) {\n OpratingContainerInterface opratingContainerTemp;\n for (int i = 0; i < getComponentCount(); i++) {\n if (getComponent(i) instanceof OpratingContainerInterface) {\n opratingContainerTemp = (OpratingContainerInterface) getComponent(i);\n opratingContainerTemp.autoCollapse(currentOpratingContainer);\n }\n }\n// }\n }\n\n\n}" }, { "identifier": "ModuleControlContainerModel", "path": "ui-code-generation/src/main/java/com/lazycoder/uicodegeneration/proj/stostr/operation/container/ModuleControlContainerModel.java", "snippet": "@Data\npublic class ModuleControlContainerModel extends AbstractFormatOperatingContainerModel {\n\n\tprivate String className = null;\n\n\tprivate String moduleName = null;\n\n\tprivate String moduleId = null;\n\n\tpublic ModuleControlContainerModel() {\n\t\t// TODO Auto-generated constructor stub\n\t\tsuper(MODULE_CONTROL_CONTAINER);\n\t}\n\n}" }, { "identifier": "ModuleTypeContainerModel", "path": "ui-code-generation/src/main/java/com/lazycoder/uicodegeneration/proj/stostr/operation/containerput/ModuleTypeContainerModel.java", "snippet": "@Data\npublic class ModuleTypeContainerModel extends AbstractCodeControlPaneModel {\n\n\tprivate String moduleSetType = null;\n\n\tprivate String moduleId = null;\n\n\tpublic ModuleTypeContainerModel() {\n\t\t// TODO Auto-generated constructor stub\n\t\tsetCodeControlPaneType(MODULE_TYPE_CODE_CONTROL_PANE);\n\t}\n\n}" }, { "identifier": "SettingContainerModel", "path": "ui-code-generation/src/main/java/com/lazycoder/uicodegeneration/proj/stostr/operation/containerput/SettingContainerModel.java", "snippet": "@Data\npublic class SettingContainerModel extends AbstractCodeControlPaneModel {\n\t/**\n\t * 该类的containerList废弃不用\n\t */\n\t@JSONField(deserializeUsing = ModuleControlContainerModelDeserializer.class)\n\tprivate ModuleControlContainerModel moduleControlContainerModel;\n\n\t@JSONField(deserializeUsing = ModuleTypeContainerModelListDeserializer.class)\n\tprivate ArrayList<ModuleTypeContainerModel> moduleTypeContainerModelList = new ArrayList<>();\n\n\tpublic SettingContainerModel() {\n\t\t// TODO Auto-generated constructor stub\n\t\tsetCodeControlPaneType(SETTING_CONTAINER);\n\t}\n\n}" } ]
import com.lazycoder.database.common.MarkElementName; import com.lazycoder.database.model.ModuleInfo; import com.lazycoder.database.model.formodule.ModuleInfoStaticMethod; import com.lazycoder.uicodegeneration.component.operation.container.ModuleControlContainer; import com.lazycoder.uicodegeneration.component.operation.container.OpratingContainerInterface; import com.lazycoder.uicodegeneration.component.operation.container.sendparam.ModuleTypeOperatingContainerParam; import com.lazycoder.uicodegeneration.generalframe.operation.component.AbstractCodeControlPane; import com.lazycoder.uicodegeneration.proj.stostr.operation.container.ModuleControlContainerModel; import com.lazycoder.uicodegeneration.proj.stostr.operation.containerput.ModuleTypeContainerModel; import com.lazycoder.uicodegeneration.proj.stostr.operation.containerput.SettingContainerModel; import java.awt.Component; import java.util.ArrayList;
7,793
moduleTypeContainerParamTemp.setModule(moduleTypeContainerParam.getModule()); moduleTypeContainerParamTemp.setModuleInfo(moduleTypeContainerParam.getModuleInfo()); moduleTypeContainerParamTemp .setFormatControlPane(moduleTypeContainerParam.getFormatControlPane()); moduleTypeContainerParamTemp.setModuleSetType(typeList.get(i)); moduleTypeContainerParamTemp.setSetButton(this.moduleTypeContainerParam.getSetButton()); moduleTypeContainer = new ModuleTypeContainer(moduleTypeContainerParamTemp, false); addContainer(moduleTypeContainer); } } } } } @Override public SettingContainerModel getFormatStructureModel() { // TODO Auto-generated method stub Component component; ModuleTypeContainer moduleTypeContainer; SettingContainerModel model = new SettingContainerModel(); int flag = moduleInfo.getWhetherModuleControlIsRequired(); if (ModuleInfo.TRUE_ == flag) {// 添加模块控制窗口 model.setModuleControlContainerModel(this.moduleControlContainer.getFormatStructureModel()); } if (moduleInfo.getNumOfSetCodeType() > 0) { for (int i = 0; i < getComponentCount(); i++) { component = getComponent(i); if (component instanceof ModuleTypeContainer) { moduleTypeContainer = (ModuleTypeContainer) component; model.getModuleTypeContainerModelList().add(moduleTypeContainer.getFormatStructureModel()); } } } return model; } @Override public ArrayList<OpratingContainerInterface> getAllOpratingContainer() { // TODO Auto-generated method stub ArrayList<OpratingContainerInterface> opratingContainerList = new ArrayList<OpratingContainerInterface>(); if (ModuleInfo.TRUE_ == moduleInfo.getWhetherModuleControlIsRequired()) { opratingContainerList.add(moduleControlContainer); opratingContainerList.addAll(moduleControlContainer.getAllOpratingContainerListInThis()); } if (moduleInfo.getNumOfSetCodeType() > 0) { ModuleTypeContainer moduleTypeContainer = null; for (int i = 0; i < getComponentCount(); i++) { if (getComponent(i) instanceof ModuleTypeContainer) { moduleTypeContainer = (ModuleTypeContainer) getComponent(i); opratingContainerList.addAll(moduleTypeContainer.getAllOpratingContainerList()); } } } return opratingContainerList; } /** * 从各个方法那里的组件进入,一个个删除里面的模块 * * @param moduleId */ @Override public void delModuleOpratingContainerFromComponent(String moduleId) { if (ModuleInfo.TRUE_ == moduleInfo.getWhetherModuleControlIsRequired()) {// 添加模块控制窗口 moduleControlContainer.delModuleOpratingContainerFromComponent(moduleId); } if (moduleInfo.getNumOfSetCodeType() > 0) { ModuleTypeContainer moduleTypeContainer = null; for (int i = 0; i < getComponentCount(); i++) { if (getComponent(i) instanceof ModuleTypeContainer) { moduleTypeContainer = (ModuleTypeContainer) getComponent(i); moduleTypeContainer.delModuleOpratingContainerFromComponent(moduleId); } } } } public void delModuleOpratingContainer() { if (ModuleInfo.TRUE_ == moduleInfo.getWhetherModuleControlIsRequired()) {// 添加模块控制窗口 moduleControlContainer.delThis(); } if (moduleInfo.getNumOfSetCodeType() > 0) { ModuleTypeContainer moduleTypeContainer = null; for (int i = 0; i < getComponentCount(); i++) { if (getComponent(i) instanceof ModuleTypeContainer) { moduleTypeContainer = (ModuleTypeContainer) getComponent(i); moduleTypeContainer.delThis(); } } } } /** * 收取里面的组件 */ @Override public void collapseThis() { if (ModuleInfo.TRUE_ == moduleInfo.getWhetherModuleControlIsRequired()) {// 添加模块控制窗口 moduleControlContainer.collapseThis(); } if (moduleInfo.getNumOfSetCodeType() > 0) { ModuleTypeContainer moduleTypeContainer = null; for (int i = 0; i < getComponentCount(); i++) { if (getComponent(i) instanceof ModuleTypeContainer) { moduleTypeContainer = (ModuleTypeContainer) getComponent(i); moduleTypeContainer.collapseThis(); } } } } @Override public void autoCollapse(OpratingContainerInterface currentOpratingContainer) { if (currentOpratingContainer != null) { if (ModuleInfo.TRUE_ == moduleInfo.getWhetherModuleControlIsRequired()) {// 添加模块控制窗口 moduleControlContainer.autoCollapse(currentOpratingContainer); } if (moduleInfo.getNumOfSetCodeType() > 0) {
package com.lazycoder.uicodegeneration.component.operation.component.typeset.module; /** * 存放模块控制面板和对应的模块分类面板的面板,放在SettingFrame上 * * @author admin */ public class SettingContainer extends AbstractCodeControlPane { /** * */ private static final long serialVersionUID = -1391022073897256338L; private ModuleControlContainer moduleControlContainer = null; private ModuleTypeOperatingContainerParam moduleTypeContainerParam = null; private ModuleInfo moduleInfo; /** * 新建 * * @param moduleTypeContainerParam */ public SettingContainer(ModuleTypeOperatingContainerParam moduleTypeContainerParam) { super(moduleTypeContainerParam.getFormatControlPane(), 0); this.moduleInfo = moduleTypeContainerParam.getModuleInfo(); this.moduleTypeContainerParam = moduleTypeContainerParam; newInit(); } /** * 还原 * * @param moduleTypeContainerParam * @param settingContainerModel */ public SettingContainer(ModuleTypeOperatingContainerParam moduleTypeContainerParam, SettingContainerModel settingContainerModel) { super(moduleTypeContainerParam.getFormatControlPane(), 0); this.moduleInfo = moduleTypeContainerParam.getModuleInfo(); this.moduleTypeContainerParam = moduleTypeContainerParam; restoreInit(settingContainerModel); } private void restoreInit(SettingContainerModel settingContainerModel) { if (moduleInfo != null) { if (ModuleInfo.TRUE_ == moduleInfo.getWhetherModuleControlIsRequired()) {// 添加模块控制窗口 ModuleControlContainerModel moduleControlContainerModel = settingContainerModel .getModuleControlContainerModel(); if (moduleControlContainerModel != null) { moduleControlContainer = new ModuleControlContainer(); this.moduleControlContainer.restore(settingContainerModel.getModuleControlContainerModel(), moduleTypeContainerParam, this); addContainer(moduleControlContainer); } } if (moduleInfo.getNumOfSetCodeType() > 0) {// 添加模块类型 ModuleTypeOperatingContainerParam moduleTypeContainerParamTemp; ModuleTypeContainer moduleTypeContainer = null; ArrayList<ModuleTypeContainerModel> moduleTypeContainerModelList = settingContainerModel .getModuleTypeContainerModelList(); for (ModuleTypeContainerModel moduleTypeContainerModel : moduleTypeContainerModelList) { moduleTypeContainerParamTemp = new ModuleTypeOperatingContainerParam(); moduleTypeContainerParamTemp.setModule(moduleTypeContainerParam.getModule()); moduleTypeContainerParamTemp.setModuleInfo(moduleTypeContainerParam.getModuleInfo()); moduleTypeContainerParamTemp.setFormatControlPane(moduleTypeContainerParam.getFormatControlPane()); moduleTypeContainerParamTemp.setModuleSetType(moduleTypeContainerModel.getModuleSetType()); moduleTypeContainerParamTemp.setSetButton(this.moduleTypeContainerParam.getSetButton()); moduleTypeContainer = new ModuleTypeContainer(moduleTypeContainerModel, moduleTypeContainerParamTemp, false); addContainer(moduleTypeContainer); } } } } private void newInit() { if (moduleInfo != null) { if (ModuleInfo.TRUE_ == moduleInfo.getWhetherModuleControlIsRequired()) {// 添加模块控制窗口 moduleControlContainer = new ModuleControlContainer(); moduleControlContainer.build(moduleTypeContainerParam, this); addContainer(moduleControlContainer); } if (moduleInfo.getNumOfSetCodeType() > 0) {// 添加模块类型 ModuleTypeContainer moduleTypeContainer = null; ArrayList<String> typeList = ModuleInfoStaticMethod.getModuleSetTypeListParam(moduleInfo); ModuleTypeOperatingContainerParam moduleTypeContainerParamTemp; if (typeList != null) { for (int i = 0; i < typeList.size(); i++) { moduleTypeContainerParamTemp = new ModuleTypeOperatingContainerParam(); moduleTypeContainerParamTemp.setModule(moduleTypeContainerParam.getModule()); moduleTypeContainerParamTemp.setModuleInfo(moduleTypeContainerParam.getModuleInfo()); moduleTypeContainerParamTemp .setFormatControlPane(moduleTypeContainerParam.getFormatControlPane()); moduleTypeContainerParamTemp.setModuleSetType(typeList.get(i)); moduleTypeContainerParamTemp.setSetButton(this.moduleTypeContainerParam.getSetButton()); moduleTypeContainer = new ModuleTypeContainer(moduleTypeContainerParamTemp, false); addContainer(moduleTypeContainer); } } } } } @Override public SettingContainerModel getFormatStructureModel() { // TODO Auto-generated method stub Component component; ModuleTypeContainer moduleTypeContainer; SettingContainerModel model = new SettingContainerModel(); int flag = moduleInfo.getWhetherModuleControlIsRequired(); if (ModuleInfo.TRUE_ == flag) {// 添加模块控制窗口 model.setModuleControlContainerModel(this.moduleControlContainer.getFormatStructureModel()); } if (moduleInfo.getNumOfSetCodeType() > 0) { for (int i = 0; i < getComponentCount(); i++) { component = getComponent(i); if (component instanceof ModuleTypeContainer) { moduleTypeContainer = (ModuleTypeContainer) component; model.getModuleTypeContainerModelList().add(moduleTypeContainer.getFormatStructureModel()); } } } return model; } @Override public ArrayList<OpratingContainerInterface> getAllOpratingContainer() { // TODO Auto-generated method stub ArrayList<OpratingContainerInterface> opratingContainerList = new ArrayList<OpratingContainerInterface>(); if (ModuleInfo.TRUE_ == moduleInfo.getWhetherModuleControlIsRequired()) { opratingContainerList.add(moduleControlContainer); opratingContainerList.addAll(moduleControlContainer.getAllOpratingContainerListInThis()); } if (moduleInfo.getNumOfSetCodeType() > 0) { ModuleTypeContainer moduleTypeContainer = null; for (int i = 0; i < getComponentCount(); i++) { if (getComponent(i) instanceof ModuleTypeContainer) { moduleTypeContainer = (ModuleTypeContainer) getComponent(i); opratingContainerList.addAll(moduleTypeContainer.getAllOpratingContainerList()); } } } return opratingContainerList; } /** * 从各个方法那里的组件进入,一个个删除里面的模块 * * @param moduleId */ @Override public void delModuleOpratingContainerFromComponent(String moduleId) { if (ModuleInfo.TRUE_ == moduleInfo.getWhetherModuleControlIsRequired()) {// 添加模块控制窗口 moduleControlContainer.delModuleOpratingContainerFromComponent(moduleId); } if (moduleInfo.getNumOfSetCodeType() > 0) { ModuleTypeContainer moduleTypeContainer = null; for (int i = 0; i < getComponentCount(); i++) { if (getComponent(i) instanceof ModuleTypeContainer) { moduleTypeContainer = (ModuleTypeContainer) getComponent(i); moduleTypeContainer.delModuleOpratingContainerFromComponent(moduleId); } } } } public void delModuleOpratingContainer() { if (ModuleInfo.TRUE_ == moduleInfo.getWhetherModuleControlIsRequired()) {// 添加模块控制窗口 moduleControlContainer.delThis(); } if (moduleInfo.getNumOfSetCodeType() > 0) { ModuleTypeContainer moduleTypeContainer = null; for (int i = 0; i < getComponentCount(); i++) { if (getComponent(i) instanceof ModuleTypeContainer) { moduleTypeContainer = (ModuleTypeContainer) getComponent(i); moduleTypeContainer.delThis(); } } } } /** * 收取里面的组件 */ @Override public void collapseThis() { if (ModuleInfo.TRUE_ == moduleInfo.getWhetherModuleControlIsRequired()) {// 添加模块控制窗口 moduleControlContainer.collapseThis(); } if (moduleInfo.getNumOfSetCodeType() > 0) { ModuleTypeContainer moduleTypeContainer = null; for (int i = 0; i < getComponentCount(); i++) { if (getComponent(i) instanceof ModuleTypeContainer) { moduleTypeContainer = (ModuleTypeContainer) getComponent(i); moduleTypeContainer.collapseThis(); } } } } @Override public void autoCollapse(OpratingContainerInterface currentOpratingContainer) { if (currentOpratingContainer != null) { if (ModuleInfo.TRUE_ == moduleInfo.getWhetherModuleControlIsRequired()) {// 添加模块控制窗口 moduleControlContainer.autoCollapse(currentOpratingContainer); } if (moduleInfo.getNumOfSetCodeType() > 0) {
if (MarkElementName.SET_MARK.equals(currentOpratingContainer.getPaneType())) {
0
2023-11-16 11:55:06+00:00
12k
kash-developer/HomeDeviceEmulator
app/src/main/java/kr/or/kashi/hde/MainFragment.java
[ { "identifier": "PropertyMap", "path": "app/src/main/java/kr/or/kashi/hde/base/PropertyMap.java", "snippet": "public abstract class PropertyMap {\n /** Get the value of a property */\n public <E> E get(String name, Class<E> clazz) {\n return (E) get(name).getValue();\n }\n\n /** Put new string value to a property */\n public void put(String name, String value) {\n put(new PropertyValue<String>(name, value));\n }\n\n /** Put new boolean value to a property */\n public void put(String name, boolean value) {\n put(new PropertyValue<Boolean>(name, value));\n }\n\n /** Put new integer value to a property */\n public void put(String name, int value) {\n put(new PropertyValue<Integer>(name, value));\n }\n\n /** Put new long value to a property */\n public void put(String name, long value) {\n put(new PropertyValue<Long>(name, value));\n }\n\n /** Put new float value to a property */\n public void put(String name, float value) {\n put(new PropertyValue<Float>(name, value));\n }\n\n /** Put new double value to a property */\n public void put(String name, double value) {\n put(new PropertyValue<Double>(name, value));\n }\n\n /** Put only bits of value in mask to a property */\n public void putBit(String name, int mask, boolean set) {\n int current = get(name, Integer.class);\n if (set) {\n current |= mask;\n } else {\n current &= ~mask;\n }\n put(name, current);\n }\n\n /** Put only bits of value in mask to a property */\n public void putBit(String name, long mask, boolean set) {\n long current = get(name, Long.class);\n if (set) {\n current |= mask;\n } else {\n current &= ~mask;\n }\n put(name, current);\n }\n\n /** Put only bits of value in mask to a property */\n public void putBits(String name, int mask, int value) {\n int current = get(name, Integer.class);\n for (int i=0; i<Integer.SIZE; i++) {\n int indexBit = (1 << i);\n if ((mask & indexBit) != 0) {\n if ((value & indexBit) != 0)\n current |= indexBit;\n else\n current &= ~indexBit;\n }\n }\n put(name, current);\n }\n\n /** Put only bits of value in mask to a property */\n public void putBits(String name, long mask, long value) {\n long current = get(name, Long.class);\n for (int i=0; i<Long.SIZE; i++) {\n long indexBit = (1 << i);\n if ((mask & indexBit) != 0) {\n if ((value & indexBit) != 0)\n current |= indexBit;\n else\n current &= ~indexBit;\n }\n }\n put(name, current);\n }\n\n /** Get all the property values as list */\n public List<PropertyValue> getAll() {\n // TODO: Consider to return cached list if not changed.\n return getAllInternal();\n }\n\n /** Get all the property values as map */\n public Map<String, PropertyValue> toMap() {\n final List<PropertyValue> props = getAll();\n Map<String, PropertyValue> map = new ArrayMap<>(props.size());\n for (PropertyValue prop : props) {\n map.put(prop.getName(), prop);\n }\n return map;\n }\n\n /** Put all the property value from other map */\n public void putAll(PropertyMap map) {\n putAll(map.getAll());\n }\n\n /** Put all the property value from other map */\n public void putAll(Map<String, PropertyValue> map) {\n putAll(map.values());\n }\n\n /** Put all the property value from other collection */\n public void putAll(Collection<PropertyValue> props) {\n for (PropertyValue prop : props) {\n put(prop);\n }\n }\n\n /** Get a property value */\n public PropertyValue get(String name) {\n return getInternal(name);\n }\n\n /** Put a property value */\n public void put(PropertyValue prop) {\n boolean changed = putInternal(prop);\n if (changed) onChanged();\n }\n\n private long mVersion = 1L;\n private List<WeakReference<Runnable>> mChangeRunnables = new ArrayList<>();\n\n /** @hide */\n public long version() {\n return mVersion;\n }\n\n /** @hide */\n public void addChangeRunnable(Runnable changeRunnable) {\n synchronized (mChangeRunnables) {\n mChangeRunnables.add(new WeakReference<>(changeRunnable));\n }\n }\n\n protected void onChanged() {\n mVersion++;\n\n List<WeakReference<Runnable>> runnables;\n synchronized (mChangeRunnables) {\n runnables = new ArrayList<>(mChangeRunnables);\n }\n\n ListIterator<WeakReference<Runnable>> iter = runnables.listIterator();\n while(iter.hasNext()){\n WeakReference<Runnable> runnable = iter.next();\n if (runnable.get() != null) {\n runnable.get().run();\n } else {\n iter.remove();\n }\n }\n }\n\n protected abstract PropertyValue getInternal(String name);\n protected abstract List<PropertyValue> getAllInternal();\n protected abstract boolean putInternal(PropertyValue prop);\n}" }, { "identifier": "DeviceTestCallback", "path": "app/src/main/java/kr/or/kashi/hde/test/DeviceTestCallback.java", "snippet": "public interface DeviceTestCallback {\n default void onTestRunnerStarted() {}\n default void onTestRunnerFinished() {}\n default void onDeviceTestStarted(HomeDevice device) {}\n default void onDeviceTestExecuted(HomeDevice device, TestCase test, TestResult result, int progress) {}\n default void onDeviceTestFinished(HomeDevice device) {}\n}" }, { "identifier": "DebugLog", "path": "app/src/main/java/kr/or/kashi/hde/util/DebugLog.java", "snippet": "public interface DebugLog {\n public static final int EVENT = 1 << 1;\n public static final int TXRX = 1 << 2;\n\n class LoggerHolder {\n public DebugLog logger = null;\n }\n public static LoggerHolder sHolder = new LoggerHolder();\n\n public static void setLogger(DebugLog logger) {\n sHolder.logger = logger;\n }\n\n public static void printEvent(String text) {\n print(EVENT, text);\n }\n\n public static void printTxRx(String text) {\n print(TXRX, text);\n }\n\n public static void print(int type, String text) {\n if (sHolder.logger != null) {\n sHolder.logger.onPrint(type, text);\n }\n }\n\n void onPrint(int type, String text);\n}" }, { "identifier": "LocalPreferences", "path": "app/src/main/java/kr/or/kashi/hde/util/LocalPreferences.java", "snippet": "public class LocalPreferences {\n private static final int CURRENT_VERSION = 1;\n\n public class Pref {\n public static final String VERSION = \"version\";\n public static final String LAST_RUNNING = \"last_running\";\n public static final String PORT_INDEX = \"port_index\";\n public static final String PROTOCOL_INDEX = \"protocol_index\";\n public static final String MODE_INDEX = \"mode_index\";\n public static final String SELECTED_DEVICE_TYPES = \"selected_device_types\";\n public static final String RANGE_GROUP_CHECKED = \"range_group_checked\";\n public static final String RANGE_GROUP_LAST_ID = \"range_group_last_id\";\n public static final String RANGE_GROUP_FULL_CHECKED = \"range_group_full_CHECKED\";\n public static final String RANGE_SINGLE_CHECKED = \"range_single_checked\";\n public static final String RANGE_SINGLE_LAST_ID = \"range_single_last_id\";\n public static final String RANGE_SINGLE_FULL_CHECKED = \"range_single_full_checked\";\n public static final String DEBUG_LOG_EVENT_ENABLED = \"debug_log_event_enabled\";\n public static final String DEBUG_LOG_TXRX_ENABLED = \"debug_log_txrx_enabled\";\n public static final String POLLING_INTERVAL_INDEX = \"polling_interval_index\";\n };\n\n private static SharedPreferences sSharedPreferences = null;\n private static SharedPreferences.Editor sCurrentEditor = null;\n private static Handler sAutoCommitHandler = new Handler(Looper.getMainLooper());\n private static Runnable sOnCommitRunnalble = () -> {\n if (sCurrentEditor != null) {\n sCurrentEditor.commit();\n }\n };\n\n public static void init(Context context) {\n sSharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);\n if (sSharedPreferences.getInt(Pref.VERSION, 0) != CURRENT_VERSION) {\n sSharedPreferences.edit().clear().commit();\n sSharedPreferences.edit().putInt(Pref.VERSION, CURRENT_VERSION).commit();\n }\n }\n\n private static SharedPreferences prefs() {\n return sSharedPreferences;\n }\n\n private static SharedPreferences.Editor edit() {\n if (sCurrentEditor == null) {\n sCurrentEditor = prefs().edit();\n }\n if (sAutoCommitHandler.hasCallbacks(sOnCommitRunnalble) == false) {\n sAutoCommitHandler.postDelayed(sOnCommitRunnalble, 10);\n }\n return sCurrentEditor;\n }\n\n public static boolean getBoolean(String key) {\n return getBoolean(key, false);\n }\n\n public static boolean getBoolean(String key, boolean defValue) {\n return prefs().getBoolean(key, defValue);\n }\n\n public static void putBoolean(String key, boolean value) {\n edit().putBoolean(key, value);\n }\n\n public static int getInt(String key) {\n return getInt(key, 0);\n }\n\n public static int getInt(String key, int defValue) {\n return prefs().getInt(key, defValue);\n }\n\n public static void putInt(String key, int value) {\n edit().putInt(key, value);\n }\n\n public static Set<String> getSelectedDeviceTypes() {\n return new HashSet<>(prefs().getStringSet(Pref.SELECTED_DEVICE_TYPES, new HashSet<>()));\n }\n\n public static void putSelectedDeviceTypes(Set<String> types) {\n edit().putStringSet(Pref.SELECTED_DEVICE_TYPES, types);\n }\n}" }, { "identifier": "Pref", "path": "app/src/main/java/kr/or/kashi/hde/util/LocalPreferences.java", "snippet": "public class Pref {\n public static final String VERSION = \"version\";\n public static final String LAST_RUNNING = \"last_running\";\n public static final String PORT_INDEX = \"port_index\";\n public static final String PROTOCOL_INDEX = \"protocol_index\";\n public static final String MODE_INDEX = \"mode_index\";\n public static final String SELECTED_DEVICE_TYPES = \"selected_device_types\";\n public static final String RANGE_GROUP_CHECKED = \"range_group_checked\";\n public static final String RANGE_GROUP_LAST_ID = \"range_group_last_id\";\n public static final String RANGE_GROUP_FULL_CHECKED = \"range_group_full_CHECKED\";\n public static final String RANGE_SINGLE_CHECKED = \"range_single_checked\";\n public static final String RANGE_SINGLE_LAST_ID = \"range_single_last_id\";\n public static final String RANGE_SINGLE_FULL_CHECKED = \"range_single_full_checked\";\n public static final String DEBUG_LOG_EVENT_ENABLED = \"debug_log_event_enabled\";\n public static final String DEBUG_LOG_TXRX_ENABLED = \"debug_log_txrx_enabled\";\n public static final String POLLING_INTERVAL_INDEX = \"polling_interval_index\";\n};" }, { "identifier": "Utils", "path": "app/src/main/java/kr/or/kashi/hde/util/Utils.java", "snippet": "public final class Utils {\n private static final char[] HEX_DIGITS = \"0123456789ABCDEF\".toCharArray();\n\n public static final long SECOND_MS = 1000;\n public static final long MINUTE_MS = 60 * SECOND_MS;\n public static final long HOUR_MS = 60 * MINUTE_MS;\n public static final long DAY_MS = 24 * HOUR_MS;\n\n public static float[] toFloatArray(List<Float> list) {\n final int size = list.size();\n final float[] array = new float[size];\n for (int i = 0; i < size; ++i) {\n array[i] = list.get(i);\n }\n return array;\n }\n\n public static int[] toIntArray(List<Integer> list) {\n final int size = list.size();\n final int[] array = new int[size];\n for (int i = 0; i < size; ++i) {\n array[i] = list.get(i);\n }\n return array;\n }\n\n public static byte[] toByteArray(List<Byte> list) {\n final int size = list.size();\n final byte[] array = new byte[size];\n for (int i = 0; i < size; ++i) {\n array[i] = list.get(i);\n }\n return array;\n }\n\n public static String toHexString(byte b) {\n char[] buf = new char[2]; // We always want two digits.\n buf[0] = HEX_DIGITS[(b >> 4) & 0xf];\n buf[1] = HEX_DIGITS[b & 0xf];\n return new String(buf);\n }\n\n public static String toHexString(byte[] b) {\n return toHexString(b, b.length);\n }\n\n public static String toHexString(byte[] b, int length) {\n if (b == null) {\n return null;\n }\n int len = Math.min(length, b.length);\n StringBuilder sb = new StringBuilder(len * 3);\n for (int i = 0; i < len; i++) {\n sb.append(toHexString(b[i]));\n if (i < len-1) sb.append(\" \");\n }\n return sb.toString();\n }\n\n public static String toHexString(ByteBuffer byteBuffer) {\n byteBuffer.flip();\n int size = byteBuffer.remaining();\n if (size <= 0) return \"\";\n byte[] buffer = new byte[size];\n byteBuffer.get(buffer);\n return toHexString(buffer);\n }\n\n public static Point getDisplaySize(Context context) {\n Point size = new Point(0, 0);\n DisplayManager dm = (DisplayManager)context.getSystemService(Context.DISPLAY_SERVICE);\n Display display = dm.getDisplay(Display.DEFAULT_DISPLAY);\n display.getRealSize(size);\n return size;\n }\n\n public static void changeDensity(Context context, int densityDpi) {\n DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();\n Configuration config = context.getResources().getConfiguration();\n displayMetrics.densityDpi = densityDpi;\n config.densityDpi = densityDpi;\n displayMetrics.setTo(displayMetrics);\n config.setTo(config);\n context.getResources().updateConfiguration(config, displayMetrics);\n }\n\n public static Context createContextByDensity(Context context, int densityDpi) {\n Configuration config = context.getResources().getConfiguration();\n config.densityDpi = densityDpi;\n return context.createConfigurationContext(config);\n }\n\n public static Context createDensityAdjustedContextByHeight(Context context, int heightPixels) {\n return Utils.createContextByDensity(context, Utils.getTargetDensityByHeight(context, heightPixels));\n }\n\n public static int getTargetDensityByHeight(Context context, int heightPixels) {\n DisplayMetrics displayMetrics = new DisplayMetrics();\n WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);\n windowManager.getDefaultDisplay().getMetrics(displayMetrics);\n // e.g.) 600(heightPixels) : 1080(displayMetrics.heightPixels) = 160 : targetDendity\n return (displayMetrics.heightPixels * 160) / heightPixels;\n }\n\n public static void adjustDensityByHeight(Context context, int heightPixels) {\n changeDensity(context, getTargetDensityByHeight(context, heightPixels));\n }\n\n public static long daysToMillis(double days) {\n return (long)(days * DAY_MS);\n }\n\n public static double millisToDays(long ms) {\n return Math.round(((double)ms / (double)DAY_MS) * 100000.0) / 100000.0;\n }\n}" }, { "identifier": "CheckableListAdapter", "path": "app/src/main/java/kr/or/kashi/hde/widget/CheckableListAdapter.java", "snippet": "public class CheckableListAdapter<T> extends BaseAdapter {\n private Context mContext;\n private Set<T> mSelectedItems;\n private List<T> mAllItems;\n private Runnable mChangeRunnable;\n\n public CheckableListAdapter(Context context, List<T> allItems, Set<T> selectedItems) {\n mContext = context;\n mAllItems = allItems;\n mSelectedItems = selectedItems;\n }\n\n public void setChangeRunnable(Runnable runnable) {\n mChangeRunnable = runnable;\n }\n\n @Override\n public int getCount() {\n return mAllItems.size();\n }\n\n @Override\n public Object getItem(int position) {\n return mAllItems.get(position);\n }\n\n @Override\n public long getItemId(int position) {\n return 0;\n }\n\n @Override\n public View getView(int position, View convertView, ViewGroup parent) {\n final ViewHolder holder;\n if (convertView == null ) {\n LayoutInflater layoutInflator = LayoutInflater.from(mContext);\n convertView = layoutInflator.inflate(R.layout.checkable_list_item, parent, false);\n\n holder = new ViewHolder();\n holder.mTextView = convertView.findViewById(R.id.text);\n holder.mCheckBox = convertView.findViewById(R.id.checkbox);\n convertView.setTag(holder);\n } else {\n holder = (ViewHolder) convertView.getTag();\n }\n\n final int listPos = position;\n holder.mTextView.setText(mAllItems.get(listPos).toString());\n\n final T item = mAllItems.get(listPos);\n boolean isSel = mSelectedItems.contains(item);\n\n holder.mCheckBox.setOnCheckedChangeListener(null);\n holder.mCheckBox.setChecked(isSel);\n\n holder.mCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {\n @Override\n public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {\n if (isChecked) {\n mSelectedItems.add(item);\n } else {\n mSelectedItems.remove(item);\n }\n\n if (mChangeRunnable != null) {\n mChangeRunnable.run();\n }\n }\n });\n\n holder.mTextView.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View view) {\n holder.mCheckBox.toggle();\n }\n });\n\n return convertView;\n }\n\n private class ViewHolder {\n private TextView mTextView;\n private CheckBox mCheckBox;\n }\n}" }, { "identifier": "CustomLayoutManager", "path": "app/src/main/java/kr/or/kashi/hde/widget/CustomLayoutManager.java", "snippet": "public class CustomLayoutManager extends LinearLayoutManager {\n\n public CustomLayoutManager(Context context) {\n super(context, VERTICAL, false);\n }\n\n public CustomLayoutManager(Context context, int orientation, boolean reverseLayout) {\n super(context, orientation, reverseLayout);\n }\n\n @Override\n public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state,\n int position) {\n RecyclerView.SmoothScroller smoothScroller = new TopSnappedSmoothScroller(recyclerView.getContext());\n smoothScroller.setTargetPosition(position);\n startSmoothScroll(smoothScroller);\n }\n\n private class TopSnappedSmoothScroller extends LinearSmoothScroller {\n public TopSnappedSmoothScroller(Context context) {\n super(context);\n }\n\n @Override\n public PointF computeScrollVectorForPosition(int targetPosition) {\n return CustomLayoutManager.this.computeScrollVectorForPosition(targetPosition);\n }\n\n @Override\n protected int getVerticalSnapPreference() {\n return SNAP_TO_START;\n }\n }\n}" }, { "identifier": "DebugLogView", "path": "app/src/main/java/kr/or/kashi/hde/widget/DebugLogView.java", "snippet": "public class DebugLogView extends RecyclerView implements DebugLog {\n private static final String TAG = \"DebugLogView\";\n\n private final DebugLogAdapter mAdapter;\n private final LinearLayoutManager mLayoutManager;\n private final Handler mHandler = new Handler(Looper.getMainLooper());\n private OnTouchListener mOnRawTouchListener;\n private final Runnable mScrollRunnable = this::scrollToLast;\n private int mFilteredTypes = 0;\n private boolean mAutoScrollOn = true;\n private long mScrollDelay = 200;\n\n public DebugLogView(Context context, AttributeSet attrs) {\n super(context, attrs);\n mAdapter = new DebugLogAdapter(context);\n mLayoutManager = new LinearLayoutManager(context);\n setLayoutManager(mLayoutManager);\n setAdapter(mAdapter);\n setItemAnimator(null);\n setHasFixedSize(true);\n }\n\n public void setOnRawTouchListener(OnTouchListener l) {\n mOnRawTouchListener = l;\n }\n\n @Override\n protected void onFinishInflate () {\n super.onFinishInflate();\n }\n\n @Override\n public boolean dispatchTouchEvent(MotionEvent event) {\n if (mOnRawTouchListener != null) {\n mOnRawTouchListener.onTouch(this, event);\n }\n return super.dispatchTouchEvent(event);\n }\n\n @Override\n public void onPrint(int type, String text) {\n if ((mFilteredTypes & type) != type) {\n return;\n }\n\n mHandler.post(() -> {\n int oldPos = mLayoutManager.findFirstVisibleItemPosition();\n int oldCount = mAdapter.getLogCount();\n\n mAdapter.addLog(text);\n\n int newCount = mAdapter.getLogCount();\n\n boolean autoScrolled = triggerAutoScrollIf();\n if (!autoScrolled && oldCount > newCount) {\n// int reduce = oldCount - newCount;\n// int newPos = oldPos + reduce;\n// scrollToPosition(newPos);\n }\n });\n }\n\n public void clear() {\n mAdapter.clearAll();\n }\n\n public void setFilter(int typeBits) {\n mFilteredTypes = typeBits;\n }\n\n public void setAutoScroll(boolean on) {\n if (on == mAutoScrollOn) return;\n mAutoScrollOn = on;\n\n if (on == false) {\n mHandler.removeCallbacks(mScrollRunnable);\n } else {\n triggerAutoScrollIf();\n }\n }\n\n public void setScrollDelay(long delayMs) {\n mScrollDelay = delayMs;\n }\n\n public void setTextSize(int textSizeSp) {\n// mDebugLogText.setTextSize(textSizeSp);\n }\n\n private boolean triggerAutoScrollIf() {\n if (!mAutoScrollOn) {\n return false;\n }\n\n if (mScrollDelay <= 0) {\n scrollToLast();\n } else if (!mHandler.hasCallbacks(mScrollRunnable)) {\n mHandler.postDelayed(mScrollRunnable, mScrollDelay);\n }\n\n return true;\n }\n\n private void scrollToLast() {\n scrollToPosition(mAdapter.getItemCount() - 1);\n }\n}" }, { "identifier": "DeviceInfoView", "path": "app/src/main/java/kr/or/kashi/hde/widget/DeviceInfoView.java", "snippet": "public class DeviceInfoView extends LinearLayout {\n private static final String TAG = DeviceInfoView.class.getSimpleName();\n private final Context mContext;\n\n private TextView mDeviceTypeText;\n private TextView mDeviceIdText;\n private TextView mDeviceSubIdText;\n\n public DeviceInfoView(Context context, @Nullable AttributeSet attrs) {\n super(context, attrs);\n mContext = context;\n }\n\n @Override\n protected void onFinishInflate() {\n super.onFinishInflate();\n\n mDeviceTypeText = findViewById(R.id.device_type_text);\n mDeviceIdText = findViewById(R.id.device_id_text);\n mDeviceSubIdText = findViewById(R.id.device_sub_id_text);\n }\n\n public void setDevice(HomeDevice device) {\n if (device != null) {\n mDeviceTypeText.setText(\"[\" + HomeDevice.typeToString(device.getType()) + \"]\");\n mDeviceIdText.setText(device.getAddress().substring(2, 4));\n mDeviceSubIdText.setText(device.getAddress().substring(4, 6));\n setVisibility(View.VISIBLE);\n } else {\n setVisibility(View.INVISIBLE);\n }\n }\n}" }, { "identifier": "DeviceListAdapter", "path": "app/src/main/java/kr/or/kashi/hde/widget/DeviceListAdapter.java", "snippet": "public class DeviceListAdapter extends RecyclerView.Adapter<DeviceListAdapter.Holder> {\n private static final String TAG = \"DeviceListAdapter\";\n\n private final Context mContext;\n private final List<HomeDevice> mDeviceList;\n private final Listener mListener;\n private Holder mSelectedHolder = null;\n private HomeDevice mSelectedDevice = null;\n private long mControlRequestTime = -1;\n\n public DeviceListAdapter(Context context, List<HomeDevice> deviceList, Listener listener) {\n mContext = context;\n mDeviceList = new ArrayList<>(deviceList);\n mListener = listener;\n\n Collections.sort(mDeviceList, (Object o1, Object o2) -> {\n HomeDevice d1 = (HomeDevice) o1;\n HomeDevice d2 = (HomeDevice) o2;\n return d1.getAddress().toString().compareTo(d2.getAddress().toString());\n });\n }\n\n @Override\n public Holder onCreateViewHolder(ViewGroup parent, int viewType) {\n View itemView = LayoutInflater.from(mContext).inflate(R.layout.device_list_item, parent, false);\n return new Holder(itemView);\n }\n\n @Override\n public void onBindViewHolder(Holder holder, int position) {\n final HomeDevice device = mDeviceList.get(position);\n holder.bind(device);\n holder.setSelected((device == mSelectedDevice));\n }\n\n @Override\n public int getItemCount() {\n return mDeviceList.size();\n }\n\n private void setSelectedItem(Holder holder) {\n if (mSelectedHolder != null) {\n mSelectedHolder.setSelected(false);\n }\n if (holder != null) {\n holder.setSelected(true);\n }\n mSelectedHolder = holder;\n mSelectedDevice = holder.device;\n }\n\n public interface Listener {\n void onItemClicked(Holder holder);\n void onItemSwitchClicked(Holder holder, boolean isChecked);\n void onItemRemoveClicked(Holder holder);\n }\n\n public class Holder extends RecyclerView.ViewHolder\n implements View.OnClickListener, HomeDevice.Callback {\n public final View rootView;\n public final TextView deviceText;\n public final TextView elapsedText;\n public final Switch onoffSwitch;\n public final Button removeButton;\n public HomeDevice device;\n\n public Holder(View itemView) {\n super(itemView);\n rootView = itemView;\n rootView.setOnClickListener(this);\n deviceText = itemView.findViewById(R.id.device_text);\n elapsedText = itemView.findViewById(R.id.elapsed_text);\n onoffSwitch = itemView.findViewById(R.id.onoff_switch);\n onoffSwitch.setOnClickListener(this);\n removeButton = itemView.findViewById(R.id.remove_button);\n removeButton.setOnClickListener(this);\n }\n\n public void bind(HomeDevice newDevice) {\n if (this.device != null) {\n this.device.removeCallback(this);\n }\n\n this.device = newDevice;\n\n if (this.device != null) {\n this.device.addCallback(this);\n }\n\n updateStates();\n }\n\n public void setSelected(boolean selected) {\n String selectedColor = selected ? \"#FFAAAAAA\" : \"#00000000\";\n this.rootView.setBackgroundColor(Color.parseColor(selectedColor));\n }\n\n public void setConnected(boolean conntected) {\n int connectedColor = conntected ? 0xFF000000 : 0xFF888888;\n this.deviceText.setTextColor(connectedColor);\n }\n\n public void updateStates() {\n final String text =\n this.device.getAddress() + \", \" +\n this.device.getName();\n this.deviceText.setText(text);\n\n this.elapsedText.setText(\"\");\n\n if (mControlRequestTime != -1) {\n long elapsedTime = SystemClock.uptimeMillis() - mControlRequestTime;\n this.elapsedText.setText(elapsedTime + \"ms\");\n mControlRequestTime = -1;\n } else {\n this.elapsedText.setText(\"\");\n }\n\n this.onoffSwitch.setChecked(this.device.isOn());\n\n setConnected(this.device.isConnected());\n }\n\n @Override\n public void onClick(View v) {\n setSelectedItem(this);\n if (v == rootView) {\n mListener.onItemClicked(this);\n } else if (v == onoffSwitch) {\n mListener.onItemSwitchClicked(this, onoffSwitch.isChecked());\n mControlRequestTime = SystemClock.uptimeMillis();\n } else if (v == removeButton) {\n mListener.onItemRemoveClicked(this);\n }\n }\n\n @Override\n public void onPropertyChanged(HomeDevice device, PropertyMap props) {\n updateStates();\n }\n\n @Override\n public void onErrorOccurred(HomeDevice device, int error) {\n }\n }\n}" }, { "identifier": "DeviceTestPartView", "path": "app/src/main/java/kr/or/kashi/hde/widget/DeviceTestPartView.java", "snippet": "public class DeviceTestPartView extends LinearLayout implements DeviceTestCallback {\n private static final String TAG = DeviceTestPartView.class.getSimpleName();\n private final Context mContext;\n private final Handler mHandler;\n private final DeviceTestRunner mDeviceTestRunner;\n private final DeviceTestReportDialog mReportDialog;\n\n private TextView mTestStateText;\n private TextView mTestProgressText;\n private Button mReportButton;\n private TestResultView mTestResultView;\n\n public DeviceTestPartView(Context context, @Nullable AttributeSet attrs) {\n super(context, attrs);\n mContext = context;\n mHandler = new Handler(Looper.getMainLooper());\n mDeviceTestRunner = new DeviceTestRunner(mHandler);\n mReportDialog = new DeviceTestReportDialog(context);\n }\n\n @Override\n protected void onFinishInflate() {\n super.onFinishInflate();\n\n mTestStateText = findViewById(R.id.test_state_text);\n mTestProgressText = findViewById(R.id.test_progress_text);\n\n mReportButton = findViewById(R.id.report_button);\n mReportButton.setOnClickListener(view -> onReportClicked());\n\n mTestResultView = findViewById(R.id.test_result_view);\n\n mDeviceTestRunner.addCallback(this);\n mDeviceTestRunner.addCallback(mTestResultView);\n mDeviceTestRunner.addCallback(mReportDialog);\n }\n\n public DeviceTestRunner getTestRunner() {\n return mDeviceTestRunner;\n }\n\n public boolean startTest(List<HomeDevice> devices) {\n return mDeviceTestRunner.start(devices);\n }\n\n public void stopTest() {\n mDeviceTestRunner.stop();\n }\n\n private void onReportClicked() {\n mReportDialog.show();\n }\n\n @Override\n public void onTestRunnerStarted() {\n DebugLog.printEvent(\"onTestRunnerStarted\");\n mReportButton.setEnabled(false);\n mReportButton.setTextColor(0xFF888888);\n mTestResultView.clear();\n mTestStateText.setText(\"RUNNING\");\n mTestProgressText.setText(\"0%\");\n }\n\n @Override\n public void onTestRunnerFinished() {\n DebugLog.printEvent(\"onTestRunnerFinished\");\n mReportButton.setEnabled(true);\n mReportButton.setTextColor(0xFF000000);\n mTestStateText.setText(\"STOPPED\");\n mTestProgressText.setText(\"100%\");\n }\n\n @Override\n public void onDeviceTestStarted(HomeDevice device) {\n DebugLog.printEvent(\"onDeviceTestStarted device:\" + device.getAddress());\n }\n\n @Override\n public void onDeviceTestExecuted(HomeDevice device, TestCase test, TestResult result, int progress) {\n DebugLog.printEvent(\"test... device:\" + device.getAddress() + \" case:\" + test.getName() + \" pass:\" + result.wasSuccessful());\n mTestProgressText.setText(progress + \"%\");\n }\n\n @Override\n public void onDeviceTestFinished(HomeDevice device) {\n DebugLog.printEvent(\"onDeviceTestFinished device:\" + device.getAddress());\n }\n}" }, { "identifier": "HomeDeviceView", "path": "app/src/main/java/kr/or/kashi/hde/widget/HomeDeviceView.java", "snippet": "public class HomeDeviceView<T extends HomeDevice> extends LinearLayout implements HomeDevice.Callback {\n private static final String TAG = HomeDeviceView.class.getSimpleName();\n private final Context mContext;\n protected T mDevice;\n protected boolean mIsSlave;\n\n public HomeDeviceView(Context context, @Nullable AttributeSet attrs) {\n super(context, attrs);\n mContext = context;\n mIsSlave = (LocalPreferences.getInt(LocalPreferences.Pref.MODE_INDEX) == 1);\n }\n\n public boolean isMaster() {\n return !isSlave();\n }\n\n public boolean isSlave() {\n return mIsSlave;\n }\n\n @Override\n protected void onFinishInflate () {\n super.onFinishInflate();\n }\n\n @Override\n protected void onAttachedToWindow() {\n super.onAttachedToWindow();\n\n if (mDevice != null) {\n mDevice.addCallback(this);\n final PropertyMap props = mDevice.getReadPropertyMap();\n onUpdateProperty(props, props);\n }\n }\n\n @Override\n protected void onDetachedFromWindow() {\n super.onDetachedFromWindow();\n\n if (mDevice != null) {\n mDevice.removeCallback(this);\n }\n }\n\n @Override\n public void onPropertyChanged(HomeDevice device, PropertyMap props) {\n onUpdateProperty(mDevice.getReadPropertyMap(), props);\n }\n\n @Override\n public void onErrorOccurred(HomeDevice device, int error) {\n // No operation\n }\n\n public void onUpdateProperty(PropertyMap props, PropertyMap changed) {\n // Override it\n }\n\n protected T device() {\n return mDevice;\n }\n\n public void setDevice(T device) {\n mDevice = device;\n }\n}" }, { "identifier": "NullRecyclerViewAdapter", "path": "app/src/main/java/kr/or/kashi/hde/widget/NullRecyclerViewAdapter.java", "snippet": "public class NullRecyclerViewAdapter extends RecyclerView.Adapter<NullRecyclerViewAdapter.Holder> {\n public NullRecyclerViewAdapter() { }\n\n @Override\n public Holder onCreateViewHolder(ViewGroup parent, int viewType) {\n return new Holder(null);\n }\n\n @Override\n public void onBindViewHolder(Holder holder, int position) { }\n\n @Override\n public int getItemCount() {\n return 0;\n }\n\n public class Holder extends RecyclerView.ViewHolder {\n public Holder(View itemView) {\n super(itemView);\n }\n }\n}" } ]
import android.annotation.SuppressLint; import android.content.Context; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.CheckBox; import android.widget.Checkable; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.SeekBar; import android.widget.Spinner; import android.widget.TextView; import android.widget.ToggleButton; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.RecyclerView; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import kr.or.kashi.hde.base.PropertyMap; import kr.or.kashi.hde.test.DeviceTestCallback; import kr.or.kashi.hde.util.DebugLog; import kr.or.kashi.hde.util.LocalPreferences; import kr.or.kashi.hde.util.LocalPreferences.Pref; import kr.or.kashi.hde.util.Utils; import kr.or.kashi.hde.widget.CheckableListAdapter; import kr.or.kashi.hde.widget.CustomLayoutManager; import kr.or.kashi.hde.widget.DebugLogView; import kr.or.kashi.hde.widget.DeviceInfoView; import kr.or.kashi.hde.widget.DeviceListAdapter; import kr.or.kashi.hde.widget.DeviceTestPartView; import kr.or.kashi.hde.widget.HomeDeviceView; import kr.or.kashi.hde.widget.NullRecyclerViewAdapter;
9,704
/* * Copyright (C) 2023 Korea Association of AI Smart Home. * Copyright (C) 2023 KyungDong Navien Co, Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kr.or.kashi.hde; public class MainFragment extends Fragment { private static final String TAG = "HomeTestFragment"; private static final String SAVED_DEVICES_FILENAME = "saved_devices"; private final Context mContext; private final HomeNetwork mNetwork; private HomeDevice mSelectedDevice; private CheckBox mEventLogCheck; private CheckBox mTxRxLogCheck; private ToggleButton mAutoScrollToggle; private DebugLogView mDebugLogView; private ToggleButton mDiscoveryToggle; private ListView mDeviceTypeListView; private CheckBox mGroupIdCheckBox; private SeekBar mGroupIdSeekBar; private TextView mGroupIdTextView; private ToggleButton mGroupFullToggle; private CheckBox mSingleIdCheckBox; private SeekBar mSingleIdSeekBar; private TextView mSingleIdTextView; private ToggleButton mSingleFullToggle; private TextView mRangeTextView; private Spinner mPollingIntervalsSpinner; private ToggleButton mAutoTestToggle; private TextView mDeviceCountText; private RecyclerView mDeviceListView; private ProgressBar mDiscoveryProgress; private ViewGroup mDeviceDetailPart; private DeviceInfoView mDeviceInfoView; private ViewGroup mDeviceControlArea; private DeviceTestPartView mDeviceTestPart; private Map<String, Integer> mDeviceToKsIdMap = new TreeMap<>(); private Set<String> mSelectedDeviceTypes = new HashSet<>(); private DeviceDiscovery.Callback mDiscoveryCallback = new DeviceDiscovery.Callback() { List<HomeDevice> mStagedDevices = new ArrayList<>(); @Override public void onDiscoveryStarted() { debug("onDiscoveryStarted "); mDiscoveryProgress.setVisibility(View.VISIBLE); mStagedDevices.clear(); } @Override public void onDiscoveryFinished() { debug("onDiscoveryFinished "); if (mStagedDevices.size() > 0) { for (HomeDevice device: mStagedDevices) { mNetwork.addDevice(device); } mStagedDevices.clear(); } // Wait for a while until new devices are up to date by polling its state new Handler().postDelayed(() -> { updateDeviceList(); mDiscoveryProgress.setVisibility(View.GONE); mDiscoveryToggle.setChecked(false); }, 1000); } @Override public void onDeviceDiscovered(HomeDevice device) { final String clsName = device.getClass().getSimpleName(); debug("onDeviceDiscovered " + clsName + " " + device.getAddress()); mStagedDevices.add(device); } }; private HomeDevice.Callback mDeviceCallback = new HomeDevice.Callback() { public void onPropertyChanged(HomeDevice device, PropertyMap props) { for (String name : props.toMap().keySet()) { debug("onPropertyChanged - " + name + " : " + device.dc().getProperty(name).getValue()); } } public void onErrorOccurred(HomeDevice device, int error) { debug("onErrorOccurred:" + error); } }; public MainFragment(Context context, HomeNetwork network) { mContext = context; mNetwork = network; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mNetwork.getDeviceDiscovery().addCallback(mDiscoveryCallback); mDeviceToKsIdMap.put("AirConditioner", 0x02); mDeviceToKsIdMap.put("BatchSwitch", 0x33); mDeviceToKsIdMap.put("Curtain", 0x13); mDeviceToKsIdMap.put("DoorLock", 0x31); mDeviceToKsIdMap.put("GasValve", 0x12); mDeviceToKsIdMap.put("HouseMeter", 0x30); mDeviceToKsIdMap.put("Light", 0x0E); mDeviceToKsIdMap.put("PowerSaver", 0x39); mDeviceToKsIdMap.put("Thermostat", 0x36); mDeviceToKsIdMap.put("Ventilation", 0x32); mSelectedDeviceTypes = LocalPreferences.getSelectedDeviceTypes(); } @SuppressLint("ClickableViewAccessibility") @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstance) { final View v = inflater.inflate(R.layout.main, container, false); v.findViewById(R.id.clear_log_button).setOnClickListener(view -> { mDebugLogView.clear(); mAutoScrollToggle.setChecked(true); mDebugLogView.setAutoScroll(true); }); mEventLogCheck = (CheckBox) v.findViewById(R.id.event_log_check);
/* * Copyright (C) 2023 Korea Association of AI Smart Home. * Copyright (C) 2023 KyungDong Navien Co, Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package kr.or.kashi.hde; public class MainFragment extends Fragment { private static final String TAG = "HomeTestFragment"; private static final String SAVED_DEVICES_FILENAME = "saved_devices"; private final Context mContext; private final HomeNetwork mNetwork; private HomeDevice mSelectedDevice; private CheckBox mEventLogCheck; private CheckBox mTxRxLogCheck; private ToggleButton mAutoScrollToggle; private DebugLogView mDebugLogView; private ToggleButton mDiscoveryToggle; private ListView mDeviceTypeListView; private CheckBox mGroupIdCheckBox; private SeekBar mGroupIdSeekBar; private TextView mGroupIdTextView; private ToggleButton mGroupFullToggle; private CheckBox mSingleIdCheckBox; private SeekBar mSingleIdSeekBar; private TextView mSingleIdTextView; private ToggleButton mSingleFullToggle; private TextView mRangeTextView; private Spinner mPollingIntervalsSpinner; private ToggleButton mAutoTestToggle; private TextView mDeviceCountText; private RecyclerView mDeviceListView; private ProgressBar mDiscoveryProgress; private ViewGroup mDeviceDetailPart; private DeviceInfoView mDeviceInfoView; private ViewGroup mDeviceControlArea; private DeviceTestPartView mDeviceTestPart; private Map<String, Integer> mDeviceToKsIdMap = new TreeMap<>(); private Set<String> mSelectedDeviceTypes = new HashSet<>(); private DeviceDiscovery.Callback mDiscoveryCallback = new DeviceDiscovery.Callback() { List<HomeDevice> mStagedDevices = new ArrayList<>(); @Override public void onDiscoveryStarted() { debug("onDiscoveryStarted "); mDiscoveryProgress.setVisibility(View.VISIBLE); mStagedDevices.clear(); } @Override public void onDiscoveryFinished() { debug("onDiscoveryFinished "); if (mStagedDevices.size() > 0) { for (HomeDevice device: mStagedDevices) { mNetwork.addDevice(device); } mStagedDevices.clear(); } // Wait for a while until new devices are up to date by polling its state new Handler().postDelayed(() -> { updateDeviceList(); mDiscoveryProgress.setVisibility(View.GONE); mDiscoveryToggle.setChecked(false); }, 1000); } @Override public void onDeviceDiscovered(HomeDevice device) { final String clsName = device.getClass().getSimpleName(); debug("onDeviceDiscovered " + clsName + " " + device.getAddress()); mStagedDevices.add(device); } }; private HomeDevice.Callback mDeviceCallback = new HomeDevice.Callback() { public void onPropertyChanged(HomeDevice device, PropertyMap props) { for (String name : props.toMap().keySet()) { debug("onPropertyChanged - " + name + " : " + device.dc().getProperty(name).getValue()); } } public void onErrorOccurred(HomeDevice device, int error) { debug("onErrorOccurred:" + error); } }; public MainFragment(Context context, HomeNetwork network) { mContext = context; mNetwork = network; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mNetwork.getDeviceDiscovery().addCallback(mDiscoveryCallback); mDeviceToKsIdMap.put("AirConditioner", 0x02); mDeviceToKsIdMap.put("BatchSwitch", 0x33); mDeviceToKsIdMap.put("Curtain", 0x13); mDeviceToKsIdMap.put("DoorLock", 0x31); mDeviceToKsIdMap.put("GasValve", 0x12); mDeviceToKsIdMap.put("HouseMeter", 0x30); mDeviceToKsIdMap.put("Light", 0x0E); mDeviceToKsIdMap.put("PowerSaver", 0x39); mDeviceToKsIdMap.put("Thermostat", 0x36); mDeviceToKsIdMap.put("Ventilation", 0x32); mSelectedDeviceTypes = LocalPreferences.getSelectedDeviceTypes(); } @SuppressLint("ClickableViewAccessibility") @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstance) { final View v = inflater.inflate(R.layout.main, container, false); v.findViewById(R.id.clear_log_button).setOnClickListener(view -> { mDebugLogView.clear(); mAutoScrollToggle.setChecked(true); mDebugLogView.setAutoScroll(true); }); mEventLogCheck = (CheckBox) v.findViewById(R.id.event_log_check);
mEventLogCheck.setChecked(LocalPreferences.getBoolean(Pref.DEBUG_LOG_EVENT_ENABLED, true));
4
2023-11-10 01:19:44+00:00
12k
erhenjt/twoyi2
app/src/main/java/io/twoyi/ui/SelectAppActivity.java
[ { "identifier": "AppKV", "path": "app/src/main/java/io/twoyi/utils/AppKV.java", "snippet": "public class AppKV {\n\n\n private static final String PREF_NAME = \"app_kv\";\n\n public static final String ADD_APP_NOT_SHOW_SYSTEM= \"add_app_not_show_system\";\n public static final String ADD_APP_NOT_SHOW_ADDED = \"add_app_not_show_added\";\n public static final String SHOW_ANDROID12_TIPS = \"show_android12_tips_v2\";\n public static final String ADD_APP_NOT_SHOW_32BIT = \"add_app_not_show_32bit\";\n\n // 是否应该重新安装 ROM\n // 1. 恢复出厂设置\n // 2. 替换 ROM\n public static final String FORCE_ROM_BE_RE_INSTALL = \"rom_should_be_re_install\";\n\n // 是否应该使用第三方 ROM\n public static final String SHOULD_USE_THIRD_PARTY_ROM = \"should_use_third_party_rom\";\n public static boolean getBooleanConfig(Context context, String key, boolean fallback) {\n return getPref(context).getBoolean(key, fallback);\n }\n\n @SuppressLint(\"ApplySharedPref\")\n public static void setBooleanConfig(Context context, String key, boolean value) {\n getPref(context).edit().putBoolean(key, value).commit();\n }\n\n private static SharedPreferences getPref(Context context) {\n return context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);\n }\n}" }, { "identifier": "CacheManager", "path": "app/src/main/java/io/twoyi/utils/CacheManager.java", "snippet": "public class CacheManager {\n\n private static final byte[] LABEL_LOCK = new byte[0];\n\n private static ACache sLabelCache;\n\n public static ACache getLabelCache(Context context) {\n synchronized (LABEL_LOCK) {\n if (sLabelCache != null) {\n return sLabelCache;\n }\n Context appContext = context.getApplicationContext();\n if (appContext == null) {\n appContext = context;\n }\n\n sLabelCache = ACache.get(appContext, \"labelCache\");\n return sLabelCache;\n }\n }\n\n public static String getLabel(Context context, ApplicationInfo info, PackageManager pm) {\n PackageManager packageManager;\n if (pm != null) {\n packageManager = pm;\n } else {\n packageManager = context.getPackageManager();\n }\n\n if (info == null) {\n return null;\n }\n\n String key = info.packageName;\n ACache labelCache = getLabelCache(context);\n synchronized (LABEL_LOCK) {\n String label = labelCache.getAsString(key);\n if (label == null) {\n // 缓存没有,那么直接读\n String label1 = info.loadLabel(packageManager).toString();\n labelCache.put(key, label1);\n return label1;\n }\n return label;\n }\n }\n}" }, { "identifier": "IOUtils", "path": "app/src/main/java/io/twoyi/utils/IOUtils.java", "snippet": "@Keep\npublic class IOUtils {\n\n public static void ensureCreated(File file) {\n if (!file.exists()) {\n boolean ret = file.mkdirs();\n if (!ret) {\n throw new RuntimeException(\"create dir: \" + file + \" failed\");\n }\n }\n }\n\n public static boolean deleteDir(File dir) {\n if (dir == null) {\n return false;\n }\n boolean success = true;\n if (dir.isDirectory()) {\n String[] children = dir.list();\n for (String file : children) {\n boolean ret = deleteDir(new File(dir, file));\n if (!ret) {\n success = false;\n }\n }\n if (success) {\n // if all subdirectory are deleted, delete the dir itself.\n return dir.delete();\n }\n }\n return dir.delete();\n }\n\n public static void deleteAll(List<File> files) {\n if (files.isEmpty()) {\n return;\n }\n\n for (File file : files) {\n //noinspection ResultOfMethodCallIgnored\n file.delete();\n }\n }\n\n public static void copyFile(File source, File target) throws IOException {\n FileInputStream inputStream = null;\n FileOutputStream outputStream = null;\n try {\n inputStream = new FileInputStream(source);\n outputStream = new FileOutputStream(target);\n FileChannel iChannel = inputStream.getChannel();\n FileChannel oChannel = outputStream.getChannel();\n\n ByteBuffer buffer = ByteBuffer.allocate(1024);\n while (true) {\n buffer.clear();\n int r = iChannel.read(buffer);\n if (r == -1)\n break;\n buffer.limit(buffer.position());\n buffer.position(0);\n oChannel.write(buffer);\n }\n } finally {\n closeSilently(inputStream);\n closeSilently(outputStream);\n }\n }\n\n public static void closeSilently(Closeable closeable) {\n if (closeable == null) {\n return;\n }\n try {\n closeable.close();\n } catch (IOException e) {\n // e.printStackTrace();\n }\n }\n\n public static void setPermissions(String path, int mode, int uid, int gid) {\n try {\n Class<?> fileUtilsClass = Class.forName(\"android.os.FileUtils\");\n Method setPermissions = fileUtilsClass.getDeclaredMethod(\"setPermissions\", String.class, int.class, int.class, int.class);\n setPermissions.setAccessible(true);\n setPermissions.invoke(null, path, mode, uid, gid);\n } catch (Throwable e) {\n e.printStackTrace();\n }\n }\n\n public static void writeContent(File file, String content) {\n if (file == null || TextUtils.isEmpty(content)) {\n return;\n }\n FileWriter fileWriter = null;\n try {\n fileWriter = new FileWriter(file);\n fileWriter.write(content);\n fileWriter.flush();\n } catch (Throwable ignored) {\n } finally {\n IOUtils.closeSilently(fileWriter);\n }\n }\n\n public static String readContent(File file) {\n if (file == null) {\n return null;\n }\n BufferedReader fileReader = null;\n try {\n fileReader = new BufferedReader(new FileReader(file));\n StringBuilder sb = new StringBuilder();\n String line;\n while ((line = fileReader.readLine()) != null) {\n sb.append(line);\n sb.append('\\n');\n }\n return sb.toString().trim();\n } catch (Throwable ignored) {\n return null;\n } finally {\n IOUtils.closeSilently(fileReader);\n }\n }\n\n public static boolean deleteDirectory(File directory) {\n try {\n Files.walk(directory.toPath())\n .sorted(Comparator.reverseOrder())\n .map(Path::toFile)\n .forEach(File::delete);\n return true;\n } catch (IOException e) {\n return false;\n }\n }\n}" }, { "identifier": "Installer", "path": "app/src/main/java/io/twoyi/utils/Installer.java", "snippet": "public class Installer {\n\n public interface InstallResult {\n void onSuccess(List<File> files);\n\n void onFail(List<File> files, String msg);\n }\n\n private static final String TAG = \"Installer\";\n\n public static final int REQUEST_INSTALL_APP = 101;\n\n public static void installAsync(Context context, String path, InstallResult callback) {\n installAsync(context, Collections.singletonList(new File(path)), callback);\n }\n\n public static void installAsync(Context context, List<File> files, InstallResult callback) {\n new Thread(() -> install(context, files, callback)).start();\n }\n\n public static void install(Context context, List<File> files, InstallResult callback) {\n\n// Shell.enableVerboseLogging = true;\n\n String nativeLibraryDir = context.getApplicationInfo().nativeLibraryDir;\n String adbPath = nativeLibraryDir + File.separator + \"libadb.so\";\n\n String connectTarget = \"localhost:22122\";\n\n final int ADB_PORT = 9563;\n\n String adbCommand = String.format(Locale.US, \"%s -P %d connect %s\", adbPath, ADB_PORT, connectTarget);\n\n String envPath = context.getCacheDir().getAbsolutePath();\n String envCmd = String.format(\"export TMPDIR=%s;export HOME=%s;\", envPath, envPath);\n\n String adbServerCommand = String.format(Locale.US, \"%s -P %d nodaemon server\", adbPath, ADB_PORT);\n ShellUtil.newSh().newJob().add(envCmd).add(adbServerCommand).submit();\n\n Shell shell = ShellUtil.newSh();\n\n Shell.Result result = shell.newJob().add(envCmd).add(adbCommand).to(new ArrayList<>(), new ArrayList<>()).exec();\n\n String errMsg = Arrays.toString(result.getErr().toArray(new String[0]));\n String outMsg = Arrays.toString(result.getOut().toArray(new String[0]));\n\n Log.w(TAG, \"success: \" + result.isSuccess() + \" err: \" + errMsg + \" out: \" + outMsg);\n\n boolean connected = false;\n for (String s : result.getOut()) {\n\n // connected to localhost:22122\n // already connected to localhost\n if (s.contains(\"connected to\")) {\n connected = true;\n }\n }\n\n try {\n shell.waitAndClose(1, TimeUnit.SECONDS);\n } catch (Throwable ignored) {\n }\n\n if (!connected) {\n if (callback != null) {\n callback.onFail(files, \"Adb connect failed!\");\n }\n return;\n }\n\n StringBuilder sb = new StringBuilder();\n for (File file : files) {\n sb.append(file.getAbsolutePath()).append(\" \");\n }\n\n String fileArgs = sb.toString();\n\n String installCommand;\n if (files.size() == 1) {\n installCommand = String.format(Locale.US, \"%s -P %d -s %s install -t -r %s\", adbPath, ADB_PORT, connectTarget, fileArgs);\n } else {\n // http://aospxref.com/android-10.0.0_r47/xref/system/core/adb/client/adb_install.cpp#447\n installCommand = String.format(Locale.US, \"%s -P %d -s %s install-multiple -t -r %s\", adbPath, ADB_PORT, connectTarget, fileArgs);\n }\n\n Log.w(TAG, \"installCommand: \" + installCommand);\n\n Shell installShell = ShellUtil.newSh();\n\n installShell.newJob().add(envCmd).add(installCommand).to(new ArrayList<>(), new ArrayList<>()).submit(out1 -> {\n Log.w(TAG, \"install result: \" + out1.isSuccess());\n\n if (callback == null) {\n return;\n }\n if (out1.isSuccess()) {\n callback.onSuccess(files);\n } else {\n String msg = Arrays.toString(out1.getErr().toArray(new String[0]));\n Log.w(TAG, \"msg: \" + msg);\n\n callback.onFail(files, msg);\n }\n });\n }\n\n public static boolean checkFile(Context context, List<File> files) {\n boolean valid = true;\n for (File file : files) {\n if (!checkFile(context, file.getAbsolutePath())) {\n valid = false;\n break;\n }\n }\n\n return valid;\n }\n\n public static boolean checkFile(Context context, String path) {\n if (path == null) {\n return false;\n }\n\n PackageManager pm = context.getPackageManager();\n if (pm == null) {\n return false;\n }\n\n PackageInfo packageInfo = pm.getPackageArchiveInfo(path, 0);\n\n if (packageInfo == null) {\n Toast.makeText(context.getApplicationContext(), R.string.check_file_invlid_apk, Toast.LENGTH_SHORT).show();\n return false;\n }\n\n String packageName = packageInfo.packageName;\n\n if (TextUtils.equals(packageName, context.getPackageName())) {\n Toast.makeText(context.getApplicationContext(), R.string.check_file_create_self_tip, Toast.LENGTH_SHORT).show();\n return false;\n }\n\n return true;\n }\n}" }, { "identifier": "UIHelper", "path": "app/src/main/java/io/twoyi/utils/UIHelper.java", "snippet": "public class UIHelper {\n private static final AndroidDeferredManager gDM = new AndroidDeferredManager();\n\n public static ExecutorService GLOBAL_EXECUTOR = Executors.newCachedThreadPool();\n\n public static AndroidDeferredManager defer() {\n return gDM;\n }\n\n public static void dismiss(Dialog dialog) {\n if (dialog == null) {\n return;\n }\n\n try {\n dialog.dismiss();\n } catch (Throwable ignored) {\n ignored.printStackTrace();\n }\n }\n\n public static void openWeiXin(Context context, String weixin) {\n try {\n // 获取剪贴板管理服务\n ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);\n if (cm == null) {\n return;\n }\n cm.setText(weixin);\n\n Intent intent = new Intent(Intent.ACTION_MAIN);\n ComponentName cmp = new ComponentName(\"com.tencent.mm\", \"com.tencent.mm.ui.LauncherUI\");\n intent.addCategory(Intent.CATEGORY_LAUNCHER);\n intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);\n intent.setComponent(cmp);\n\n context.startActivity(intent);\n Toast.makeText(context, R.string.wechat_public_account_tips, Toast.LENGTH_LONG).show();\n } catch (Throwable e) {\n Toast.makeText(context, \"WeChat is not installed.\", Toast.LENGTH_SHORT).show();\n }\n }\n\n public static void show(Dialog dialog) {\n if (dialog == null) {\n return;\n }\n\n try {\n dialog.show();\n } catch (Throwable ignored) {\n ignored.printStackTrace();\n }\n }\n\n public static AlertDialog.Builder getDialogBuilder(Context context) {\n AlertDialog.Builder builder = new AlertDialog.Builder(context, com.google.android.material.R.style.ThemeOverlay_MaterialComponents_MaterialAlertDialog);\n builder.setIcon(R.mipmap.ic_launcher);\n return builder;\n }\n\n public static AlertDialog.Builder getWebViewBuilder(Context context, String title, String url) {\n AlertDialog.Builder dialogBuilder = getDialogBuilder(context);\n if (!TextUtils.isEmpty(title)) {\n dialogBuilder.setTitle(title);\n }\n WebView webView = new WebView(context);\n webView.loadUrl(url);\n dialogBuilder.setView(webView);\n dialogBuilder.setPositiveButton(R.string.i_know_it, null);\n return dialogBuilder;\n }\n\n public static ProgressDialog getProgressDialog(Context context) {\n ProgressDialog dialog = new ProgressDialog(context);\n dialog.setIcon(R.mipmap.ic_launcher);\n dialog.setTitle(R.string.progress_dialog_title);\n return dialog;\n }\n\n public static MaterialDialog getNumberProgressDialog(Context context) {\n return new MaterialDialog.Builder(context)\n .title(R.string.progress_dialog_title)\n .iconRes(R.mipmap.ic_launcher)\n .progress(false, 0, true)\n .build();\n }\n\n public static void showPrivacy(Context context) {\n try {\n Intent intent = new Intent(Intent.ACTION_VIEW);\n if (!(context instanceof AppCompatActivity)) {\n intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);\n }\n intent.setData(Uri.parse(\"https://twoyi.app/privacy\"));\n context.startActivity(intent);\n } catch (Throwable ignored) {\n }\n }\n\n public static void showFAQ(Context context) {\n try {\n Intent intent = new Intent(Intent.ACTION_VIEW);\n if (!(context instanceof AppCompatActivity)) {\n intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);\n }\n intent.setData(Uri.parse(\"https://twoyi.app/guide\"));\n context.startActivity(intent);\n } catch (Throwable ignored) {\n ignored.printStackTrace();\n }\n }\n\n public static void goWebsite(Context context) {\n visitSite(context, \"https://twoyi.app\");\n }\n\n public static void goTelegram(Context context) {\n visitSite(context, \"https://t.me/twoyi\");\n }\n\n public static void visitSite(Context context, String url) {\n try {\n Intent intent = new Intent(Intent.ACTION_VIEW);\n intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);\n intent.setData(Uri.parse(url));\n context.startActivity(intent);\n } catch (Throwable ignored) {\n }\n }\n\n public static int dpToPx(Context context, int dp) {\n return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,\n context.getResources().getDisplayMetrics());\n }\n\n public static List<ApplicationInfo> getInstalledApplications(PackageManager packageManager) {\n if (packageManager == null) {\n return Collections.emptyList();\n }\n\n @SuppressLint(\"WrongConstant\")\n List<ApplicationInfo> installedApplications = packageManager.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES\n | PackageManager.GET_DISABLED_COMPONENTS);\n int userApp = 0;\n for (ApplicationInfo installedApplication : installedApplications) {\n if ((installedApplication.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {\n if (userApp++ > 3) {\n return installedApplications;\n }\n }\n }\n\n List<ApplicationInfo> applicationInfos = new ArrayList<>();\n for (int uid = 0; uid <= Process.LAST_APPLICATION_UID; uid++) {\n String[] packagesForUid = packageManager.getPackagesForUid(uid);\n if (packagesForUid == null || packagesForUid.length == 0) {\n continue;\n }\n for (String pkg : packagesForUid) {\n try {\n ApplicationInfo applicationInfo = packageManager.getApplicationInfo(pkg, 0);\n applicationInfos.add(applicationInfo);\n } catch (PackageManager.NameNotFoundException ignored) {\n }\n }\n }\n\n return applicationInfos;\n }\n\n public static String toModuleScope(Set<String> scopes) {\n if (scopes == null || scopes.isEmpty()) {\n return \"\";\n }\n\n StringBuilder sb = new StringBuilder();\n int size = scopes.size();\n\n int i = 0;\n for (String scope : scopes) {\n sb.append(scope);\n\n if (i++ < size - 1) {\n sb.append(',');\n }\n\n }\n return sb.toString();\n }\n\n public static void shareText(Context context, @StringRes int shareTitle, String extraText) {\n Intent intent = new Intent(Intent.ACTION_SEND);\n intent.setType(\"text/plain\");\n intent.putExtra(Intent.EXTRA_SUBJECT, context.getString(shareTitle));\n intent.putExtra(Intent.EXTRA_TEXT, extraText);//extraText为文本的内容\n intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);//为Activity新建一个任务栈\n context.startActivity(\n Intent.createChooser(intent, context.getString(shareTitle)));\n }\n\n public static String paste(Context context) {\n ClipboardManager manager = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);\n if (manager == null) {\n return null;\n }\n boolean hasPrimaryClip = manager.hasPrimaryClip();\n if (!hasPrimaryClip) {\n return null;\n }\n ClipData primaryClip = manager.getPrimaryClip();\n if (primaryClip == null) {\n return null;\n }\n if (primaryClip.getItemCount() <= 0) {\n return null;\n }\n CharSequence addedText = primaryClip.getItemAt(0).getText();\n return String.valueOf(addedText);\n }\n\n public static void startActivity(Context context, Class<?> clazz) {\n if (context == null) {\n return;\n }\n\n Intent intent = new Intent(context, clazz);\n\n if (!(context instanceof AppCompatActivity)) {\n intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);\n }\n\n try {\n context.startActivity(intent);\n } catch (Throwable ignored) {\n }\n }\n\n @TargetApi(Build.VERSION_CODES.LOLLIPOP)\n private static boolean isVM64(Set<String> supportedABIs) {\n if (Build.SUPPORTED_64_BIT_ABIS.length == 0) {\n return false;\n }\n\n if (supportedABIs == null || supportedABIs.isEmpty()) {\n return true;\n }\n\n for (String supportedAbi : supportedABIs) {\n if (\"arm64-v8a\".endsWith(supportedAbi) || \"x86_64\".equals(supportedAbi) || \"mips64\".equals(supportedAbi)) {\n return true;\n }\n }\n\n return false;\n }\n\n private static Set<String> getABIsFromApk(String apk) {\n try (ZipFile apkFile = new ZipFile(apk)) {\n Enumeration<? extends ZipEntry> entries = apkFile.entries();\n Set<String> supportedABIs = new HashSet<String>();\n while (entries.hasMoreElements()) {\n ZipEntry entry = entries.nextElement();\n String name = entry.getName();\n if (name.contains(\"../\")) {\n continue;\n }\n if (name.startsWith(\"lib/\") && !entry.isDirectory() && name.endsWith(\".so\")) {\n String supportedAbi = name.substring(name.indexOf(\"/\") + 1, name.lastIndexOf(\"/\"));\n supportedABIs.add(supportedAbi);\n }\n }\n return supportedABIs;\n } catch (Exception e) {\n e.printStackTrace();\n }\n\n return null;\n }\n\n public static boolean isApk64(String apk) {\n long start = SystemClock.elapsedRealtime();\n Set<String> abIsFromApk = getABIsFromApk(apk);\n return isVM64(abIsFromApk);\n }\n\n @SuppressWarnings(\"JavaReflectionMemberAccess\")\n @SuppressLint(\"DiscouragedPrivateApi\")\n public static boolean isAppSupport64bit(ApplicationInfo info) {\n try {\n // fast path, the isApk64 is too heavy!\n Field primaryCpuAbiField = ApplicationInfo.class.getDeclaredField(\"primaryCpuAbi\");\n String primaryCpuAbi = (String) primaryCpuAbiField.get(info);\n if (primaryCpuAbi == null) {\n // no native libs, support!\n return true;\n }\n\n return Arrays.asList(\"arm64-v8a\", \"x86_64\").contains(primaryCpuAbi.toLowerCase());\n } catch (Throwable e) {\n return isApk64(info.sourceDir);\n }\n }\n}" }, { "identifier": "GlideModule", "path": "app/src/main/java/io/twoyi/utils/image/GlideModule.java", "snippet": "@com.bumptech.glide.annotation.GlideModule\npublic class GlideModule extends AppGlideModule {\n\n @Override\n public void registerComponents(@NonNull Context context, @NonNull Glide glide, @NonNull Registry registry) {\n registry.prepend(ApplicationInfo.class, Drawable.class, new DrawableModelLoaderFactory(context));\n }\n\n public static void loadApplicationIcon(Context context, ApplicationInfo applicationInfo, ImageView view) {\n GlideApp.with(context)\n .load(applicationInfo)\n .into(view);\n }\n}" } ]
import android.app.Activity; import android.app.ProgressDialog; import android.content.ClipData; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.content.pm.ApplicationInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.res.ColorStateList; import android.graphics.ColorMatrix; import android.graphics.ColorMatrixColorFilter; import android.net.Uri; import android.os.Bundle; import android.os.SystemClock; import android.text.TextUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.EditorInfo; import android.widget.BaseAdapter; import android.widget.CheckBox; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.SearchView; import androidx.core.view.MenuItemCompat; import androidx.core.widget.CompoundButtonCompat; import com.afollestad.materialdialogs.MaterialDialog; import com.github.clans.fab.FloatingActionButton; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; import io.twoyi.R; import io.twoyi.utils.AppKV; import io.twoyi.utils.CacheManager; import io.twoyi.utils.IOUtils; import io.twoyi.utils.Installer; import io.twoyi.utils.UIHelper; import io.twoyi.utils.image.GlideModule;
7,686
// 输入后点击回车改变文本 @Override public boolean onQueryTextSubmit(String query) { return false; } // 随着输入改变文本 @Override public boolean onQueryTextChange(String newText) { filterListByText(newText); return false; } }); searchView.setOnCloseListener(() -> { mDisplayItems.clear(); mDisplayItems.addAll(mAllApps); notifyDataSetChangedWithSort(); return false; }); setFilterMenuItem(menu, R.id.menu_not_show_system, AppKV.ADD_APP_NOT_SHOW_SYSTEM, true); setFilterMenuItem(menu, R.id.menu_not_show_32bit, AppKV.ADD_APP_NOT_SHOW_32BIT, true); return super.onCreateOptionsMenu(menu); } private MenuItem setFilterMenuItem(Menu menu, int id, String key, boolean defalutValue) { MenuItem menuItem = menu.findItem(id); menuItem.setChecked(AppKV.getBooleanConfig(getApplicationContext(), key, defalutValue)); menuItem.setOnMenuItemClickListener(item -> { boolean checked = !item.isChecked(); item.setChecked(checked); AppKV.setBooleanConfig(getApplicationContext(), key, checked); // 重新加载所有配置 // loadAsync 的时候会检查这个标记 loadAsync(); return true; }); return menuItem; } private void filterListByText(String query) { if (TextUtils.isEmpty(query)) { mDisplayItems.clear(); mDisplayItems.addAll(mAllApps); notifyDataSetChangedWithSort(); return; } List<AppItem> newApps = new ArrayList<>(); Set<CharSequence> pkgs = new HashSet<>(); for (AppItem mAllApp : mAllApps) { pkgs.add(mAllApp.pkg); } for (AppItem appItem : mAllApps) { String name = appItem.name.toString().toLowerCase(Locale.ROOT); String pkg = appItem.pkg.toString().toLowerCase(Locale.ROOT); String queryLower = query.toLowerCase(Locale.ROOT); if (name.contains(queryLower) || pkg.contains(queryLower)) { newApps.add(appItem); } if (appItem.selected && !pkgs.contains(appItem.pkg)) { newApps.add(appItem); } } mDisplayItems.clear(); mDisplayItems.addAll(newApps); notifyDataSetChangedWithSort(); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (!(requestCode == REQUEST_GET_FILE && resultCode == Activity.RESULT_OK)) { return; } if (data == null) { return; } ClipData clipData = data.getClipData(); List<Uri> fileUris = new ArrayList<>(); if (clipData == null) { // single file fileUris.add(data.getData()); } else { // multiple file int itemCount = clipData.getItemCount(); for (int i = 0; i < itemCount; i++) { ClipData.Item item = clipData.getItemAt(i); Uri uri = item.getUri(); fileUris.add(uri); } } if (fileUris.isEmpty()) { Toast.makeText(getApplicationContext(), R.string.select_app_app_not_found, Toast.LENGTH_SHORT).show(); return; } ProgressDialog dialog = UIHelper.getProgressDialog(this); dialog.setCancelable(false); dialog.show(); // start copy and install UIHelper.defer().when(() -> { List<File> files = copyFilesFromUri(fileUris); Log.i(TAG, "files copied: " + files);
/* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ package io.twoyi.ui; /** * @author weishu * @date 2018/7/21. */ public class SelectAppActivity extends AppCompatActivity { private static final String TAG = "SelectAppActivity"; private static final int REQUEST_GET_FILE = 1; private static int TAG_KEY = R.id.create_app_list; private ListAppAdapter mAdapter; private final List<AppItem> mDisplayItems = new ArrayList<>(); private final List<AppItem> mAllApps = new ArrayList<>(); private AppItem mSelectItem; private TextView mEmptyView; private final Set<String> specifiedPackages = new HashSet<>(); @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_createapp); ListView mListView = findViewById(R.id.create_app_list); mAdapter = new ListAppAdapter(); mListView.setAdapter(mAdapter); mEmptyView = findViewById(R.id.empty_view); mListView.setEmptyView(mEmptyView); FloatingActionButton mFloatButton = findViewById(R.id.create_app_from_external); mFloatButton.setColorNormalResId(R.color.colorPrimary); mFloatButton.setColorPressedResId(R.color.colorPrimaryOpacity); mFloatButton.setOnClickListener((v) -> { Intent intent = new Intent(Intent.ACTION_GET_CONTENT); intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true); intent.setType("application/vnd.android.package-archive"); // apk file intent.addCategory(Intent.CATEGORY_OPENABLE); try { startActivityForResult(intent, REQUEST_GET_FILE); } catch (Throwable ignored) { Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_SHORT).show(); } }); TextView createApp = findViewById(R.id.create_app_btn); createApp.setBackgroundResource(R.color.colorPrimary); createApp.setText(R.string.select_app_button); createApp.setOnClickListener((v) -> { Set<AppItem> selectedApps = new HashSet<>(); for (AppItem displayItem : mDisplayItems) { if (displayItem.selected) { selectedApps.add(displayItem); } } if (selectedApps.isEmpty()) { Toast.makeText(this, R.string.select_app_tips, Toast.LENGTH_SHORT).show(); return; } selectComplete(selectedApps); }); ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true); // actionBar.setBackgroundDrawable(getResources().getDrawable(R.color.colorPrimary)); actionBar.setTitle(R.string.create_app_activity); } Intent intent = getIntent(); if (intent != null) { Uri data = intent.getData(); if (data != null && TextUtils.equals(data.getScheme(), "package")) { String schemeSpecificPart = data.getSchemeSpecificPart(); if (schemeSpecificPart != null) { String[] split = schemeSpecificPart.split("\\|"); specifiedPackages.clear(); specifiedPackages.addAll(Arrays.asList(split)); } } } if (true) { int size = specifiedPackages.size(); if (size > 1) { specifiedPackages.clear(); } } loadAsync(); } private void selectComplete(Set<AppItem> pkgs) { if (pkgs.size() != 1) { // TODO: support install mutilpe apps together Toast.makeText(getApplicationContext(), R.string.please_install_one_by_one, Toast.LENGTH_SHORT).show(); return; } ProgressDialog progressDialog = UIHelper.getProgressDialog(this); progressDialog.setCancelable(false); progressDialog.show(); for (AppItem pkg : pkgs) { List<File> apks = new ArrayList<>(); ApplicationInfo applicationInfo = pkg.applicationInfo; // main apk String sourceDir = applicationInfo.sourceDir; apks.add(new File(sourceDir)); String[] splitSourceDirs = applicationInfo.splitSourceDirs; if (splitSourceDirs != null) { for (String splitSourceDir : splitSourceDirs) { apks.add(new File(splitSourceDir)); } } startInstall(apks, progressDialog, false); } } @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { switch (item.getItemId()) { case android.R.id.home: onBackPressed(); return true; } return super.onOptionsItemSelected(item); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.search_menu, menu); MenuItem searchItem = menu.findItem(R.id.menu_search); SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem); // 当SearchView获得焦点时弹出软键盘的类型,就是设置输入类型 searchView.setIconified(false); searchView.onActionViewExpanded(); searchView.setInputType(EditorInfo.TYPE_CLASS_TEXT); // 设置回车键表示查询操作 searchView.setImeOptions(EditorInfo.IME_ACTION_SEARCH); // 为searchView添加事件 searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { // 输入后点击回车改变文本 @Override public boolean onQueryTextSubmit(String query) { return false; } // 随着输入改变文本 @Override public boolean onQueryTextChange(String newText) { filterListByText(newText); return false; } }); searchView.setOnCloseListener(() -> { mDisplayItems.clear(); mDisplayItems.addAll(mAllApps); notifyDataSetChangedWithSort(); return false; }); setFilterMenuItem(menu, R.id.menu_not_show_system, AppKV.ADD_APP_NOT_SHOW_SYSTEM, true); setFilterMenuItem(menu, R.id.menu_not_show_32bit, AppKV.ADD_APP_NOT_SHOW_32BIT, true); return super.onCreateOptionsMenu(menu); } private MenuItem setFilterMenuItem(Menu menu, int id, String key, boolean defalutValue) { MenuItem menuItem = menu.findItem(id); menuItem.setChecked(AppKV.getBooleanConfig(getApplicationContext(), key, defalutValue)); menuItem.setOnMenuItemClickListener(item -> { boolean checked = !item.isChecked(); item.setChecked(checked); AppKV.setBooleanConfig(getApplicationContext(), key, checked); // 重新加载所有配置 // loadAsync 的时候会检查这个标记 loadAsync(); return true; }); return menuItem; } private void filterListByText(String query) { if (TextUtils.isEmpty(query)) { mDisplayItems.clear(); mDisplayItems.addAll(mAllApps); notifyDataSetChangedWithSort(); return; } List<AppItem> newApps = new ArrayList<>(); Set<CharSequence> pkgs = new HashSet<>(); for (AppItem mAllApp : mAllApps) { pkgs.add(mAllApp.pkg); } for (AppItem appItem : mAllApps) { String name = appItem.name.toString().toLowerCase(Locale.ROOT); String pkg = appItem.pkg.toString().toLowerCase(Locale.ROOT); String queryLower = query.toLowerCase(Locale.ROOT); if (name.contains(queryLower) || pkg.contains(queryLower)) { newApps.add(appItem); } if (appItem.selected && !pkgs.contains(appItem.pkg)) { newApps.add(appItem); } } mDisplayItems.clear(); mDisplayItems.addAll(newApps); notifyDataSetChangedWithSort(); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (!(requestCode == REQUEST_GET_FILE && resultCode == Activity.RESULT_OK)) { return; } if (data == null) { return; } ClipData clipData = data.getClipData(); List<Uri> fileUris = new ArrayList<>(); if (clipData == null) { // single file fileUris.add(data.getData()); } else { // multiple file int itemCount = clipData.getItemCount(); for (int i = 0; i < itemCount; i++) { ClipData.Item item = clipData.getItemAt(i); Uri uri = item.getUri(); fileUris.add(uri); } } if (fileUris.isEmpty()) { Toast.makeText(getApplicationContext(), R.string.select_app_app_not_found, Toast.LENGTH_SHORT).show(); return; } ProgressDialog dialog = UIHelper.getProgressDialog(this); dialog.setCancelable(false); dialog.show(); // start copy and install UIHelper.defer().when(() -> { List<File> files = copyFilesFromUri(fileUris); Log.i(TAG, "files copied: " + files);
boolean allValid = Installer.checkFile(getApplicationContext(), files);
3
2023-11-11 22:08:20+00:00
12k
EmonerRobotics/2023Robot
src/main/java/frc/robot/RobotContainer.java
[ { "identifier": "IntakeConstants", "path": "src/main/java/frc/robot/Constants.java", "snippet": "public final class IntakeConstants{\n\n public static final double kEncoderTick2Meter = 1.0 / 4096.0 * 0.1 * Math.PI;\n\n //üst sistem joystick sabitleri\n public static final int Joystick2 = 1; //usb ports\n \n //pinomatik aç-kapat kontrolleri\n public static final int SolenoidOnB = 6; //LB\n public static final int SolenoidOffB = 5; //RB\n \n //asansor motor pwm\n public static final int LiftRedline1 = 0;\n \n //asansör motor analog kontrolü\n public static final int LiftControllerC = 5; //sağ yukarı asagı ters cevir\n \n //acili mekanizma neo500 id\n public static final int AngleMechanismId = 9;\n\n //üst sistem mekanizma pozisyon kontrolleri\n public static final int GroundLevelB = 1; //A\n public static final int FirstLevelB = 3; //X\n public static final int HumanPB = 2; //B\n public static final int TopLevelB = 4; //Y\n public static final int MoveLevelB = 9; //sol analog butonu\n\n //açılı intake kontrolleri\n public static final int AngleController = 1; //sol yukarı aşagı \n}" }, { "identifier": "AutoElevator", "path": "src/main/java/frc/robot/commands/AutoElevator.java", "snippet": "public class AutoElevator extends CommandBase {\n\n private final LiftSubsystem liftSubsystem;\n private final PIDController pidController;\n private final ElevatorPosition elevatorPosition;\n\n public static enum ElevatorPosition{\n GROUND,\n MIDDLE,\n TOP,\n HUMANP\n }\n\n /** Creates a new AutoElevator. */\n public AutoElevator(LiftSubsystem liftSubsystem, double setPoint, ElevatorPosition elevatorPosition) {\n this.liftSubsystem = liftSubsystem;\n this.elevatorPosition = elevatorPosition;\n this.pidController = new PIDController(2.5, 0.3,0);\n pidController.setSetpoint(setPoint);\n addRequirements(liftSubsystem);\n }\n\n // Called when the command is initially scheduled.\n @Override\n public void initialize() {\n pidController.reset();\n System.out.println(\"ElevatorPIDCmd started!\");\n }\n\n // Called every time the scheduler runs while the command is scheduled.\n @Override\n public void execute() {\n double speed = pidController.calculate(liftSubsystem.getEncoderMeters());\n liftSubsystem.manuelLiftControl(speed);\n }\n\n // Called once the command ends or is interrupted.\n @Override\n public void end(boolean interrupted) {\n liftSubsystem.manuelLiftControl(0);\n System.out.println(\"ElevatorPIDCmd ended!\");\n }\n\n // Returns true when the command should end.\n @Override\n public boolean isFinished() {\n \n if(elevatorPosition == ElevatorPosition.GROUND){\n return this.liftSubsystem.isAtGround();\n \n }else if(elevatorPosition == ElevatorPosition.MIDDLE){\n return this.liftSubsystem.isAtMid();\n \n }else if(elevatorPosition == ElevatorPosition.TOP){\n return this.liftSubsystem.isAtTop();\n \n }else if(elevatorPosition == ElevatorPosition.HUMANP){\n return this.liftSubsystem.isAtHuman();\n \n }else{\n return false;\n }\n }\n}" }, { "identifier": "AutoIntake", "path": "src/main/java/frc/robot/commands/AutoIntake.java", "snippet": "public class AutoIntake extends CommandBase {\n\n private final IntakeSubsystem intakeSubsystem;\n private final PIDController pidController; \n private final IntakePosition intakePosition;\n\n public static enum IntakePosition{\n CLOSED,\n HALF,\n STRAIGHT,\n STRAIGHTHD\n }\n\n /** Creates a new AutoIntake. */\n public AutoIntake(IntakeSubsystem intakeSubsystem, double setPoint, IntakePosition intakePosition) {\n this.intakeSubsystem = intakeSubsystem;\n this.intakePosition = intakePosition;\n this.pidController = new PIDController(1.2, .3, .1);\n pidController.setSetpoint(setPoint);\n addRequirements(intakeSubsystem);\n }\n\n // Called when the command is initially scheduled.\n @Override\n public void initialize() {\n pidController.reset();\n System.out.println(\"IntakePIDCmd started!\");\n\n }\n\n // Called every time the scheduler runs while the command is scheduled.\n @Override\n public void execute() {\n double speed = pidController.calculate(intakeSubsystem.getEncoderMeters());\n intakeSubsystem.manuelIntakeAngle(-speed * .5);\n \n }\n\n // Called once the command ends or is interrupted.\n @Override\n public void end(boolean interrupted) {\n intakeSubsystem.manuelIntakeAngle(0);\n System.out.println(\"IntakePIDCmd ended!\");\n }\n\n // Returns true when the command should end.\n @Override\n public boolean isFinished() {\n if(intakePosition == IntakePosition.STRAIGHT){\n return this.intakeSubsystem.isAtStraight();\n\n }else if(intakePosition == IntakePosition.CLOSED){\n return this.intakeSubsystem.isAtClose();\n\n }else if(intakePosition == IntakePosition.HALF){\n return this.intakeSubsystem.isAtHalf();\n \n }else if(intakePosition == IntakePosition.STRAIGHTHD){\n return this.intakeSubsystem.isAtStraighTHuman();\n }else{\n return false;\n }\n }\n}" }, { "identifier": "DriveWithJoysticks", "path": "src/main/java/frc/robot/commands/DriveWithJoysticks.java", "snippet": "public class DriveWithJoysticks implements Command {\n private final Drivetrain drivetrain;\n private final PoseEstimation poseEstimation;\n\n private final Joystick translation;\n\n private Rotation2d fieldOrientationZeroOffset = new Rotation2d();\n\n public DriveWithJoysticks(Drivetrain drivetrain, PoseEstimation poseEstimation, Joystick translation) {\n this.drivetrain = drivetrain;\n this.poseEstimation = poseEstimation;\n\n this.translation = translation;\n drivetrain.resetEncoders();\n }\n\n @Override\n public void execute() {\n //double sensitivity = RobotContainer.joystickLeft.getRawButtonPressed(5)? 0.25: 1;\n\n // Negative because joysticks are inverted\n double ty = MathUtil.applyDeadband(-translation.getRawAxis(0), 0.1);\n double tx = MathUtil.applyDeadband(-translation.getRawAxis(1), 0.1);\n double r = MathUtil.applyDeadband(-translation.getRawAxis(2), 0.1);\n\n double vx = tx * DriveConstants.MAX_SPEED_METERS_PER_SECOND;\n double vy = ty * DriveConstants.MAX_SPEED_METERS_PER_SECOND;\n double omega = r * DriveConstants.MAX_ANGULAR_SPEED;\n\n ChassisSpeeds fieldRelSpeeds = new ChassisSpeeds(vx, vy, omega);\n ChassisSpeeds robotRelSpeeds = ChassisSpeeds.fromFieldRelativeSpeeds(fieldRelSpeeds, poseEstimation.getEstimatedPose().getRotation().minus(AllianceUtils.getFieldOrientationZero().plus(fieldOrientationZeroOffset)));\n\n drivetrain.drive(robotRelSpeeds);\n }\n\n @Override\n public Set<Subsystem> getRequirements() {\n return Set.of(drivetrain);\n }\n\n public void resetFieldOrientation() {\n fieldOrientationZeroOffset = poseEstimation.getEstimatedPose().getRotation().minus(AllianceUtils.getFieldOrientationZero());\n }\n}" }, { "identifier": "GetInRange", "path": "src/main/java/frc/robot/commands/GetInRange.java", "snippet": "public class GetInRange extends CommandBase {\n\n public static enum LimelightPositionCheck{\n fiftyFive,\n oneTwenty\n }\n\n private final LimelightSubsystem limelightSubsystem;\n private final PIDController pidController;\n private final Drivetrain drivetrain;\n private final PoseEstimation poseEstimation;\n private final LimelightPositionCheck limelightCheck;\n private Rotation2d fieldOrientationZeroOffset = new Rotation2d();\n private double setPoint;\n private double speedY;\n\n /** Creates a new GetInRange. */\n public GetInRange(Drivetrain drivetrain, PoseEstimation poseEstimation, LimelightSubsystem limelightSubsystem, double setPoint, LimelightPositionCheck limelightCheck) {\n this.drivetrain = drivetrain;\n this.poseEstimation = poseEstimation;\n this.pidController = new PIDController(0.4, 0.05, 0);\n this.limelightCheck = limelightCheck;\n this.setPoint = setPoint;\n //pidController.setSetpoint(setPoint);\n this.limelightSubsystem = limelightSubsystem;\n drivetrain.resetEncoders();\n }\n\n // Called when the command is initially scheduled.\n @Override\n public void initialize() {\n pidController.reset();\n System.out.println(\"GetInRangePIDCommand Started\");\n }\n\n // Called every time the scheduler runs while the command is scheduled.\n @Override\n public void execute() {\n \n if(limelightSubsystem.hasTargets()){\n \n double distanceError = (limelightSubsystem.EstimatedDistance() - setPoint);\n SmartDashboard.putNumber(\"DistanceError: \", distanceError);\n double speedX = 0.04 * distanceError;\n\n if(limelightSubsystem.getId() == 4 || limelightSubsystem.getId() == 5){\n Constants.LimelightConstants.goalHeightInches = 30.31496; //26.37795\n }else{\n Constants.LimelightConstants.goalHeightInches = 21.25984; //21.25984 \n }\n\n if(Math.abs(limelightSubsystem.getAim()) > -18){\n if(limelightSubsystem.getAim() < -18){\n speedY = 0.04 * limelightSubsystem.getAim() + 0.01;\n }else{\n speedY = 0.04 * limelightSubsystem.getAim() - 0.01;\n }\n }\n \n //double speed = pidController.calculate(limelightSubsystem.EstimatedDistance());\n ChassisSpeeds fieldRelSpeeds = new ChassisSpeeds(-speedX, 0, 0);\n ChassisSpeeds robotRelSpeeds = ChassisSpeeds.fromFieldRelativeSpeeds(fieldRelSpeeds, poseEstimation.getEstimatedPose().getRotation().minus(AllianceUtils.getFieldOrientationZero().plus(fieldOrientationZeroOffset)));\n drivetrain.drive(robotRelSpeeds);\n System.out.println(\"Getting in range: \" + speedX);\n System.out.println(Constants.LimelightConstants.goalHeightInches);\n \n }else{\n System.out.println(\"NO TARGET\");\n } \n }\n\n @Override\n public void end(boolean interrupted) {\n ChassisSpeeds fieldRelSpeeds = new ChassisSpeeds(0, 0, 0);\n System.out.println(\"GetInRangePIDCommand Finished\");\n }\n\n // Returns true when the command should end.\n @Override\n public boolean isFinished() {\n if(limelightCheck == LimelightPositionCheck.fiftyFive){\n return this.limelightSubsystem.isAtDistance0();\n }else if(limelightCheck == LimelightPositionCheck.oneTwenty){\n return this.limelightSubsystem.isAtDistance1();\n }else{\n return false;\n }\n }\n}" }, { "identifier": "IntakeCommand", "path": "src/main/java/frc/robot/commands/IntakeCommand.java", "snippet": "public class IntakeCommand extends CommandBase {\n\n private final IntakeSubsystem intakeSubsystem;\n private final Supplier<Double> controller;\n\n /** Creates a new IntakeCommand. */\n public IntakeCommand(IntakeSubsystem intakeSubsystem, Supplier<Double> controller) {\n this.intakeSubsystem = intakeSubsystem;\n this.controller = controller;\n addRequirements(intakeSubsystem);\n }\n\n // Called when the command is initially scheduled.\n @Override\n public void initialize() {}\n\n // Called every time the scheduler runs while the command is scheduled.\n @Override\n public void execute() {\n double controllers = controller.get();\n intakeSubsystem.manuelIntakeAngle(controllers);\n }\n\n // Called once the command ends or is interrupted.\n @Override\n public void end(boolean interrupted) {}\n\n // Returns true when the command should end.\n @Override\n public boolean isFinished() {\n return false;\n }\n}" }, { "identifier": "LiftCommand", "path": "src/main/java/frc/robot/commands/LiftCommand.java", "snippet": "public class LiftCommand extends CommandBase {\n\n private final LiftSubsystem liftSubsystem;\n private final Supplier<Double> controls;\n\n public LiftCommand(LiftSubsystem liftSubsystem, Supplier<Double> controls) {\n this.liftSubsystem = liftSubsystem;\n this.controls = controls;\n addRequirements(liftSubsystem);\n }\n\n // Called when the command is initially scheduled.\n @Override\n public void initialize() {}\n\n // Called every time the scheduler runs while the command is scheduled.\n @Override\n public void execute() {\n double speed = controls.get();\n liftSubsystem.manuelLiftControl(speed);\n }\n\n // Called once the command ends or is interrupted.\n @Override\n public void end(boolean interrupted) {}\n\n // Returns true when the command should end.\n @Override\n public boolean isFinished() {\n return false;\n }\n}" }, { "identifier": "PneumaticCommand", "path": "src/main/java/frc/robot/commands/PneumaticCommand.java", "snippet": "public class PneumaticCommand extends CommandBase {\n\n private final PneumaticSubsystem pneumaticSubsystem;\n private final boolean SolenoidOn;\n private final boolean SolenoidOff;\n /** Creates a new PneumaticCommand. */\n public PneumaticCommand(PneumaticSubsystem pneumaticSubsystem, boolean SolenoidOn, boolean SolenoidOff) {\n this.pneumaticSubsystem = pneumaticSubsystem;\n this.SolenoidOn = SolenoidOn;\n this.SolenoidOff = SolenoidOff;\n addRequirements(pneumaticSubsystem);\n }\n\n // Called when the command is initially scheduled.\n @Override\n public void initialize() {}\n\n // Called every time the scheduler runs while the command is scheduled.\n @Override\n public void execute() {\n pneumaticSubsystem.SolenoidForward(SolenoidOn);\n pneumaticSubsystem.SolenoidReverse(SolenoidOff);\n }\n\n // Called once the command ends or is interrupted.\n @Override\n public void end(boolean interrupted) {\n }\n\n // Returns true when the command should end.\n @Override\n public boolean isFinished() {\n if(SolenoidOff){\n return true;\n }else if(SolenoidOn){\n return true;\n }else{\n return false;\n }\n }\n}" }, { "identifier": "ElevatorPosition", "path": "src/main/java/frc/robot/commands/AutoElevator.java", "snippet": "public static enum ElevatorPosition{\n GROUND,\n MIDDLE,\n TOP,\n HUMANP\n}" }, { "identifier": "IntakePosition", "path": "src/main/java/frc/robot/commands/AutoIntake.java", "snippet": "public static enum IntakePosition{\n CLOSED,\n HALF,\n STRAIGHT,\n STRAIGHTHD\n}" }, { "identifier": "LimelightPositionCheck", "path": "src/main/java/frc/robot/commands/GetInRange.java", "snippet": "public static enum LimelightPositionCheck{\n fiftyFive,\n oneTwenty\n}" }, { "identifier": "AutoBalance", "path": "src/main/java/frc/robot/commands/autonomous/AutoBalance.java", "snippet": "public class AutoBalance implements Command{\n \n int NumOscillation = 0;\n Rotation2d lastInclineAngle;\n double lastDistance = 0;\n private final Drivetrain drivetrain;\n //private final PIDController pidController = new PIDController(0, 0, 0);\n\n public AutoBalance(Drivetrain drivetrain) {\n this.drivetrain = drivetrain;\n //RobotContainer.autoTab.add(\"AutoBalance\", pidController).withWidget(BuiltInWidgets.kPIDController);\n }\n\n @Override\n public void initialize() {\n NumOscillation = 0;\n\n Rotation3d rot = drivetrain.getRotation3d();\n Translation3d normal = new Translation3d(0, 0, 1).rotateBy(rot);\n Translation2d inclineDirection = normal.toTranslation2d().rotateBy(drivetrain.getRotation().unaryMinus());\n lastDistance = inclineDirection.getDistance(new Translation2d(0, 0));\n lastInclineAngle = inclineDirection.getAngle();\n }\n\n @Override\n public void execute() {\n Rotation3d rot = drivetrain.getRotation3d();\n\n Translation3d normal = new Translation3d(0, 0, 1).rotateBy(rot);\n Translation2d inclineDirection = normal.toTranslation2d().rotateBy(drivetrain.getRotation().unaryMinus());\n \n double distance = inclineDirection.getDistance(new Translation2d(0, 0));\n if (distance < Math.sin(Constants.DriveConstants.CHARGE_TOLERANCE)/* || (distance - lastDistance) < -0.01*/) {\n drivetrain.setX();\n //lastDistance = distance;\n return;\n }\n //lastDistance = distance;\n\n Rotation2d inclineAngle = inclineDirection.getAngle();\n\n if (inclineAngle.minus(lastInclineAngle).getRadians() > Math.PI/2) {\n NumOscillation ++;\n }\n lastInclineAngle = inclineAngle;\n\n SmartDashboard.putNumber(\"InclineAngle: \", inclineAngle.getDegrees());\n\n //double driveSpeed = pidController.calculate(inclineDirection.getDistance(new Translation2d(0, 0)), 0);\n double driveSpeed = MathUtil.clamp(distance/Math.sin(Math.toRadians(15)), -1, 1 );\n if (distance < Math.sin(Constants.DriveConstants.CHARGE_TIPPING_ANGLE)) {\n driveSpeed *= Constants.DriveConstants.CHARGE_REDUCED_SPEED;\n } else {\n driveSpeed *= Constants.DriveConstants.CHARGE_MAX_SPEED;\n }\n driveSpeed /= NumOscillation + 1; // dampen the robot's oscillations by slowing down after oscillating\n Translation2d driveVelocity = new Translation2d(driveSpeed, inclineAngle);\n\n ChassisSpeeds speeds = new ChassisSpeeds(driveVelocity.getY(), -driveVelocity.getX(), 0);\n\n drivetrain.drive(speeds);\n }\n\n @Override\n public Set<Subsystem> getRequirements() {\n return Set.of(drivetrain);\n }\n}" }, { "identifier": "AutoCommand", "path": "src/main/java/frc/robot/commands/autonomous/AutoCommand.java", "snippet": "public class AutoCommand {\n //LiftSubsystem liftSubsystem = new LiftSubsystem();\n SmartDashboard smartDashboard;\n\n //static HashMap<String, Command> eventMap = new HashMap<>();\n \n \n static Map<String, Command> eventMap = Map.of(\n \"event1\", new InstantCommand(() -> System.out.println(\"event triggered\"))); \n \n public static Command makeAutoCommand(Drivetrain drivetrain, PoseEstimation poseEstimation, String name) {\n name = name.concat(AllianceUtils.isBlue()? \".blue\" : \".red\");\n List<PathPlannerTrajectory> pathGroup = PathPlanner.loadPathGroup(name, new PathConstraints(Constants.AutoConstants.MAX_SPEED_METERS_PER_SECOND, Constants.AutoConstants.MAX_ACCELERATION_METERS_PER_SECOND_SQUARED));\n\n RobotContainer.field.getObject(\"Auto Path\").setTrajectory(pathGroup.get(0));\n\n // Create the AutoBuilder. This only needs to be created once when robot code starts, not every time you want to create an auto command. A good place to put this is in RobotContainer along with your subsystems.\n SwerveAutoBuilder autoBuilder = new SwerveAutoBuilder(\n poseEstimation::getEstimatedPose, // Pose2d supplier\n (pose) -> poseEstimation.resetPose(pose), // Pose 2d consumer, used to reset odometry at the beginning of auto\n Constants.DriveConstants.DRIVE_KINEMATICS, // SwerveDriveKinematics\n new PIDConstants(Constants.AutoConstants.P_TRANSLATION_PATH_CONTROLLER, 0.0, 0.0), // PID constants to correct for translation error (used to create the X and Y PID controllers)\n new PIDConstants(Constants.AutoConstants.P_THETA_PATH_CONTROLLER, 0.0, 0.0), // PID constants to correct for rotation error (used to create the rotation controller)\n drivetrain::setModuleStates, // Module states consumer used to output to the drive subsystem\n eventMap,\n true, // Should the path be automatically mirrored depending on alliance color. Optional, defaults to true\n drivetrain // The drive subsystem. Used to properly set the requirements of path following commands\n );\n \n return autoBuilder.fullAuto(pathGroup);\n } \n}" }, { "identifier": "OnePieceCharge", "path": "src/main/java/frc/robot/commands/autonomous/OnePieceCharge.java", "snippet": "public class OnePieceCharge extends SequentialCommandGroup {\n /** Creates a new OnePieceCharge. */\n public OnePieceCharge() {\n // Add your commands in the addCommands() call, e.g.\n // addCommands(new FooCommand(), new BarCommand());\n addCommands(\n new AutoElevator(RobotContainer.getLiftSubsystem(), Constants.LiftMeasurements.TOPH, ElevatorPosition.TOP),\n new AutoIntake(RobotContainer.getIntakeSubsystem(), Constants.IntakeMeasurements.IntakeStraightOpenD, IntakePosition.STRAIGHT),\n new WaitCommand(1.5),\n new PneumaticCommand(RobotContainer.getPneumaticSubsystem(), true, false),\n new AutoIntake(RobotContainer.getIntakeSubsystem(), Constants.IntakeMeasurements.IntakeClosedD, IntakePosition.CLOSED),\n new AutoElevator(RobotContainer.getLiftSubsystem(), Constants.LiftMeasurements.GROUNDH, ElevatorPosition.GROUND)\n );\n }\n}" }, { "identifier": "PoseEstimation", "path": "src/main/java/frc/robot/poseestimation/PoseEstimation.java", "snippet": "public class PoseEstimation {\n private PhotonVisionBackend photonVision;\n private SwerveDrivePoseEstimator poseEstimator;\n\n private GenericEntry usePhotonVisionEntry = RobotContainer.autoTab.add(\"Use PhotonVision\", true).withWidget(BuiltInWidgets.kToggleButton).getEntry();\n\n private TimeInterpolatableBuffer<Pose2d> poseHistory = TimeInterpolatableBuffer.createBuffer(1.5);\n\n private static final double DIFFERENTIATION_TIME = Robot.kDefaultPeriod;\n\n public PoseEstimation() {\n poseEstimator = new SwerveDrivePoseEstimator(\n DriveConstants.DRIVE_KINEMATICS,\n RobotContainer.drivetrain.getRotation(),\n RobotContainer.drivetrain.getModulePositions(),\n new Pose2d(),\n Constants.DriveConstants.ODOMETRY_STD_DEV,\n VecBuilder.fill(0, 0, 0) // will be overwritten for each measurement\n );\n\n try {\n photonVision = new PhotonVisionBackend();\n } catch (Exception e) {\n System.out.println(\"Failed to initialize PhotonVision\");\n e.printStackTrace();\n }\n\n }\n\n public void periodic() {\n poseHistory.addSample(Timer.getFPGATimestamp(), poseEstimator.getEstimatedPosition());\n\n if (usePhotonVisionEntry.getBoolean(false)) {\n try {\n photonVision.getMeasurement().filter(measurement -> measurement.ambiguity < Constants.VisionConstants.AMBIGUITY_FILTER).ifPresent(this::addVisionMeasurement);\n }\n catch(Exception e) {\n e.printStackTrace();\n }\n }\n\n RobotContainer.field.setRobotPose(getEstimatedPose());\n }\n\n public void updateOdometry(Rotation2d gyro, SwerveModulePosition[] modulePositions) {\n poseEstimator.update(gyro, modulePositions);\n }\n\n public Pose2d getEstimatedPose() {\n return poseEstimator.getEstimatedPosition();\n }\n\n public Translation2d getEstimatedVelocity() {\n double now = Timer.getFPGATimestamp();\n\n Translation2d current = poseHistory.getSample(now).get().getTranslation();\n Translation2d previous = poseHistory.getSample(now - DIFFERENTIATION_TIME).get().getTranslation();\n\n return current.minus(previous).div(DIFFERENTIATION_TIME);\n }\n\n public void resetPose(Pose2d pose) {\n poseEstimator.resetPosition(RobotContainer.drivetrain.getRotation(), RobotContainer.drivetrain.getModulePositions(), pose);\n }\n\n private void addVisionMeasurement(VisionBackend.Measurement measurement) {\n poseEstimator.addVisionMeasurement(measurement.pose.toPose2d(), measurement.timestamp, measurement.stdDeviation);\n }\n}" }, { "identifier": "IntakeSubsystem", "path": "src/main/java/frc/robot/subsystems/IntakeSubsystem.java", "snippet": "public class IntakeSubsystem extends SubsystemBase {\n\n private CANSparkMax neoMotor;\n\n private RelativeEncoder m_angleEncoder;\n\n \n /** Creates a new Intake. */\n public IntakeSubsystem() {\n neoMotor = new CANSparkMax(IntakeConstants.AngleMechanismId, MotorType.kBrushless);\n neoMotor.setSmartCurrentLimit(20);\n m_angleEncoder = neoMotor.getEncoder();\n \n }\n\n public void manuelIntakeAngle(double controller){\n neoMotor.set(controller * .5);\n }\n\n public double getEncoderMeters() {\n return m_angleEncoder.getPosition() * -0.1; \n\n }\n\n public boolean isAtClose(){\n double error = getEncoderMeters() - Constants.IntakeMeasurements.IntakeClosedD;\n return (Math.abs(error) < Constants.IntakeMeasurements.IntakeAllowedError);\n }\n\n public boolean isAtHalf(){\n double error = getEncoderMeters() - Constants.IntakeMeasurements.IntakeHalfOpenD;\n return (Math.abs(error) < Constants.IntakeMeasurements.IntakeAllowedError);\n }\n\n public boolean isAtStraight(){\n double error = getEncoderMeters() - Constants.IntakeMeasurements.IntakeStraightOpenD;\n return (Math.abs(error) < Constants.IntakeMeasurements.IntakeAllowedError);\n }\n\n public boolean isAtStraighTHuman(){\n double error = getEncoderMeters() - Constants.IntakeMeasurements.IntakeStraightOpenHD;\n return (Math.abs(error) < Constants.IntakeMeasurements.IntakeAllowedError);\n }\n\n\n @Override\n public void periodic() {\n SmartDashboard.putNumber(\"Degrees: \", getEncoderMeters()); \n }\n}" }, { "identifier": "LiftSubsystem", "path": "src/main/java/frc/robot/subsystems/LiftSubsystem.java", "snippet": "public class LiftSubsystem extends SubsystemBase {\n \n private PWMVictorSPX liftMotor;\n\n private Encoder liftEncoder;\n\n public LiftSubsystem() {\n\n //redline motor\n liftMotor = new PWMVictorSPX(IntakeConstants.LiftRedline1);\n\n //lift encoder\n liftEncoder = new Encoder(6, 7); //true, EncodingType.k4X\n liftEncoder.reset();\n }\n\n public void manuelLiftControl(double speed){\n liftMotor.set(-speed);\n }\n\n public double getEncoderMeters(){\n return (liftEncoder.get() * -IntakeConstants.kEncoderTick2Meter);\n }\n\n public boolean isAtGround(){\n double error = getEncoderMeters() - Constants.LiftMeasurements.GROUNDH;\n return (Math.abs(error) < Constants.LiftMeasurements.LiftAllowedError);\n }\n\n public boolean isAtMid(){\n double error = getEncoderMeters() - Constants.LiftMeasurements.MIDH;\n return (Math.abs(error) < Constants.LiftMeasurements.LiftAllowedError);\n }\n\n public boolean isAtTop(){\n double error = getEncoderMeters() - Constants.LiftMeasurements.TOPH;\n return (Math.abs(error) < Constants.LiftMeasurements.LiftAllowedError);\n }\n\n public boolean isAtHuman(){\n double error = getEncoderMeters() - Constants.LiftMeasurements.HUMANPH;\n return (Math.abs(error) < Constants.LiftMeasurements.LiftAllowedError);\n }\n\n @Override\n public void periodic() {\n //double liftHeight = liftEncoder.get() / IntakeConstants.degrees2Cm;\n SmartDashboard.putNumber(\"Meters: \", getEncoderMeters()); \n }\n}" }, { "identifier": "LimelightSubsystem", "path": "src/main/java/frc/robot/subsystems/LimelightSubsystem.java", "snippet": "public class LimelightSubsystem extends SubsystemBase {\n\n NetworkTable table = NetworkTableInstance.getDefault().getTable(\"limelight\");\n \n /** Creates a new LimelightSubsystem. */\n public LimelightSubsystem() {}\n\n @Override\n public void periodic() {\n EstimatedDistance();\n SmartDashboard.putBoolean(\"Found Target\", hasTargets());\n }\n\n public double getAim(){\n NetworkTableEntry tx = table.getEntry(\"tx\");\n double headingError = tx.getDouble(0.0);\n return headingError;\n }\n\n public double EstimatedDistance(){\n \n NetworkTableEntry ty = table.getEntry(\"ty\");\n \n double targetOffsetAngle_Vertical = ty.getDouble(0.0);\n \n // how many degrees back is your limelight rotated from perfectly vertical?\n double limelightMountAngleDegrees = 28;\n \n // distance from the center of the Limelight lens to the floor\n double limelightLensHeightInches = 10.62992; //18.58268\n \n // distance from the target to the floor\n \n double angleToGoalDegrees = limelightMountAngleDegrees + targetOffsetAngle_Vertical;\n double angleToGoalRadians = angleToGoalDegrees * (3.14159 / 180.0);\n \n //calculate distance\n double distanceFromLimelightToGoalInches = ((Constants.LimelightConstants.goalHeightInches - limelightLensHeightInches)/Math.tan(angleToGoalRadians));\n SmartDashboard.putNumber(\"DISTANCE: \", distanceFromLimelightToGoalInches);\n return distanceFromLimelightToGoalInches;\n }\n\n public double getId(){\n NetworkTableEntry tid = table.getEntry(\"tid\");\n double tId = tid.getDouble(0.0);\n return tId;\n }\n\n public boolean hasTargets(){\n NetworkTableEntry tv = table.getEntry(\"tv\");\n float isTrue = tv.getFloat(0); \n return (isTrue == 0.0f) ? false : true;\n }\n\n public boolean isAtDistance0(){\n double error = EstimatedDistance() - 21.65;\n return (Math.abs(error) < 0.5);\n }\n\n public boolean isAtDistance1(){\n double error = EstimatedDistance() - 120;\n return (Math.abs(error) < 0.5);\n }\n}" }, { "identifier": "PneumaticSubsystem", "path": "src/main/java/frc/robot/subsystems/PneumaticSubsystem.java", "snippet": "public class PneumaticSubsystem extends SubsystemBase {\n \n private Compressor compressor;\n private DoubleSolenoid solenoid;\n private boolean statement = true;\n\n /** Creates a new PneumaticSubsystem. */\n public PneumaticSubsystem() {\n compressor = new Compressor(PneumaticsModuleType.REVPH);\n solenoid = new DoubleSolenoid(PneumaticsModuleType.REVPH, 10, 8);\n }\n\n public void SolenoidForward(boolean SolenoidOn){\n if(SolenoidOn){\n solenoid.set(Value.kForward);\n statement = true;\n }\n }\n\n public void SolenoidReverse(boolean SolenoidOff){\n if(SolenoidOff){\n solenoid.set(Value.kReverse);\n statement = false;\n }\n }\n\n @Override\n public void periodic() {\n SmartDashboard.putBoolean(\"Piston\", statement);\n compressor.enableDigital();\n }\n}" }, { "identifier": "Drivetrain", "path": "src/main/java/frc/robot/subsystems/drivetrain/Drivetrain.java", "snippet": "public class Drivetrain extends SubsystemBase {\n\n // Create MAXSwerveModules\n private final SwerveModules swerveModules;\n\n // The gyro sensor\n private final Gyro gyro;\n\n /**\n * Creates a new DriveSubsystem.\n */\n public Drivetrain() {\n if (RobotBase.isSimulation()) {\n this.swerveModules = new SwerveModules(\n new SIMSwerveModule(DriveConstants.FRONT_LEFT_CHASSIS_ANGULAR_OFFSET),\n new SIMSwerveModule(DriveConstants.FRONT_RIGHT_CHASSIS_ANGULAR_OFFSET),\n new SIMSwerveModule(DriveConstants.REAR_LEFT_CHASSIS_ANGULAR_OFFSET),\n new SIMSwerveModule(DriveConstants.REAR_RIGHT_CHASSIS_ANGULAR_OFFSET)\n );\n } else {\n this.swerveModules = new SwerveModules(\n new MAXSwerveModule(\n DriveConstants.FRONT_LEFT_DRIVING_CAN_ID,\n DriveConstants.FRONT_LEFT_TURNING_CAN_ID,\n DriveConstants.FRONT_LEFT_CHASSIS_ANGULAR_OFFSET\n ),\n new MAXSwerveModule(\n DriveConstants.FRONT_RIGHT_DRIVING_CAN_ID,\n DriveConstants.FRONT_RIGHT_TURNING_CAN_ID,\n DriveConstants.FRONT_RIGHT_CHASSIS_ANGULAR_OFFSET\n ),\n new MAXSwerveModule(\n DriveConstants.REAR_LEFT_DRIVING_CAN_ID,\n DriveConstants.REAR_LEFT_TURNING_CAN_ID,\n DriveConstants.REAR_LEFT_CHASSIS_ANGULAR_OFFSET\n ),\n new MAXSwerveModule(\n DriveConstants.REAR_RIGHT_DRIVING_CAN_ID,\n DriveConstants.REAR_RIGHT_TURNING_CAN_ID,\n DriveConstants.REAR_RIGHT_CHASSIS_ANGULAR_OFFSET\n )\n );\n }\n\n gyro = (RobotBase.isReal() ? new NavXGyro() : new SIMGyro(swerveModules));\n\n //RobotContainer.swerveTab.addNumber(\"Front Left\", swerveModules.frontLeft::getSwerveEncoderPosition).withWidget(BuiltInWidgets.kGraph);\n //RobotContainer.swerveTab.addNumber(\"Front Right\", swerveModules.frontRight::getSwerveEncoderPosition).withWidget(BuiltInWidgets.kGraph);\n //RobotContainer.swerveTab.addNumber(\"Back Left\", swerveModules.rearLeft::getSwerveEncoderPosition).withWidget(BuiltInWidgets.kGraph);\n //RobotContainer.swerveTab.addNumber(\"Back Right\", swerveModules.rearRight::getSwerveEncoderPosition).withWidget(BuiltInWidgets.kGraph);\n\n //RobotContainer.swerveTab.addNumber(\"Gyro\", () -> gyro.getAngle().getRadians()).withWidget(BuiltInWidgets.kGraph);\n }\n\n @Override\n public void periodic() {\n RobotContainer.poseEstimation.updateOdometry(\n getRotation(),\n getModulePositions()\n );\n\n gyro.update();\n swerveModules.update();\n\n logModuleStates(\"Swerve State\", swerveModules.getStates().asArray());\n logModuleStates(\"Swerve Set State\", new SwerveModuleState[]{\n swerveModules.frontLeft.getSetState(),\n swerveModules.frontRight.getSetState(),\n swerveModules.rearLeft.getSetState(),\n swerveModules.rearRight.getSetState()\n });\n SmartDashboard.putNumberArray(\"Swerve Module Distance\", new double[] {\n swerveModules.frontLeft.getPosition().distanceMeters / Constants.ModuleConstants.WHEEL_CIRCUMFERENCE_METERS,\n swerveModules.frontRight.getPosition().distanceMeters / Constants.ModuleConstants.WHEEL_CIRCUMFERENCE_METERS,\n swerveModules.rearLeft.getPosition().distanceMeters / Constants.ModuleConstants.WHEEL_CIRCUMFERENCE_METERS,\n swerveModules.rearRight.getPosition().distanceMeters / Constants.ModuleConstants.WHEEL_CIRCUMFERENCE_METERS});\n\n SmartDashboard.putNumberArray(\"Swerve Module Distance Revolutions\", new double[] {\n swerveModules.frontLeft.getPosition().distanceMeters,\n swerveModules.frontRight.getPosition().distanceMeters,\n swerveModules.rearLeft.getPosition().distanceMeters,\n swerveModules.rearRight.getPosition().distanceMeters});\n }\n\n private void logModuleStates(String key, SwerveModuleState[] swerveModuleStates) {\n List<Double> dataList = new ArrayList<>();\n for (SwerveModuleState swerveModuleState : swerveModuleStates) {\n dataList.add(swerveModuleState.angle.getRadians());\n dataList.add(swerveModuleState.speedMetersPerSecond);\n }\n SmartDashboard.putNumberArray(key,\n dataList.stream().mapToDouble(Double::doubleValue).toArray());\n }\n\n public Rotation2d getRotation() {\n Rotation2d rot = gyro.getAngle();\n\n if (DriveConstants.GYRO_REVERSED) {\n rot = rot.unaryMinus();\n }\n\n return rot;\n }\n \n public Rotation3d getRotation3d() {\n return gyro.getRotation3d();\n }\n\n public SwerveModulePosition[] getModulePositions() {\n return swerveModules.getPositions().asArray();\n }\n\n /**\n * Method to drive the drivetrain using chassis speeds.\n *\n * @param speeds The chassis speeds.\n */\n public void drive(ChassisSpeeds speeds) {\n SwerveModuleState[] swerveModuleStates = DriveConstants.DRIVE_KINEMATICS.toSwerveModuleStates(speeds);\n setModuleStates(swerveModuleStates);\n }\n\n /**\n * Sets the wheels into an X formation to prevent movement.\n */\n public void setX() {\n swerveModules.setDesiredStates(\n new SwerveModules.States(\n // front left\n new SwerveModuleState(0, Rotation2d.fromDegrees(45)),\n // front right\n new SwerveModuleState(0, Rotation2d.fromDegrees(-45)),\n // rear left\n new SwerveModuleState(0, Rotation2d.fromDegrees(-45)),\n // rear right\n new SwerveModuleState(0, Rotation2d.fromDegrees(45))\n ).asArray()\n );\n }\n\n /**\n * Sets the swerve ModuleStates.\n *\n * @param desiredStates The desired SwerveModule states.\n */\n public void setModuleStates(SwerveModuleState[] desiredStates) {\n SwerveDriveKinematics.desaturateWheelSpeeds(desiredStates, DriveConstants.MAX_SPEED_METERS_PER_SECOND);\n swerveModules.setDesiredStates(desiredStates);\n }\n\n /**\n * Resets the drive encoders to currently read a position of 0.\n */\n public void resetEncoders() {\n swerveModules.resetEncoders();\n }\n\n /**\n * Zeroes the heading of the robot.\n */\n public void zeroHeading() {\n gyro.reset();\n }\n\n /**\n * Returns the heading of the robot.\n *\n * @return the robot's heading in degrees, from -180 to 180\n */\n public Rotation2d getHeading() {\n return gyro.getAngle();\n }\n\n /**\n * Returns the turn rate of the robot.\n *\n * @return The turn rate of the robot, in degrees per second\n */\n public double getTurnRate() {\n return gyro.getRate().getDegrees();\n }\n}" }, { "identifier": "AllianceUtils", "path": "src/main/java/frc/robot/utils/AllianceUtils.java", "snippet": "public class AllianceUtils {\n public static Pose2d allianceToField(Pose2d alliancePose) {\n switch (DriverStation.getAlliance()) {\n case Blue:\n return alliancePose;\n case Red:\n return new Pose2d(\n new Translation2d(\n FieldConstants.fieldLength - alliancePose.getX(),\n alliancePose.getY()\n ),\n alliancePose.getRotation().minus(Rotation2d.fromRadians(Math.PI))\n );\n default:\n return null;\n }\n }\n\n public static Pose2d fieldToAlliance(Pose2d fieldPose) {\n switch (DriverStation.getAlliance()) {\n case Blue:\n return fieldPose;\n case Red:\n return new Pose2d(\n new Translation2d(\n FieldConstants.fieldLength - fieldPose.getX(),\n fieldPose.getY()\n ),\n fieldPose.getRotation().minus(new Rotation2d(Math.PI))\n );\n default:\n return null;\n }\n }\n\n public static boolean isBlue() {\n //Red seçince blue planı çalışıyo\n //Blue seçince red planı çalışıyo\n return DriverStation.getAlliance().equals(Alliance.Red);\n }\n\n public static double getDistanceFromAlliance(Pose2d pose) {\n return isBlue()? pose.getX() : FieldConstants.fieldLength - pose.getX();\n }\n\n public static Rotation2d getFieldOrientationZero() {\n return Rotation2d.fromRadians(isBlue() ? 0 : Math.PI);\n }\n}" } ]
import edu.wpi.first.math.geometry.Pose2d; import edu.wpi.first.math.geometry.Rotation2d; import edu.wpi.first.math.geometry.Translation2d; import edu.wpi.first.wpilibj.DriverStation; import edu.wpi.first.wpilibj.Joystick; import edu.wpi.first.wpilibj.shuffleboard.Shuffleboard; import edu.wpi.first.wpilibj.shuffleboard.ShuffleboardTab; import edu.wpi.first.wpilibj.smartdashboard.Field2d; import edu.wpi.first.wpilibj.smartdashboard.FieldObject2d; import edu.wpi.first.wpilibj.smartdashboard.SendableChooser; import edu.wpi.first.wpilibj2.command.Command; import edu.wpi.first.wpilibj2.command.InstantCommand; import edu.wpi.first.wpilibj2.command.RunCommand; import edu.wpi.first.wpilibj2.command.SequentialCommandGroup; import edu.wpi.first.wpilibj2.command.WaitCommand; import edu.wpi.first.wpilibj2.command.button.JoystickButton; import frc.robot.Constants.IntakeConstants; import frc.robot.commands.AutoElevator; import frc.robot.commands.AutoIntake; import frc.robot.commands.DriveWithJoysticks; import frc.robot.commands.GetInRange; import frc.robot.commands.IntakeCommand; import frc.robot.commands.LiftCommand; import frc.robot.commands.PneumaticCommand; import frc.robot.commands.AutoElevator.ElevatorPosition; import frc.robot.commands.AutoIntake.IntakePosition; import frc.robot.commands.GetInRange.LimelightPositionCheck; import frc.robot.commands.autonomous.AutoBalance; import frc.robot.commands.autonomous.AutoCommand; import frc.robot.commands.autonomous.OnePieceCharge; import frc.robot.poseestimation.PoseEstimation; import frc.robot.subsystems.IntakeSubsystem; import frc.robot.subsystems.LiftSubsystem; import frc.robot.subsystems.LimelightSubsystem; import frc.robot.subsystems.PneumaticSubsystem; import frc.robot.subsystems.drivetrain.Drivetrain; import frc.robot.utils.AllianceUtils; import com.pathplanner.lib.server.PathPlannerServer;
10,417
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. package frc.robot; /** * This class is where the bulk of the robot should be declared. Since Command-based is a * "declarative" paradigm, very little robot logic should actually be handled in the {@link Robot} * periodic methods (other than the scheduler calls). Instead, the structure of the robot (including * subsystems, commands, and trigger mappings) should be declared here. */ public class RobotContainer { //Limelight public static final LimelightSubsystem limelightSubsystem = new LimelightSubsystem(); //Intake public static final IntakeSubsystem intakeSubsystem = new IntakeSubsystem(); //Pneumatic public static final PneumaticSubsystem pneumaticSubsystem = new PneumaticSubsystem(); //Lift
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. package frc.robot; /** * This class is where the bulk of the robot should be declared. Since Command-based is a * "declarative" paradigm, very little robot logic should actually be handled in the {@link Robot} * periodic methods (other than the scheduler calls). Instead, the structure of the robot (including * subsystems, commands, and trigger mappings) should be declared here. */ public class RobotContainer { //Limelight public static final LimelightSubsystem limelightSubsystem = new LimelightSubsystem(); //Intake public static final IntakeSubsystem intakeSubsystem = new IntakeSubsystem(); //Pneumatic public static final PneumaticSubsystem pneumaticSubsystem = new PneumaticSubsystem(); //Lift
public static final LiftSubsystem liftSubsystem = new LiftSubsystem();
16
2023-11-18 14:02:20+00:00
12k
NewXdOnTop/skyblock-remake
src/main/java/com/sweattypalms/skyblock/SkyBlock.java
[ { "identifier": "CommandRegistry", "path": "src/main/java/com/sweattypalms/skyblock/commands/CommandRegistry.java", "snippet": "public class CommandRegistry {\n private static CommandRegistry instance;\n private final Map<String, MethodContainer> commands = new HashMap<>();\n\n public CommandRegistry() {\n instance = this;\n }\n\n public static CommandRegistry getInstance() {\n if (instance == null) {\n throw new IllegalStateException(\"Cannot call getInstance() before the plugin has been enabled!\");\n }\n return instance;\n }\n\n public int getCommandsAmt() {\n return this.commands.size();\n }\n\n public void registerAll() {\n //Reflections reflections = new Reflections(\"com.sweattypalms.skyblock.commands.handlers\");\n Reflections reflections = new Reflections(new ConfigurationBuilder()\n .setUrls(ClasspathHelper.forPackage(\"com.sweattypalms.skyblock.commands.handlers\"))\n .setScanners(Scanners.MethodsAnnotated));\n\n Set<Method> methods = reflections.getMethodsAnnotatedWith(Command.class);\n\n for (Method method : methods) {\n Object instance;\n try {\n instance = method.getDeclaringClass().getDeclaredConstructor().newInstance();\n register(instance);\n } catch (InstantiationException | IllegalAccessException | NoSuchMethodException |\n InvocationTargetException e) {\n e.printStackTrace();\n }\n }\n\n for (MethodContainer container : commands.values()) {\n registerCommandWithBukkit(container);\n }\n }\n\n private void registerCommandWithBukkit(MethodContainer container) {\n try {\n Command cmdInfo = container.commandMethod.getAnnotation(Command.class);\n\n final Field bukkitCommandMap = Bukkit.getServer().getClass().getDeclaredField(\"commandMap\");\n bukkitCommandMap.setAccessible(true);\n CommandMap commandMap = (CommandMap) bukkitCommandMap.get(Bukkit.getServer());\n\n commandMap.register(cmdInfo.name(), new BukkitCommand(cmdInfo.name()) {\n @Override\n public boolean execute(org.bukkit.command.CommandSender sender, String commandLabel, String[] args) {\n // This method will be overridden regardless by the CommandPreProcess event\n return true;\n }\n });\n\n } catch (NoSuchFieldException | IllegalAccessException e) {\n System.out.printf(\"Failed to register command %s%n\", container.commandMethod.getName());\n throw new RuntimeException(e);\n }\n }\n\n private void register(Object obj) {\n for (Method method : obj.getClass().getDeclaredMethods()) {\n if (method.isAnnotationPresent(Command.class)) {\n Command commandInfo = method.getAnnotation(Command.class);\n commands.put(commandInfo.name().toLowerCase(), new MethodContainer(obj, method));\n\n for (String alias : commandInfo.aliases()) {\n commands.put(alias.toLowerCase(), new MethodContainer(obj, method));\n }\n }\n }\n // Run tab completer afterwards because the command may not be registered before.\n for (Method method : obj.getClass().getDeclaredMethods()) {\n // Register tab completer methods\n if (method.isAnnotationPresent(TabCompleter.class)) {\n TabCompleter completerInfo = method.getAnnotation(TabCompleter.class);\n MethodContainer container = commands.get(completerInfo.command().toLowerCase());\n\n if (container != null) {\n container.tabCompleterMethod = method;\n } else {\n // Handle case where there's a completer for a non-existent command\n System.out.println(ChatColor.YELLOW + \"[Warning] TabCompleter for non-existent command: \" + completerInfo.command());\n }\n }\n }\n }\n\n public boolean executeCommand(Player player, String command, String[] args) {\n MethodContainer container = commands.get(command.toLowerCase());\n if (container == null) return false;\n\n Command cmdInfo = container.commandMethod.getAnnotation(Command.class);\n if (cmdInfo.op() && !player.isOp()) {\n player.sendMessage(ChatColor.RED + \"You do not have permission to use this command.\");\n return true;\n }\n\n // First try to get a commandMethod with args of (Player player, String[] args)\n try {\n container.commandMethod.invoke(container.instance, player, args);\n return true;\n } catch (IllegalArgumentException | IllegalAccessException | InvocationTargetException e) {\n // If first failed, try to get a commandMethod with args of (Player player)\n try {\n container.commandMethod.invoke(container.instance, player);\n return true;\n } catch (IllegalArgumentException | IllegalAccessException | InvocationTargetException _i) {\n }\n }\n\n return false;\n }\n\n public List<String> handleTabCompletion(CommandSender sender, String command, String[] args) {\n MethodContainer container = commands.get(command.toLowerCase());\n if (container != null && container.tabCompleterMethod != null) {\n try {\n return (List<String>) container.tabCompleterMethod.invoke(container.instance, sender, args);\n } catch (Exception e) {\n // Handle the exception gracefully, possibly log it for debugging\n e.printStackTrace();\n return new ArrayList<>();\n }\n }\n return new ArrayList<>();\n }\n\n public static class MethodContainer {\n public Method commandMethod;\n public Method tabCompleterMethod;\n public Object instance;\n\n public MethodContainer(Object instance, Method commandMethod) {\n this.instance = instance;\n this.commandMethod = commandMethod;\n }\n }\n}" }, { "identifier": "EnchantManager", "path": "src/main/java/com/sweattypalms/skyblock/core/enchants/EnchantManager.java", "snippet": "public class EnchantManager {\n public static final Map<String, Enchantment> ENCHANTMENTS = new HashMap<>();\n\n\n public static void init() {\n Reflections reflections = new Reflections(\"com.sweattypalms.skyblock.core.enchants.impl\");\n\n Set<Class<? extends Enchantment>> enchantmentClasses = reflections.getSubTypesOf(Enchantment.class);\n\n enchantmentClasses.forEach(clazz -> {\n\n if (Modifier.isAbstract(clazz.getModifiers())) {\n return;\n }\n\n try {\n Enchantment enchantment = clazz.getDeclaredConstructor().newInstance();\n ENCHANTMENTS.put(enchantment.getId(), enchantment);\n } catch (Exception e) {\n e.printStackTrace();\n }\n });\n }\n\n public static void registerEnchantment(Enchantment enchantment) {\n ENCHANTMENTS.put(enchantment.getId(), enchantment);\n }\n\n public static Enchantment getEnchantment(String id) throws IllegalArgumentException {\n if (!ENCHANTMENTS.containsKey(id)) {\n throw new IllegalArgumentException(\"Enchantment with id \" + id + \" does not exist!\");\n }\n return ENCHANTMENTS.get(id);\n }\n\n public static void triggerEnchantment(String id, Event event) {\n Enchantment enchantment = ENCHANTMENTS.get(id);\n// if (enchantment instanceof ITriggerable triggerableEnchant) {\n// triggerableEnchant.trigger(event);\n// }\n }\n\n public static Optional<Integer> getEnchantment(ItemStack item, String id) {\n String enchants = PDCHelper.getString(item, \"enchants\");\n if (enchants.isEmpty()) {\n return Optional.empty();\n }\n\n enchants = enchants.replace(\"[\", \"\").replace(\"]\", \"\");\n List<String> enchantList = List.of(enchants.split(\",\"));\n\n for (String enchant : enchantList) {\n String[] enchantData = enchant.split(\":\");\n if (enchantData[0].equals(id)) {\n return Optional.of(Integer.parseInt(enchantData[1]));\n }\n }\n\n return Optional.empty();\n }\n\n public static boolean hasEnchantment(ItemStack item, String id) {\n return getEnchantment(item, id).isPresent();\n }\n\n public static void addEnchantment(ItemStack item, String id, int level) {\n String enchants = PDCHelper.getString(item, \"enchants\");\n if (enchants.isEmpty()) {\n enchants = \"[\" + id + \":\" + level + \"]\";\n } else {\n enchants = enchants.replace(\"[\", \"\").replace(\"]\", \"\");\n List<String> enchantList = getEnchantmentList(id, level, enchants);\n\n enchants = \"[\" + String.join(\",\", enchantList) + \"]\";\n }\n\n PDCHelper.setString(item, \"enchants\", enchants);\n }\n\n\n\n @NotNull\n private static List<String> getEnchantmentList(String id, int level, String enchants) {\n List<String> enchantList = new ArrayList<>(List.of(enchants.split(\",\")));\n\n boolean found = false;\n for (int i = 0; i < enchantList.size(); i++) {\n String enchant = enchantList.get(i);\n String[] enchantData = enchant.split(\":\");\n if (enchantData[0].equals(id)) {\n enchantList.set(i, id + \":\" + level);\n found = true;\n break;\n }\n }\n\n if (!found) {\n enchantList.add(id + \":\" + level);\n }\n return enchantList;\n }\n\n public static List<Tuple<Enchantment, Integer>> getEnchantments(ItemStack item) {\n String enchants = PDCHelper.getString(item, \"enchants\");\n if (enchants.isEmpty()) {\n return Collections.emptyList();\n }\n\n enchants = enchants.replace(\"[\", \"\").replace(\"]\", \"\");\n List<String> enchantList = List.of(enchants.split(\",\"));\n\n List<Tuple<Enchantment, Integer>> enchantments = new ArrayList<>();\n for (String enchant : enchantList) {\n String[] enchantData = enchant.split(\":\");\n Enchantment enchantment = getEnchantment(enchantData[0]);\n if (enchantment != null) {\n enchantments.add(new Tuple<>(enchantment, Integer.parseInt(enchantData[1])));\n }\n }\n\n return enchantments;\n }\n\n\n public static void run(Player player, Event event) {\n ItemStack item = player.getInventory().getItemInHand();\n\n List<Tuple<Enchantment, Integer>> enchantments = getEnchantments(item);\n\n for (Tuple<Enchantment, Integer> enchantment : enchantments) {\n if (enchantment.a() instanceof ITriggerableEnchant triggerableEnchant && triggerableEnchant.should(event)) {\n triggerableEnchant.execute(enchantment.b(), event);\n }\n }\n\n }\n}" }, { "identifier": "ItemManager", "path": "src/main/java/com/sweattypalms/skyblock/core/items/ItemManager.java", "snippet": "public class ItemManager {\n public static Map<String, SkyblockItem> ITEMS_LIST = new HashMap<>(Map.of(\n ));\n\n public static ItemStack getItemStack(String id) {\n try {\n return ITEMS_LIST.get(id).toItemStack();\n } catch (Exception e) {\n return null;\n }\n }\n\n public static void init() {\n initReflection();\n initSimpleItems();\n Vanilla.init();\n }\n\n private static void initReflection() {\n Reflections reflections = new Reflections(\"com.sweattypalms.skyblock.core.items.types\");\n Set<Class<? extends SkyblockItem>> itemClasses = reflections.getSubTypesOf(SkyblockItem.class);\n\n for (Class<? extends SkyblockItem> clazz : itemClasses) {\n try {\n if (clazz == SimpleSkyblockItem.class) continue;\n SkyblockItem item = clazz.getDeclaredConstructor().newInstance();\n ITEMS_LIST.put(item.getId(), item);\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n }\n private static void initSimpleItems() {\n diamondSword();\n undeadSword();\n }\n private static void diamondSword(){\n SkyblockItem diamondSword = SimpleSkyblockItem.builder()\n .id(\"diamond_sword\")\n .displayName(\"Diamond Sword\")\n .material(Material.DIAMOND_SWORD)\n .stats(Map.of(Stats.DAMAGE, 35d))\n .baseRarity(Rarity.UNCOMMON)\n .itemType(SkyblockItemType.SWORD)\n .build();\n\n }\n private static void undeadSword(){\n SkyblockItem undeadSword = SimpleSkyblockItem.builder()\n .id(\"undead_sword\")\n .displayName(\"Undead Sword\")\n .material(Material.IRON_SWORD)\n .staticLore(List.of(\"$7Deals $a+100% $7damage to\", \"$7Skeletons, Zombies,\", \"$7Withers, and Zombie\", \"$7Pigwomen.\"))\n .stats(Map.of(Stats.DAMAGE, 30d, Stats.HEALTH, 50d))\n .baseRarity(Rarity.COMMON)\n .itemType(SkyblockItemType.SWORD)\n .abilities(List.of(AbilityManager.UNDEAD_SWORD_ABILITY))\n .build();\n }\n\n public SkyblockItem getFromVanillaItem(Material material) {\n SkyblockItemType itemType;\n\n for (SkyblockItemType value : SkyblockItemType.values()) {\n if(material.toString().contains(value.toString())) {\n itemType = value;\n break;\n }\n }\n\n return null;\n//\n// SkyblockItem skyblockItem = SimpleSkyblockItem\n// .builder()\n// .material(material)\n// .itemType(itemType)\n// .\n }\n}" }, { "identifier": "ReforgeManager", "path": "src/main/java/com/sweattypalms/skyblock/core/items/builder/reforges/ReforgeManager.java", "snippet": "public class ReforgeManager {\n public static Map<String, Reforge> REFORGES_LIST = new HashMap<>();\n\n public static void init(){\n Reflections reflections = new Reflections(\"com.sweattypalms.skyblock.core.items.builder.reforges.impl\");\n Set<Class<? extends Reforge>> reforgeClasses = reflections.getSubTypesOf(Reforge.class);\n\n for (Class<? extends Reforge> clazz : reforgeClasses) {\n try {\n Reforge reforge = clazz.getDeclaredConstructor().newInstance();\n REFORGES_LIST.put(reforge.getName().toLowerCase(), reforge);\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n }\n public static List<String> getReforgeLore(@Nullable Reforge reforge) {\n if (reforge == null) return new ArrayList<>();\n\n List<String> lore = new ArrayList<>();\n if (reforge instanceof IAdvancedReforge advancedReforge) {\n lore.add(\"$9\" + reforge.getName() + \" Bonus\");\n lore.addAll(advancedReforge.getLore());\n }\n lore = PlaceholderFormatter.format(lore);\n return lore;\n }\n\n public static Reforge getReforge(String name){\n if(REFORGES_LIST.containsKey(name)){\n return REFORGES_LIST.get(name);\n }\n return null;\n }\n}" }, { "identifier": "MobManager", "path": "src/main/java/com/sweattypalms/skyblock/core/mobs/builder/MobManager.java", "snippet": "public class MobManager {\n\n public static Map<String, Class<? extends ISkyblockMob>> MOBS_LIST = new HashMap<>();\n\n public static void init() {\n Reflections reflections = new Reflections(\"com.sweattypalms.skyblock\");\n\n for (Class<? extends ISkyblockMob> clazz : reflections.getSubTypesOf(ISkyblockMob.class)) {\n try {\n if (clazz.isInterface() || Modifier.isAbstract(clazz.getModifiers())) continue;\n\n String id = clazz.getDeclaredField(\"ID\").get(null).toString();\n MozangStuff.addToMaps(clazz, id, MozangStuff.getMobID(clazz.getSuperclass()));\n MOBS_LIST.put(id, clazz);\n } catch (Exception e) {\n System.out.println(\"Failed to load mob: \" + clazz.getName());\n System.out.println(\"Are you missing the `ID` field?\");\n }\n }\n }\n\n\n public static SkyblockMob getInstance(String id) throws IllegalArgumentException {\n// try {\n// return new SkyblockMob(id, MOBS_LIST.get(id));\n// } catch (Exception e) {\n// throw new IllegalArgumentException(\"Unknown mob id: \" + id);\n// }\n Class<? extends ISkyblockMob> clazz = MOBS_LIST.get(id);\n if (clazz == null) {\n throw new IllegalArgumentException(\"Unknown mob id: \" + id);\n }\n\n try {\n return new SkyblockMob(id, clazz);\n } catch (Exception e) {\n throw new IllegalArgumentException(\"Unknown mob id: \" + id);\n }\n }\n}" }, { "identifier": "DragonManager", "path": "src/main/java/com/sweattypalms/skyblock/core/mobs/builder/dragons/DragonManager.java", "snippet": "public class DragonManager {\n // (relative to 0,0)\n private final static List<Point> altarPoints = List.of(\n new Point(2, 1),\n new Point(2, -1),\n\n new Point(1, 2),\n new Point(1, -2),\n\n new Point(-1, 2),\n new Point(-1, -2),\n\n new Point(-2, 1),\n new Point(-2, -1)\n );\n public static Map<Location, Material> temp_save_backup = new HashMap<>();\n public static Map<Location, Byte> temp_save_backup_data = new HashMap<>();\n private static World endWorld; // TODO: implement better system\n private static DragonManager instance;\n private final Map<Block, UUID> altarBlocks = new HashMap<>();\n\n private int summoningEyes = 0;\n private SkyblockMob dragon;\n private final Map<UUID, Double> playerDamage = new HashMap<>();\n\n public double getPlayerDamage(UUID playerUUID) {\n return this.playerDamage.getOrDefault(playerUUID, 0d);\n }\n\n public void addPlayerDamage(UUID playerUUID, double damage) {\n double before = this.playerDamage.getOrDefault(playerUUID, 0.0);\n this.playerDamage.put(playerUUID, before + damage);\n }\n\n public DragonManager() {\n endWorld = Bukkit.getWorld(\"skyblock_end\");\n instance = this;\n }\n\n public static DragonManager getInstance() {\n if (instance == null) {\n throw new IllegalStateException(\"Cannot get instance of a singleton class before it is instantiated\");\n }\n return instance;\n }\n\n public void addSummoningEye(SkyblockPlayer player, Location location) {\n if (summoningEyes >= altarPoints.size()) {\n String message = \"$cThe altar is full!\";\n player.sendMessage(message);\n return;\n }\n\n Block altarBlock = location.getBlock();\n byte data = altarBlock.getData();\n\n\n if (data == 4) {\n String message = \"$cSorry, there is already an eye here!\";\n player.sendMessage(message);\n return;\n }\n\n if (this.dragon != null) {\n String message = \"$cThere is already a dragon in place!\";\n player.sendMessage(message);\n return;\n }\n\n summoningEyes++;\n\n String defaultMessage = \"$5⇒ %s $5placed a Summoning Eye! $7(%s%d$7/$a%d$7)\";\n String message = PlaceholderFormatter.format(String.format(defaultMessage, player.getPlayer().getDisplayName(), summoningEyes == altarPoints.size() ? \"$a\" : \"$e\", summoningEyes, altarPoints.size()));\n String myMessage = PlaceholderFormatter.format(String.format(defaultMessage, \"You\", summoningEyes == altarPoints.size() ? \"$a\" : \"$e\", summoningEyes, altarPoints.size()));\n assert endWorld != null;\n endWorld.getPlayers().stream().filter(_player -> _player.getUniqueId() != player.getPlayer().getUniqueId()).forEach(_player -> _player.sendMessage(message));\n player.getPlayer().sendMessage(myMessage);\n\n altarBlocks.put(altarBlock, player.getPlayer().getUniqueId()); // Will be used for taking out eyes.\n\n altarBlock.setData((byte) 4);\n\n\n ItemStack summoningEye = ItemManager.getItemStack(UsedSummoningEye.ID);\n player.getPlayer().getInventory().setItemInHand(summoningEye);\n\n if (summoningEyes == altarPoints.size()) {\n altarBlocks.values().forEach(uuid -> {\n int placedEyes = altarBlocks.values().stream().filter(_uuid -> _uuid.equals(uuid)).mapToInt(_uuid -> 1).sum();\n Player _player = Bukkit.getPlayer(uuid);\n final int[] removed = {0};\n int end = 45;\n for (int slot = 0; slot < end; slot++) {\n if (removed[0] >= placedEyes) break;\n ItemStack itemStack = _player.getInventory().getItem(slot);\n if (itemStack == null) continue;\n String id = PDCHelper.getString(itemStack, \"id\");\n if (id == null) continue;\n if (id.equals(UsedSummoningEye.ID)) {\n ItemStack remnantOfTheEye = ItemManager.getItemStack(RemnantOfTheEye.ID);\n player.getPlayer().getInventory().setItem(slot, remnantOfTheEye);\n removed[0]++;\n }\n }\n assert _player != null;\n _player.updateInventory();\n _player.sendMessage(\"removed \" + removed[0] + \" eyes\");\n });\n\n summonDragon();\n }\n }\n\n public void removeSummoningEye(SkyblockPlayer player, Location location) {\n if (!altarBlocks.containsKey(location.getBlock())) return;\n if (!altarBlocks.get(location.getBlock()).equals(player.getPlayer().getUniqueId())) {\n String message = \"$cYou cannot take out this eye!\";\n message = PlaceholderFormatter.format(message);\n player.getPlayer().sendMessage(message);\n return;\n }\n\n Block altarBlock = location.getBlock();\n altarBlock.setData((byte) 0);\n summoningEyes--;\n\n altarBlocks.remove(location.getBlock());\n\n ItemStack summoningEye = ItemManager.getItemStack(SummoningEye.ID);\n player.getPlayer().getInventory().setItemInHand(summoningEye);\n }\n\n private void summonDragon() {\n assert endWorld != null;\n\n// -8, 34, -8\n// -8 , 34, 9\n// 9, 34, 8\n// 9, 34, -8\n\n // diagonal\n final Location START_LOCATION = new Location(endWorld, -8, 34, -8);\n final Location END_LOCATION = new Location(endWorld, 9, 34, 8);\n\n Sequence sequence = new Sequence();\n\n int allStart = 34;\n for (int y = 28; y <= 68; y++) {\n Block blockAtLoc = endWorld.getBlockAt(0, y, 0);\n if (blockAtLoc.getType() == Material.WOOL && blockAtLoc.getData() == 10) {\n break;\n }\n int finalY = y;\n\n sequence.add(new SequenceAction(() -> {\n for (int x = START_LOCATION.getBlockX(); x <= END_LOCATION.getBlockX(); x++) {\n for (int z = START_LOCATION.getBlockZ(); z <= END_LOCATION.getBlockZ(); z++) {\n Location loc = new Location(endWorld, x, finalY, z);\n if (loc.getBlock().getType() == Material.AIR) continue;\n if (finalY > allStart) {\n if (checkSolidBlock(loc.getBlock())) continue;\n temp_save_backup.put(loc.getBlock().getLocation(), loc.getBlock().getType());\n temp_save_backup_data.put(loc.getBlock().getLocation(), loc.getBlock().getData());\n endWorld.getBlockAt(loc).setType(Material.AIR);\n }\n if (x == 0 && z == 0) {\n if (checkSolidBlock(loc.getBlock())) continue;\n temp_save_backup.put(loc.getBlock().getLocation(), XMaterial.PURPLE_STAINED_GLASS.parseMaterial());\n temp_save_backup_data.put(loc.getBlock().getLocation(), (byte) 10);\n endWorld.getBlockAt(loc).setType(Material.AIR);\n loc.clone().add(0, 1, 0).getBlock().setType(XMaterial.PURPLE_STAINED_GLASS.parseMaterial());\n loc.clone().add(0, 1, 0).getBlock().setData((byte) 10);\n if (loc.clone().add(0, 2, 0).getBlock().getType() == Material.WOOL && loc.clone().add(0, 2, 0).getBlock().getData() == 10) {\n break;\n }\n loc.clone().add(0, 2, 0).getBlock().setType(Material.SEA_LANTERN);\n }\n }\n }\n }, 4));\n }\n\n sequence.add(new SequenceAction(() -> {\n Location eggCenter = new Location(endWorld, 0, 83, 0);\n\n List<FallingBlock> blocks = new ArrayList<>();\n for (int y = 68; y < 100; y++) {\n for (int x = START_LOCATION.getBlockX(); x <= END_LOCATION.getBlockX(); x++) {\n for (int z = START_LOCATION.getBlockZ(); z <= END_LOCATION.getBlockZ(); z++) {\n Location loc = new Location(endWorld, x, y, z);\n if (loc.getBlock().getType() == Material.AIR) continue;\n if (checkSolidBlock(loc.getBlock())) continue;\n temp_save_backup.put(loc.getBlock().getLocation(), loc.getBlock().getType());\n temp_save_backup_data.put(loc.getBlock().getLocation(), loc.getBlock().getData());\n blocks.add(convertToFalling(loc, loc.getBlock().getType()));\n }\n }\n }\n\n simulateExplosion(blocks, eggCenter);\n\n TNTPrimed tnt = endWorld.spawn(eggCenter, TNTPrimed.class);\n tnt.setFuseTicks(0); // Explode immediately.\n tnt.setYield(0f); // No block damage.\n tnt.setIsIncendiary(false); // No fire.\n }, 5));\n\n sequence.add(new SequenceAction(\n () -> {\n String summonMessage = String.format(\"$5⇒ $l%s $5Dragon Spawned!\", \"Strong\");\n summonMessage = PlaceholderFormatter.format(summonMessage);\n String finalSummonMessage = summonMessage;\n endWorld.getPlayers().forEach(player -> player.sendMessage(finalSummonMessage));\n SkyblockMob dragon = MobManager.getInstance(StrongDragon.ID);\n dragon.spawn(new Location(endWorld, 0, 85, 0));\n this.dragon = dragon;\n },\n 30\n ));\n\n sequence.start();\n Location soundLoc = new Location(endWorld, 0, 35, 0);\n endWorld.playSound(soundLoc, Sound.ENDERDRAGON_DEATH, 8, 1);\n\n }\n\n private FallingBlock convertToFalling(Location loc, Material material) {\n FallingBlock fallingBlock = loc.getWorld().spawnFallingBlock(loc, material, (byte) 0);\n fallingBlock.setDropItem(false);\n fallingBlock.setHurtEntities(false);\n MozangStuff.noHit(fallingBlock);\n loc.getBlock().setType(Material.AIR);\n return fallingBlock;\n }\n\n private void simulateExplosion(List<FallingBlock> blocks, Location center) {\n for (FallingBlock block : blocks) {\n Vector direction = block.getLocation().subtract(center).toVector().normalize().multiply(2);\n direction.setY(0.5); // A slight upward direction.\n block.setVelocity(direction);\n }\n }\n\n private boolean checkSolidBlock(Block block) {\n BlockFace[] faces = {BlockFace.NORTH, BlockFace.SOUTH, BlockFace.EAST, BlockFace.WEST, BlockFace.UP, BlockFace.DOWN};\n\n for (BlockFace face : faces) {\n if (block.getRelative(face).getType() == Material.AIR) {\n return false;\n }\n }\n return true;\n }\n\n public void onEnderDragonDeath() {\n this.summoningEyes = 0;\n this.dragon.despawn();\n this.dragon = null;\n this.altarBlocks.keySet().forEach(block -> {\n block.setData((byte) 0);\n });\n this.altarBlocks.clear();\n this.playerDamage.clear();\n\n temp_save_backup.forEach((loc, type) -> {\n loc.getBlock().setType(type);\n loc.getBlock().setData(temp_save_backup_data.getOrDefault(loc, (byte) 0));\n });\n }\n\n private Location pointToLocation(Point point) {\n return new Location(endWorld, point.getX(), 30, point.getZ());\n }\n\n public boolean isDragonActive() {\n return dragon != null;\n }\n\n public SkyblockMob getActiveDragon() {\n return dragon;\n }\n}" }, { "identifier": "SkyblockPlayer", "path": "src/main/java/com/sweattypalms/skyblock/core/player/SkyblockPlayer.java", "snippet": "@Getter\npublic class SkyblockPlayer {\n private static final HashMap<UUID, SkyblockPlayer> players = new HashMap<>();\n\n private final Random random = new Random();\n private final StatsManager statsManager;\n private final InventoryManager inventoryManager;\n private final BonusManager bonusManager;\n private final CooldownManager cooldownManager;\n private final ActionBarManager actionBarManager;\n private final ScoreboardManager scoreboardManager;\n private final SlayerManager slayerManager;\n private final SkillManager skillManager;\n private final CurrencyManager currencyManager;\n private final Player player;\n private BukkitTask tickRunnable;\n\n @Getter @Setter\n private Regions lastKnownRegion = null;\n\n /**\n * This is used to get last use time of abilities\n */\n private final Map<String, Long> cooldowns = new HashMap<>();\n\n public SkyblockPlayer(Player player) {\n this.player = player;\n\n this.statsManager = new StatsManager(this);\n this.inventoryManager = new InventoryManager(this);\n this.bonusManager = new BonusManager(this);\n this.cooldownManager = new CooldownManager(this);\n this.actionBarManager = new ActionBarManager(this);\n this.slayerManager = new SlayerManager(this);\n this.skillManager = new SkillManager(this);\n this.currencyManager = new CurrencyManager(this);\n // Should be last because it uses the other managers\n this.scoreboardManager = new ScoreboardManager(this);\n\n players.put(player.getUniqueId(), this);\n init();\n }\n\n public static SkyblockPlayer getSkyblockPlayer(Player player) {\n return players.get(player.getUniqueId());\n }\n\n public static void newPlayer(Player player) {\n new SkyblockPlayer(player);\n }\n\n private void init() {\n\n String displayName = \"$c[OWNER] \" + this.player.getName();\n displayName = PlaceholderFormatter.format(displayName);\n this.player.setDisplayName(displayName);\n\n this.tickRunnable = new BukkitRunnable() {\n @Override\n public void run() {\n tick();\n }\n }.runTaskTimerAsynchronously(SkyBlock.getInstance(), 0, 1);\n\n this.statsManager.initHealth();\n }\n\n private int tickCount = 0;\n private void tick() {\n if (!this.player.isOnline()) {\n SkyblockPlayer.players.remove(this.player.getUniqueId());\n this.tickRunnable.cancel();\n }\n if (this.player.isDead()){\n return;\n }\n this.tickCount++;\n\n if (this.tickCount % 20 != 0) return;\n\n this.bonusManager.cleanupExpiredBonuses();\n this.statsManager.tick();\n this.actionBarManager.tick();\n\n this.scoreboardManager.updateScoreboard();\n RegionManager.updatePlayerRegion(this);\n }\n\n /**\n * Damage the player\n * TODO: Add various damage types\n * @param damage Damage to deal (With reduction)\n */\n public void damage(double damage) {\n if (this.player.getGameMode() != GameMode.SURVIVAL)\n return;\n this.player.setHealth(\n Math.max(\n this.player.getHealth() - damage,\n 0\n )\n );\n }\n\n public void damageWithReduction(double damage){\n double defense = this.statsManager.getMaxStats().get(Stats.DEFENSE);\n double finalDamage = DamageCalculator.calculateDamageReduction(defense, damage);\n this.damage(finalDamage);\n }\n\n /**\n * Send auto formatted message to player\n * @param s Message to send\n */\n public void sendMessage(String s) {\n this.player.sendMessage(PlaceholderFormatter.format(s));\n }\n\n public long getLastUseTime(String key){\n return this.cooldowns.getOrDefault(key, 0L);\n }\n\n public void setLastUseTime(String key, long time){\n this.cooldowns.put(key, time);\n }\n}" }, { "identifier": "WorldManager", "path": "src/main/java/com/sweattypalms/skyblock/core/world/WorldManager.java", "snippet": "public class WorldManager {\n\n static double tickTime = 0;\n public static void tick(){\n tickTime++;\n\n if (tickTime % 40 == 0) { // Every 2 seconds\n cleanupArrow();\n }\n }\n\n private static void cleanupArrow(){\n Bukkit.getWorlds().forEach(world -> world.getEntitiesByClass(Arrow.class).forEach(arrow ->{\n if (arrow.isOnGround()){\n arrow.remove();\n }\n }));\n }\n\n public static void init() {\n//later\n }\n}" } ]
import com.sweattypalms.skyblock.commands.CommandRegistry; import com.sweattypalms.skyblock.core.enchants.EnchantManager; import com.sweattypalms.skyblock.core.items.ItemManager; import com.sweattypalms.skyblock.core.items.builder.reforges.ReforgeManager; import com.sweattypalms.skyblock.core.mobs.builder.MobManager; import com.sweattypalms.skyblock.core.mobs.builder.dragons.DragonManager; import com.sweattypalms.skyblock.core.player.SkyblockPlayer; import com.sweattypalms.skyblock.core.world.WorldManager; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.event.Listener; import org.bukkit.plugin.java.JavaPlugin; import org.reflections.Reflections; import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import java.util.Set;
8,377
package com.sweattypalms.skyblock; // TODO: Work on skills + loot. public final class SkyBlock extends JavaPlugin { private static SkyBlock instance; public static SkyBlock getInstance() { return instance; } public boolean debug = true; @Override public void onEnable() { instance = this; long start = System.currentTimeMillis(); this.registerServer(); // Init the plugin asynchronously to speed up Bukkit.getScheduler().runTaskAsynchronously(this, () -> { registerCommands(); registerListeners(); registerCraft(); configs(); long end = System.currentTimeMillis() - start; System.out.println(ChatColor.GREEN + "Skyblock has been enabled! This took " + ChatColor.YELLOW + end + "ms"); }); drawAscii(); Bukkit.getOnlinePlayers().forEach(SkyblockPlayer::newPlayer); } private void registerServer() { WorldManager.init(); Bukkit.getScheduler().scheduleSyncRepeatingTask(this, WorldManager::tick, 0L, 1L); new DragonManager(); } private void registerCraft() { System.out.println("Registering items..."); ItemManager.init(); System.out.println(ChatColor.GREEN + "Successfully loaded " + ItemManager.ITEMS_LIST.size() + " items."); System.out.println("Registering mobs..."); MobManager.init(); System.out.println(ChatColor.GREEN + "Successfully loaded " + MobManager.MOBS_LIST.size() + " mobs."); System.out.println("Registering reforges...");
package com.sweattypalms.skyblock; // TODO: Work on skills + loot. public final class SkyBlock extends JavaPlugin { private static SkyBlock instance; public static SkyBlock getInstance() { return instance; } public boolean debug = true; @Override public void onEnable() { instance = this; long start = System.currentTimeMillis(); this.registerServer(); // Init the plugin asynchronously to speed up Bukkit.getScheduler().runTaskAsynchronously(this, () -> { registerCommands(); registerListeners(); registerCraft(); configs(); long end = System.currentTimeMillis() - start; System.out.println(ChatColor.GREEN + "Skyblock has been enabled! This took " + ChatColor.YELLOW + end + "ms"); }); drawAscii(); Bukkit.getOnlinePlayers().forEach(SkyblockPlayer::newPlayer); } private void registerServer() { WorldManager.init(); Bukkit.getScheduler().scheduleSyncRepeatingTask(this, WorldManager::tick, 0L, 1L); new DragonManager(); } private void registerCraft() { System.out.println("Registering items..."); ItemManager.init(); System.out.println(ChatColor.GREEN + "Successfully loaded " + ItemManager.ITEMS_LIST.size() + " items."); System.out.println("Registering mobs..."); MobManager.init(); System.out.println(ChatColor.GREEN + "Successfully loaded " + MobManager.MOBS_LIST.size() + " mobs."); System.out.println("Registering reforges...");
ReforgeManager.init();
3
2023-11-15 15:05:58+00:00
12k
cometcake575/Origins-Reborn
src/main/java/com/starshootercity/abilities/ShulkerInventory.java
[ { "identifier": "OriginSwapper", "path": "src/main/java/com/starshootercity/OriginSwapper.java", "snippet": "public class OriginSwapper implements Listener {\n private final static NamespacedKey displayKey = new NamespacedKey(OriginsReborn.getInstance(), \"display-item\");\n private final static NamespacedKey confirmKey = new NamespacedKey(OriginsReborn.getInstance(), \"confirm-select\");\n private final static NamespacedKey originKey = new NamespacedKey(OriginsReborn.getInstance(), \"origin-name\");\n private final static NamespacedKey swapTypeKey = new NamespacedKey(OriginsReborn.getInstance(), \"swap-type\");\n private final static NamespacedKey pageSetKey = new NamespacedKey(OriginsReborn.getInstance(), \"page-set\");\n private final static NamespacedKey pageScrollKey = new NamespacedKey(OriginsReborn.getInstance(), \"page-scroll\");\n private final static Random random = new Random();\n\n public static String getInverse(String string) {\n StringBuilder result = new StringBuilder();\n for (char c : string.toCharArray()) {\n result.append(getInverse(c));\n }\n return result.toString();\n }\n\n public static void openOriginSwapper(Player player, PlayerSwapOriginEvent.SwapReason reason, int slot, int scrollAmount, boolean forceRandom) {\n if (OriginLoader.origins.size() == 0) return;\n boolean enableRandom = OriginsReborn.getInstance().getConfig().getBoolean(\"origin-selection.random-option.enabled\");\n while (slot > OriginLoader.origins.size() || slot == OriginLoader.origins.size() && !enableRandom) {\n slot -= OriginLoader.origins.size() + (enableRandom ? 1 : 0);\n }\n while (slot < 0) {\n slot += OriginLoader.origins.size() + (enableRandom ? 1 : 0);\n }\n ItemStack icon;\n String name;\n char impact;\n LineData data;\n if (slot == OriginLoader.origins.size()) {\n List<String> excludedOrigins = OriginsReborn.getInstance().getConfig().getStringList(\"origin-selection.random-option.exclude\");\n icon = OrbOfOrigin.orb;\n name = \"Random\";\n impact = '\\uE002';\n StringBuilder names = new StringBuilder(\"You'll be assigned one of the following:\\n\\n\");\n for (Origin origin : OriginLoader.origins) {\n if (!excludedOrigins.contains(origin.getName())) {\n names.append(origin.getName()).append(\"\\n\");\n }\n }\n data = new LineData(LineData.makeLineFor(\n names.toString(),\n LineData.LineComponent.LineType.DESCRIPTION\n ));\n } else {\n Origin origin = OriginLoader.origins.get(slot);\n icon = origin.getIcon();\n name = origin.getName();\n impact = origin.getImpact();\n data = new LineData(origin);\n }\n StringBuilder compressedName = new StringBuilder(\"\\uF001\");\n for (char c : name.toCharArray()) {\n compressedName.append(c);\n compressedName.append('\\uF000');\n }\n Component component = Component.text(\"\\uF000\\uE000\\uF001\\uE001\\uF002\" + impact)\n .font(Key.key(\"minecraft:origin_selector\"))\n .color(NamedTextColor.WHITE)\n .append(Component.text(compressedName.toString())\n .font(Key.key(\"minecraft:origin_title_text\"))\n .color(NamedTextColor.WHITE)\n )\n .append(Component.text(getInverse(name) + \"\\uF000\")\n .font(Key.key(\"minecraft:reverse_text\"))\n .color(NamedTextColor.WHITE)\n );\n for (Component c : data.getLines(scrollAmount)) {\n component = component.append(c);\n }\n Inventory swapperInventory = Bukkit.createInventory(null, 54,\n component\n );\n ItemMeta meta = icon.getItemMeta();\n meta.getPersistentDataContainer().set(originKey, PersistentDataType.STRING, name.toLowerCase());\n if (meta instanceof SkullMeta skullMeta) {\n skullMeta.setOwningPlayer(player);\n }\n meta.getPersistentDataContainer().set(displayKey, PersistentDataType.BOOLEAN, true);\n meta.getPersistentDataContainer().set(swapTypeKey, PersistentDataType.STRING, reason.getReason());\n icon.setItemMeta(meta);\n swapperInventory.setItem(1, icon);\n ItemStack confirm = new ItemStack(Material.LIGHT_GRAY_STAINED_GLASS_PANE);\n ItemStack invisibleConfirm = new ItemStack(Material.LIGHT_GRAY_STAINED_GLASS_PANE);\n ItemMeta confirmMeta = confirm.getItemMeta();\n ItemMeta invisibleConfirmMeta = invisibleConfirm.getItemMeta();\n\n confirmMeta.displayName(Component.text(\"Confirm\")\n .color(NamedTextColor.WHITE)\n .decoration(TextDecoration.ITALIC, false));\n confirmMeta.setCustomModelData(5);\n confirmMeta.getPersistentDataContainer().set(confirmKey, PersistentDataType.BOOLEAN, true);\n\n invisibleConfirmMeta.displayName(Component.text(\"Confirm\")\n .color(NamedTextColor.WHITE)\n .decoration(TextDecoration.ITALIC, false));\n invisibleConfirmMeta.setCustomModelData(6);\n invisibleConfirmMeta.getPersistentDataContainer().set(confirmKey, PersistentDataType.BOOLEAN, true);\n\n if (!forceRandom) {\n ItemStack left = new ItemStack(Material.LIGHT_GRAY_STAINED_GLASS_PANE);\n ItemStack right = new ItemStack(Material.LIGHT_GRAY_STAINED_GLASS_PANE);\n ItemStack up = new ItemStack(Material.LIGHT_GRAY_STAINED_GLASS_PANE);\n ItemStack down = new ItemStack(Material.LIGHT_GRAY_STAINED_GLASS_PANE);\n ItemMeta leftMeta = left.getItemMeta();\n ItemMeta rightMeta = right.getItemMeta();\n ItemMeta upMeta = up.getItemMeta();\n ItemMeta downMeta = down.getItemMeta();\n\n leftMeta.displayName(Component.text(\"Previous origin\")\n .color(NamedTextColor.WHITE)\n .decoration(TextDecoration.ITALIC, false));\n leftMeta.getPersistentDataContainer().set(pageSetKey, PersistentDataType.INTEGER, slot - 1);\n leftMeta.getPersistentDataContainer().set(pageScrollKey, PersistentDataType.INTEGER, 0);\n leftMeta.setCustomModelData(1);\n\n\n rightMeta.displayName(Component.text(\"Next origin\")\n .color(NamedTextColor.WHITE)\n .decoration(TextDecoration.ITALIC, false));\n rightMeta.getPersistentDataContainer().set(pageSetKey, PersistentDataType.INTEGER, slot + 1);\n rightMeta.getPersistentDataContainer().set(pageScrollKey, PersistentDataType.INTEGER, 0);\n rightMeta.setCustomModelData(2);\n\n int scrollSize = OriginsReborn.getInstance().getConfig().getInt(\"origin-selection.scroll-amount\", 1);\n\n upMeta.displayName(Component.text(\"Up\")\n .color(NamedTextColor.WHITE)\n .decoration(TextDecoration.ITALIC, false));\n if (scrollAmount != 0) {\n upMeta.getPersistentDataContainer().set(pageSetKey, PersistentDataType.INTEGER, slot);\n upMeta.getPersistentDataContainer().set(pageScrollKey, PersistentDataType.INTEGER, Math.max(scrollAmount - scrollSize, 0));\n }\n upMeta.setCustomModelData(3 + (scrollAmount == 0 ? 6 : 0));\n\n\n int size = data.lines.size() - scrollAmount - 6;\n boolean canGoDown = size > 0;\n\n downMeta.displayName(Component.text(\"Down\")\n .color(NamedTextColor.WHITE)\n .decoration(TextDecoration.ITALIC, false));\n if (canGoDown) {\n downMeta.getPersistentDataContainer().set(pageSetKey, PersistentDataType.INTEGER, slot);\n downMeta.getPersistentDataContainer().set(pageScrollKey, PersistentDataType.INTEGER, Math.min(scrollAmount + scrollSize, scrollAmount + size));\n }\n downMeta.setCustomModelData(4 + (!canGoDown ? 6 : 0));\n\n left.setItemMeta(leftMeta);\n right.setItemMeta(rightMeta);\n up.setItemMeta(upMeta);\n down.setItemMeta(downMeta);\n\n swapperInventory.setItem(47, left);\n swapperInventory.setItem(51, right);\n swapperInventory.setItem(52, up);\n swapperInventory.setItem(53, down);\n }\n\n confirm.setItemMeta(confirmMeta);\n invisibleConfirm.setItemMeta(invisibleConfirmMeta);\n swapperInventory.setItem(48, confirm);\n swapperInventory.setItem(49, invisibleConfirm);\n swapperInventory.setItem(50, invisibleConfirm);\n player.openInventory(swapperInventory);\n }\n\n @EventHandler\n public void onInventoryClick(InventoryClickEvent event) {\n ItemStack item = event.getWhoClicked().getOpenInventory().getItem(1);\n if (item != null) {\n if (item.getItemMeta() == null) return;\n if (item.getItemMeta().getPersistentDataContainer().has(displayKey)) {\n event.setCancelled(true);\n }\n if (event.getWhoClicked() instanceof Player player) {\n ItemStack currentItem = event.getCurrentItem();\n if (currentItem == null) return;\n Integer page = currentItem.getItemMeta().getPersistentDataContainer().get(pageSetKey, PersistentDataType.INTEGER);\n if (page != null) {\n Integer scroll = currentItem.getItemMeta().getPersistentDataContainer().get(pageScrollKey, PersistentDataType.INTEGER);\n if (scroll == null) return;\n player.playSound(player, Sound.UI_BUTTON_CLICK, SoundCategory.MASTER, 1, 1);\n openOriginSwapper(player, getReason(item), page, scroll, false);\n }\n if (currentItem.getItemMeta().getPersistentDataContainer().has(confirmKey)) {\n String originName = item.getItemMeta().getPersistentDataContainer().get(originKey, PersistentDataType.STRING);\n if (originName == null) return;\n Origin origin;\n if (originName.equalsIgnoreCase(\"random\")) {\n List<String> excludedOrigins = OriginsReborn.getInstance().getConfig().getStringList(\"origin-selection.random-option.exclude\");\n List<Origin> origins = new ArrayList<>(OriginLoader.origins);\n origins.removeIf(origin1 -> excludedOrigins.contains(origin1.getName()));\n if (origins.isEmpty()) {\n origin = OriginLoader.origins.get(0);\n } else {\n origin = origins.get(random.nextInt(origins.size()));\n }\n } else {\n origin = OriginLoader.originNameMap.get(originName);\n }\n PlayerSwapOriginEvent.SwapReason reason = getReason(item);\n player.playSound(player, Sound.UI_BUTTON_CLICK, SoundCategory.MASTER, 1, 1);\n player.closeInventory();\n\n ItemMeta meta = player.getInventory().getItemInMainHand().getItemMeta();\n\n if (reason == PlayerSwapOriginEvent.SwapReason.ORB_OF_ORIGIN) {\n EquipmentSlot hand = null;\n if (meta != null) {\n if (meta.getPersistentDataContainer().has(OrbOfOrigin.orbKey)) {\n hand = EquipmentSlot.HAND;\n }\n }\n if (hand == null) {\n ItemMeta offhandMeta = player.getInventory().getItemInOffHand().getItemMeta();\n if (offhandMeta != null) {\n if (offhandMeta.getPersistentDataContainer().has(OrbOfOrigin.orbKey)) {\n hand = EquipmentSlot.OFF_HAND;\n }\n }\n }\n if (hand == null) return;\n orbCooldown.put(player, System.currentTimeMillis());\n player.swingHand(hand);\n if (OriginsReborn.getInstance().getConfig().getBoolean(\"orb-of-origin.consume\")) {\n player.getInventory().getItem(hand).setAmount(player.getInventory().getItem(hand).getAmount() - 1);\n }\n }\n boolean resetPlayer = shouldResetPlayer(reason);\n setOrigin(player, origin, reason, resetPlayer);\n }\n }\n }\n }\n\n public boolean shouldResetPlayer(PlayerSwapOriginEvent.SwapReason reason) {\n return switch (reason) {\n case COMMAND -> OriginsReborn.getInstance().getConfig().getBoolean(\"swap-command.reset-player\");\n case ORB_OF_ORIGIN -> OriginsReborn.getInstance().getConfig().getBoolean(\"orb-of-origin.reset-player\");\n default -> false;\n };\n }\n\n public static int getWidth(char c) {\n return switch (c) {\n case ':', '.', '\\'', 'i', ';', '|', '!', ',', '\\uF00A' -> 2;\n case 'l', '`' -> 3;\n case '(', '}', ')', '*', '[', ']', '{', '\"', 'I', 't', ' ' -> 4;\n case '<', 'k', '>', 'f' -> 5;\n case '^', '/', 'X', 'W', 'g', 'h', '=', 'x', 'J', '\\\\', 'n', 'y', 'w', 'L', 'j', 'Z', '1', '?', '-', 'G', 'H', 'K', 'N', '0', '7', '8', 'O', 'V', 'p', 'Y', 'z', '+', 'A', '2', 'd', 'T', 'B', 'b', 'R', 'q', 'F', 'Q', 'a', '6', 'e', 'C', 'U', '3', 'S', '#', 'P', 'M', '9', 'v', '_', 'o', 'm', '&', 'u', 'c', 'D', 'E', '4', '5', 'r', 's', '$', '%' -> 6;\n case '@', '~' -> 7;\n default -> throw new IllegalStateException(\"Unexpected value: \" + c);\n };\n }\n\n public static int getWidth(String s) {\n int result = 0;\n for (char c : s.toCharArray()) {\n result += getWidth(c);\n }\n return result;\n }\n\n public static char getInverse(char c) {\n return switch (getWidth(c)) {\n case 2 -> '\\uF001';\n case 3 -> '\\uF002';\n case 4 -> '\\uF003';\n case 5 -> '\\uF004';\n case 6 -> '\\uF005';\n case 7 -> '\\uF006';\n case 8 -> '\\uF007';\n case 9 -> '\\uF008';\n case 10 -> '\\uF009';\n default -> throw new IllegalStateException(\"Unexpected value: \" + c);\n };\n }\n\n public static Map<Player, Long> orbCooldown = new HashMap<>();\n\n public static void resetPlayer(Player player, boolean full) {\n AttributeInstance speedInstance = player.getAttribute(Attribute.GENERIC_MOVEMENT_SPEED);\n if (speedInstance != null) {\n speedInstance.removeModifier(player.getUniqueId());\n }\n ClientboundSetBorderWarningDistancePacket warningDistancePacket = new ClientboundSetBorderWarningDistancePacket(new WorldBorder() {{\n setWarningBlocks(player.getWorld().getWorldBorder().getWarningDistance());\n }});\n ((CraftPlayer) player).getHandle().connection.send(warningDistancePacket);\n player.setCooldown(Material.SHIELD, 0);\n player.setAllowFlight(false);\n player.setFlying(false);\n for (Player otherPlayer : Bukkit.getOnlinePlayers()) {\n AbilityRegister.updateEntity(player, otherPlayer);\n }\n AttributeInstance instance = player.getAttribute(Attribute.GENERIC_MAX_HEALTH);\n double maxHealth = getMaxHealth(player);\n if (instance != null) {\n instance.setBaseValue(maxHealth);\n }\n for (PotionEffect effect : player.getActivePotionEffects()) {\n if (effect.getAmplifier() == -1 || effect.getDuration() == PotionEffect.INFINITE_DURATION) player.removePotionEffect(effect.getType());\n }\n if (!full) return;\n player.getInventory().clear();\n player.getEnderChest().clear();\n player.setSaturation(5);\n player.setFallDistance(0);\n player.setRemainingAir(player.getMaximumAir());\n player.setFoodLevel(20);\n player.setFireTicks(0);\n player.setHealth(maxHealth);\n ShulkerInventory.getInventoriesConfig().set(player.getUniqueId().toString(), null);\n for (PotionEffect effect : player.getActivePotionEffects()) {\n player.removePotionEffect(effect.getType());\n }\n World world = getRespawnWorld(getOrigin(player));\n player.teleport(world.getSpawnLocation());\n player.setBedSpawnLocation(null);\n }\n\n public static @NotNull World getRespawnWorld(@Nullable Origin origin) {\n if (origin != null) {\n for (Ability ability : origin.getAbilities()) {\n if (ability instanceof DefaultSpawnAbility defaultSpawnAbility) {\n World world = defaultSpawnAbility.getWorld();\n if (world != null) return world;\n }\n }\n }\n String overworld = OriginsReborn.getInstance().getConfig().getString(\"worlds.world\");\n if (overworld == null) {\n overworld = \"world\";\n OriginsReborn.getInstance().getConfig().set(\"worlds.world\", \"world\");\n OriginsReborn.getInstance().saveConfig();\n }\n World world = Bukkit.getWorld(overworld);\n if (world == null) return Bukkit.getWorlds().get(0);\n return world;\n }\n\n public static double getMaxHealth(Player player) {\n Origin origin = getOrigin(player);\n if (origin == null) return 20;\n for (Ability ability : origin.getAbilities()) {\n if (ability instanceof HealthModifierAbility healthModifierAbility) {\n return healthModifierAbility.getHealth();\n }\n }\n return 20;\n }\n\n public static double getSpeedIncrease(Player player) {\n Origin origin = getOrigin(player);\n if (origin == null) return 0;\n for (Ability ability : origin.getAbilities()) {\n if (ability instanceof SpeedModifierAbility speedModifierAbility) {\n return speedModifierAbility.getSpeedIncrease();\n }\n }\n return 0;\n }\n\n @EventHandler\n public void onServerTickEnd(ServerTickEndEvent event) {\n for (Player player : Bukkit.getOnlinePlayers()) {\n if (getOrigin(player) == null) {\n if (player.isDead()) continue;\n if (player.getOpenInventory().getType() != InventoryType.CHEST) {\n if (OriginsReborn.getInstance().getConfig().getBoolean(\"origin-selection.randomise\")) {\n selectRandomOrigin(player, PlayerSwapOriginEvent.SwapReason.INITIAL);\n } else openOriginSwapper(player, PlayerSwapOriginEvent.SwapReason.INITIAL, 0, 0, false);\n }\n } else {\n AttributeInstance healthInstance = player.getAttribute(Attribute.GENERIC_MAX_HEALTH);\n if (healthInstance != null) healthInstance.setBaseValue(getMaxHealth(player));\n AttributeInstance speedInstance = player.getAttribute(Attribute.GENERIC_MOVEMENT_SPEED);\n if (speedInstance != null) {\n AttributeModifier modifier = speedInstance.getModifier(player.getUniqueId());\n if (modifier == null) {\n modifier = new AttributeModifier(player.getUniqueId(), \"speed-increase\", getSpeedIncrease(player), AttributeModifier.Operation.MULTIPLY_SCALAR_1);\n speedInstance.addModifier(modifier);\n }\n }\n player.setAllowFlight(AbilityRegister.canFly(player));\n player.setFlySpeed(AbilityRegister.getFlySpeed(player));\n player.setInvisible(AbilityRegister.isInvisible(player));\n }\n }\n }\n\n public void selectRandomOrigin(Player player, PlayerSwapOriginEvent.SwapReason reason) {\n Origin origin = OriginLoader.origins.get(random.nextInt(OriginLoader.origins.size()));\n setOrigin(player, origin, reason, shouldResetPlayer(reason));\n openOriginSwapper(player, reason, OriginLoader.origins.indexOf(origin), 0, true);\n }\n\n @EventHandler\n public void onPlayerRespawn(PlayerRespawnEvent event) {\n if (event.getPlayer().getBedSpawnLocation() == null) {\n World world = getRespawnWorld(getOrigin(event.getPlayer()));\n event.setRespawnLocation(world.getSpawnLocation());\n }\n if (event.getRespawnReason() != PlayerRespawnEvent.RespawnReason.DEATH) return;\n FileConfiguration config = OriginsReborn.getInstance().getConfig();\n if (config.getBoolean(\"origin-selection.death-origin-change\")) {\n setOrigin(event.getPlayer(), null, PlayerSwapOriginEvent.SwapReason.DIED, false);\n if (OriginsReborn.getInstance().getConfig().getBoolean(\"origin-selection.randomise\")) {\n selectRandomOrigin(event.getPlayer(), PlayerSwapOriginEvent.SwapReason.INITIAL);\n } else openOriginSwapper(event.getPlayer(), PlayerSwapOriginEvent.SwapReason.INITIAL, 0, 0, false);\n }\n }\n\n public PlayerSwapOriginEvent.SwapReason getReason(ItemStack icon) {\n return PlayerSwapOriginEvent.SwapReason.get(icon.getItemMeta().getPersistentDataContainer().get(swapTypeKey, PersistentDataType.STRING));\n }\n\n public static Origin getOrigin(Player player) {\n if (player.getPersistentDataContainer().has(originKey)) {\n return OriginLoader.originNameMap.get(player.getPersistentDataContainer().get(originKey, PersistentDataType.STRING));\n } else {\n String name = originFileConfiguration.getString(player.getUniqueId().toString());\n if (name == null) return null;\n player.getPersistentDataContainer().set(originKey, PersistentDataType.STRING, name);\n return OriginLoader.originNameMap.get(name);\n }\n }\n public static void setOrigin(Player player, @Nullable Origin origin, PlayerSwapOriginEvent.SwapReason reason, boolean resetPlayer) {\n PlayerSwapOriginEvent swapOriginEvent = new PlayerSwapOriginEvent(player, reason, resetPlayer, getOrigin(player), origin);\n if (!swapOriginEvent.callEvent()) return;\n if (swapOriginEvent.getNewOrigin() == null) {\n originFileConfiguration.set(player.getUniqueId().toString(), null);\n player.getPersistentDataContainer().remove(originKey);\n saveOrigins();\n resetPlayer(player, swapOriginEvent.isResetPlayer());\n return;\n }\n originFileConfiguration.set(player.getUniqueId().toString(), swapOriginEvent.getNewOrigin().getName().toLowerCase());\n player.getPersistentDataContainer().set(originKey, PersistentDataType.STRING, swapOriginEvent.getNewOrigin().getName().toLowerCase());\n saveOrigins();\n resetPlayer(player, swapOriginEvent.isResetPlayer());\n }\n\n\n private static File originFile;\n private static FileConfiguration originFileConfiguration;\n public OriginSwapper() {\n originFile = new File(OriginsReborn.getInstance().getDataFolder(), \"selected-origins.yml\");\n if (!originFile.exists()) {\n boolean ignored = originFile.getParentFile().mkdirs();\n OriginsReborn.getInstance().saveResource(\"selected-origins.yml\", false);\n }\n originFileConfiguration = new YamlConfiguration();\n try {\n originFileConfiguration.load(originFile);\n } catch (IOException | InvalidConfigurationException e) {\n throw new RuntimeException(e);\n }\n }\n\n public static void saveOrigins() {\n try {\n originFileConfiguration.save(originFile);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n public static class LineData {\n public static List<LineComponent> makeLineFor(String text, LineComponent.LineType type) {\n StringBuilder result = new StringBuilder();\n List<LineComponent> list = new ArrayList<>();\n List<String> splitLines = new ArrayList<>(Arrays.stream(text.split(\"\\n\", 2)).toList());\n StringBuilder otherPart = new StringBuilder();\n String firstLine = splitLines.remove(0);\n if (firstLine.contains(\" \") && getWidth(firstLine) > 140) {\n List<String> split = new ArrayList<>(Arrays.stream(firstLine.split(\" \")).toList());\n StringBuilder firstPart = new StringBuilder(split.get(0));\n split.remove(0);\n boolean canAdd = true;\n for (String s : split) {\n if (canAdd && getWidth(firstPart + \" \" + s) <= 140) {\n firstPart.append(\" \");\n firstPart.append(s);\n } else {\n canAdd = false;\n if (otherPart.length() > 0) otherPart.append(\" \");\n otherPart.append(s);\n }\n }\n firstLine = firstPart.toString();\n }\n for (String s : splitLines) {\n if (otherPart.length() > 0) otherPart.append(\"\\n\");\n otherPart.append(s);\n }\n if (type == LineComponent.LineType.DESCRIPTION) firstLine = '\\uF00A' + firstLine;\n for (char c : firstLine.toCharArray()) {\n result.append(c);\n result.append('\\uF000');\n }\n String finalText = firstLine;\n list.add(new LineComponent(\n Component.text(result.toString())\n .color(type == LineComponent.LineType.TITLE ? NamedTextColor.WHITE : TextColor.fromHexString(\"#CACACA\"))\n .append(Component.text(getInverse(finalText))),\n type\n ));\n if (otherPart.length() != 0) {\n list.addAll(makeLineFor(otherPart.toString(), type));\n }\n return list;\n }\n public static class LineComponent {\n public enum LineType {\n TITLE,\n DESCRIPTION\n }\n private final Component component;\n private final LineType type;\n\n public LineComponent(Component component, LineType type) {\n this.component = component;\n this.type = type;\n }\n\n public LineComponent() {\n this.type = LineType.DESCRIPTION;\n this.component = Component.empty();\n }\n\n public Component getComponent(int lineNumber) {\n @Subst(\"minecraft:text_line_0\") String formatted = \"minecraft:%stext_line_%s\".formatted(type == LineType.DESCRIPTION ? \"\" : \"title_\", lineNumber);\n return component.font(\n Key.key(formatted)\n );\n }\n }\n private final List<LineComponent> lines;\n public LineData(Origin origin) {\n lines = new ArrayList<>();\n lines.addAll(origin.getLineData());\n List<VisibleAbility> visibleAbilities = origin.getVisibleAbilities();\n int size = visibleAbilities.size();\n int count = 0;\n if (size > 0) lines.add(new LineComponent());\n for (VisibleAbility visibleAbility : visibleAbilities) {\n count++;\n lines.addAll(visibleAbility.getTitle());\n lines.addAll(visibleAbility.getDescription());\n if (count < size) lines.add(new LineComponent());\n }\n }\n public LineData(List<LineComponent> lines) {\n this.lines = lines;\n }\n\n public List<Component> getLines(int startingPoint) {\n List<Component> resultLines = new ArrayList<>();\n for (int i = startingPoint; i < startingPoint + 6 && i < lines.size(); i++) {\n resultLines.add(lines.get(i).getComponent(i - startingPoint));\n }\n return resultLines;\n }\n }\n}" }, { "identifier": "OriginsReborn", "path": "src/main/java/com/starshootercity/OriginsReborn.java", "snippet": "public class OriginsReborn extends JavaPlugin {\n private static OriginsReborn instance;\n\n public static OriginsReborn getInstance() {\n return instance;\n }\n\n private Economy economy;\n\n public Economy getEconomy() {\n return economy;\n }\n\n private boolean setupEconomy() {\n try {\n RegisteredServiceProvider<Economy> economyProvider = getServer().getServicesManager().getRegistration(net.milkbowl.vault.economy.Economy.class);\n if (economyProvider != null) {\n economy = economyProvider.getProvider();\n }\n return (economy != null);\n } catch (NoClassDefFoundError e) {\n return false;\n }\n }\n\n private boolean vaultEnabled;\n\n public boolean isVaultEnabled() {\n return vaultEnabled;\n }\n\n @Override\n public void onEnable() {\n instance = this;\n\n if (getConfig().getBoolean(\"swap-command.vault.enabled\")) {\n vaultEnabled = setupEconomy();\n if (!vaultEnabled) {\n getLogger().warning(\"Vault is not missing, origin swaps will not cost currency\");\n }\n } else vaultEnabled = false;\n saveDefaultConfig();\n PluginCommand command = getCommand(\"origin\");\n if (command != null) command.setExecutor(new OriginCommand());\n OriginLoader.loadOrigins();\n Bukkit.getPluginManager().registerEvents(new OriginSwapper(), this);\n Bukkit.getPluginManager().registerEvents(new OrbOfOrigin(), this);\n Bukkit.getPluginManager().registerEvents(new BreakSpeedModifierAbility.BreakSpeedModifierAbilityListener(), this);\n\n //<editor-fold desc=\"Register abilities\">\n List<Ability> abilities = new ArrayList<>() {{\n add(new PumpkinHate());\n add(new FallImmunity());\n add(new WeakArms());\n add(new Fragile());\n add(new SlowFalling());\n add(new FreshAir());\n add(new Vegetarian());\n add(new LayEggs());\n add(new Unwieldy());\n add(new MasterOfWebs());\n add(new Tailwind());\n add(new Arthropod());\n add(new Climbing());\n add(new Carnivore());\n add(new WaterBreathing());\n add(new WaterVision());\n add(new CatVision());\n add(new NineLives());\n add(new BurnInDaylight());\n add(new WaterVulnerability());\n add(new Phantomize());\n add(new Invisibility());\n add(new ThrowEnderPearl());\n add(new PhantomizeOverlay());\n add(new FireImmunity());\n add(new AirFromPotions());\n add(new SwimSpeed());\n add(new LikeWater());\n add(new LightArmor());\n add(new MoreKineticDamage());\n add(new DamageFromPotions());\n add(new DamageFromSnowballs());\n add(new Hotblooded());\n add(new BurningWrath());\n add(new SprintJump());\n add(new AerialCombatant());\n add(new Elytra());\n add(new LaunchIntoAir());\n add(new HungerOverTime());\n add(new MoreExhaustion());\n add(new Aquatic());\n add(new NetherSpawn());\n add(new Claustrophobia());\n add(new VelvetPaws());\n add(new AquaAffinity());\n add(new FlameParticles());\n add(new EnderParticles());\n add(new Phasing());\n add(new ScareCreepers());\n add(new StrongArms());\n add(new StrongArmsBreakSpeed());\n }};\n for (Ability ability : abilities) {\n AbilityRegister.registerAbility(ability);\n }\n //</editor-fold>\n }\n}" } ]
import com.starshootercity.OriginSwapper; import com.starshootercity.OriginsReborn; import net.kyori.adventure.key.Key; import net.kyori.adventure.text.Component; import org.bukkit.Bukkit; import org.bukkit.NamespacedKey; import org.bukkit.configuration.InvalidConfigurationException; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.event.inventory.InventoryCloseEvent; import org.bukkit.event.inventory.InventoryType; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.bukkit.persistence.PersistentDataType; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.File; import java.io.IOException; import java.util.List;
7,292
package com.starshootercity.abilities; public class ShulkerInventory implements VisibleAbility, Listener { @Override public @NotNull Key getKey() { return Key.key("origins:shulker_inventory"); } @Override
package com.starshootercity.abilities; public class ShulkerInventory implements VisibleAbility, Listener { @Override public @NotNull Key getKey() { return Key.key("origins:shulker_inventory"); } @Override
public @NotNull List<OriginSwapper.LineData.LineComponent> getDescription() {
0
2023-11-10 21:39:16+00:00
12k
Hikaito/Fox-Engine
src/system/gui/project/ProjectFileSelection.java
[ { "identifier": "ProjectManager", "path": "src/system/project/ProjectManager.java", "snippet": "public class ProjectManager {\n\n // UUID methods\n public String getUUID(){return root.getUUID();}\n public boolean matchesUUID(String other){\n return root.getUUID().equals(other);\n }\n\n public String getTitle(){return root.getTitle();}\n\n // reject if program number is lower than project\n public static boolean evaluateProjectNumber(VersionNumber program, VersionNumber project){\n if(program.compareTo(project) < 0) return false;\n return true;\n }\n\n // project root\n protected ProjectRoot root;\n public ProjectRoot getRoot(){return root;}\n\n // tree generation\n public DefaultMutableTreeNode getTree(){\n return root.getTree();\n }\n\n // updates menu offshoot entities\n public void updateDependencies(){\n buildDictionary();\n root.generateMenu();\n }\n\n //region dictionary----------------------------\n // dictionary\n protected HashMap<Long, ProjectFile> dictionary;\n\n //build dictionary\n public void buildDictionary(){\n dictionary = new HashMap<>(); // generate new dictionary\n addDict(root); // build from root\n }\n\n // build dictionary recursive\n protected void addDict(ProjectUnitCore root){\n // case file: add to dictionary\n if (root instanceof ProjectFile){\n ProjectFile unit = (ProjectFile) root; //cast object\n dictionary.put(unit.getID(), unit);\n }\n //recurse to all children for file types\n else if (root instanceof ProjectFolderInterface){\n ProjectFolderInterface unit = (ProjectFolderInterface) root; //cast object\n for (ProjectUnitCore child: unit.getChildren()){\n addDict(child);\n }\n }\n }\n\n //query dictionary; returns null if none found\n public ProjectFile getFile(long code){\n // return null if nocode\n if(code == Program.getDefaultFileCode()) return null;\n\n return dictionary.get(code);\n }\n // endregion\n\n // save file------------------------------------\n // GSON builder\n private static final Gson gson = new GsonBuilder()\n .excludeFieldsWithoutExposeAnnotation() // only includes fields with expose tag\n .setPrettyPrinting() // creates a pretty version of the output\n .registerTypeAdapter(Color.class, new ColorAdapter()) // register color adapter\n .registerTypeAdapter(TreeUnit.class, new RendererTypeAdapter()) // register sorting deserializer for renderer\n .registerTypeAdapter(ProjectUnitCore.class, new ProjectTypeAdapter()) // registers abstract classes\n .create();\n\n // function for saving file\n public boolean saveFile(){\n // derive json\n String json = gson.toJson(root);\n\n //generate absolute path to location\n String path = Paths.get(root.getPath(), Program.getProjectFile()).toString();\n\n // write json to file\n try {\n FileWriter out = new FileWriter(path, false);\n out.write(json);\n out.close();\n // log action\n Program.log(\"File '\" + Program.getProjectFile() + \"' saved as project file at \" + path);\n } catch (IOException e) {\n e.printStackTrace();\n return false;\n }\n\n return true;\n }\n\n // initialization function----------------------------\n public void initializeEmpty(){\n root = new ProjectRoot(\"Null Project\"); //create project root\n\n Program.log(\"Project initialized from filesystem.\");\n }\n\n public void initializeProject(String fullpath){\n // attempt opening\n ProjectRoot tempRoot = readTree(fullpath); // read file\n\n // test version number\n if(!evaluateProjectNumber(Program.getProgramVersion(), tempRoot.getProgramVersion())){\n WarningWindow.warningWindow(\"Project version invalid. Program version: \" + Program.getProgramVersion() + \"; Project version: \" + tempRoot.getProgramVersion());\n initializeEmpty();\n return;\n }\n\n // open directory\n root = tempRoot; // if project version acceptible, save project\n root = readTree(fullpath);\n\n Program.log(\"Project at \"+ fullpath + \" imported.\");\n\n // open file editing dialogue\n // dictionary generated on window close\n try {\n ProjectEditor window = new ProjectEditor(this);\n } catch (IOException e) {\n e.printStackTrace();\n }\n\n }\n\n protected ProjectRoot readTree(String fullpath){\n // open directory\n File file = new File(fullpath); // create file object to represent path\n String title = file.getName(); //set project name to folder title\n ProjectRoot tempRoot = new ProjectRoot(title); //create project root\n tempRoot.setPath(fullpath); //set directory path\n\n // recurse for each item in folder on created folder as parent\n File[] files = file.listFiles();\n assert files != null;\n for(File child: files){\n initializeTree(tempRoot.getChildren(), child, tempRoot);\n }\n // generate parents when complete\n tempRoot.generateParents();\n\n Program.log(\"Project at \"+ fullpath + \" read from filesystem.\");\n\n return tempRoot;\n }\n\n protected void initializeTree(LinkedList<ProjectUnitCore> folder, File file, ProjectRoot temproot){\n //recursive case: folder; repeat call for each file inside\n if (file.isDirectory()){\n // exclude internal folders\n if(file.getAbsolutePath().endsWith(Program.getSaveFolder())\n || file.getAbsolutePath().endsWith(Program.getRenderFolder())\n || file.getAbsolutePath().endsWith(Program.getTemplateFolder())){\n return;\n }\n\n // create a folder node and add to tree\n ProjectFolder folderObj = new ProjectFolder(file.getName(), temproot.getNextID());\n folder.addLast(folderObj);\n\n // recurse for each item in folder on created folder as parent\n File[] files = file.listFiles();\n assert files != null;\n for(File child: files){\n initializeTree(folderObj.getChildren(), child, temproot);\n }\n }\n // base case: file. add file if a valid file is found\n else{\n // if the file has a valid extension\n if (FileOperations.validExtension(file.getName(), Program.getFileExtensionLoadImage())) {\n //create a file node and add to tree\n ProjectFile newFile = new ProjectFile(FileOperations.trimDirectory(temproot.getPath(),file.getAbsolutePath()).toString(),\n FileOperations.stripExtension(file.getName(), Program.getFileExtensionLoadImage()),\n temproot.getNextID());\n newFile.setValid(true);\n folder.addLast(newFile);\n }\n }\n }\n\n // loading function: folder selection\n public void loadProject(){\n\n String text = FileOperations.selectFolder(System.getProperty(\"user.dir\")); // get project, starting at local directory\n // if a directory was selected\n if(text != null){\n // autosave file\n Program.generateManagerFile(Program.getAutosavePath(\"PROJECT_CHANGE\")); // autosave layer tree\n loadProject(text); // load project\n Program.newFileNoWarning(); // remove null file NOTE it is importannt that this occur after the project change\n Program.redrawAllRegions();\n Program.redrawMenuBar();\n Program.setProjectPath(text); // set new project path\n }\n }\n\n // loading function\n public void loadProject(String path){\n String fullpath = Paths.get(path, Program.getProjectFile()).toString(); //generate absolute path to project\n\n //load root\n try {\n String json = new String(Files.readAllBytes(Paths.get(fullpath))); // read json from file\n ProjectRoot tempRootLoad = gson.fromJson(json, ProjectRoot.class); // convert json to object of interest\n Program.log(\"Project loaded from \" + fullpath);\n\n // set root path\n tempRootLoad.setPath(path);\n\n // evaluate project number\n if(!evaluateProjectNumber(Program.getProgramVersion(), tempRootLoad.getProgramVersion())){\n WarningWindow.warningWindow(\"Project version invalid. Program version: \" + Program.getProgramVersion() + \"; Project version: \" + tempRootLoad.getProgramVersion());\n initializeEmpty();\n return;\n }\n\n root = tempRootLoad; // keep load\n\n // load project tree\n ProjectRoot tempRoot = readTree(path);\n\n // place\n SortedSet<ProjectFile> discoveredFiles = new TreeSet<>();\n SortedSet<ProjectFile> existingFiles = new TreeSet<>();\n\n //traverse trees\n fillFileList(tempRoot, discoveredFiles);\n fillFileList(root, existingFiles);\n\n //eliminate common files\n //common files list exists to prevent concurrent removal and traversal errors\n SortedSet<ProjectFile> commonFiles = new TreeSet<>();\n // find files that are common\n for(ProjectFile file:existingFiles){\n // if a file was found, remove it from both lists\n if (discoveredFiles.contains(file)){\n commonFiles.add(file); //add to common list\n }\n }\n // remove common files\n for(ProjectFile file:commonFiles){\n // if a file was found, remove it from both lists\n discoveredFiles.remove(file);\n existingFiles.remove(file);\n file.setValid(true);\n }\n\n // open reconciliation dialogue\n // if files remain in either list, open window\n if (discoveredFiles.size() != 0 || existingFiles.size() != 0){\n // dictionary generated on window close\n ProjectReconciliation window = new ProjectReconciliation(this, existingFiles, discoveredFiles);\n }\n else{\n root.generateParents(); //generate parents to menu\n updateDependencies(); // generate dictionary if all is well\n }\n\n // save new location\n Program.setProjectPath(path);\n\n }\n // return null if no object could be loaded; initialize instead\n catch (IOException e) {\n Program.log(\"Project file could not be read. Source: \" + fullpath);\n initializeProject(path);\n }\n }\n\n // tree traversal function for collecting files into a sorted list\n protected void fillFileList(ProjectUnitCore root, SortedSet<ProjectFile> files){\n // if file, add to files and return\n if(root instanceof ProjectFile){\n files.add((ProjectFile) root);\n return;\n }\n // if folder, generate children list\n LinkedList<ProjectUnitCore> children;\n if (root instanceof ProjectRoot) children = ((ProjectRoot) root).getChildren();\n else if (root instanceof ProjectFolder) children = ((ProjectFolder) root).getChildren();\n else return;\n\n // recurse on children\n for (ProjectUnitCore child:children){\n fillFileList(child, files);\n }\n }\n\n public String getAbsolutePath(ProjectFile file){\n return Paths.get(root.getPath(), file.getPath()).toString();\n }\n\n public static void mergeFile(ProjectFile keep, ProjectFile flake){\n keep.setValid(flake.isValid()); // copy validity\n keep.setPath(flake.getPath()); // copy path\n }\n\n public void addFile(ProjectFile file){\n file.setValid(true); //set valid as true\n file.setID(root.getNextID()); // assign a proper ID value\n root.getChildren().addLast(file); // add element to root list\n file.setParent(root); // register root as parent\n }\n\n public void openEditor(){\n try {\n //generates dictionary on close\n ProjectEditor window = new ProjectEditor(this);\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n // selector for layer\n public void openSelector(Layer layer){\n try {\n ProjectFileSelection window = new ProjectFileSelection(this, layer);\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n // selector for folder\n public void openSelector(Folder folder){\n try {\n ProjectFileSelection window = new ProjectFileSelection(this, folder);\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n\n public JMenu getMenu(){\n return root.generateMenu();\n }\n\n}" }, { "identifier": "CoreGlobal", "path": "src/system/setting/CoreGlobal.java", "snippet": "public class CoreGlobal {\n public static final int LEFT_BASE_PAD = 40;\n public static final int LEFT_INCREMENTAL_PAD = 50;\n public static final int LEFT_PAD = LEFT_BASE_PAD + LEFT_INCREMENTAL_PAD;\n public static final int TREE_LEVEL_PAD = 30;\n public static final int MAX_HEIGHT_TREE_BAR = 50;\n public static final int MAX_WIDTH = 9000;\n\n public static final int EDITOR_WINDOW_HEIGHT = 600;\n public static final int EDITOR_WINDOW_WIDTH = 1000;\n public static final int EDITOR_WINDOW_IMAGE = 500;\n public static final int RECONCILIATION_WINDOW_HEIGHT = 600;\n public static final int RECONCILIATION_WINDOW_WIDTH = 1200;\n //public static final int RECONCILIATION_WINDOW_IMAGE = 500;\n public static final int WARNING_WINDOW_HEIGHT = 200;\n public static final int WARNING_WINDOW_WIDTH = 500;\n}" }, { "identifier": "Folder", "path": "src/system/layerTree/data/Folder.java", "snippet": "public class Folder extends LayerCore implements Copy<Folder>, Renderable, LayerTreeFolder {\n\n //region constructor and Copy interface------------------------------------\n\n //constructor\n public Folder(){\n super(\"folder\"); //fixme remove this element entirelly later\n\n //folder\n displayChildren = true;\n clipIntersect = false;\n }\n\n //copy interface\n @Override\n public Folder copy() {\n return copy(true);\n }\n\n //internal copy\n // true = use copy title, false = true title\n public Folder copy(boolean label){\n Folder obj = new Folder();\n\n //LayerCORE\n obj.clipToParent = clipToParent;\n obj.visible = visible;\n obj.alpha = alpha;\n // use copy title if indicated\n if(label) obj.title = title + \" (copy)\";\n else obj.title = title;\n\n //Folder\n obj.displayChildren = displayChildren;\n // clone internal elements\n LinkedList<TreeUnit> children = getChildren();\n LinkedList<TreeUnit> newChildren = obj.getChildren();\n // copy each applicable object\n for(TreeUnit child:children){\n if (child instanceof Copy){\n TreeUnit clone = (TreeUnit) ((Copy<?>) child).copy(); // copy object\n clone.setParent(obj); // set parent\n newChildren.addLast(clone); // add object to new list\n }\n }\n obj.clipIntersect = clipIntersect;\n obj.intersectImage = intersectImage.copy();\n\n // rendering\n //fixme i think this can be optimized for large folders by copying the original image object\n obj.requireRender();\n\n return obj;\n }\n //endregion\n //region intersect clipping----------------------------------\n\n // Purpose: controls intersect clipping False = no clipping, True = clipping\n @Expose\n @SerializedName(value = \"intersect_clip\")\n protected boolean clipIntersect;\n\n // accessor\n public boolean getIntersectClip(){\n return clipIntersect;\n }\n public boolean hasIntersectImage(){\n if (intersectImage == null) return false;\n return true;\n }\n\n\n // mutator (no argument = toggle)\n public void setIntersectClip(){\n // invert value if permission exists; otherwise revoke intersect\n if (intersectImage == null){\n clipIntersect = false;\n }\n else{\n clipIntersect = !clipIntersect;\n }\n\n // mark for rerendering and render\n Program.markImageForRender(this); // mark tree for rerender\n Program.redrawAllRegions(); // signal for redraw\n }\n\n // Purpose: set and store image\n @Expose\n @SerializedName(value = \"intersect_image\")\n protected ImageUnit intersectImage = null;\n\n // set intersect image\n public void setIntersectImage(long fileCode){\n intersectImage = new ImageUnit(fileCode); // create image unit\n clipIntersect = true; // automatically use clipping\n\n // mark for rerendering and render\n Program.markImageForRender(this); // mark tree for rerender\n Program.redrawAllRegions(); // signal for redraw\n }\n\n // remove intersect image\n public void revokeIntersectImage(){\n intersectImage = null; // revoke image\n clipIntersect = false; // revoke clip permission\n\n // mark for rerendering and render\n Program.markImageForRender(this); // mark tree for rerender\n Program.redrawAllRegions(); // signal for redraw\n }\n\n // accessor for intersect image title\n public String getIntersectTitle(){\n if (intersectImage != null) return intersectImage.getTitle();\n return \"no image selected\";\n }\n\n //endregion\n //region renderable interface----------------------------------\n\n //requires render boolean\n protected boolean requiresRender = true;\n protected BufferedImage imageSource = new BufferedImage(Program.getDefaultCanvasWidth(), Program.getDefaultCanvasHeight(), BufferedImage.TYPE_INT_ARGB); //image raw\n protected BufferedImage imageAlpha = imageSource; //colored image with alpha mask applied\n\n // get image\n @Override\n public BufferedImage getImage(){\n // regenerate sources if marked as changed\n if (requiresRender){\n //fixme add internal booleans for marking alpha editing to skip steps\n\n // regenerate source image-----------------------------------------\n // get largest size among children that generate an image; also generates any rendering\n int maxH = 1;\n int maxW = 1;\n BufferedImage temp;\n LinkedList<TreeUnit> children = getChildren();\n for(TreeUnit child: children){\n if (child instanceof Renderable){\n temp = ((Renderable)child).getImage();\n if (temp.getWidth() > maxW) maxW = temp.getWidth();\n if (temp.getHeight() > maxH) maxH = temp.getHeight();\n }\n }\n\n // generate stacking\n temp = new BufferedImage(maxW, maxH, BufferedImage.TYPE_INT_ARGB);\n Graphics g = temp.getGraphics(); // get graphics for image\n\n // for each child, iterating from reverse, draw graphics if applicable.\n // Note: there are two 'currents' for handling clipping\n ListIterator<TreeUnit> iterator = children.listIterator(children.size());\n BufferedImage cliptemp = null;\n\n // while children exist, iterate\n while(iterator.hasPrevious()){\n TreeUnit child = iterator.previous(); // get child\n // if child is renderable\n if (child instanceof Renderable){\n\n // if current is set to clip, apply to cliptemp layer\n if (child instanceof LayerCore && ((LayerCore) child).getClipToParent()){\n // draw to cliptemp if cliptemp exists\n if (cliptemp != null){\n //cliptemp = ImageOperations.clipIntersect(cliptemp, ((Renderable) child).getImage()); fixme this is masking\n cliptemp = ImageOperations.clipMerge(cliptemp, ((Renderable) child).getImage());\n }\n }\n // if current is not set to clip, make new cliptemp layer and apply cliptemp layer\n else{\n // if there is a cliptemp, draw to image\n if (cliptemp != null) g.drawImage(cliptemp, 0, 0, null);\n\n // collect image to cliptemp\n cliptemp = ((Renderable)child).getImage();\n }\n }\n }\n //cleanup cliptemp\n if (cliptemp != null){g.drawImage(cliptemp, 0, 0, null);}\n\n g.dispose(); //clean up after self\n imageSource = temp;\n\n // mark requirement regenerate imageAlpha\n requiresAlphaRerender = true;\n\n //resolve require render\n unrequireRender();\n }\n if (requiresAlphaRerender){\n //regenerate imageAlpha; simply preserve source if alpha is full\n if (alpha == 1.0) imageAlpha = imageSource;\n else imageAlpha = ImageOperations.shiftAlpha(imageSource, alpha);\n\n // add intersection mask as appropriate\n if(hasIntersectImage() && clipIntersect){\n imageAlpha = ImageOperations.clipIntersect(intersectImage.get(), imageAlpha);\n }\n\n requiresAlphaRerender = false;\n }\n\n // if not visible, return empty buffered image\n if (!visible) return new BufferedImage(imageAlpha.getWidth(), imageAlpha.getHeight(), BufferedImage.TYPE_INT_ARGB);\n\n // otherwise return colored image\n return imageAlpha;\n }\n\n // get render state\n @Override\n public boolean getRenderState(){\n return requiresRender;\n }\n\n // flag for rerender\n @Override\n public void requireRender(){\n requiresRender = true;\n }\n\n // set render to false\n @Override\n public void unrequireRender() {\n requiresRender = false;\n }\n //endregion\n //region LayerTreeFolder interface and associates---------------------------------\n\n //children\n @Expose\n @SerializedName(value = \"children\")\n private LinkedList<TreeUnit> children = new LinkedList<>();\n\n // region display children boolean---------------------------------\n @Expose\n @SerializedName(value = \"display_children\")\n public boolean displayChildren = true;\n\n //accessor and mutator for children visibility\n public Boolean getChildrenVisiblity(){return displayChildren;}\n public void toggleChildrenVisibility(){\n displayChildren = !displayChildren;\n }\n //endregion\n\n // grant access to children list\n @Override\n public LinkedList<TreeUnit> getChildren(){\n return children;\n }\n\n // clear children list\n @Override\n public void clearChildren(){\n children = new LinkedList<>();\n // .clear() does not explicitly clear\n }\n //endregion\n}" }, { "identifier": "Layer", "path": "src/system/layerTree/data/Layer.java", "snippet": "public class Layer extends LayerCore implements Copy<Layer>, Renderable {\n\n //region constructor and copy interface--------------\n public Layer(){\n super(\"layer\");\n useColor = true;\n color = Color.darkGray;\n }\n\n @Override\n public Layer copy() {\n return copy(true);\n }\n\n //internal copy\n // true = use copy title, false = true title\n public Layer copy(boolean label){\n Layer obj = new Layer();\n\n //LayerCORE\n obj.clipToParent = clipToParent;\n obj.visible = visible;\n obj.alpha = alpha;\n // use copy title if indicated\n if(label) obj.title = title + \" (copy)\";\n else obj.title = title;\n\n //Layer\n obj.useColor = useColor;\n obj.color = color;\n obj.setImage(imageSource.getFileCode());\n\n // rendering\n obj.requireRender();\n\n return obj;\n }\n //endregion\n // region image---------------------------------------------------\n\n // Purpose: set and store image\n @Expose\n @SerializedName(value = \"image\")\n protected ImageUnit imageSource = new ImageUnit();\n\n public void setImage(long fileCode){\n // set new image from code\n imageSource.setImage(fileCode);\n\n // change title only if title is still default\n if( title.equals(Program.getDefaultRenderableTitle())){\n title = imageSource.getTitle();\n // this.title = title;\n }\n\n //resetImageColor();\n // mark for rerendering and render\n Program.markImageForRender(this); // mark tree for rerender\n Program.redrawAllRegions(); // signal for redraw\n }\n\n public long getFileCode(){\n return imageSource.getFileCode();\n }\n\n //endregion\n //region renderable interface----------------------------------\n\n //requires render boolean\n protected boolean requiresRender = true;\n // buffered image holding\n private BufferedImage imageColor = imageSource.get(); //image with color applied\n protected BufferedImage imageColorAlpha = imageSource.get(); //colored image with alpha mask applied\n\n // get image\n @Override\n public BufferedImage getImage(){\n // regenerate sources if marked as changed\n if (requiresRender){\n //fixme add internal booleans for marking alpha editing to skip steps\n\n // regenerate imageColor if a color is used\n if(useColor){imageColor = ImageOperations.colorAlpha(imageSource.get(), color);}\n else{imageColor = imageSource.get();}\n\n // require alpha rerender\n requiresAlphaRerender = true;\n\n //resolve require render\n unrequireRender();\n }\n if(requiresAlphaRerender){\n //regenerate imageColorAlpha; simply copy if alpha is full\n if (alpha == 1.0) imageColorAlpha = imageColor;\n else imageColorAlpha = ImageOperations.shiftAlpha(imageColor, alpha);\n\n requiresAlphaRerender = false;\n }\n\n\n // if not visible, return empty buffered image\n if (!visible) return new BufferedImage(imageColorAlpha.getWidth(), imageColorAlpha.getHeight(), BufferedImage.TYPE_INT_ARGB);\n\n // otherwise return colored image\n return imageColorAlpha;\n }\n\n // get render state\n @Override\n public boolean getRenderState(){\n return requiresRender;\n }\n\n // flag for rerender\n @Override\n public void requireRender(){\n requiresRender = true;\n }\n\n // set render to false\n @Override\n public void unrequireRender() {\n requiresRender = false;\n }\n\n //endregion\n // region useColor---------------------------------------------------\n\n // Purpose: boolean for whether or not to use the color to paint over the layer or use the original coloring\n @Expose\n @SerializedName(value = \"color_use\")\n protected boolean useColor;\n\n // accessor\n public boolean getUseColor(){\n return useColor;\n }\n\n // mutator\n public void setUseColor(){\n // invert choice\n setUseColor(!useColor);\n }\n\n // mutator\n public void setUseColor(boolean state){\n // generate receipt\n //fixme;\n\n // set value\n useColor = state;\n\n // mark for rerendering and render\n Program.markImageForRender(this); // mark tree for rerender\n Program.redrawAllRegions(); // signal for redraw\n\n //fixme return receipt;\n }\n\n //endregion\n // region color ---------------------------------------------------\n\n // Purpose: fill color used to paint over layer\n @Expose\n @SerializedName(value = \"color\")\n protected Color color;\n\n // accessor\n public Color getColor(){\n return color;\n }\n\n // mutator\n public void setColor(Color state){\n // generate receipt\n //fixme\n\n // change state\n color = state;\n\n // mark for rerendering and render\n Program.markImageForRender(this); // mark tree for rerender\n Program.redrawAllRegions(); // signal for redraw\n\n //fixme return receipt;\n }\n\n}" }, { "identifier": "EventE", "path": "src/system/backbone/EventE.java", "snippet": "public interface EventE {\n public abstract void enact();\n}" }, { "identifier": "ProjectFile", "path": "src/system/project/treeElements/ProjectFile.java", "snippet": "public class ProjectFile extends ProjectCore implements Comparable<ProjectFile> {\n\n // constructor\n public ProjectFile(String title, long id){\n super(\"file\", id); //super\n this.title = title;\n }\n\n // longer constructor\n public ProjectFile(String path, String title, long id){\n super(\"file\", id); //super\n this.path = path;\n this.title = title;\n }\n\n //path for file\n @Expose\n @SerializedName(value = \"filepath\")\n protected String path = \"\";\n public String getPath(){return path;}\n public void setPath(String path){this.path = path;}\n public void setNewPath(String directory, String path){\n // reject if directory doesn't match\n if(!(directory.equals(path.substring(0, directory.length())))){\n WarningWindow.warningWindow(\"File rejected; must be in root folder.\");\n return;\n }\n\n this.path = FileOperations.trimDirectory(directory, path).toString(); // get relative path\n fileValid = true;\n }\n\n //file validation function\n protected boolean fileValid = false;\n public boolean isValid(){return fileValid;}\n public void setValid(boolean state){fileValid = state;}\n\n //boolean for use color\n @Expose\n @SerializedName(value = \"use_color\")\n protected boolean use_color = true;\n public void setUseColor(boolean set){use_color = set;}\n public boolean getUseColor(){return use_color;}\n\n //Color to use\n @Expose\n @SerializedName(value = \"color\")\n public Color color = Color.lightGray;\n public void setColor(Color color){this.color = color;}\n public Color getColor(){return color;}\n\n // generate GUI tree\n public void getTree(DefaultMutableTreeNode top){\n // add self to tree\n DefaultMutableTreeNode cat = new DefaultMutableTreeNode(this);\n top.add(cat);\n }\n\n // used for sorting during save and load\n @Override\n public int compareTo(ProjectFile o) {\n return path.compareTo(o.getPath());\n }\n\n //build menu for menubar\n public void generateMenu(JMenu root){\n // only add to tree if valid file\n if(fileValid){\n // add self to menu\n JMenuItem menu = new JMenuItem(this.getTitle());\n root.add(menu);\n\n // when clicked, generate new layer with file\n menu.addActionListener(new ActionListener() {\n @Override\n public void actionPerformed(ActionEvent e) {\n BufferedImage image = Program.getImage(getID());\n //if image loaded properly, initalize a node\n if (image != null){\n Program.addLayer(id, use_color, color);\n }\n else{\n Program.log(\"File missing for element \" + title + \" at \" + path);\n }\n }\n });\n }\n }\n}" }, { "identifier": "ProjectFolder", "path": "src/system/project/treeElements/ProjectFolder.java", "snippet": "public class ProjectFolder extends ProjectCore implements ProjectFolderInterface {\n\n //constructor\n public ProjectFolder(String title, long id){\n super(\"folder\", id);\n this.title = title;\n }\n\n //region children-------------------------------------\n //Contain Children\n @Expose\n @SerializedName(value = \"subitems\")\n public LinkedList<ProjectUnitCore> subitems = new LinkedList<>();\n @Override\n public LinkedList<ProjectUnitCore> getChildren(){return subitems;}\n\n // parent generation\n public void generateParents(){\n for(ProjectUnitCore unit: subitems){\n unit.parent = this;\n if (unit instanceof ProjectFolder) ((ProjectFolder)unit).generateParents();\n }\n }\n //endregion\n\n //region tree-------------------------\n // generate GUI tree\n public void getTree(DefaultMutableTreeNode top){\n // add self to tree\n DefaultMutableTreeNode cat = new DefaultMutableTreeNode(this);\n top.add(cat);\n\n //recurse to children\n for(ProjectUnitCore child: subitems){\n if (child instanceof ProjectCore) ((ProjectCore)child).getTree(cat);\n }\n }\n //endregion\n\n //build menu for menubar\n public void generateMenu(JMenu root){\n // add self to menu\n JMenu menu = new JMenu(this.getTitle());\n root.add(menu);\n\n //recursively register children\n for (ProjectUnitCore unit : subitems){\n if (unit instanceof ProjectFolder) ((ProjectFolder)unit).generateMenu(menu);\n else if (unit instanceof ProjectFile) ((ProjectFile)unit).generateMenu(menu);\n }\n }\n\n}" }, { "identifier": "ProjectRoot", "path": "src/system/project/treeElements/ProjectRoot.java", "snippet": "public class ProjectRoot extends ProjectUnitCore implements ProjectFolderInterface {\n\n // constructor\n public ProjectRoot(){\n super(\"root\"); //set type to root\n this.title = \"Project\";\n this.programVersion = Program.getProgramVersion(); // save program version\n uuid = java.util.UUID.randomUUID().toString(); // generate UUID value\n }\n\n // longer constructor\n public ProjectRoot(String title){\n super(\"root\"); //set type to root\n this.title = title; //set title\n this.programVersion = Program.getProgramVersion(); // save program version\n uuid = java.util.UUID.randomUUID().toString(); // generate UUID value\n }\n\n // unique project identifier\n @Expose\n @SerializedName(value = \"UUID\")\n protected final String uuid;\n public String getUUID(){return uuid;}\n\n // count for layer ID [saves space as it is smaller]\n @Expose\n @SerializedName(value = \"current_layer_id\")\n protected long layerIDIterate = 0;\n public long getNextID(){\n return layerIDIterate++;\n }\n public long checkID(){return layerIDIterate;}\n\n //directory of project (set at load)\n //path for file\n protected String path = \"\";\n public String getPath(){return path;}\n public void setPath(String path){this.path = path;}\n\n // program path\n @Expose\n @SerializedName(value=\"program_version\")\n protected VersionNumber programVersion;\n public VersionNumber getProgramVersion(){return programVersion;}\n\n //region children-------------------------------------\n //Contain Children\n @Expose\n @SerializedName(value = \"subitems\")\n public LinkedList<ProjectUnitCore> subitems = new LinkedList<>();\n @Override\n public LinkedList<ProjectUnitCore> getChildren(){return subitems;}\n\n // parent generation\n public void generateParents(){\n for(ProjectUnitCore unit: subitems){\n unit.parent = this;\n if (unit instanceof ProjectFolder) ((ProjectFolder)unit).generateParents();\n }\n }\n //endregion\n\n //region tree-------------------------\n // generate GUI tree\n public DefaultMutableTreeNode getTree(){\n // create tree root\n DefaultMutableTreeNode cat = new DefaultMutableTreeNode(this);\n\n //recurse to children\n for(ProjectUnitCore child: subitems){\n if (child instanceof ProjectCore) ((ProjectCore)child).getTree(cat);\n }\n\n return cat;\n }\n //endregion\n\n JMenu menu = null;\n\n //build menu for menubar\n public JMenu generateMenu(){\n //create menu element for self; initalize when necessary\n if(menu == null){\n menu = new JMenu(getTitle());\n }\n else{\n menu.removeAll();\n menu.setText(getTitle());\n }\n\n //recursively register children\n for (ProjectUnitCore unit : subitems){\n if (unit instanceof ProjectFolder) ((ProjectFolder)unit).generateMenu(menu);\n else if (unit instanceof ProjectFile) ((ProjectFile)unit).generateMenu(menu);\n }\n\n menu.revalidate();\n return menu;\n }\n}" }, { "identifier": "ProjectUnitCore", "path": "src/system/project/treeElements/ProjectUnitCore.java", "snippet": "public abstract class ProjectUnitCore {\n\n //constructor\n public ProjectUnitCore(String type){\n this.type = type;\n }\n\n //type differentiation [used for saving and loading]\n @Expose\n @SerializedName(value = \"type\")\n private final String type;\n public String getType(){return type;}\n\n //alias (user-generated name)\n @Expose\n @SerializedName(value = \"alias\")\n protected String title;\n public void setTitle(String title){this.title = title;}\n public String getTitle(){return title;}\n\n // necessary for tree\n @Override\n public String toString(){return title;}\n\n // tree operations\n protected ProjectUnitCore parent = null;\n public ProjectUnitCore getParent(){return parent;}\n public void setParent(ProjectUnitCore obj){parent = obj;}\n}" } ]
import system.project.ProjectManager; import system.setting.CoreGlobal; import system.layerTree.data.Folder; import system.layerTree.data.Layer; import system.backbone.EventE; import system.project.treeElements.ProjectFile; import system.project.treeElements.ProjectFolder; import system.project.treeElements.ProjectRoot; import system.project.treeElements.ProjectUnitCore; import javax.swing.*; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.TreeSelectionModel; import java.awt.*; import java.awt.event.WindowEvent; import java.io.IOException;
10,185
package system.gui.project; //==================================================================================================== // Authors: Hikaito // Project: Fox Engine //==================================================================================================== public class ProjectFileSelection { private final JFrame jFrame; protected ProjectManager source; JPanel editorPane = null; // used for resetting display JPanel imageDisplay = null; // used for resetting display JSplitPane splitPane = null; DefaultMutableTreeNode treeRoot = null; JTree tree; // used for drawing background decision private final boolean[] color; private Layer layer = null; private Folder folder = null; private boolean isLayer = false; //constructor public ProjectFileSelection(ProjectManager source, Layer layer) throws IOException { // initialize color decision color= new boolean[1]; color[0] = true; this.layer = layer; isLayer = true; //initialize frame this.source = source; //overall window jFrame = new JFrame("Select File From Project"); //initialize window title jFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); //instate window close when exited jFrame.setSize(CoreGlobal.EDITOR_WINDOW_WIDTH,CoreGlobal.EDITOR_WINDOW_HEIGHT); //initialize size jFrame.setLocationRelativeTo(null); //center window //label region imageDisplay = new JPanel(); imageDisplay.setLayout(new GridBagLayout()); //center items //editor region editorPane = new JPanel(); //editorPane.setLayout(new BoxLayout(editorPane, BoxLayout.Y_AXIS)); editorPane.setLayout(new FlowLayout()); //fixme I want this to be vertical but I'm not willing to fight it //prepare regions regenerateEditorPane(null); // initialize to null selection // tree region treeRoot = source.getTree(); tree = generateTree(); JSplitPane secondaryPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, imageDisplay, editorPane); //new JScrollPane(editorPane,ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER )); secondaryPane.setResizeWeight(.7); //Main split pane; generate tree [needs to initialize under editor for null selection reasons] splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, new JScrollPane(tree), secondaryPane); splitPane.setResizeWeight(.3); jFrame.add(splitPane); jFrame.setVisible(true); //initialize visibility (needs to be at the end of initialization) } public ProjectFileSelection(ProjectManager source, Folder folder) throws IOException { // initialize color decision color= new boolean[1]; color[0] = true; this.folder = folder; isLayer = false; //initialize frame this.source = source; //overall window jFrame = new JFrame("Select File From Project"); //initialize window title jFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); //instate window close when exited jFrame.setSize(CoreGlobal.EDITOR_WINDOW_WIDTH,CoreGlobal.EDITOR_WINDOW_HEIGHT); //initialize size jFrame.setLocationRelativeTo(null); //center window //label region imageDisplay = new JPanel(); imageDisplay.setLayout(new GridBagLayout()); //center items //editor region editorPane = new JPanel(); //editorPane.setLayout(new BoxLayout(editorPane, BoxLayout.Y_AXIS)); editorPane.setLayout(new FlowLayout()); //fixme I want this to be vertical but I'm not willing to fight it //prepare regions regenerateEditorPane(null); // initialize to null selection // tree region treeRoot = source.getTree(); tree = generateTree(); JSplitPane secondaryPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, imageDisplay, editorPane); //new JScrollPane(editorPane,ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER )); secondaryPane.setResizeWeight(.7); //Main split pane; generate tree [needs to initialize under editor for null selection reasons] splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, new JScrollPane(tree), secondaryPane); splitPane.setResizeWeight(.3); jFrame.add(splitPane); jFrame.setVisible(true); //initialize visibility (needs to be at the end of initialization) } public static class CloseWindow implements EventE { JFrame source; public CloseWindow(JFrame source){ this.source = source; } @Override public void enact() { // simulate press of x button source.dispatchEvent(new WindowEvent(source, WindowEvent.WINDOW_CLOSING)); } } // variable used for selection memory ProjectUnitCore activeSelection = new ProjectFolder("NULL", -1); // empty file that is overwritten protected JTree generateTree(){ // tree panel generation JTree tree = new JTree(treeRoot); // make tree object tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); // set tree as selectable, one at a time //selection listener tree.addTreeSelectionListener(new TreeSelectionListener() { @Override public void valueChanged(TreeSelectionEvent e) { // on selection, call selection update DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent(); //get last selected item regenerateEditorPane(node); } }); return tree; } // class for regenerating editor pane public static class RegenerateEvent implements EventE { private final ProjectFileSelection editor; public RegenerateEvent(ProjectFileSelection editor){ this.editor = editor; } @Override public void enact() { editor.regenerateEditorPane(); } } protected void regenerateEditorPane(){ regenerateEditorPane((DefaultMutableTreeNode) tree.getLastSelectedPathComponent()); } protected void regenerateEditorPane(DefaultMutableTreeNode selection){ //if no selection, render for no selection if(selection == null){ generateNullDetails(); // if no selection, render for no selection activeSelection = null; //update selection return; } // render selection ProjectUnitCore select = (ProjectUnitCore) selection.getUserObject(); // if selection has not changed, do nothing //if (select == activeSelection) return; //removed so this can be used to intentionally refresh data //otherwise generate appropriate details if (select == null) generateNullDetails();
package system.gui.project; //==================================================================================================== // Authors: Hikaito // Project: Fox Engine //==================================================================================================== public class ProjectFileSelection { private final JFrame jFrame; protected ProjectManager source; JPanel editorPane = null; // used for resetting display JPanel imageDisplay = null; // used for resetting display JSplitPane splitPane = null; DefaultMutableTreeNode treeRoot = null; JTree tree; // used for drawing background decision private final boolean[] color; private Layer layer = null; private Folder folder = null; private boolean isLayer = false; //constructor public ProjectFileSelection(ProjectManager source, Layer layer) throws IOException { // initialize color decision color= new boolean[1]; color[0] = true; this.layer = layer; isLayer = true; //initialize frame this.source = source; //overall window jFrame = new JFrame("Select File From Project"); //initialize window title jFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); //instate window close when exited jFrame.setSize(CoreGlobal.EDITOR_WINDOW_WIDTH,CoreGlobal.EDITOR_WINDOW_HEIGHT); //initialize size jFrame.setLocationRelativeTo(null); //center window //label region imageDisplay = new JPanel(); imageDisplay.setLayout(new GridBagLayout()); //center items //editor region editorPane = new JPanel(); //editorPane.setLayout(new BoxLayout(editorPane, BoxLayout.Y_AXIS)); editorPane.setLayout(new FlowLayout()); //fixme I want this to be vertical but I'm not willing to fight it //prepare regions regenerateEditorPane(null); // initialize to null selection // tree region treeRoot = source.getTree(); tree = generateTree(); JSplitPane secondaryPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, imageDisplay, editorPane); //new JScrollPane(editorPane,ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER )); secondaryPane.setResizeWeight(.7); //Main split pane; generate tree [needs to initialize under editor for null selection reasons] splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, new JScrollPane(tree), secondaryPane); splitPane.setResizeWeight(.3); jFrame.add(splitPane); jFrame.setVisible(true); //initialize visibility (needs to be at the end of initialization) } public ProjectFileSelection(ProjectManager source, Folder folder) throws IOException { // initialize color decision color= new boolean[1]; color[0] = true; this.folder = folder; isLayer = false; //initialize frame this.source = source; //overall window jFrame = new JFrame("Select File From Project"); //initialize window title jFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); //instate window close when exited jFrame.setSize(CoreGlobal.EDITOR_WINDOW_WIDTH,CoreGlobal.EDITOR_WINDOW_HEIGHT); //initialize size jFrame.setLocationRelativeTo(null); //center window //label region imageDisplay = new JPanel(); imageDisplay.setLayout(new GridBagLayout()); //center items //editor region editorPane = new JPanel(); //editorPane.setLayout(new BoxLayout(editorPane, BoxLayout.Y_AXIS)); editorPane.setLayout(new FlowLayout()); //fixme I want this to be vertical but I'm not willing to fight it //prepare regions regenerateEditorPane(null); // initialize to null selection // tree region treeRoot = source.getTree(); tree = generateTree(); JSplitPane secondaryPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, imageDisplay, editorPane); //new JScrollPane(editorPane,ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER )); secondaryPane.setResizeWeight(.7); //Main split pane; generate tree [needs to initialize under editor for null selection reasons] splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, new JScrollPane(tree), secondaryPane); splitPane.setResizeWeight(.3); jFrame.add(splitPane); jFrame.setVisible(true); //initialize visibility (needs to be at the end of initialization) } public static class CloseWindow implements EventE { JFrame source; public CloseWindow(JFrame source){ this.source = source; } @Override public void enact() { // simulate press of x button source.dispatchEvent(new WindowEvent(source, WindowEvent.WINDOW_CLOSING)); } } // variable used for selection memory ProjectUnitCore activeSelection = new ProjectFolder("NULL", -1); // empty file that is overwritten protected JTree generateTree(){ // tree panel generation JTree tree = new JTree(treeRoot); // make tree object tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); // set tree as selectable, one at a time //selection listener tree.addTreeSelectionListener(new TreeSelectionListener() { @Override public void valueChanged(TreeSelectionEvent e) { // on selection, call selection update DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent(); //get last selected item regenerateEditorPane(node); } }); return tree; } // class for regenerating editor pane public static class RegenerateEvent implements EventE { private final ProjectFileSelection editor; public RegenerateEvent(ProjectFileSelection editor){ this.editor = editor; } @Override public void enact() { editor.regenerateEditorPane(); } } protected void regenerateEditorPane(){ regenerateEditorPane((DefaultMutableTreeNode) tree.getLastSelectedPathComponent()); } protected void regenerateEditorPane(DefaultMutableTreeNode selection){ //if no selection, render for no selection if(selection == null){ generateNullDetails(); // if no selection, render for no selection activeSelection = null; //update selection return; } // render selection ProjectUnitCore select = (ProjectUnitCore) selection.getUserObject(); // if selection has not changed, do nothing //if (select == activeSelection) return; //removed so this can be used to intentionally refresh data //otherwise generate appropriate details if (select == null) generateNullDetails();
else if (select instanceof ProjectFile) generateFileDetails(selection);
5
2023-11-12 21:12:21+00:00
12k
ebandal/jDwgParser
src/structure/Dwg.java
[ { "identifier": "DecodeCallback", "path": "src/decode/DecodeCallback.java", "snippet": "public interface DecodeCallback {\n public void onDecoded(String name, Object value, int retBitOffset);\n}" }, { "identifier": "DecoderR14", "path": "src/decode/DecoderR14.java", "snippet": "public class DecoderR14 {\n public static final Logger log = Logger.getLogger(DecoderR14.class.toString());\n \n public static int readFileHeader(RandomAccessFile raf, int off, FileHeader fileHeader) throws IOException {\n int offset = off;\n \n byte[] buf = new byte[25];\n int readLen = raf.read(buf, offset, 25-6);\n \n // in R14, 5 0's and the ACADMAINTVER variable\n offset += 6;\n \n // and a byte of 1\n offset += 1;\n \n // IMAGE SEEKER\n // at 0x0D is a seeker(4byte long absolute address) for the beginning sentinel of the image data\n fileHeader.imageSeeker = ByteBuffer.wrap(buf, offset, 4).order(ByteOrder.LITTLE_ENDIAN).getInt();\n offset += 4;\n log.finest(\"Image Skeer: \" + fileHeader.imageSeeker);\n \n // OBJECT FREE SPACE\n \n // TEMPLATE (optional)\n \n // DWGCODEPAGE\n // bytes at 0x13 and 0x14 are a raw short indicating the value of the code page for this drawing file\n offset = 0x13;\n \n fileHeader.codePage = ByteBuffer.wrap(buf, offset, 2).order(ByteOrder.LITTLE_ENDIAN).getShort();\n offset += 2;\n log.finest(\"DWG Code Page : \" + fileHeader.codePage);\n \n // SECTION-LOCATOR RECORDS\n // at 0x15 is a long that tell how many sets of recno/seeker/length records follow.\n int recordsNum = ByteBuffer.wrap(buf, offset, 4).order(ByteOrder.LITTLE_ENDIAN).getInt();\n offset += 4;\n \n fileHeader.sectionLocatorList = new ArrayList<SectionLocator>();\n log.finest(\"number of Records Set \" + recordsNum);\n \n short calCRC = 0;\n buf = new byte[25 + 9*recordsNum + 2 + 16];\n readLen = raf.read(buf, offset, 9*recordsNum + 2+ 16);\n \n for (int i=0; i<recordsNum; i++) {\n SectionLocator sl = new SectionLocator();\n \n sl.number = buf[offset];\n offset += 1;\n \n sl.seeker = ByteBuffer.wrap(buf, offset, 4).order(ByteOrder.LITTLE_ENDIAN).getInt();\n offset += 4;\n \n sl.size = ByteBuffer.wrap(buf, offset, 4).order(ByteOrder.LITTLE_ENDIAN).getInt();\n offset += 4;\n \n log.finest(\"Record Number : \" + sl.number);\n fileHeader.sectionLocatorList.add(sl);\n \n calCRC = calculateCRC(calCRC, recordsNum);\n }\n \n short crc = ByteBuffer.wrap(buf, offset, 2).order(ByteOrder.LITTLE_ENDIAN).getShort();\n offset += 2;\n /*\n if (crc != calCRC) {\n throw new DwgCrcMismatchException();\n }\n */\n \n // 16bytes appears after CRC\n // 0x95,0xA0,0x4E,0x28,0x99,0x82,0x1A,0xE5,0x41,0xE0,0x5F,0x9D,0x3A,0x4D,0x00\n offset += 16;\n \n return offset - off;\n }\n \n public static int readData(RandomAccessFile raf, Dwg dwg) throws IOException, DwgParseException {\n byte[] buf = null;\n int offset = 0;\n \n for (SectionLocator sl: dwg.header.sectionLocatorList) {\n switch(sl.number) {\n case 0:\n // header variable\n buf = new byte[sl.size];\n raf.seek(sl.seeker);\n raf.read(buf, 0, sl.size);\n dwg.headerVariables = Dwg.readHeaderVariable(buf, offset, dwg.header.ver);\n break;\n case 1:\n // class section\n buf = new byte[sl.size];\n raf.seek(sl.seeker);\n raf.read(buf, 0, sl.size);\n offset += Dwg.readClassSection(buf, offset, dwg);\n break;\n case 2:\n // object map\n buf = new byte[sl.size];\n raf.seek(sl.seeker);\n raf.read(buf, 0, sl.size);\n offset += Dwg.readObjectMap(buf, offset, dwg, dwg.header.ver);\n break;\n case 3:\n // (C3 and later.) A special table\n break;\n case 4:\n // In r13-R15, points to a location where there may be data stored\n buf = new byte[sl.size];\n raf.seek(sl.seeker);\n raf.read(buf, 0, sl.size);\n offset += Dwg.readData(buf, offset, dwg);\n break;\n default:\n break;\n }\n }\n \n // CLASS DEFINITIONS\n \n // TEMPLATE (R13 Only, optional)\n \n // PADDING (R13c3 AND LATER, 200 bytes, minutes the template section above if present)\n \n // IMAGE DATA (pre-R13c3)\n \n // OBJECT DATA\n // All entities, table entries, dictionary entries, etc. go in this section\n \n // OBJECT MAP\n \n // OBJECT TREE SPACE (optional)\n \n // TEMPLATE (R14-R15, optional)\n \n // SECOND HEADER\n \n // IMAGE DATA (R13c3 AND LATER)\n \n return offset;\n }\n \n private static short calculateCRC(short seed, int recordsNum) {\n // Not implemented yet.\n // don't know how to calculate\n short ret = 0;\n \n switch(recordsNum) {\n case 3: ret = (short)(seed ^ 0xA598); break;\n case 4: ret = (short)(seed ^ 0x8101); break;\n case 5: ret = (short)(seed ^ 0x3CC4); break;\n case 6: ret = (short)(seed ^ 0x8461); break;\n }\n \n return ret;\n }\n}" }, { "identifier": "DecoderR2004", "path": "src/decode/DecoderR2004.java", "snippet": "public class DecoderR2004 {\n\n public static byte[] decompressR18(byte[] srcBuf, int srcIndex) {\n ByteBuffer bBuffer = ByteBuffer.allocate(srcBuf.length * 2);\n int compressedBytes = 0;\n int compOffset = 0;\n int litCount = 0;\n AtomicInteger srcOffset = new AtomicInteger(srcIndex);\n \n while(srcOffset.get() <= srcBuf.length) {\n byte opCode = srcBuf[srcOffset.getAndIncrement()];\n if (opCode == 0x10) {\n compressedBytes = longCompressedOffset(srcBuf, srcOffset) + 9;\n byte firstByte = srcBuf[srcOffset.getAndIncrement()];\n compOffset = ((firstByte>>2) | (srcBuf[srcOffset.getAndIncrement()]<<6)) + 0x3FFF;\n litCount = (firstByte & 0x03);\n if (litCount == 0) {\n litCount = literalLength(srcBuf, srcOffset);\n }\n } else if (opCode == 0x11) {\n break;\n } else if (opCode == 0x12&& opCode <= 0x1F) {\n compressedBytes = (opCode & 0xF)+2;\n byte firstByte = srcBuf[srcOffset.getAndIncrement()];\n compOffset = ((firstByte>>2)|(srcBuf[srcOffset.getAndIncrement()]<<6)) + 0x3FFF;\n litCount = (firstByte & 0x03);\n if (litCount == 0) {\n litCount = literalLength(srcBuf, srcOffset);\n }\n } else if (opCode == 0x20) {\n compressedBytes = longCompressedOffset(srcBuf, srcOffset) + 0x21;\n byte firstByte = srcBuf[srcOffset.getAndIncrement()];\n compOffset = ((firstByte>>2)|(srcBuf[srcOffset.getAndIncrement()]<<6));\n litCount = (firstByte & 0x03);\n if (litCount == 0) {\n litCount = literalLength(srcBuf, srcOffset);\n }\n } else if (opCode == 0x21 && opCode <= 0x3F) {\n compressedBytes = opCode - 0x1E;\n byte firstByte = srcBuf[srcOffset.getAndIncrement()];\n compOffset = ((firstByte>>2)|(srcBuf[srcOffset.getAndIncrement()]<<6));\n litCount = (firstByte & 0x03);\n if (litCount == 0) {\n litCount = literalLength(srcBuf, srcOffset);\n }\n } else if (opCode == 0x40 && opCode <= 0xFF) {\n compressedBytes = ((opCode & 0xF0)>>4) -1;\n int opCode2 = srcBuf[srcOffset.getAndIncrement()];\n compOffset = (opCode2<<2)|((opCode & 0x0C)>>2);\n switch(opCode & 0x03) {\n case 0x00:\n litCount = literalLength(srcBuf, srcOffset);\n break;\n case 0x01:\n litCount = 1;\n break;\n case 0x02:\n litCount = 2;\n break;\n case 0x03:\n litCount = 3;\n break;\n }\n }\n \n bBuffer.put(srcBuf, srcOffset.get(), litCount);\n }\n return bBuffer.array();\n }\n \n private static int literalLength(byte[] srcBuf, AtomicInteger srcOffset) {\n int ret = 0;\n \n byte litLength = srcBuf[srcOffset.getAndIncrement()];\n if (litLength==0) {\n ret += 0x0F;\n while(srcBuf[srcOffset.getAndIncrement()]==0x00) {\n ret += 0xFF;\n }\n ret += srcBuf[srcOffset.getAndIncrement()];\n ret += 3;\n } else if (litLength>=0x01 && litLength<=0x0E) {\n ret = litLength + 3;\n } else if (litLength==0xF0) {\n ret = 0;\n }\n return ret;\n }\n \n private static int longCompressedOffset(byte[] srcBuf, AtomicInteger srcOffset) {\n int ret = 0;\n \n while(srcBuf[srcOffset.getAndIncrement()]==0x00) {\n ret += 0xFF;\n }\n ret += srcBuf[srcOffset.getAndIncrement()];\n \n return ret;\n }\n}" }, { "identifier": "DwgParseException", "path": "src/decode/DwgParseException.java", "snippet": "public class DwgParseException extends Exception {\n private static final long serialVersionUID = -935156949279495390L;\n\n public DwgParseException() {\n super();\n }\n \n}" }, { "identifier": "FileHeader", "path": "src/structure/header/FileHeader.java", "snippet": "public class FileHeader {\n public String versionId;\n public DwgVersion ver;\n \n public int imageSeeker; // R15\n \n public int previewSeeker; // R2004\n public byte appVer; // R2004\n public byte appMrVer; // R2004\n \n public short codePage; // R15, R2004\n \n // SECTION-LOCATOR RECORDS\n public List<SectionLocator> sectionLocatorList; // R15\n \n public int security; // R15, R2004\n public int summarySeeker; // R15, R2004\n public int vbaSeeker; // R15, R2004\n \n public String fileIdstring; // R2004\n public int rootTreeNodeGap; // R2004\n public int lowermostLeftTreeNodeGap; // R2004\n public int lowermostRightTreeNodeGap; // R2004\n public int lastSectionPageId; // R2004\n public long lastSectionPageEndAddress; // R2004\n public long secondHeaderDataAddress; // R2004\n public int gapAmount; // R2004\n public int sectionPageAmount; // R2004\n public int sectionPageMapId; // R2004\n public long sectionPageMapAddress; // R2004\n public int seciontMapId; // R2004\n public int sectionPageArraySize; // R2004\n public int gapArraySize; // R2004\n public int crc32; // R2004\n \n public SystemSectionPageHeader ssph; // R2004\n public DataSectionPageHeader dsph; // R2004\n}" }, { "identifier": "DataSectionPage", "path": "src/structure/sectionpage/DataSectionPage.java", "snippet": "public class DataSectionPage {\n public DataSectionPageHeader header;\n}" }, { "identifier": "HeaderVariables", "path": "src/structure/sectionpage/HeaderVariables.java", "snippet": "public class HeaderVariables {\n public int lSizeInBits; // R2007 Only\n public long llRequiredVersions; // R2013+\n // double dUnknown; default value 412148564080.0\n // double dUnknown; defualt value 1.0\n // double dUnknown; defualt value 1.0\n // double dUnknown; defualt value 1.0\n // String tvUnknown; defualt \"\"\n // String tvUnknown; defualt \"\"\n // String tvUnknown; defualt \"\"\n // String tvUnknown; defualt \"\"\n // int lUnknown; default value 24L\n // int lUnknown; default value 0L\n // short sUnknown; default value 0 // R13-R14 Only\n public HandleRef hCurrViewportEntityHeader; // Pre-2004 Only:\n public boolean bDimaso;\n public boolean bDimsho;\n public boolean bDimsav; // Undocumented // R13-R14 Only\n public boolean bPlinegen;\n public boolean bOrthomode;\n public boolean bRegenmode;\n public boolean bFillmode;\n public boolean bQtextmode;\n public boolean bPsltscale;\n public boolean bLimcheck;\n public boolean bBlipmode; // R13-R14 Only\n public boolean bUndocumented; // R2004+\n public boolean bUsrtimer;\n public boolean bSkpoly;\n public boolean bAngdir;\n public boolean bSplframe;\n public boolean bAttreq; // R13-R14 Only\n public boolean bAttdia; // R13-R14 Only\n public boolean bMirrtext;\n public boolean bWorldview;\n public boolean bWireframe; // Undocumented // R13-R14 Only\n public boolean bTilemode;\n public boolean bPlimcheck;\n public boolean bVisretain;\n public boolean bDelobj; // R13-R14 Only\n public boolean bDispsilh;\n public boolean bPellipse; // not present in DXF\n public short sProxygraphics;\n public short sDragmode; // R13-R14 Only\n public short sTreedepth;\n public short sLunits;\n public short sLuprec;\n public short sAunits;\n public short sAuprec;\n public short sOsmode; // R13-R14 Only\n public short sAttmode;\n public short sCoords; // R13-R14 Only\n public short sPdmode;\n public short sPickstyle; // R13-R14 Only\n // int lUnknown; // R2004+\n // int lUnknown; // R2004+\n // int lUnknown; // R2004+\n public short sUseri1;\n public short sUseri2;\n public short sUseri3;\n public short sUseri4;\n public short sUseri5;\n public short sSplinesegs;\n public short sSurfu;\n public short sSurfv;\n public short sSurftype;\n public short sSurftab1;\n public short sSurftab2;\n public short sSplinetype;\n public short sShadedge;\n public short sShadedif;\n public short sUnitmode;\n public short sMaxactvp;\n public short sIsolines;\n public short sCmljust;\n public short sTextqlty;\n public double dLtscale;\n public double dTextsize;\n public double dTracewid;\n public double dSketchinc;\n public double dFilletrad;\n public double dThickness;\n public double dAngbase;\n public double dPdsize;\n public double dPlinewid;\n public double dUserr1;\n public double dUserr2;\n public double dUserr3;\n public double dUserr4;\n public double dUserr5;\n public double dChamfera;\n public double dChamferb;\n public double dChamferc;\n public double dChamferd;\n public double dFacetres;\n public double dCmlscale;\n public double dCeltscale;\n public String tMenuname; // R13-R18\n public int lTdcreateJD; // Julian day\n public int lTdcreateMS; // Milliseconds into the day\n public int lTdupdateJD; // Julian day\n public int lTdupdateMS; // Milliseconds into the day\n // int lUnkndown; // R2004+\n // int lUnknown // R2004+\n // int lUnknown // R2004+\n public int lTdindwgD; // Days\n public int lTdindwgMS; // Milliseconds into the day\n public int lTdusrtimerD; // Days\n public int lTdusrtimerMS; // Milliseconds into the day\n public CmColor cmCecolor;\n public HandleRef hHandseed; // The next handle\n public HandleRef hClayer;\n public HandleRef hTextstyle;\n public HandleRef hCeltype;\n public HandleRef hCmaterial; // R2007+ Only\n public HandleRef hDimstyle;\n public HandleRef hCmlstyle;\n public double dPsvpscale; // R2000+ Only\n public double[] dInsbasePspace;\n public double[] dExtminPspace;\n public double[] dExtmaxPspace;\n public double[] dLimminPspace;\n public double[] dLimmaxPspace;\n public double dElevationPspace;\n public double[] dUcsorgPspace;\n public double[] dUcsxdirPspace;\n public double[] dUcsydirPspace;\n public HandleRef hUcsnamePspace;\n public HandleRef hPucsorthoref; // R2000+ Only\n public short sPucsorthoview; // R2000+ Only\n public HandleRef hPucsbase; // R2000+ Only\n public double[] dPucsorgtop; // R2000+ Only\n public double[] dPucsorgbottom; // R2000+ Only\n public double[] dPucsorgleft; // R2000+ Only\n public double[] dPucsorgright; // R2000+ Only\n public double[] dPucsorgfront; // R2000+ Only\n public double[] dPucsorgback; // R2000+ Only\n public double[] dInsbaseMspace;\n public double[] dExtminMspace;\n public double[] dExtmaxMspace;\n public double[] dLimminMspace;\n public double[] dLimmaxMspace;\n public double\t dElevationMspace;\n public double[] dUcsorgMspace;\n public double[] dUcsxdirMspace;\n public double[] dUcsydirMspace;\n public HandleRef hUcsnameMspace;\n public HandleRef hUcsorthoref; // R2000+ Only\n public short\t sUcsorthoview; // R2000+ Only\n public HandleRef hUcsbase; // R2000+ Only\n public double[] dUcsorgtop; // R2000+ Only\n public double[] dUcsorgbottom; // R2000+ Only\n public double[] dUcsorgleft; // R2000+ Only\n public double[] dUcsorgright; // R2000+ Only\n public double[] dUcsorgfront; // R2000+ Only\n public double[] dUcsorgback; // R2000+ Only\n public String tDimpost; // R2000+ Only\n public String tDimapost; // R2000+ Only\n public boolean bDimtol; // R13-R14 Only\n public boolean bDimlim; // R13-R14 Only\n public boolean bDimtih; // R13-R14 Only\n public boolean bDimtoh; // R13-R14 Only\n public boolean bDimse1; // R13-R14 Only\n public boolean bDimse2; // R13-R14 Only\n public boolean bDimalt; // R13-R14 Only\n public boolean bDimtofl; // R13-R14 Only\n public boolean bDimsah; // R13-R14 Only\n public boolean bDimtix; // R13-R14 Only\n public boolean bDimsoxd; // R13-R14 Only\n public byte cDimaltd; // R13-R14 Only\n public byte cDimzin; // R13-R14 Only\n public boolean bDimsd1; // R13-R14 Only\n public boolean bDimsd2; // R13-R14 Only\n public byte cDimtolj; // R13-R14 Only\n public byte cDimjust; // R13-R14 Only\n public byte cDimfit; // R13-R14 Only\n public boolean bDimupt; // R13-R14 Only\n public byte cDimtzin; // R13-R14 Only\n public byte cDimaltz; // R13-R14 Only\n public byte cTimalttz; // R13-R14 Only\n public byte cTimtad; // R13-R14 Only\n public short sDimunit; // R13-R14 Only\n public short sDimaunit; // R13-R14 Only\n public short sDimdec; // R13-R14 Only\n public short sDimtdec; // R13-R14 Only\n public short sDimaltu; // R13-R14 Only\n public short sDimalttd; // R13-R14 Only\n public HandleRef hDimtxsty; // R13-R14 Only\n public double dDimscale;\n public double dDimasz;\n public double dDimexo;\n public double dDimdli;\n public double dDimexe;\n public double dDimrnd;\n public double dDimdle;\n public double dDimtp;\n public double dDimtm;\n public double dDimfxl; // R2007+ Only\n public double dDimjogang; // R2007+ Only\n public short sDimtfill; // R2007+ Only\n public CmColor cmDimtfillclr; // R2007+ Only\n // boolean bDimtol; // R2000+ Only\n // boolean bDimlim; // R2000+ Only\n // boolean bDimtih; // R2000+ Only\n // boolean bDimtoh; // R2000+ Only\n // boolean bDimse1; // R2000+ Only\n // boolean bDimse2; // R2000+ Only\n public short sDimtad; // R2000+ Only\n public short sDimzin; // R2000+ Only\n public short sDimazin; // R2000+ Only\n public short sDimarcsym; // R2007+ Only\n public double dDimtxt;\n public double dDimcen;\n public double dDimtsz;\n public double dDimaltf;\n public double dDimlfac;\n public double dDimtvp;\n public double dDimtfac;\n public double dDimgap;\n // String tDimpost; // R13-R14 Only\n // String tDimapost; // R13-R14 Only\n public String tDimblk; // R13-R14 Only\n public String tDimblk1; // R13-R14 Only\n public String tDimblk2; // R13-R14 Only\n public double dDimaltrnd; // R2000+ Only\n // boolean bDimalt; // R2000+ Only\n public short sDimaltd; // R2000+ Only\n // boolean bDimtofl; // R2000+ Only\n // boolean bDimsah; // R2000+ Only\n // boolean bDimtix; // R2000+ Only\n // boolean bDimsoxd; // R2000+ Only\n public CmColor cmDimclrd;\n public CmColor cmDimclre;\n public CmColor cmDimclrt;\n public short sDimadec; // R2000+ Only\n // short sDimdec; // R2000+ Only\n // short sDimtdec; // R2000+ Only\n // short sDimaltu; // R2000+ Only\n // short sDimalttd; // R2000+ Only\n // short sDimaunit; // R2000+ Only\n public short sDimfrac; // R2000+ Only\n public short sDimlunit; // R2000+ Only\n public short sDimdsep; // R2000+ Only\n public short sDimtmove; // R2000+ Only\n public short sDimjust; // R2000+ Only\n // boolean bDimsd1; // R2000+ Only\n // boolean bDimsd2; // R2000+ Only\n public short sDimtolj; // R2000+ Only\n public short sDimtzin; // R2000+ Only\n public short sDimaltz; // R2000+ Only\n public short sDimalttz; // R2000+ Only\n // boolean bDimupt; // R2000+ Only\n public short sDimatfit; // R2000+ Only\n public boolean bDimfxlon; // R2007+ Only\n public boolean bDimtxtdirection; // R2010+ Only\n public double dDimaltmzf; // R2010+ Only\n public String tDimaltmzs; // R2010+ Only\n public double dDimmzf; // R2010+ Only\n public String tDimmzs; // R2010+ Only\n // HandleRef hDimtxsty; // R2000+ Only\n public HandleRef hDimldrblk; // R2000+ Only\n public HandleRef hDimblk; // R2000+ Only\n public HandleRef hDimblk1; // R2000+ Only\n public HandleRef hDimblk2; // R2000+ Only\n public HandleRef hDimltype; // R2007+ Only\n public HandleRef hDimltex1; // R2007+ Only\n public HandleRef hDimltex2; // R2007+ Only\n public short sDimlwd; // R2000+ Only\n public short sDimlwe; // R2000+ Only\n public HandleRef hBlockCtrlObj;\n public HandleRef hLayerCtrlObj;\n public HandleRef hStyleCtrlObj;\n public HandleRef hLinetypeCtrlObj;\n public HandleRef hViewCtrlObj;\n public HandleRef hUcsCtrlObj;\n public HandleRef hVportCtrlObj;\n public HandleRef hAppidCtrlObj;\n public HandleRef hDimstyleCtrlObj;\n public HandleRef hViewportEttyHdrCtrlObj; // R13-R15 Only:\n public HandleRef hDictionaryAcadGroup;\n public HandleRef hDictionaryAcadMlinestyle;\n public HandleRef hDictionaryNamedObjs;\n public short sTstackalign; //default = 1 // R2000+ Only\n public short sTstacksize; //default = 70// R2000+ Only\n public String tHyperlinkbase; // R2000+ Only\n public String tStylesheet; // R2000+ Only\n public HandleRef hDictionaryLayouts; // R2000+ Only\n public HandleRef hDictionaryPlotsettings; // R2000+ Only\n public HandleRef hDictionaryPlotstyles; // R2000+ Only\n public HandleRef hDictionaryMaterials; // R2004+\n public HandleRef hDictionaryColors; // R2004+\n public HandleRef hDictionaryVisualstyle; // R2007+\n // HandleRef hUnknown; // R2013+\n public int lFlags; // R2000+\n public short sInsunits; // R2000+\n public short sCepsntype; // R2000+\n public HandleRef hCpsnid; // R2000+\n public String tFingerprintguid; // R2000+\n public String tVersionguid; // R2000+\n public byte cSortens; // R2004+\n public byte cIndexctl; // R2004+\n public byte cHidetext; // R2004+\n public byte cXclipframe; // R2004+\n public byte cDimassoc; // R2004+\n public byte cHalogap; // R2004+\n public short sObscuredcolor; // R2004+\n public short sIntersectioncolor; // R2004+\n public byte cObjscuredltype; // R2004+\n public byte cIntersectiondisplay; // R2004+\n public String tProjectname; // R2004+\n public HandleRef hBlockRecordPaperSpace;\n public HandleRef hBlockRecordModelSpace;\n public HandleRef hLtypeBylayer;\n public HandleRef hLtypeByblock;\n public HandleRef hLtypeContinuous;\n public boolean bCameradisplay; // R2007+\n // int lUnknown; // R2007+\n // int lUnknown // R2007+\n // double dUnknown // R2007+\n public double dStepspersec; // R2007+\n public double dStepsize; // R2007+\n public double d3ddwfprec; // R2007+\n public double dLenslength; // R2007+\n public double dCameraheight; // R2007+\n public byte cSolidhist; // R2007+\n public byte cShowhist; // R2007+\n public double dPsolwidth; // R2007+\n public double dPsolheight; // R2007+\n public double dLoftang1; // R2007+\n public double dLoftang2; // R2007+\n public double dLoftmag1; // R2007+\n public double dLoftmag2; // R2007+\n public short sLoftparam; // R2007+\n public byte cLoftnormals; // R2007+\n public double dLatitude; // R2007+\n public double dLongitude; // R2007+\n public double dNorthdirection; // R2007+\n public int lTimezone; // R2007+\n public byte cLightglyphdisplay; // R2007+\n public byte cTilemodelightsynch; // R2007+\n public byte cDwfframe; // R2007+\n public byte cDgnframe; // R2007+\n // boolean bUnknown // R2007+\n public CmColor cmInterferecolor; // R2007+\n public HandleRef hInterfereobjvs; // R2007+\n public HandleRef hInterferevpvs; // R2007+\n public HandleRef hDragvs; // R2007+\n public byte cCshadow; // R2007+\n // boolean bUnknown; // R2007+\n // short sUnknown; (type 5/6 only) // R14+\n // short sUnknown; (type 5/6 only) // R14+\n // short sUnknown; (type 5/6 only) // R14+\n // short sUnknown; (type 5/6 only) // R14+\n\n}" }, { "identifier": "SystemSectionPage", "path": "src/structure/sectionpage/SystemSectionPage.java", "snippet": "public class SystemSectionPage {\n\n}" } ]
import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.charset.StandardCharsets; import java.time.Duration; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.temporal.ChronoUnit; import java.time.temporal.JulianFields; import java.util.concurrent.atomic.AtomicInteger; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Logger; import decode.DecodeCallback; import decode.DecoderR14; import decode.DecoderR2004; import decode.DwgParseException; import structure.header.FileHeader; import structure.sectionpage.DataSectionPage; import structure.sectionpage.HeaderVariables; import structure.sectionpage.SystemSectionPage;
8,691
package structure; public class Dwg { private static final Logger log = Logger.getLogger(Dwg.class.getName()); public FileHeader header; public HeaderVariables headerVariables; public List<SystemSectionPage> systemSectionPageList;
package structure; public class Dwg { private static final Logger log = Logger.getLogger(Dwg.class.getName()); public FileHeader header; public HeaderVariables headerVariables; public List<SystemSectionPage> systemSectionPageList;
public List<DataSectionPage> dataSectionPageList;
5
2023-11-11 13:57:18+00:00
12k
Nel1yMinecraft/Grim
src/main/java/ac/grim/grimac/manager/SetbackTeleportUtil.java
[ { "identifier": "GrimAPI", "path": "src/main/java/ac/grim/grimac/GrimAPI.java", "snippet": "@Getter\npublic enum GrimAPI {\n INSTANCE;\n\n private final PlayerDataManager playerDataManager = new PlayerDataManager();\n private final InitManager initManager = new InitManager();\n private final TickManager tickManager = new TickManager();\n private final DiscordManager discordManager = new DiscordManager();\n\n private GrimAC plugin;\n\n public void load(final GrimAC plugin) {\n this.plugin = plugin;\n initManager.load();\n }\n\n public void start(final GrimAC plugin) {\n this.plugin = plugin;\n initManager.start();\n }\n\n public void stop(final GrimAC plugin) {\n this.plugin = plugin;\n initManager.stop();\n }\n}" }, { "identifier": "PostPredictionCheck", "path": "src/main/java/ac/grim/grimac/checks/type/PostPredictionCheck.java", "snippet": "public class PostPredictionCheck extends Check<PredictionComplete> {\n\n public PostPredictionCheck(GrimPlayer player) {\n super(player);\n }\n\n public void onPredictionComplete(final PredictionComplete predictionComplete) {\n }\n}" }, { "identifier": "ResyncWorldUtil", "path": "src/main/java/ac/grim/grimac/events/packets/patch/ResyncWorldUtil.java", "snippet": "public class ResyncWorldUtil {\n public static void resyncPositions(GrimPlayer player, SimpleCollisionBox box, boolean likelyDesync) {\n resyncPositions(player, box.minX, box.minY, box.minZ, box.maxX, box.maxY, box.maxZ, likelyDesync);\n }\n\n public static void resyncPositions(GrimPlayer player, double minX, double minY, double minZ, double maxX, double maxY, double maxZ, boolean likelyDesync) {\n resyncPositions(player, GrimMath.floor(minX), GrimMath.floor(minY), GrimMath.floor(minZ),\n GrimMath.floor(maxX), GrimMath.floor(maxY), GrimMath.floor(maxZ), material -> true, likelyDesync);\n }\n\n public static void resyncPositions(GrimPlayer player, int minX, int minY, int minZ, int maxX, int maxY, int maxZ, Predicate<Pair<BaseBlockState, Vector3i>> shouldSend, boolean likelyDesync) {\n // TODO: Use bukkit, PR a multi block change wrapper to packetevents\n }\n}" }, { "identifier": "GrimPlayer", "path": "src/main/java/ac/grim/grimac/player/GrimPlayer.java", "snippet": "public class GrimPlayer {\n public final UUID playerUUID;\n public final int entityID;\n public final Player bukkitPlayer;\n // Determining player ping\n // The difference between keepalive and transactions is that keepalive is async while transactions are sync\n public final Queue<Pair<Short, Long>> transactionsSent = new ConcurrentLinkedQueue<>();\n // Sync this to the netty thread because when spamming transactions, they can get out of order... somehow\n public final ConcurrentList<Short> didWeSendThatTrans = new ConcurrentList<>();\n private final AtomicInteger transactionIDCounter = new AtomicInteger(0);\n public Vector clientVelocity = new Vector();\n public double lastWasClimbing = 0;\n public boolean canSwimHop = false;\n public int riptideSpinAttackTicks = 0;\n public boolean hasGravity = true;\n public boolean playerEntityHasGravity = true;\n public VectorData predictedVelocity = new VectorData(new Vector(), VectorData.VectorType.Normal);\n public Vector actualMovement = new Vector();\n public Vector stuckSpeedMultiplier = new Vector(1, 1, 1);\n public Vector blockSpeedMultiplier = new Vector(1, 1, 1);\n public UncertaintyHandler uncertaintyHandler;\n public double gravity;\n public float friction;\n public double speed;\n public double x;\n public double y;\n public double z;\n public double lastX;\n public double lastY;\n public double lastZ;\n public float xRot;\n public float yRot;\n public float lastXRot;\n public float lastYRot;\n public boolean onGround;\n public boolean lastOnGround;\n public boolean isSneaking;\n public boolean wasSneaking;\n public boolean isCrouching;\n public boolean isSprinting;\n public boolean lastSprinting;\n public AlmostBoolean isUsingItem;\n public boolean isFlying;\n public boolean wasFlying;\n // If a player collides with the ground, their flying will be set false after their movement\n // But we need to know if they were flying DURING the movement\n // Thankfully we can 100% recover from this using some logic in PredictionData\n // If the player touches the ground and was flying, and now isn't flying - the player was flying during movement\n // Or if the player is flying - the player is flying during movement\n public boolean specialFlying;\n public boolean isSwimming;\n public boolean wasSwimming;\n public boolean isClimbing;\n public boolean isGliding;\n public boolean wasGliding;\n public boolean isRiptidePose = false;\n public double fallDistance;\n public SimpleCollisionBox boundingBox;\n public Pose pose = Pose.STANDING;\n // Determining slow movement has to be done before pose is updated\n public boolean isSlowMovement = false;\n public World playerWorld;\n public boolean isInBed = false;\n public boolean lastInBed = false;\n public boolean isDead = false;\n public float depthStriderLevel;\n public float flySpeed;\n public VehicleData vehicleData = new VehicleData();\n // The client claims this\n public boolean clientClaimsLastOnGround;\n // Set from base tick\n public boolean wasTouchingWater = false;\n public boolean wasTouchingLava = false;\n // For slightly reduced vertical lava friction and jumping\n public boolean slightlyTouchingLava = false;\n // For jumping\n public boolean slightlyTouchingWater = false;\n public boolean wasEyeInWater = false;\n public FluidTag fluidOnEyes;\n public boolean horizontalCollision;\n public boolean verticalCollision;\n public boolean clientControlledHorizontalCollision;\n public boolean clientControlledVerticalCollision;\n // Okay, this is our 0.03 detection\n //\n // couldSkipTick determines if an input could have resulted in the player skipping a tick < 0.03\n //\n // skippedTickInActualMovement determines if, relative to actual movement, the player didn't move enough\n // and a 0.03 vector was \"close enough\" to be an accurate prediction\n public boolean couldSkipTick = false;\n // This determines if the\n public boolean skippedTickInActualMovement = false;\n public boolean canGroundRiptide = false;\n // You cannot initialize everything here for some reason\n public CompensatedFlying compensatedFlying;\n public CompensatedFireworks compensatedFireworks;\n public CompensatedRiptide compensatedRiptide;\n public CompensatedWorld compensatedWorld;\n public CompensatedEntities compensatedEntities;\n public CompensatedPotions compensatedPotions;\n public LatencyUtils latencyUtils = new LatencyUtils();\n public PointThreeEstimator pointThreeEstimator;\n public TrigHandler trigHandler;\n public PacketStateData packetStateData;\n // Keep track of basetick stuff\n public Vector baseTickAddition = new Vector();\n public Vector baseTickWaterPushing = new Vector();\n public AtomicInteger lastTransactionSent = new AtomicInteger(0);\n public AtomicInteger lastTransactionReceived = new AtomicInteger(0);\n // For syncing the player's full swing in 1.9+\n public int movementPackets = 0;\n public VelocityData firstBreadKB = null;\n public VelocityData likelyKB = null;\n public VelocityData firstBreadExplosion = null;\n public VelocityData likelyExplosions = null;\n public CheckManager checkManager;\n public MovementCheckRunner movementCheckRunner;\n public boolean tryingToRiptide = false;\n public int minPlayerAttackSlow = 0;\n public int maxPlayerAttackSlow = 0;\n public boolean inVehicle;\n public Integer vehicle = null;\n public PacketEntity playerVehicle;\n public PacketEntity lastVehicle;\n public GameMode gamemode;\n PacketTracker packetTracker;\n private ClientVersion clientVersion;\n private int transactionPing = 0;\n private long playerClockAtLeast = 0;\n public Vector3d bedPosition;\n\n public GrimPlayer(Player player) {\n this.bukkitPlayer = player;\n this.playerUUID = player.getUniqueId();\n this.entityID = player.getEntityId();\n this.playerWorld = player.getWorld();\n\n clientVersion = PacketEvents.get().getPlayerUtils().getClientVersion(bukkitPlayer);\n\n // We can't send transaction packets to this player, disable the anticheat for them\n if (!ViaBackwardsManager.isViaLegacyUpdated && getClientVersion().isOlderThanOrEquals(ClientVersion.v_1_16_4)) {\n LogUtil.warn(ChatColor.RED + \"Please update ViaBackwards to 4.0.2 or newer\");\n LogUtil.warn(ChatColor.RED + \"An important packet is broken for 1.16 and below clients on this ViaBackwards version\");\n LogUtil.warn(ChatColor.RED + \"Disabling all checks for 1.16 and below players as otherwise they WILL be falsely banned\");\n LogUtil.warn(ChatColor.RED + \"Supported version: \" + ChatColor.WHITE + \"https://github.com/ViaVersion/ViaBackwards/actions/runs/1039987269\");\n return;\n }\n\n // Geyser players don't have Java movement\n if (PacketEvents.get().getPlayerUtils().isGeyserPlayer(playerUUID)) return;\n\n Location loginLocation = player.getLocation();\n lastX = loginLocation.getX();\n lastY = loginLocation.getY();\n lastZ = loginLocation.getZ();\n\n isFlying = bukkitPlayer.isFlying();\n wasFlying = bukkitPlayer.isFlying();\n\n if (ViaVersionLookupUtils.isAvailable()) {\n UserConnection connection = Via.getManager().getConnectionManager().getConnectedClient(playerUUID);\n packetTracker = connection != null ? connection.getPacketTracker() : null;\n }\n\n if (XMaterial.isNewVersion()) {\n compensatedWorld = new CompensatedWorldFlat(this);\n } else {\n compensatedWorld = new CompensatedWorld(this);\n }\n\n compensatedFlying = new CompensatedFlying(this);\n compensatedFireworks = new CompensatedFireworks(this);\n compensatedRiptide = new CompensatedRiptide(this);\n compensatedEntities = new CompensatedEntities(this);\n compensatedPotions = new CompensatedPotions(this);\n trigHandler = new TrigHandler(this);\n uncertaintyHandler = new UncertaintyHandler(this);\n pointThreeEstimator = new PointThreeEstimator(this);\n\n packetStateData = new PacketStateData();\n packetStateData.lastSlotSelected = bukkitPlayer.getInventory().getHeldItemSlot();\n\n checkManager = new CheckManager(this);\n movementCheckRunner = new MovementCheckRunner(this);\n\n playerWorld = bukkitPlayer.getLocation().getWorld();\n if (ServerVersion.getVersion().isNewerThanOrEquals(ServerVersion.v_1_17)) {\n compensatedWorld.setMinHeight(bukkitPlayer.getWorld().getMinHeight());\n compensatedWorld.setMaxWorldHeight(bukkitPlayer.getWorld().getMaxHeight());\n }\n\n x = bukkitPlayer.getLocation().getX();\n y = bukkitPlayer.getLocation().getY();\n z = bukkitPlayer.getLocation().getZ();\n xRot = bukkitPlayer.getLocation().getYaw();\n yRot = bukkitPlayer.getLocation().getPitch();\n isDead = bukkitPlayer.isDead();\n\n lastX = bukkitPlayer.getLocation().getX();\n lastY = bukkitPlayer.getLocation().getY();\n lastZ = bukkitPlayer.getLocation().getZ();\n lastXRot = bukkitPlayer.getLocation().getYaw();\n lastYRot = bukkitPlayer.getLocation().getPitch();\n\n gamemode = bukkitPlayer.getGameMode();\n\n uncertaintyHandler.pistonPushing.add(0d);\n uncertaintyHandler.collidingEntities.add(0);\n\n getSetbackTeleportUtil().setSafeSetbackLocation(playerWorld, new Vector3d(x, y, z));\n\n boundingBox = GetBoundingBox.getBoundingBoxFromPosAndSize(x, y, z, 0.6, 1.8);\n\n GrimAPI.INSTANCE.getPlayerDataManager().addPlayer(this);\n }\n\n public Set<VectorData> getPossibleVelocities() {\n Set<VectorData> set = new HashSet<>();\n\n if (firstBreadKB != null) {\n set.add(new VectorData(firstBreadKB.vector.clone(), VectorData.VectorType.Knockback));\n }\n\n if (likelyKB != null) {\n // Allow water pushing to affect knockback\n set.add(new VectorData(likelyKB.vector.clone(), VectorData.VectorType.Knockback));\n }\n\n set.addAll(getPossibleVelocitiesMinusKnockback());\n return set;\n }\n\n public Set<VectorData> getPossibleVelocitiesMinusKnockback() {\n Set<VectorData> possibleMovements = new HashSet<>();\n possibleMovements.add(new VectorData(clientVelocity, VectorData.VectorType.Normal));\n\n // A player cannot swim hop (> 0 y vel) and be on the ground\n // Fixes bug with underwater stepping movement being confused with swim hopping movement\n if (canSwimHop && !onGround) {\n possibleMovements.add(new VectorData(clientVelocity.clone().setY(0.3f), VectorData.VectorType.Swimhop));\n }\n\n // If the player has that client sided riptide thing and has colliding with an entity this tick\n if (riptideSpinAttackTicks >= 0 && uncertaintyHandler.collidingEntities.getLast() > 0) {\n possibleMovements.add(new VectorData(clientVelocity.clone().multiply(-0.2), VectorData.VectorType.Trident));\n }\n\n if (lastWasClimbing != 0) {\n possibleMovements.add(new VectorData(clientVelocity.clone().setY(lastWasClimbing + baseTickAddition.getY()), VectorData.VectorType.Climbable));\n }\n\n // Knockback takes precedence over piston pushing in my testing\n // It's very difficult to test precedence so if there's issues with this bouncy implementation let me know\n for (VectorData data : new HashSet<>(possibleMovements)) {\n for (BlockFace direction : uncertaintyHandler.slimePistonBounces) {\n if (direction.getModX() != 0) {\n possibleMovements.add(data.returnNewModified(data.vector.clone().setX(direction.getModX()), VectorData.VectorType.SlimePistonBounce));\n } else if (direction.getModY() != 0) {\n possibleMovements.add(data.returnNewModified(data.vector.clone().setY(direction.getModY()), VectorData.VectorType.SlimePistonBounce));\n } else if (direction.getModZ() != 0) {\n possibleMovements.add(data.returnNewModified(data.vector.clone().setZ(direction.getModZ()), VectorData.VectorType.SlimePistonBounce));\n }\n }\n }\n\n return possibleMovements;\n }\n\n // Players can get 0 ping by repeatedly sending invalid transaction packets, but that will only hurt them\n // The design is allowing players to miss transaction packets, which shouldn't be possible\n // But if some error made a client miss a packet, then it won't hurt them too bad.\n // Also it forces players to take knockback\n public boolean addTransactionResponse(short id) {\n // Disable ViaVersion packet limiter\n // Required as ViaVersion listens before us for converting packets between game versions\n if (packetTracker != null)\n packetTracker.setIntervalPackets(0);\n\n Pair<Short, Long> data = null;\n boolean hasID = false;\n for (Pair<Short, Long> iterator : transactionsSent) {\n if (iterator.getFirst() == id) {\n hasID = true;\n break;\n }\n }\n\n if (hasID) {\n do {\n data = transactionsSent.poll();\n if (data == null)\n break;\n\n int incrementingID = lastTransactionReceived.incrementAndGet();\n transactionPing = (int) (System.nanoTime() - data.getSecond());\n playerClockAtLeast = data.getSecond();\n\n latencyUtils.handleNettySyncTransaction(incrementingID);\n } while (data.getFirst() != id);\n }\n\n // Were we the ones who sent the packet?\n return data != null && data.getFirst() == id;\n }\n\n public void baseTickAddWaterPushing(Vector vector) {\n baseTickWaterPushing.add(vector);\n }\n\n public void baseTickAddVector(Vector vector) {\n clientVelocity.add(vector);\n baseTickAddition.add(vector);\n }\n\n public float getMaxUpStep() {\n if (playerVehicle == null) return 0.6f;\n\n if (playerVehicle.type == EntityType.BOAT) {\n return 0f;\n }\n\n // Pigs, horses, striders, and other vehicles all have 1 stepping height\n return 1.0f;\n }\n\n public void sendTransaction() {\n short transactionID = getNextTransactionID(1);\n try {\n addTransactionSend(transactionID);\n\n if (ServerVersion.getVersion().isNewerThanOrEquals(ServerVersion.v_1_17)) {\n PacketEvents.get().getPlayerUtils().sendPacket(bukkitPlayer, new WrappedPacketOutPing(transactionID));\n } else {\n PacketEvents.get().getPlayerUtils().sendPacket(bukkitPlayer, new WrappedPacketOutTransaction(0, transactionID, false));\n }\n } catch (Exception exception) {\n exception.printStackTrace();\n }\n }\n\n public short getNextTransactionID(int add) {\n // Take the 15 least significant bits, multiply by 1.\n // Short range is -32768 to 32767\n // We return a range of -32767 to 0\n // Allowing a range of -32768 to 0 for velocity + explosions\n return (short) (-1 * (transactionIDCounter.getAndAdd(add) & 0x7FFF));\n }\n\n public void addTransactionSend(short id) {\n didWeSendThatTrans.add(id);\n }\n\n public boolean isEyeInFluid(FluidTag tag) {\n return this.fluidOnEyes == tag;\n }\n\n public double getEyeHeight() {\n return GetBoundingBox.getEyeHeight(isCrouching, isGliding, isSwimming, isRiptidePose, isInBed, getClientVersion());\n }\n\n public Pose getSneakingPose() {\n return getClientVersion().isNewerThanOrEquals(ClientVersion.v_1_14) ? Pose.CROUCHING : Pose.NINE_CROUCHING;\n }\n\n public void pollClientVersion() {\n this.clientVersion = PacketEvents.get().getPlayerUtils().getClientVersion(bukkitPlayer);\n }\n\n public ClientVersion getClientVersion() {\n return clientVersion;\n }\n\n public void setVulnerable() {\n // Essentials gives players invulnerability after teleport, which is bad\n try {\n Plugin essentials = Bukkit.getServer().getPluginManager().getPlugin(\"Essentials\");\n if (essentials == null) return;\n\n Object user = ((Essentials) essentials).getUser(bukkitPlayer);\n if (user == null) return;\n\n // Use reflection because there isn't an API for this\n Field invulnerable = user.getClass().getDeclaredField(\"teleportInvulnerabilityTimestamp\");\n invulnerable.setAccessible(true);\n invulnerable.set(user, 0);\n } catch (Exception e) { // Might error from very outdated Essentials builds\n e.printStackTrace();\n }\n }\n\n public List<Double> getPossibleEyeHeights() { // We don't return sleeping eye height\n if (getClientVersion().isNewerThanOrEquals(ClientVersion.v_1_14)) { // Elytra, sneaking (1.14), standing\n return Arrays.asList(0.4, 1.27, 1.62);\n } else if (getClientVersion().isNewerThanOrEquals(ClientVersion.v_1_9)) { // Elytra, sneaking, standing\n return Arrays.asList(0.4, 1.54, 1.62);\n } else { // Only sneaking or standing\n return Arrays.asList(1.54, 1.62);\n }\n }\n\n public int getKeepAlivePing() {\n return PacketEvents.get().getPlayerUtils().getPing(bukkitPlayer);\n }\n\n public int getTransactionPing() {\n return transactionPing;\n }\n\n public long getPlayerClockAtLeast() {\n return playerClockAtLeast;\n }\n\n public SetbackTeleportUtil getSetbackTeleportUtil() {\n return checkManager.getSetbackUtil();\n }\n\n public boolean wouldCollisionResultFlagGroundSpoof(double inputY, double collisionY) {\n boolean verticalCollision = inputY != collisionY;\n boolean calculatedOnGround = verticalCollision && inputY < 0.0D;\n\n // We don't care about ground results here\n if (exemptOnGround()) return false;\n\n // If the player is on the ground with a y velocity of 0, let the player decide (too close to call)\n if (inputY == -SimpleCollisionBox.COLLISION_EPSILON && collisionY > -SimpleCollisionBox.COLLISION_EPSILON && collisionY <= 0)\n return false;\n\n return calculatedOnGround != onGround;\n }\n\n public boolean exemptOnGround() {\n return inVehicle\n || uncertaintyHandler.pistonX != 0 || uncertaintyHandler.pistonY != 0\n || uncertaintyHandler.pistonZ != 0 || uncertaintyHandler.isSteppingOnSlime\n || isFlying || uncertaintyHandler.isStepMovement || isDead\n || isInBed || lastInBed || uncertaintyHandler.lastFlyingStatusChange > -30\n || uncertaintyHandler.lastHardCollidingLerpingEntity > -3 || uncertaintyHandler.isOrWasNearGlitchyBlock;\n }\n}" }, { "identifier": "PredictionComplete", "path": "src/main/java/ac/grim/grimac/utils/anticheat/update/PredictionComplete.java", "snippet": "@AllArgsConstructor\n@Getter\n@Setter\npublic class PredictionComplete {\n private double offset;\n private PositionUpdate data;\n}" }, { "identifier": "Column", "path": "src/main/java/ac/grim/grimac/utils/chunks/Column.java", "snippet": "public class Column {\n public final int x;\n public final int z;\n public BaseChunk[] chunks;\n public final int transaction;\n public boolean markedForRemoval = false;\n\n public Column(int x, int z, BaseChunk[] chunks, int transaction) {\n this.chunks = chunks;\n this.x = x;\n this.z = z;\n this.transaction = transaction;\n }\n\n public BaseChunk[] getChunks() {\n return chunks;\n }\n\n // This ability was removed in 1.17 because of the extended world height\n // Therefore, the size of the chunks are ALWAYS 16!\n public void mergeChunks(BaseChunk[] toMerge) {\n for (int i = 0; i < 16; i++) {\n if (toMerge[i] != null) chunks[i] = toMerge[i];\n }\n }\n}" }, { "identifier": "SetBackData", "path": "src/main/java/ac/grim/grimac/utils/data/SetBackData.java", "snippet": "@Getter\n@Setter\npublic class SetBackData {\n Location position;\n float xRot, yRot;\n Vector velocity;\n Integer vehicle;\n int trans;\n boolean isComplete = false;\n boolean isPlugin = false;\n\n public SetBackData(Location position, float xRot, float yRot, Vector velocity, Integer vehicle, int trans) {\n this.position = position;\n this.xRot = xRot;\n this.yRot = yRot;\n this.velocity = velocity;\n this.vehicle = vehicle;\n this.trans = trans;\n }\n\n public SetBackData(Location position, float xRot, float yRot, Vector velocity, Integer vehicle, int trans, boolean isPlugin) {\n this.position = position;\n this.xRot = xRot;\n this.yRot = yRot;\n this.velocity = velocity;\n this.vehicle = vehicle;\n this.trans = trans;\n this.isPlugin = isPlugin;\n }\n}" }, { "identifier": "TeleportAcceptData", "path": "src/main/java/ac/grim/grimac/utils/data/TeleportAcceptData.java", "snippet": "@Getter\n@Setter\npublic class TeleportAcceptData {\n boolean isTeleport;\n SetBackData setback;\n}" }, { "identifier": "GrimMath", "path": "src/main/java/ac/grim/grimac/utils/math/GrimMath.java", "snippet": "public class GrimMath {\n public static int floor(double d) {\n return (int) Math.floor(d);\n }\n\n public static int ceil(double d) {\n return (int) Math.ceil(d);\n }\n\n public static double clamp(double d, double d2, double d3) {\n if (d < d2) {\n return d2;\n }\n return Math.min(d, d3);\n }\n\n public static float clampFloat(float d, float d2, float d3) {\n if (d < d2) {\n return d2;\n }\n return Math.min(d, d3);\n }\n\n public static double lerp(double lerpAmount, double start, double end) {\n return start + lerpAmount * (end - start);\n }\n\n public static int sign(double p_14206_) {\n if (p_14206_ == 0.0D) {\n return 0;\n } else {\n return p_14206_ > 0.0D ? 1 : -1;\n }\n }\n\n public static double frac(double p_14186_) {\n return p_14186_ - lfloor(p_14186_);\n }\n\n public static long lfloor(double p_14135_) {\n long i = (long) p_14135_;\n return p_14135_ < (double) i ? i - 1L : i;\n }\n\n // Find the closest distance to (1 / 64)\n // All poses horizontal length is 0.2 or 0.6 (0.1 or 0.3)\n // and we call this from the player's position\n //\n // We must find the minimum of the three numbers:\n // Distance to (1 / 64) when we are around -0.1\n // Distance to (1 / 64) when we are around 0\n // Distance to (1 / 64) when we are around 0.1\n //\n // Someone should likely just refactor this entire method, although it is cold being called twice every movement\n public static double distanceToHorizontalCollision(double position) {\n return Math.min(Math.abs(position % (1 / 640d)), Math.abs(Math.abs(position % (1 / 640d)) - (1 / 640d)));\n }\n\n public static boolean isCloseEnoughEquals(double d, double d2) {\n return Math.abs(d2 - d) < 9.999999747378752E-6;\n }\n\n public static double calculateAverage(List<Integer> marks) {\n long sum = 0;\n for (Integer mark : marks) {\n sum += mark;\n }\n return marks.isEmpty() ? 0 : 1.0 * sum / marks.size();\n }\n\n public static double calculateAverageLong(List<Long> marks) {\n long sum = 0;\n for (Long mark : marks) {\n sum += mark;\n }\n return marks.isEmpty() ? 0 : 1.0 * sum / marks.size();\n }\n}" }, { "identifier": "VectorUtils", "path": "src/main/java/ac/grim/grimac/utils/math/VectorUtils.java", "snippet": "public class VectorUtils {\n public static Vector cutBoxToVector(Vector vectorToCutTo, Vector min, Vector max) {\n SimpleCollisionBox box = new SimpleCollisionBox(min, max).sort();\n return cutBoxToVector(vectorToCutTo, box);\n }\n\n public static Vector cutBoxToVector(Vector vectorCutTo, SimpleCollisionBox box) {\n return new Vector(GrimMath.clamp(vectorCutTo.getX(), box.minX, box.maxX),\n GrimMath.clamp(vectorCutTo.getY(), box.minY, box.maxY),\n GrimMath.clamp(vectorCutTo.getZ(), box.minZ, box.maxZ));\n }\n\n public static Vector fromVec3d(Vector3d vector3d) {\n return new Vector(vector3d.getX(), vector3d.getY(), vector3d.getZ());\n }\n\n // Clamping stops the player from causing an integer overflow and crashing the netty thread\n public static Vector3d clampVector(Vector3d toClamp) {\n double x = GrimMath.clamp(toClamp.getX(), -3.0E7D, 3.0E7D);\n double y = GrimMath.clamp(toClamp.getY(), -2.0E7D, 2.0E7D);\n double z = GrimMath.clamp(toClamp.getZ(), -3.0E7D, 3.0E7D);\n\n return new Vector3d(x, y, z);\n }\n}" } ]
import ac.grim.grimac.GrimAPI; import ac.grim.grimac.checks.type.PostPredictionCheck; import ac.grim.grimac.events.packets.patch.ResyncWorldUtil; import ac.grim.grimac.player.GrimPlayer; import ac.grim.grimac.utils.anticheat.update.PredictionComplete; import ac.grim.grimac.utils.chunks.Column; import ac.grim.grimac.utils.data.SetBackData; import ac.grim.grimac.utils.data.TeleportAcceptData; import ac.grim.grimac.utils.math.GrimMath; import ac.grim.grimac.utils.math.VectorUtils; import io.github.retrooper.packetevents.utils.pair.Pair; import io.github.retrooper.packetevents.utils.vector.Vector3d; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.entity.Entity; import org.bukkit.util.Vector; import java.util.concurrent.ConcurrentLinkedDeque; import java.util.concurrent.ConcurrentLinkedQueue;
7,651
package ac.grim.grimac.manager; public class SetbackTeleportUtil extends PostPredictionCheck { // Sync to NETTY (Why does the bukkit thread have to modify this, can we avoid it?) // I think it should be safe enough because the worst that can happen is we overwrite another plugin teleport // // This is required because the required setback position is not sync to bukkit, and we must avoid // setting the player back to a position where they were cheating public boolean hasAcceptedSetbackPosition = true; // Sync to netty final ConcurrentLinkedQueue<Pair<Integer, Location>> teleports = new ConcurrentLinkedQueue<>(); // Map of teleports that bukkit is about to send to the player on netty (fixes race condition) final ConcurrentLinkedDeque<Location> pendingTeleports = new ConcurrentLinkedDeque<>(); // Sync to netty, a player MUST accept a teleport to spawn into the world public boolean hasAcceptedSpawnTeleport = false; // Was there a ghost block that forces us to block offsets until the player accepts their teleport? public boolean blockOffsets = false; public int bukkitTeleportsProcessed = 0; // This required setback data is sync to the BUKKIT MAIN THREAD (!) SetBackData requiredSetBack = null; // Sync to the anticheat thread // The anticheat thread MUST be the only thread that controls these safe setback position variables // This one prevents us from pulling positions the tick before a setback boolean wasLastMovementSafe = true; // Sync to anything, worst that can happen is sending an extra world update (which won't be noticed) long lastWorldResync = 0; // Sync to anticheat thread Vector lastMovementVel = new Vector(); // Generally safe teleport position (ANTICHEAT THREAD!) // Determined by the latest movement prediction // Positions until the player's current setback is accepted cannot become safe teleport positions SetbackLocationVelocity safeTeleportPosition; public SetbackTeleportUtil(GrimPlayer player) { super(player); } /** * Generates safe setback locations by looking at the current prediction * <p> * 2021-10-9 This method seems to be safe and doesn't allow bypasses */ @Override
package ac.grim.grimac.manager; public class SetbackTeleportUtil extends PostPredictionCheck { // Sync to NETTY (Why does the bukkit thread have to modify this, can we avoid it?) // I think it should be safe enough because the worst that can happen is we overwrite another plugin teleport // // This is required because the required setback position is not sync to bukkit, and we must avoid // setting the player back to a position where they were cheating public boolean hasAcceptedSetbackPosition = true; // Sync to netty final ConcurrentLinkedQueue<Pair<Integer, Location>> teleports = new ConcurrentLinkedQueue<>(); // Map of teleports that bukkit is about to send to the player on netty (fixes race condition) final ConcurrentLinkedDeque<Location> pendingTeleports = new ConcurrentLinkedDeque<>(); // Sync to netty, a player MUST accept a teleport to spawn into the world public boolean hasAcceptedSpawnTeleport = false; // Was there a ghost block that forces us to block offsets until the player accepts their teleport? public boolean blockOffsets = false; public int bukkitTeleportsProcessed = 0; // This required setback data is sync to the BUKKIT MAIN THREAD (!) SetBackData requiredSetBack = null; // Sync to the anticheat thread // The anticheat thread MUST be the only thread that controls these safe setback position variables // This one prevents us from pulling positions the tick before a setback boolean wasLastMovementSafe = true; // Sync to anything, worst that can happen is sending an extra world update (which won't be noticed) long lastWorldResync = 0; // Sync to anticheat thread Vector lastMovementVel = new Vector(); // Generally safe teleport position (ANTICHEAT THREAD!) // Determined by the latest movement prediction // Positions until the player's current setback is accepted cannot become safe teleport positions SetbackLocationVelocity safeTeleportPosition; public SetbackTeleportUtil(GrimPlayer player) { super(player); } /** * Generates safe setback locations by looking at the current prediction * <p> * 2021-10-9 This method seems to be safe and doesn't allow bypasses */ @Override
public void onPredictionComplete(final PredictionComplete predictionComplete) {
4
2023-11-11 05:14:12+00:00
12k
CodecNomad/CodecClient
src/main/java/com/github/codecnomad/codecclient/command/MainCommand.java
[ { "identifier": "Client", "path": "src/main/java/com/github/codecnomad/codecclient/Client.java", "snippet": "@Mod(modid = \"codecclient\", useMetadata = true)\npublic class Client {\n public static Map<String, Module> modules = new HashMap<>();\n public static Minecraft mc = Minecraft.getMinecraft();\n public static Rotation rotation = new Rotation();\n public static Config guiConfig;\n\n static {\n modules.put(\"FishingMacro\", new FishingMacro());\n }\n\n @Mod.EventHandler\n public void init(FMLInitializationEvent event) {\n guiConfig = new Config();\n\n MinecraftForge.EVENT_BUS.register(this);\n MinecraftForge.EVENT_BUS.register(rotation);\n\n MinecraftForge.EVENT_BUS.register(MainCommand.pathfinding);\n\n CommandManager.register(new MainCommand());\n }\n\n @SubscribeEvent\n public void disconnect(FMLNetworkEvent.ClientDisconnectionFromServerEvent event) {\n for (Map.Entry<String, Module> moduleMap : modules.entrySet()) {\n moduleMap.getValue().unregister();\n }\n }\n}" }, { "identifier": "Config", "path": "src/main/java/com/github/codecnomad/codecclient/ui/Config.java", "snippet": "@SuppressWarnings(\"unused\")\npublic class Config extends cc.polyfrost.oneconfig.config.Config {\n @Color(\n name = \"Color\",\n category = \"Visuals\"\n )\n public static OneColor VisualColor = new OneColor(100, 60, 160, 200);\n @KeyBind(\n name = \"Fishing key-bind\",\n category = \"Macros\",\n subcategory = \"Fishing\"\n )\n public static OneKeyBind FishingKeybinding = new OneKeyBind(Keyboard.KEY_F);\n @Number(\n name = \"Catch delay\",\n category = \"Macros\",\n subcategory = \"Fishing\",\n min = 1,\n max = 20\n )\n public static int FishingDelay = 10;\n @Number(\n name = \"Kill delay\",\n category = \"Macros\",\n subcategory = \"Fishing\",\n min = 1,\n max = 40\n )\n public static int KillDelay = 20;\n @Number(\n name = \"Attack c/s\",\n category = \"Macros\",\n subcategory = \"Fishing\",\n min = 5,\n max = 20\n )\n public static int AttackCps = 10;\n\n @Number(\n name = \"Smoothing\",\n category = \"Macros\",\n subcategory = \"Fishing\",\n min = 2,\n max = 10\n )\n public static int RotationSmoothing = 4;\n\n @Number(\n name = \"Random movement frequency\",\n category = \"Macros\",\n subcategory = \"Fishing\",\n min = 5,\n max = 50\n )\n public static int MovementFrequency = 15;\n\n @Switch(\n name = \"Auto kill\",\n category = \"Macros\",\n subcategory = \"Fishing\"\n )\n public static boolean AutoKill = true;\n\n @Switch(\n name = \"Only sound failsafe\",\n category = \"Macros\",\n subcategory = \"Fishing\"\n )\n public static boolean OnlySound = false;\n\n @Number(\n name = \"Weapon slot\",\n category = \"Macros\",\n subcategory = \"Fishing\",\n min = 1,\n max = 9\n )\n public static int WeaponSlot = 9;\n\n @Switch(\n name = \"Right click attack\",\n category = \"Macros\",\n subcategory = \"Fishing\"\n )\n public static boolean RightClick = false;\n\n @HUD(\n name = \"Fishing HUD\",\n category = \"Visuals\"\n )\n public FishingHud hudFishing = new FishingHud();\n\n public Config() {\n super(new Mod(\"CodecClient\", ModType.UTIL_QOL), \"config.json\");\n initialize();\n\n registerKeyBind(FishingKeybinding, () -> toggle(\"FishingMacro\"));\n save();\n }\n\n private static void toggle(String name) {\n Module helperClassModule = Client.modules.get(name);\n if (helperClassModule.state) {\n helperClassModule.unregister();\n } else {\n helperClassModule.register();\n }\n }\n}" }, { "identifier": "Chat", "path": "src/main/java/com/github/codecnomad/codecclient/utils/Chat.java", "snippet": "public class Chat {\n public static void sendMessage(String message) {\n Client.mc.thePlayer.addChatMessage(new ChatComponentText(String.format(\"§c§lCodecClient >> §7 %s\", message)));\n }\n}" }, { "identifier": "Pathfinding", "path": "src/main/java/com/github/codecnomad/codecclient/utils/Pathfinding.java", "snippet": "public class Pathfinding {\n ConcurrentSkipListSet<Node> open = new ConcurrentSkipListSet<>(Comparator.comparingDouble(Node::getF));\n Set<Node> closed = new ConcurrentSet<>();\n\n @SubscribeEvent\n public void lastWorld(RenderWorldLastEvent event) {\n// for (Node node : open) {\n// Render.drawOutlinedFilledBoundingBox(node.position, Color.green, event.partialTicks);\n// }\n//\n// for (Node node : closed) {\n// Render.drawOutlinedFilledBoundingBox(node.position, Color.red, event.partialTicks);\n// }\n }\n\n public List<BlockPos> createPath(BlockPos s, BlockPos t) {\n open.clear();\n closed.clear();\n\n Node start = new Node(s.add(0.5, 0.5, 0.5));\n Node target = new Node(t.add(0.5, 0.5, 0.5));\n\n start.gCost = 0;\n start.hCost = start.distanceTo(target);\n\n open.add(start);\n\n long startTime = System.currentTimeMillis();\n while (!open.isEmpty() && (System.currentTimeMillis() - startTime) < 5000) {\n Node currentNode = open.pollFirst();\n\n if (currentNode == null) {\n break;\n }\n\n closed.add(currentNode);\n\n if (currentNode.equals(target)) {\n return reconstructPath(currentNode);\n }\n\n for (BlockPos neighbourPosition : currentNode.getNeighbourPositions()) {\n Node neighbourNode = new Node(neighbourPosition.add(0.5, 0.5, 0.5));\n\n if (neighbourNode.getBlockState() == null) {\n return reconstructPath(currentNode);\n }\n\n if (!neighbourNode.getBlockMaterial().blocksMovement()) {\n continue;\n }\n\n if (neighbourNode.isIn(closed)) {\n continue;\n }\n\n Node node1 = new Node(neighbourNode.position.add(0, 1, 0).add(0.5, 0.5, 0.5));\n Node node2 = new Node(neighbourNode.position.add(0, 2, 0).add(0.5, 0.5, 0.5));\n Node node3 = new Node(neighbourNode.position.add(0, 3, 0).add(0.5, 0.5, 0.5));\n\n IBlockState node1BS = node1.getBlockState();\n IBlockState node2BS = node2.getBlockState();\n IBlockState node3BS = node3.getBlockState();\n\n AxisAlignedBB node1BB = null;\n AxisAlignedBB node2BB = null;\n AxisAlignedBB node3BB = null;\n\n try {\n node1BB = node1BS.getBlock().getCollisionBoundingBox(Client.mc.theWorld, node1.position, node1BS);\n } catch (Exception ignored) {}\n try {\n node2BB = node2BS.getBlock().getCollisionBoundingBox(Client.mc.theWorld, node1.position, node2BS);\n } catch (Exception ignored) {}\n try {\n node3BB = node3BS.getBlock().getCollisionBoundingBox(Client.mc.theWorld, node1.position, node3BS);\n } catch (Exception ignored) {}\n\n double allBB = 0;\n if (node1BB != null) {\n allBB += (node1BB.maxY - node1BB.minY);\n }\n\n if (node2BB != null) {\n allBB += (node2BB.maxY - node2BB.minY);\n }\n\n if (node3BB != null) {\n allBB += (node3BB.maxY - node3BB.minY);\n }\n\n if (allBB > 0.2) {\n continue;\n }\n\n double gCost = currentNode.gCost + 1;\n for (BlockPos pos : neighbourNode.getBigNeighbourPositions()) {\n try {\n if (Client.mc.theWorld.getBlockState(pos).getBlock().getCollisionBoundingBox(Client.mc.theWorld, pos, Client.mc.theWorld.getBlockState(pos)).maxY - Client.mc.theWorld.getBlockState(pos).getBlock().getCollisionBoundingBox(Client.mc.theWorld, pos, Client.mc.theWorld.getBlockState(pos)).minY > 0.5) {\n gCost += gCost * 2;\n }\n } catch (Exception ignored) {}\n }\n\n if (!neighbourNode.isIn(open)) {\n neighbourNode.parent = currentNode;\n neighbourNode.gCost = gCost;\n neighbourNode.hCost = neighbourNode.distanceTo(target);\n\n open.add(neighbourNode);\n }\n }\n }\n return null;\n }\n\n private List<BlockPos> reconstructPath(Node currentNode) {\n List<BlockPos> path = new ArrayList<>();\n while (currentNode != null) {\n path.add(0, currentNode.position);\n currentNode = currentNode.parent;\n }\n return smoothPath(path);\n }\n\n private List<BlockPos> smoothPath(List<BlockPos> path) {\n List<BlockPos> smoothedPath = new ArrayList<>();\n if (path.isEmpty()) {\n return smoothedPath;\n }\n\n int k = 0;\n smoothedPath.add(path.get(0));\n\n for (int i = 1; i < path.size() - 1; i++) {\n if (!canSee(smoothedPath.get(k), path.get(i + 1))) {\n k++;\n smoothedPath.add(smoothedPath.size(), path.get(i));\n }\n }\n\n smoothedPath.add(smoothedPath.size(), path.get(path.size() - 1));\n\n return smoothedPath;\n }\n\n boolean canSee(BlockPos start, BlockPos end) {\n return Client.mc.theWorld.rayTraceBlocks(Math.fromBlockPos(start.add(0, 1, 0)), Math.fromBlockPos(end.add(0, 1, 0)), false, true, false) == null && Client.mc.theWorld.rayTraceBlocks(Math.fromBlockPos(start.add(0, 2, 0)), Math.fromBlockPos(end.add(0, 2, 0)), false, true, false) == null;\n }\n\n private static class Node {\n BlockPos position;\n Node parent;\n double gCost;\n double hCost;\n\n Node(BlockPos pos) {\n position = pos;\n }\n\n double getF() {\n return gCost + hCost;\n }\n\n List<BlockPos> getNeighbourPositions() {\n List<BlockPos> neighbourPositions = new ArrayList<>();\n\n neighbourPositions.add(this.position.add(1, 0, 0));\n neighbourPositions.add(this.position.add(-1, 0, 0));\n neighbourPositions.add(this.position.add(0, 0, 1));\n neighbourPositions.add(this.position.add(0, 0, -1));\n\n neighbourPositions.add(this.position.add(1, -1, 0));\n neighbourPositions.add(this.position.add(-1, -1, 0));\n neighbourPositions.add(this.position.add(0, -1, 1));\n neighbourPositions.add(this.position.add(0, -1, -1));\n\n\n neighbourPositions.add(this.position.add(1, 1, 0));\n neighbourPositions.add(this.position.add(-1, 1, 0));\n neighbourPositions.add(this.position.add(0, 1, 1));\n neighbourPositions.add(this.position.add(0, 1, -1));\n\n return neighbourPositions;\n }\n\n List<BlockPos> getBigNeighbourPositions() {\n List<BlockPos> neighbourPositions = new ArrayList<>();\n\n for (int xOffset = -1; xOffset <= 1; xOffset++) {\n for (int zOffset = -1; zOffset <= 1; zOffset++) {\n neighbourPositions.add(this.position.add(xOffset, 1, zOffset));\n neighbourPositions.add(this.position.add(xOffset, 2, zOffset));\n }\n }\n\n return neighbourPositions;\n }\n\n double distanceTo(Node other) {\n return this.position.distanceSq(other.position);\n }\n\n @SuppressWarnings(\"EqualsWhichDoesntCheckParameterClass\")\n @Override\n public boolean equals(Object other) {\n return this.position.equals(((Node) other).position);\n }\n\n boolean isIn(Set<Node> set) {\n return set.stream().anyMatch(node -> node.position.equals(this.position));\n }\n\n boolean isIn(PriorityQueue<Node> set) {\n return set.stream().anyMatch(node -> node.position.equals(this.position));\n }\n\n\n IBlockState getBlockState() {\n return Client.mc.theWorld.getBlockState(this.position);\n }\n\n Material getBlockMaterial() {\n return getBlockState().getBlock().getMaterial();\n }\n }\n}" }, { "identifier": "Render", "path": "src/main/java/com/github/codecnomad/codecclient/utils/Render.java", "snippet": "@SuppressWarnings({\"unused\", \"DuplicatedCode\"})\npublic class Render {\n\n public static void drawOutlinedFilledBoundingBox(AxisAlignedBB aabb, Color color, float partialTicks) {\n aabb = aabb.offset(-0.001, -0.001, -0.001);\n aabb = aabb.expand(0.002, 0.002, 0.002);\n GlStateManager.pushMatrix();\n GlStateManager.enableBlend();\n GlStateManager.disableTexture2D();\n GlStateManager.depthMask(false);\n\n double width = java.lang.Math.max(1 - (Client.mc.thePlayer.getDistance(aabb.minX, aabb.minY, aabb.minZ) / 10 - 2), 2);\n Render.drawBoundingBox(aabb, color, partialTicks);\n Render.drawOutlinedBoundingBox(aabb.offset(-0.001, -0.001, -0.001).expand(0.002, 0.002, 0.002), color, (float) width, partialTicks);\n GlStateManager.depthMask(true);\n GlStateManager.enableTexture2D();\n GlStateManager.disableBlend();\n GlStateManager.popMatrix();\n }\n\n public static void drawOutlinedFilledBoundingBox(BlockPos pos, Color color, float partialTicks) {\n AxisAlignedBB aabb = new AxisAlignedBB(pos, pos.add(1, 1, 1));\n drawOutlinedFilledBoundingBox(aabb, color, partialTicks);\n }\n\n public static void drawWaypoint(BlockPos pos, Color color, String label, float partialTicks, boolean throughWalls) {\n AxisAlignedBB aabb2 = new AxisAlignedBB(pos.getX() + 0.5, pos.getY() + 1, pos.getZ() + 0.5, pos.getX() + 0.5, pos.getY() + 100, pos.getZ() + 0.5);\n\n GlStateManager.pushMatrix();\n GlStateManager.pushAttrib();\n if (throughWalls) GlStateManager.disableDepth();\n drawOutlinedFilledBoundingBox(aabb2, color, partialTicks);\n drawOutlinedFilledBoundingBox(pos, color, partialTicks);\n renderWaypointText(pos.add(0, 3, 0), label);\n if (throughWalls) GlStateManager.enableDepth();\n GlStateManager.popAttrib();\n GlStateManager.popMatrix();\n }\n\n public static void renderWaypointText(BlockPos pos, String text) {\n double x = pos.getX() + 0.5 - Client.mc.getRenderManager().viewerPosX;\n double y = pos.getY() - Client.mc.getRenderManager().viewerPosY;\n double z = pos.getZ() + 0.5 - Client.mc.getRenderManager().viewerPosZ;\n\n FontRenderer fontRenderer = Minecraft.getMinecraft().fontRendererObj;\n double distance = Minecraft.getMinecraft().thePlayer.getDistanceSq(pos.getX(), pos.getY(), pos.getZ());\n double scaleFactor = 0.005 * java.lang.Math.sqrt(distance); // Adjust the scaleFactor as needed for proper text size\n\n GlStateManager.pushMatrix();\n GlStateManager.pushAttrib();\n\n GlStateManager.disableLighting(); // Disable lighting temporarily\n GlStateManager.disableDepth(); // Disable depth testing for the background rectangle\n GlStateManager.disableTexture2D(); // Disable texture for the background rectangle\n GlStateManager.enableBlend(); // Enable blending for transparency\n GlStateManager.blendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);\n\n GlStateManager.translate(x, y, z);\n GlStateManager.rotate(-Client.mc.getRenderManager().playerViewY, 0.0F, 1.0F, 0.0F);\n GlStateManager.rotate(Client.mc.getRenderManager().playerViewX, 1.0F, 0.0F, 0.0F);\n GlStateManager.scale(-scaleFactor, -scaleFactor, scaleFactor);\n\n // Background rectangle\n Tessellator tessellator = Tessellator.getInstance();\n WorldRenderer worldrenderer = tessellator.getWorldRenderer();\n int stringWidth = fontRenderer.getStringWidth(text);\n int padding = 2;\n int rectWidth = stringWidth + padding * 2;\n int rectHeight = 8 + padding * 2;\n int alpha = 160;\n worldrenderer.begin(7, DefaultVertexFormats.POSITION_COLOR);\n worldrenderer.pos((double) -rectWidth / 2, -1, 0).color(0, 0, 0, alpha).endVertex();\n worldrenderer.pos((double) -rectWidth / 2, rectHeight - 1, 0).color(0, 0, 0, alpha).endVertex();\n worldrenderer.pos((double) rectWidth / 2, rectHeight - 1, 0).color(0, 0, 0, alpha).endVertex();\n worldrenderer.pos((double) rectWidth / 2, -1, 0).color(0, 0, 0, alpha).endVertex();\n tessellator.draw();\n\n GlStateManager.enableTexture2D();\n fontRenderer.drawString(text, -fontRenderer.getStringWidth(text) / 2, padding, 0xFFFFFF);\n\n String distanceText = \"(\" + (int) java.lang.Math.sqrt(distance) + \"m)\";\n int distanceWidth = fontRenderer.getStringWidth(distanceText);\n fontRenderer.drawString(distanceText, -(distanceWidth / 2), padding + rectHeight - 1, 0xFFFFFF);\n\n GlStateManager.enableDepth();\n GlStateManager.disableBlend();\n GlStateManager.enableLighting(); // Restore lighting settings\n\n GlStateManager.popAttrib();\n GlStateManager.popMatrix();\n\n }\n\n public static void draw3DString(Vec3 pos, String text, int color, float partialTicks) {\n Minecraft mc = Minecraft.getMinecraft();\n EntityPlayer player = mc.thePlayer;\n double x = (pos.xCoord - player.lastTickPosX) + ((pos.xCoord - player.posX) - (pos.xCoord - player.lastTickPosX)) * partialTicks;\n double y = (pos.yCoord - player.lastTickPosY) + ((pos.yCoord - player.posY) - (pos.yCoord - player.lastTickPosY)) * partialTicks;\n double z = (pos.zCoord - player.lastTickPosZ) + ((pos.zCoord - player.posZ) - (pos.zCoord - player.lastTickPosZ)) * partialTicks;\n RenderManager renderManager = mc.getRenderManager();\n\n float f = 1.6F;\n float f1 = 0.016666668F * f;\n int width = mc.fontRendererObj.getStringWidth(text) / 2;\n GlStateManager.pushMatrix();\n GlStateManager.translate(x, y, z);\n GL11.glNormal3f(0f, 1f, 0f);\n GlStateManager.rotate(-renderManager.playerViewY, 0f, 1f, 0f);\n GlStateManager.rotate(renderManager.playerViewX, 1f, 0f, 0f);\n GlStateManager.scale(-f1, -f1, -f1);\n GlStateManager.disableBlend();\n GlStateManager.tryBlendFuncSeparate(770, 771, 1, 0);\n mc.fontRendererObj.drawString(text, -width, 0, color);\n GlStateManager.popMatrix();\n }\n\n public static void draw3DStringWithShadow(Vec3 pos, String str, float partialTicks) {\n EntityPlayer player = Client.mc.thePlayer;\n double x = (pos.xCoord - player.lastTickPosX) + ((pos.xCoord - player.posX) - (pos.xCoord - player.lastTickPosX)) * partialTicks;\n double y = (pos.yCoord - player.lastTickPosY) + ((pos.yCoord - player.posY) - (pos.yCoord - player.lastTickPosY)) * partialTicks;\n double z = (pos.zCoord - player.lastTickPosZ) + ((pos.zCoord - player.posZ) - (pos.zCoord - player.lastTickPosZ)) * partialTicks;\n RenderManager renderManager = Client.mc.getRenderManager();\n\n FontRenderer fontrenderer = Client.mc.fontRendererObj;\n float f = 1.6F;\n float f1 = 0.016666668F * f;\n GlStateManager.pushMatrix();\n GlStateManager.translate((float) x + 0.0F, (float) y, (float) z);\n GL11.glNormal3f(0.0F, 1.0F, 0.0F);\n GlStateManager.rotate(-renderManager.playerViewY, 0.0F, 1.0F, 0.0F);\n GlStateManager.rotate(renderManager.playerViewX, 1.0F, 0.0F, 0.0F);\n GlStateManager.scale(-f1, -f1, f1);\n GlStateManager.disableLighting();\n GlStateManager.depthMask(false);\n GlStateManager.disableDepth();\n GlStateManager.enableBlend();\n GlStateManager.tryBlendFuncSeparate(770, 771, 1, 0);\n Tessellator tessellator = Tessellator.getInstance();\n WorldRenderer worldrenderer = tessellator.getWorldRenderer();\n int i = 0;\n int j = fontrenderer.getStringWidth(str) / 2;\n GlStateManager.disableTexture2D();\n worldrenderer.begin(7, DefaultVertexFormats.POSITION_COLOR);\n worldrenderer.pos(-j - 1, -1 + i, 0.0D).color(0.0F, 0.0F, 0.0F, 0.25F).endVertex();\n worldrenderer.pos(-j - 1, 8 + i, 0.0D).color(0.0F, 0.0F, 0.0F, 0.25F).endVertex();\n worldrenderer.pos(j + 1, 8 + i, 0.0D).color(0.0F, 0.0F, 0.0F, 0.25F).endVertex();\n worldrenderer.pos(j + 1, -1 + i, 0.0D).color(0.0F, 0.0F, 0.0F, 0.25F).endVertex();\n tessellator.draw();\n GlStateManager.enableTexture2D();\n GlStateManager.enableDepth();\n GlStateManager.depthMask(true);\n fontrenderer.drawStringWithShadow(str, (float) -fontrenderer.getStringWidth(str) / 2, i, -1);\n GlStateManager.enableLighting();\n GlStateManager.disableBlend();\n GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F);\n GlStateManager.popMatrix();\n }\n\n public static void drawOutlinedBoundingBox(AxisAlignedBB aabb, Color color, float width, float partialTicks) {\n Entity render = Minecraft.getMinecraft().getRenderViewEntity();\n\n double realX = render.lastTickPosX + (render.posX - render.lastTickPosX) * partialTicks;\n double realY = render.lastTickPosY + (render.posY - render.lastTickPosY) * partialTicks;\n double realZ = render.lastTickPosZ + (render.posZ - render.lastTickPosZ) * partialTicks;\n\n GlStateManager.pushMatrix();\n GlStateManager.translate(-realX, -realY, -realZ);\n\n GlStateManager.enableBlend();\n GlStateManager.tryBlendFuncSeparate(770, 771, 1, 0);\n GlStateManager.disableTexture2D();\n GL11.glLineWidth(width);\n\n RenderGlobal.drawOutlinedBoundingBox(aabb, color.getRed(), color.getGreen(), color.getBlue(), color.getAlpha());\n GlStateManager.translate(realX, realY, realZ);\n GlStateManager.popMatrix();\n }\n\n public static void drawBoundingBox(AxisAlignedBB aa, Color c, float partialTicks) {\n Entity render = Minecraft.getMinecraft().getRenderViewEntity();\n aa = aa.offset(-0.002, -0.001, -0.002);\n aa = aa.expand(0.004, 0.005, 0.004);\n double realX = render.lastTickPosX + (render.posX - render.lastTickPosX) * partialTicks;\n double realY = render.lastTickPosY + (render.posY - render.lastTickPosY) * partialTicks;\n double realZ = render.lastTickPosZ + (render.posZ - render.lastTickPosZ) * partialTicks;\n GlStateManager.pushMatrix();\n GlStateManager.translate(-realX, -realY, -realZ);\n GlStateManager.disableTexture2D();\n GlStateManager.enableBlend();\n GlStateManager.disableLighting();\n GlStateManager.disableAlpha();\n GlStateManager.tryBlendFuncSeparate(770, 771, 1, 0);\n\n Tessellator tessellator = Tessellator.getInstance();\n WorldRenderer worldRenderer = tessellator.getWorldRenderer();\n int color = c.getRGB();\n float a = (float) (color >> 24 & 255) / 255.0F;\n a = (float) ((double) a * 0.15D);\n float r = (float) (color >> 16 & 255) / 255.0F;\n float g = (float) (color >> 8 & 255) / 255.0F;\n float b = (float) (color & 255) / 255.0F;\n worldRenderer.begin(7, DefaultVertexFormats.POSITION_COLOR);\n worldRenderer.pos(aa.minX, aa.maxY, aa.minZ).color(r, g, b, a).endVertex();\n worldRenderer.pos(aa.minX, aa.minY, aa.minZ).color(r, g, b, a).endVertex();\n worldRenderer.pos(aa.maxX, aa.maxY, aa.minZ).color(r, g, b, a).endVertex();\n worldRenderer.pos(aa.maxX, aa.minY, aa.minZ).color(r, g, b, a).endVertex();\n worldRenderer.pos(aa.maxX, aa.maxY, aa.maxZ).color(r, g, b, a).endVertex();\n worldRenderer.pos(aa.maxX, aa.minY, aa.maxZ).color(r, g, b, a).endVertex();\n worldRenderer.pos(aa.minX, aa.maxY, aa.maxZ).color(r, g, b, a).endVertex();\n worldRenderer.pos(aa.minX, aa.minY, aa.maxZ).color(r, g, b, a).endVertex();\n tessellator.draw();\n worldRenderer.begin(7, DefaultVertexFormats.POSITION_COLOR);\n worldRenderer.pos(aa.maxX, aa.minY, aa.minZ).color(r, g, b, a).endVertex();\n worldRenderer.pos(aa.maxX, aa.maxY, aa.minZ).color(r, g, b, a).endVertex();\n worldRenderer.pos(aa.minX, aa.minY, aa.minZ).color(r, g, b, a).endVertex();\n worldRenderer.pos(aa.minX, aa.maxY, aa.minZ).color(r, g, b, a).endVertex();\n worldRenderer.pos(aa.minX, aa.minY, aa.maxZ).color(r, g, b, a).endVertex();\n worldRenderer.pos(aa.minX, aa.maxY, aa.maxZ).color(r, g, b, a).endVertex();\n worldRenderer.pos(aa.maxX, aa.minY, aa.maxZ).color(r, g, b, a).endVertex();\n worldRenderer.pos(aa.maxX, aa.maxY, aa.maxZ).color(r, g, b, a).endVertex();\n tessellator.draw();\n worldRenderer.begin(7, DefaultVertexFormats.POSITION_COLOR);\n worldRenderer.pos(aa.minX, aa.minY, aa.minZ).color(r, g, b, a).endVertex();\n worldRenderer.pos(aa.maxX, aa.minY, aa.minZ).color(r, g, b, a).endVertex();\n worldRenderer.pos(aa.maxX, aa.minY, aa.maxZ).color(r, g, b, a).endVertex();\n worldRenderer.pos(aa.minX, aa.minY, aa.maxZ).color(r, g, b, a).endVertex();\n worldRenderer.pos(aa.minX, aa.minY, aa.minZ).color(r, g, b, a).endVertex();\n worldRenderer.pos(aa.minX, aa.minY, aa.maxZ).color(r, g, b, a).endVertex();\n worldRenderer.pos(aa.maxX, aa.minY, aa.maxZ).color(r, g, b, a).endVertex();\n worldRenderer.pos(aa.maxX, aa.minY, aa.minZ).color(r, g, b, a).endVertex();\n tessellator.draw();\n worldRenderer.begin(7, DefaultVertexFormats.POSITION_COLOR);\n worldRenderer.pos(aa.minX, aa.maxY, aa.minZ).color(r, g, b, a).endVertex();\n worldRenderer.pos(aa.maxX, aa.maxY, aa.minZ).color(r, g, b, a).endVertex();\n worldRenderer.pos(aa.maxX, aa.maxY, aa.maxZ).color(r, g, b, a).endVertex();\n worldRenderer.pos(aa.minX, aa.maxY, aa.maxZ).color(r, g, b, a).endVertex();\n worldRenderer.pos(aa.minX, aa.maxY, aa.minZ).color(r, g, b, a).endVertex();\n worldRenderer.pos(aa.minX, aa.maxY, aa.maxZ).color(r, g, b, a).endVertex();\n worldRenderer.pos(aa.maxX, aa.maxY, aa.maxZ).color(r, g, b, a).endVertex();\n worldRenderer.pos(aa.maxX, aa.maxY, aa.minZ).color(r, g, b, a).endVertex();\n tessellator.draw();\n worldRenderer.begin(7, DefaultVertexFormats.POSITION_COLOR);\n worldRenderer.pos(aa.minX, aa.maxY, aa.minZ).color(r, g, b, a).endVertex();\n worldRenderer.pos(aa.minX, aa.minY, aa.minZ).color(r, g, b, a).endVertex();\n worldRenderer.pos(aa.minX, aa.maxY, aa.maxZ).color(r, g, b, a).endVertex();\n worldRenderer.pos(aa.minX, aa.minY, aa.maxZ).color(r, g, b, a).endVertex();\n worldRenderer.pos(aa.maxX, aa.maxY, aa.maxZ).color(r, g, b, a).endVertex();\n worldRenderer.pos(aa.maxX, aa.minY, aa.maxZ).color(r, g, b, a).endVertex();\n worldRenderer.pos(aa.maxX, aa.maxY, aa.minZ).color(r, g, b, a).endVertex();\n worldRenderer.pos(aa.maxX, aa.minY, aa.minZ).color(r, g, b, a).endVertex();\n tessellator.draw();\n worldRenderer.begin(7, DefaultVertexFormats.POSITION_COLOR);\n worldRenderer.pos(aa.minX, aa.minY, aa.maxZ).color(r, g, b, a).endVertex();\n worldRenderer.pos(aa.minX, aa.maxY, aa.maxZ).color(r, g, b, a).endVertex();\n worldRenderer.pos(aa.minX, aa.minY, aa.minZ).color(r, g, b, a).endVertex();\n worldRenderer.pos(aa.minX, aa.maxY, aa.minZ).color(r, g, b, a).endVertex();\n worldRenderer.pos(aa.maxX, aa.minY, aa.minZ).color(r, g, b, a).endVertex();\n worldRenderer.pos(aa.maxX, aa.maxY, aa.minZ).color(r, g, b, a).endVertex();\n worldRenderer.pos(aa.maxX, aa.minY, aa.maxZ).color(r, g, b, a).endVertex();\n worldRenderer.pos(aa.maxX, aa.maxY, aa.maxZ).color(r, g, b, a).endVertex();\n tessellator.draw();\n\n GlStateManager.translate(realX, realY, realZ);\n GlStateManager.disableBlend();\n GlStateManager.enableAlpha();\n GlStateManager.enableTexture2D();\n GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F);\n GlStateManager.popMatrix();\n }\n\n public static void draw3DLine(Vec3 pos1, Vec3 pos2, int width, Color color, float partialTicks) {\n Entity render = Minecraft.getMinecraft().getRenderViewEntity();\n WorldRenderer worldRenderer = Tessellator.getInstance().getWorldRenderer();\n\n double realX = render.lastTickPosX + (render.posX - render.lastTickPosX) * partialTicks;\n double realY = render.lastTickPosY + (render.posY - render.lastTickPosY) * partialTicks;\n double realZ = render.lastTickPosZ + (render.posZ - render.lastTickPosZ) * partialTicks;\n\n GlStateManager.pushMatrix();\n GlStateManager.translate(-realX, -realY, -realZ);\n GlStateManager.disableTexture2D();\n GlStateManager.enableBlend();\n GlStateManager.disableAlpha();\n GlStateManager.disableLighting();\n GlStateManager.tryBlendFuncSeparate(770, 771, 1, 0);\n GL11.glLineWidth(width);\n GlStateManager.color(color.getRed() / 255f, color.getGreen() / 255f, color.getBlue() / 255f, color.getAlpha() / 255f);\n worldRenderer.begin(GL11.GL_LINE_STRIP, DefaultVertexFormats.POSITION);\n\n worldRenderer.pos(pos1.xCoord, pos1.yCoord, pos1.zCoord).endVertex();\n worldRenderer.pos(pos2.xCoord, pos2.yCoord, pos2.zCoord).endVertex();\n Tessellator.getInstance().draw();\n\n GlStateManager.translate(realX, realY, realZ);\n GlStateManager.disableBlend();\n GlStateManager.enableAlpha();\n GlStateManager.enableLighting();\n GlStateManager.enableTexture2D();\n GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F);\n GlStateManager.popMatrix();\n }\n}" }, { "identifier": "Walker", "path": "src/main/java/com/github/codecnomad/codecclient/utils/Walker.java", "snippet": "public class Walker {\n List<BlockPos> wayPoints;\n Runnable callback;\n int currentPoint = 0;\n\n public void start() {\n MinecraftForge.EVENT_BUS.register(this);\n }\n\n public void stop() {\n currentPoint = 0;\n MinecraftForge.EVENT_BUS.unregister(this);\n KeyBinding.setKeyBindState(Client.mc.gameSettings.keyBindForward.getKeyCode(), false);\n KeyBinding.setKeyBindState(Client.mc.gameSettings.keyBindRight.getKeyCode(), false);\n KeyBinding.setKeyBindState(Client.mc.gameSettings.keyBindLeft.getKeyCode(), false);\n KeyBinding.setKeyBindState(Client.mc.gameSettings.keyBindBack.getKeyCode(), false);\n callback.run();\n }\n\n @SubscribeEvent\n public void clientTick(TickEvent.ClientTickEvent event) {\n if (currentPoint >= wayPoints.size()) {\n stop();\n return;\n }\n\n float yawDifference = MathHelper.wrapAngleTo180_float(Math.getYaw(wayPoints.get(currentPoint)) - MathHelper.wrapAngleTo180_float(Client.mc.thePlayer.rotationYaw));\n\n KeyBinding.setKeyBindState(Client.mc.gameSettings.keyBindForward.getKeyCode(), yawDifference > -67.5 && yawDifference <= 67.5);\n\n KeyBinding.setKeyBindState(Client.mc.gameSettings.keyBindLeft.getKeyCode(), yawDifference > -157.5 && yawDifference <= -22.5);\n\n KeyBinding.setKeyBindState(Client.mc.gameSettings.keyBindRight.getKeyCode(), yawDifference > 22.5 && yawDifference <= 157.5);\n\n KeyBinding.setKeyBindState(Client.mc.gameSettings.keyBindBack.getKeyCode(), (yawDifference > -180 && yawDifference <= -157.5) || (yawDifference > 157.5 && yawDifference <= 180));\n\n KeyBinding.setKeyBindState(Client.mc.gameSettings.keyBindJump.getKeyCode(), java.lang.Math.abs(Client.mc.thePlayer.motionX) + java.lang.Math.abs(Client.mc.thePlayer.motionZ) < Client.mc.thePlayer.capabilities.getWalkSpeed() / 3 && Client.mc.thePlayer.posY + 1 >= wayPoints.get(currentPoint).getY());\n\n if (Client.mc.thePlayer.getDistanceSq(wayPoints.get(currentPoint).add(0, 1, 0)) < 1 + java.lang.Math.abs(Client.mc.thePlayer.posY - wayPoints.get(currentPoint).add(0, 1, 0).getY())) {\n currentPoint++;\n }\n }\n\n public Walker(List<BlockPos> wayPoints, Runnable callback) {\n this.wayPoints = wayPoints;\n this.callback = callback;\n }\n}" } ]
import cc.polyfrost.oneconfig.utils.commands.annotations.Command; import cc.polyfrost.oneconfig.utils.commands.annotations.Main; import cc.polyfrost.oneconfig.utils.commands.annotations.SubCommand; import com.github.codecnomad.codecclient.Client; import com.github.codecnomad.codecclient.ui.Config; import com.github.codecnomad.codecclient.utils.Chat; import com.github.codecnomad.codecclient.utils.Pathfinding; import com.github.codecnomad.codecclient.utils.Render; import com.github.codecnomad.codecclient.utils.Walker; import net.minecraft.util.BlockPos; import net.minecraftforge.client.event.RenderWorldLastEvent; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import java.util.ArrayList; import java.util.Collection; import java.util.List;
9,471
package com.github.codecnomad.codecclient.command; @SuppressWarnings("unused") @Command(value = "codecclient", aliases = {"codec"}) public class MainCommand { List<BlockPos> waypoints = new ArrayList<>(); @Main public void mainCommand() { Client.guiConfig.openGui(); } Collection<BlockPos> path = new ArrayList<>(); public static Pathfinding pathfinding = new Pathfinding(); @SubCommand public void add(int x, int y, int z) { new Thread(() -> { MinecraftForge.EVENT_BUS.register(this); long start = System.currentTimeMillis(); path = pathfinding.createPath(Client.mc.thePlayer.getPosition().add(0, -1, 0), new BlockPos(x, y - 1, z)); Chat.sendMessage(System.currentTimeMillis() - start + " ms"); if (path != null) { waypoints.clear(); waypoints.addAll(path); Chat.sendMessage(String.format("Added waypoint: %d", waypoints.size())); } else { Chat.sendMessage("Failed to find path.."); } }).start(); } @SubscribeEvent public void renderWorld(RenderWorldLastEvent event) { if (path != null) { for (BlockPos pos : path) { Render.drawOutlinedFilledBoundingBox(pos.add(0, 1, 0), Config.VisualColor.toJavaColor(), event.partialTicks); } } } @SubCommand public void clear() { waypoints.clear(); } @SubCommand public void start() { Chat.sendMessage("STARTED!!");
package com.github.codecnomad.codecclient.command; @SuppressWarnings("unused") @Command(value = "codecclient", aliases = {"codec"}) public class MainCommand { List<BlockPos> waypoints = new ArrayList<>(); @Main public void mainCommand() { Client.guiConfig.openGui(); } Collection<BlockPos> path = new ArrayList<>(); public static Pathfinding pathfinding = new Pathfinding(); @SubCommand public void add(int x, int y, int z) { new Thread(() -> { MinecraftForge.EVENT_BUS.register(this); long start = System.currentTimeMillis(); path = pathfinding.createPath(Client.mc.thePlayer.getPosition().add(0, -1, 0), new BlockPos(x, y - 1, z)); Chat.sendMessage(System.currentTimeMillis() - start + " ms"); if (path != null) { waypoints.clear(); waypoints.addAll(path); Chat.sendMessage(String.format("Added waypoint: %d", waypoints.size())); } else { Chat.sendMessage("Failed to find path.."); } }).start(); } @SubscribeEvent public void renderWorld(RenderWorldLastEvent event) { if (path != null) { for (BlockPos pos : path) { Render.drawOutlinedFilledBoundingBox(pos.add(0, 1, 0), Config.VisualColor.toJavaColor(), event.partialTicks); } } } @SubCommand public void clear() { waypoints.clear(); } @SubCommand public void start() { Chat.sendMessage("STARTED!!");
new Walker(waypoints, () -> Chat.sendMessage("Walked it!!")).start();
5
2023-11-16 10:12:20+00:00
12k
JohnTWD/meteor-rejects-vanillacpvp
src/main/java/anticope/rejects/modules/OreSim.java
[ { "identifier": "MeteorRejectsAddon", "path": "src/main/java/anticope/rejects/MeteorRejectsAddon.java", "snippet": "public class MeteorRejectsAddon extends MeteorAddon {\n public static final Logger LOG = LoggerFactory.getLogger(\"Rejects\");\n public static final Category CATEGORY = new Category(\"Rejects\", Items.BARRIER.getDefaultStack());\n public static final HudGroup HUD_GROUP = new HudGroup(\"Rejects\");\n\n @Override\n public void onInitialize() {\n LOG.info(\"Initializing Meteor Rejects Addon\");\n\n // Modules\n Modules modules = Modules.get();\n\n modules.add(new BetterAimbot());\n modules.add(new NewerNewChunks());\n modules.add(new BaseFinderNew());\n modules.add(new Shield());\n modules.add(new TestModule());\n modules.add(((new HitboxDesync())));\n modules.add(new Announcer());\n modules.add(new PacketLogger());\n modules.add(new ManualCrystal());\n modules.add(new TweakedAutoTool());\n modules.add(new MacroAnchorAuto());\n modules.add(new AutoMend());\n modules.add(new BowBomb());\n modules.add(new AutoCityPlus());\n modules.add(new PistonAura());\n modules.add(new CevBreaker());\n\n modules.add(new AimAssist());\n modules.add(new AntiBot());\n modules.add(new AntiCrash());\n modules.add(new AntiSpawnpoint());\n modules.add(new AntiVanish());\n modules.add(new ArrowDmg());\n modules.add(new AutoBedTrap());\n modules.add(new AutoCraft());\n modules.add(new AutoExtinguish());\n modules.add(new AutoFarm());\n modules.add(new AutoGrind());\n modules.add(new AutoLogin());\n modules.add(new AutoPot());\n modules.add(new AutoSoup());\n modules.add(new AutoTNT());\n modules.add(new AutoWither());\n modules.add(new BoatGlitch());\n modules.add(new BlockIn());\n modules.add(new BoatPhase());\n modules.add(new Boost());\n modules.add(new BungeeCordSpoof());\n modules.add(new ChatBot());\n modules.add(new ChestAura());\n modules.add(new ChorusExploit());\n modules.add(new ColorSigns());\n modules.add(new Confuse());\n modules.add(new CoordLogger());\n modules.add(new CustomPackets());\n modules.add(new ExtraElytra());\n modules.add(new FullFlight());\n modules.add(new GamemodeNotifier());\n modules.add(new GhostMode());\n modules.add(new Glide());\n modules.add(new InstaMine());\n modules.add(new ItemGenerator());\n modules.add(new InteractionMenu());\n modules.add(new Jetpack());\n modules.add(new KnockbackPlus());\n modules.add(new Lavacast());\n modules.add(new MossBot());\n modules.add(new NewChunks());\n modules.add(new NoJumpDelay());\n modules.add(new ObsidianFarm());\n modules.add(new OreSim());\n modules.add(new PacketFly());\n modules.add(new Painter());\n modules.add(new Rendering());\n modules.add(new RoboWalk());\n modules.add(new ShieldBypass());\n modules.add(new SilentDisconnect());\n modules.add(new SkeletonESP());\n modules.add(new SoundLocator());\n modules.add(new TreeAura());\n modules.add(new VehicleOneHit());\n\n // Commands\n Commands.add(new CenterCommand());\n Commands.add(new ClearChatCommand());\n Commands.add(new GhostCommand());\n Commands.add(new GiveCommand());\n Commands.add(new HeadsCommand());\n Commands.add(new KickCommand());\n Commands.add(new LocateCommand());\n Commands.add(new PanicCommand());\n Commands.add(new ReconnectCommand());\n Commands.add(new ServerCommand());\n Commands.add(new SaveSkinCommand());\n Commands.add(new SeedCommand());\n Commands.add(new SetBlockCommand());\n Commands.add(new SetVelocityCommand());\n Commands.add(new TeleportCommand());\n Commands.add(new TerrainExport());\n Commands.add(new EntityDesyncCommand());\n Commands.add(new BaseFinderNewCommands());\n Commands.add(new NewChunkCounter());\n\n // HUD\n Hud hud = Systems.get(Hud.class);\n hud.register(RadarHud.INFO);\n\n // Themes\n GuiThemes.add(new MeteorRoundedGuiTheme());\n }\n\n @Override\n public void onRegisterCategories() {\n Modules.registerCategory(CATEGORY);\n }\n\n @Override\n public String getWebsite() {\n return \"https://github.com/JohnTWD/meteor-rejects-vanillacpvp\";\n }\n\n @Override\n public GithubRepo getRepo() {\n return new GithubRepo(\"JohnTWD\", \"meteor-rejects-vanilla-cpvp\");\n }\n\n @Override\n public String getCommit() {\n String commit = FabricLoader\n .getInstance()\n .getModContainer(\"meteor-rejects\")\n .get().getMetadata()\n .getCustomValue(\"github:sha\")\n .getAsString();\n LOG.info(String.format(\"Rejects version: %s\", commit));\n return commit.isEmpty() ? null : commit.trim();\n }\n\n public String getPackage() {\n return \"anticope.rejects\";\n }\n}" }, { "identifier": "PlayerRespawnEvent", "path": "src/main/java/anticope/rejects/events/PlayerRespawnEvent.java", "snippet": "public class PlayerRespawnEvent {\n private static final PlayerRespawnEvent INSTANCE = new PlayerRespawnEvent();\n\n public static PlayerRespawnEvent get() {\n return INSTANCE;\n }\n}" }, { "identifier": "SeedChangedEvent", "path": "src/main/java/anticope/rejects/events/SeedChangedEvent.java", "snippet": "public class SeedChangedEvent {\n private static final SeedChangedEvent INSTANCE = new SeedChangedEvent();\n\n public Long seed;\n\n public static SeedChangedEvent get(long seed) {\n INSTANCE.seed = seed;\n return INSTANCE;\n }\n}" }, { "identifier": "Ore", "path": "src/main/java/anticope/rejects/utils/Ore.java", "snippet": "public class Ore {\n\n private static final Setting<Boolean> coal = new BoolSetting.Builder().name(\"Coal\").build();\n private static final Setting<Boolean> iron = new BoolSetting.Builder().name(\"Iron\").build();\n private static final Setting<Boolean> gold = new BoolSetting.Builder().name(\"Gold\").build();\n private static final Setting<Boolean> redstone = new BoolSetting.Builder().name(\"Redstone\").build();\n private static final Setting<Boolean> diamond = new BoolSetting.Builder().name(\"Diamond\").build();\n private static final Setting<Boolean> lapis = new BoolSetting.Builder().name(\"Lapis\").build();\n private static final Setting<Boolean> copper = new BoolSetting.Builder().name(\"Kappa\").build();\n private static final Setting<Boolean> emerald = new BoolSetting.Builder().name(\"Emerald\").build();\n private static final Setting<Boolean> quartz = new BoolSetting.Builder().name(\"Quartz\").build();\n private static final Setting<Boolean> debris = new BoolSetting.Builder().name(\"Ancient Debris\").build();\n public static final List<Setting<Boolean>> oreSettings = new ArrayList<>(Arrays.asList(coal, iron, gold, redstone, diamond, lapis, copper, emerald, quartz, debris));\n public final Type type;\n public final Identifier dimension;\n public final Map<String, Integer> index;\n public final boolean depthAverage;\n public final Generator generator;\n public final int size;\n public final Setting<Boolean> enabled;\n public final Color color;\n public int step;\n public IntProvider count;\n public int minY;\n public int maxY;\n public float discardOnAir;\n public float chance;\n\n Ore(Type type, Identifier dimension, Map<String, Integer> index, int step, IntProvider count, float chance, boolean depthAverage, int minY, int maxY, Generator generator, int size, float discardOnAir, Setting<Boolean> enabled, Color color) {\n this.type = type;\n this.dimension = dimension;\n this.index = index;\n this.step = step;\n this.count = count;\n this.depthAverage = depthAverage;\n this.minY = minY;\n this.maxY = maxY;\n this.generator = generator;\n this.size = size;\n this.enabled = enabled;\n this.color = color;\n this.discardOnAir = discardOnAir;\n this.chance = chance;\n }\n\n Ore(Type type, Identifier dimension, int index, int step, IntProvider count, float chance, boolean depthAverage, int minY, int maxY, Generator generator, int size, float discardOnAir, Setting<Boolean> enabled, Color color) {\n this(type, dimension, indexToMap(index), step, count, chance, depthAverage, minY, maxY, generator, size, discardOnAir, enabled, color);\n }\n\n Ore(Type type, Identifier dimension, int index, int step, IntProvider count, boolean depthAverage, int minY, int maxY,\n @SuppressWarnings(\"SameParameterValue\") Generator generator, int size, Setting<Boolean> enabled, Color color) {\n this(type, dimension, indexToMap(index), step, count, 1F, depthAverage, minY, maxY, generator, size, 0F, enabled, color);\n }\n\n Ore(Type type, Identifier dimension, Map<String, Integer> index, int step, IntProvider count, boolean depthAverage, int minY, int maxY,\n @SuppressWarnings(\"SameParameterValue\") Generator generator, int size, Setting<Boolean> enabled, Color color) {\n this(type, dimension, index, step, count, 1F, depthAverage, minY, maxY, generator, size, 0F, enabled, color);\n }\n\n private static HashMap<String, Integer> indexToMap(int index) {\n HashMap<String, Integer> map = new HashMap<>();\n map.put(\"default\", index);\n return map;\n }\n \n private static List<Ore> V1_19() {\n return V1_18();\n }\n\n private static List<Ore> V1_18() {\n List<Ore> ores = new ArrayList<>();\n\n HashMap<String, Integer> extraGoldIndex = new HashMap<>();\n extraGoldIndex.put(\"default\", -1);\n String[] extraGoldBiomes = new String[]{\"badlands\", \"eroded_badlands\", \"wooded_badlands\"};\n for (String extraGoldBiome : extraGoldBiomes) {\n extraGoldIndex.put(extraGoldBiome, 27);\n }\n\n HashMap<String, Integer> emeraldIndex = new HashMap<>();\n emeraldIndex.put(\"default\", -1);\n String[] emeraldBiomes = new String[]{\"windswept_hills\", \"meadow\", \"grove\", \"jagged_peaks\", \"snowy_slopes\", \"frozen_peaks\", \"stony_peaks\"};\n for (String emeraldBiome : emeraldBiomes) {\n emeraldIndex.put(emeraldBiome, 27);\n }\n\n ores.add(new Ore(Type.COAL, DimensionTypes.OVERWORLD_ID, 9, 6, ConstantIntProvider.create(30), false, 136, 320, Generator.DEFAULT, 17, coal, new Color(47, 44, 54)));\n ores.add(new Ore(Type.COAL, DimensionTypes.OVERWORLD_ID, 10, 6, ConstantIntProvider.create(20), 1F, true, 97, 97, Generator.DEFAULT, 17, 0.5F, coal, new Color(47, 44, 54)));\n ores.add(new Ore(Type.IRON, DimensionTypes.OVERWORLD_ID, 11, 6, ConstantIntProvider.create(90), true, 233, 153, Generator.DEFAULT, 9, iron, new Color(236, 173, 119)));\n ores.add(new Ore(Type.IRON, DimensionTypes.OVERWORLD_ID, 12, 6, ConstantIntProvider.create(10), true, 17, 41, Generator.DEFAULT, 9, iron, new Color(236, 173, 119)));\n ores.add(new Ore(Type.IRON, DimensionTypes.OVERWORLD_ID, 13, 6, ConstantIntProvider.create(10), false, -64, 73, Generator.DEFAULT, 4, iron, new Color(236, 173, 119)));\n ores.add(new Ore(Type.GOLD_EXTRA, DimensionTypes.OVERWORLD_ID, extraGoldIndex, 6, ConstantIntProvider.create(50), false, 32, 257, Generator.DEFAULT, 9, gold, new Color(247, 229, 30)));\n ores.add(new Ore(Type.GOLD, DimensionTypes.OVERWORLD_ID, 14, 6, ConstantIntProvider.create(4), 1F, true, -15, 49, Generator.DEFAULT, 9, 0.5F, gold, new Color(247, 229, 30)));\n ores.add(new Ore(Type.GOLD, DimensionTypes.OVERWORLD_ID, 15, 6, UniformIntProvider.create(0, 1), 1F, false, -64, -47, Generator.DEFAULT, 9, 0.5F, gold, new Color(247, 229, 30)));\n ores.add(new Ore(Type.REDSTONE, DimensionTypes.OVERWORLD_ID, 16, 6, ConstantIntProvider.create(4), false, -64, 16, Generator.DEFAULT, 8, redstone, new Color(245, 7, 23)));\n ores.add(new Ore(Type.REDSTONE, DimensionTypes.OVERWORLD_ID, 17, 6, ConstantIntProvider.create(8), true, -63, 33, Generator.DEFAULT, 8, redstone, new Color(245, 7, 23)));\n ores.add(new Ore(Type.DIAMOND, DimensionTypes.OVERWORLD_ID, 18, 6, ConstantIntProvider.create(7), 1F, true, -63, 81, Generator.DEFAULT, 4, 0.5F, diamond, new Color(33, 244, 255)));\n ores.add(new Ore(Type.DIAMOND, DimensionTypes.OVERWORLD_ID, 19, 6, ConstantIntProvider.create(1), (1F / 9F), true, -63, 81, Generator.DEFAULT, 12, 0.7F, diamond, new Color(33, 244, 255)));\n ores.add(new Ore(Type.DIAMOND, DimensionTypes.OVERWORLD_ID, 20, 6, ConstantIntProvider.create(4), 1F, true, -63, 81, Generator.DEFAULT, 8, 1F, diamond, new Color(33, 244, 255)));\n ores.add(new Ore(Type.LAPIS, DimensionTypes.OVERWORLD_ID, 21, 6, ConstantIntProvider.create(2), true, 1, 33, Generator.DEFAULT, 7, lapis, new Color(8, 26, 189)));\n ores.add(new Ore(Type.LAPIS, DimensionTypes.OVERWORLD_ID, 22, 6, ConstantIntProvider.create(4), 1F, false, -64, 65, Generator.DEFAULT, 7, 1F, lapis, new Color(8, 26, 189)));\n ores.add(new Ore(Type.EMERALD, DimensionTypes.OVERWORLD_ID, emeraldIndex, 6, ConstantIntProvider.create(100), true, 233, 249, Generator.DEFAULT, 3, emerald, new Color(27, 209, 45)));\n //This only generates near dripstone caves. I'll need propper biome detection to get this right\n //ores.add(new Ore(Type.COPPER, \"overworld\", 23, 6, ConstantIntProvider.create(16), true, 49, 65, Generator.DEFAULT, 20, copper, new Color(239, 151, 0)));\n ores.add(new Ore(Type.COPPER, DimensionTypes.OVERWORLD_ID, 24, 6, ConstantIntProvider.create(16), true, 49, 65, Generator.DEFAULT, 10, copper, new Color(239, 151, 0)));\n ores.add(new Ore(Type.GOLD_NETHER, DimensionTypes.THE_NETHER_ID, Map.of(\"default\", 19, \"basalt_deltas\", -1), 7, ConstantIntProvider.create(10), false, 10, 118, Generator.DEFAULT, 10, gold, new Color(247, 229, 30)));\n ores.add(new Ore(Type.QUARTZ, DimensionTypes.THE_NETHER_ID, Map.of(\"default\", 20, \"basalt_deltas\", -1), 7, ConstantIntProvider.create(16), false, 10, 118, Generator.DEFAULT, 14, quartz, new Color(205, 205, 205)));\n ores.add(new Ore(Type.GOLD_NETHER, DimensionTypes.THE_NETHER_ID, Map.of(\"default\", -1, \"basalt_deltas\", 13), 7, ConstantIntProvider.create(20), false, 10, 118, Generator.DEFAULT, 10, gold, new Color(247, 229, 30)));\n ores.add(new Ore(Type.QUARTZ, DimensionTypes.THE_NETHER_ID, Map.of(\"default\", -1, \"basalt_deltas\", 14), 7, ConstantIntProvider.create(32), false, 10, 118, Generator.DEFAULT, 14, quartz, new Color(205, 205, 205)));\n ores.add(new Ore(Type.LDEBRIS, DimensionTypes.THE_NETHER_ID, 21, 7, ConstantIntProvider.create(1), true, 17, 9, Generator.NO_SURFACE, 3, debris, new Color(209, 27, 245)));\n ores.add(new Ore(Type.SDEBRIS, DimensionTypes.THE_NETHER_ID, 22, 7, ConstantIntProvider.create(1), false, 8, 120, Generator.NO_SURFACE, 2, debris, new Color(209, 27, 245)));\n return ores;\n }\n\n private static List<Ore> baseConfig() {\n List<Ore> ores = new ArrayList<>();\n HashMap<String, Integer> emeraldIndexes = new HashMap<>();\n emeraldIndexes.put(\"default\", -1);\n String[] emeraldBiomes = new String[]{\"mountains\", \"mountain_edge\", \"wooded_mountains\", \"gravelly_mountains\", \"modified_gravelly_mountains\", \"paper\"};\n for (String emeraldBiome : emeraldBiomes) {\n emeraldIndexes.put(emeraldBiome, 17);\n }\n HashMap<String, Integer> LDebrisIndexes = new HashMap<>();\n LDebrisIndexes.put(\"default\", 15);\n LDebrisIndexes.put(\"crimson_forest\", 12);\n LDebrisIndexes.put(\"warped_forest\", 13);\n HashMap<String, Integer> SDebrisIndexes = new HashMap<>();\n LDebrisIndexes.forEach((biome, index) -> SDebrisIndexes.put(biome, index + 1));\n HashMap<String, Integer> extraGoldIndexes = new HashMap<>();\n extraGoldIndexes.put(\"default\", -1);\n String[] extraGoldBiomes = new String[]{\"badlands\", \"badlands_plateau\", \"modified_badlands_plateau\", \"wooded_badlands_plateau\", \"modified_wooded_badlands_plateau\", \"eroded_badlands\", \"paper\"};\n for (String extraGoldBiome : extraGoldBiomes) {\n extraGoldIndexes.put(extraGoldBiome, 14);\n }\n ores.add(new Ore(Type.COAL, DimensionTypes.OVERWORLD_ID, 7, 6, ConstantIntProvider.create(20), false, 0, 128, Generator.DEFAULT, 20, coal, new Color(47, 44, 54)));\n ores.add(new Ore(Type.IRON,DimensionTypes.OVERWORLD_ID, 8, 6, ConstantIntProvider.create(20), false, 0, 64, Generator.DEFAULT, 9, iron, new Color(236, 173, 119)));\n ores.add(new Ore(Type.GOLD, DimensionTypes.OVERWORLD_ID, 9, 6, ConstantIntProvider.create(2), false, 0, 32, Generator.DEFAULT, 9, gold, new Color(247, 229, 30)));\n ores.add(new Ore(Type.REDSTONE, DimensionTypes.OVERWORLD_ID, 10, 6, ConstantIntProvider.create(8), false, 0, 16, Generator.DEFAULT, 8, redstone, new Color(245, 7, 23)));\n ores.add(new Ore(Type.DIAMOND, DimensionTypes.OVERWORLD_ID, 11, 6, ConstantIntProvider.create(1), false, 0, 16, Generator.DEFAULT, 8, diamond, new Color(33, 244, 255)));\n ores.add(new Ore(Type.LAPIS, DimensionTypes.OVERWORLD_ID, 12, 6, ConstantIntProvider.create(1), true, 16, 16, Generator.DEFAULT, 7, lapis, new Color(8, 26, 189)));\n ores.add(new Ore(Type.COPPER, DimensionTypes.OVERWORLD_ID, 13, 6, ConstantIntProvider.create(6), true, 49, 49, Generator.DEFAULT, 10, copper, new Color(239, 151, 0)));\n ores.add(new Ore(Type.GOLD_EXTRA, DimensionTypes.OVERWORLD_ID, extraGoldIndexes, 6, ConstantIntProvider.create(20), false, 32, 80, Generator.DEFAULT, 9, gold, new Color(247, 229, 30)));\n ores.add(new Ore(Type.EMERALD, DimensionTypes.OVERWORLD_ID, emeraldIndexes, 6, UniformIntProvider.create(6, 8), false, 4, 32, Generator.EMERALD, 1, emerald, new Color(27, 209, 45)));\n ores.add(new Ore(Type.GOLD_NETHER, DimensionTypes.THE_NETHER_ID, Map.of(\"default\", 13, \"basalt_deltas\", -1), 7, ConstantIntProvider.create(10), false, 10, 118, Generator.DEFAULT, 10, gold, new Color(247, 229, 30)));\n ores.add(new Ore(Type.QUARTZ, DimensionTypes.THE_NETHER_ID, Map.of(\"default\", 14, \"basalt_deltas\", -1), 7, ConstantIntProvider.create(16), false, 10, 118, Generator.DEFAULT, 14, quartz, new Color(205, 205, 205)));\n ores.add(new Ore(Type.GOLD_NETHER, DimensionTypes.THE_NETHER_ID, Map.of(\"default\", -1, \"basalt_deltas\", 13), 7, ConstantIntProvider.create(20), false, 10, 118, Generator.DEFAULT, 10, gold, new Color(247, 229, 30)));\n ores.add(new Ore(Type.QUARTZ, DimensionTypes.THE_NETHER_ID, Map.of(\"default\", -1, \"basalt_deltas\", 14), 7, ConstantIntProvider.create(32), false, 10, 118, Generator.DEFAULT, 14, quartz, new Color(205, 205, 205)));\n ores.add(new Ore(Type.LDEBRIS, DimensionTypes.THE_NETHER_ID, LDebrisIndexes, 7, ConstantIntProvider.create(1), true, 17, 9, Generator.NO_SURFACE, 3, debris, new Color(209, 27, 245)));\n ores.add(new Ore(Type.SDEBRIS, DimensionTypes.THE_NETHER_ID, SDebrisIndexes, 7, ConstantIntProvider.create(1), false, 8, 120, Generator.NO_SURFACE, 2, debris, new Color(209, 27, 245)));\n return ores;\n }\n\n private static List<Ore> V1_17_1() {\n return baseConfig();\n }\n\n private static List<Ore> V1_17() {\n List<Ore> ores = baseConfig();\n for (Ore ore : ores) {\n if (ore.type.equals(Type.DIAMOND)) {\n ore.maxY = 17;\n }\n if (ore.type.equals(Type.EMERALD)) {\n ore.count = UniformIntProvider.create(6, 24);\n }\n }\n return ores;\n }\n\n private static List<Ore> V1_16() {\n List<Ore> ores = baseConfig();\n ores.removeIf(ore -> ore.type.equals(Type.COPPER));\n for (Ore ore : ores) {\n if (ore.type == Type.EMERALD || ore.type == Type.GOLD_EXTRA) {\n ore.index.keySet().forEach(key -> ore.index.put(key, ore.index.get(key) - 3));\n } else if (ore.dimension == DimensionTypes.OVERWORLD_ID) {\n ore.index.keySet().forEach(key -> ore.index.put(key, ore.index.get(key) - 2));\n } else if (ore.type == Type.LDEBRIS) {\n ore.minY = 16;\n ore.maxY = 8;\n }\n }\n return ores;\n }\n\n private static List<Ore> V1_15() {\n List<Ore> ores = V1_16();\n ores.removeIf(ore -> ore.type == Type.SDEBRIS || ore.type == Type.LDEBRIS || ore.type == Type.GOLD_NETHER);\n for (Ore ore : ores) {\n ore.step -= 2;\n }\n return ores;\n }\n\n public static List<Ore> getConfig(MCVersion version) {\n if (version.isNewerOrEqualTo(MCVersion.v1_19)) {\n return V1_19();\n } else if (version.isNewerOrEqualTo(MCVersion.v1_18)) {\n return V1_18();\n } else if (version.isNewerOrEqualTo(MCVersion.v1_17_1)) {\n return V1_17_1();\n } else if (version.isNewerOrEqualTo(MCVersion.v1_17)) {\n return V1_17();\n } else if (version.isNewerOrEqualTo(MCVersion.v1_16)) {\n return V1_16();\n } else if (version.isNewerOrEqualTo(MCVersion.v1_14)) {\n return V1_15();\n } else {\n return null;\n }\n }\n\n public enum Type {\n DIAMOND, REDSTONE, GOLD, IRON, COAL, EMERALD, SDEBRIS, LDEBRIS, LAPIS, COPPER, QUARTZ, GOLD_NETHER, GOLD_EXTRA\n }\n\n public enum Generator {\n DEFAULT, EMERALD, NO_SURFACE\n }\n}" }, { "identifier": "Seed", "path": "src/main/java/anticope/rejects/utils/seeds/Seed.java", "snippet": "public class Seed {\n public final Long seed;\n public final MCVersion version;\n\n public Seed(Long seed, MCVersion version) {\n this.seed = seed;\n if (version == null)\n version = MCVersion.latest();\n this.version = version;\n }\n\n public NbtCompound toTag() {\n NbtCompound tag = new NbtCompound();\n tag.put(\"seed\", NbtLong.of(seed));\n tag.put(\"version\", NbtString.of(version.name));\n return tag;\n }\n\n public static Seed fromTag(NbtCompound tag) {\n return new Seed(\n tag.getLong(\"seed\"),\n MCVersion.fromString(tag.getString(\"version\"))\n );\n }\n\n public Text toText() {\n MutableText text = Text.literal(String.format(\"[%s%s%s] (%s)\",\n Formatting.GREEN,\n seed.toString(),\n Formatting.WHITE,\n version.toString()\n ));\n text.setStyle(text.getStyle()\n .withClickEvent(new ClickEvent(\n ClickEvent.Action.COPY_TO_CLIPBOARD,\n seed.toString()\n ))\n .withHoverEvent(new HoverEvent(\n HoverEvent.Action.SHOW_TEXT,\n Text.literal(\"Copy to clipboard\")\n ))\n );\n return text;\n }\n}" }, { "identifier": "Seeds", "path": "src/main/java/anticope/rejects/utils/seeds/Seeds.java", "snippet": "public class Seeds extends System<Seeds> {\n private static final Seeds INSTANCE = new Seeds();\n\n public HashMap<String, Seed> seeds = new HashMap<>();\n\n public Seeds() {\n super(\"seeds\");\n init();\n load(MeteorClient.FOLDER);\n }\n\n public static Seeds get() {\n return INSTANCE;\n }\n\n public Seed getSeed() {\n if (mc.isIntegratedServerRunning() && mc.getServer() != null) {\n MCVersion version = MCVersion.fromString(mc.getServer().getVersion());\n if (version == null)\n version = MCVersion.latest();\n return new Seed(mc.getServer().getOverworld().getSeed(), version);\n }\n\n return seeds.get(Utils.getWorldName());\n }\n\n public void setSeed(String seed, MCVersion version) {\n if (mc.isIntegratedServerRunning()) return;\n\n long numSeed = toSeed(seed);\n seeds.put(Utils.getWorldName(), new Seed(numSeed, version));\n MeteorClient.EVENT_BUS.post(SeedChangedEvent.get(numSeed));\n }\n\n public void setSeed(String seed) {\n if (mc.isIntegratedServerRunning()) return;\n\n ServerInfo server = mc.getCurrentServerEntry();\n MCVersion ver = null;\n if (server != null)\n ver = MCVersion.fromString(server.version.getString());\n if (ver == null) {\n String targetVer = \"unknown\";\n if (server != null) targetVer = server.version.getString();\n sendInvalidVersionWarning(seed, targetVer);\n ver = MCVersion.latest();\n }\n setSeed(seed, ver);\n }\n\n @Override\n public NbtCompound toTag() {\n NbtCompound tag = new NbtCompound();\n seeds.forEach((key, seed) -> {\n if (seed == null) return;\n tag.put(key, seed.toTag());\n });\n return tag;\n }\n\n @Override\n public Seeds fromTag(NbtCompound tag) {\n tag.getKeys().forEach(key -> {\n seeds.put(key, Seed.fromTag(tag.getCompound(key)));\n });\n return this;\n }\n\n // https://minecraft.fandom.com/wiki/Seed_(level_generation)#Java_Edition\n private static long toSeed(String inSeed) {\n try {\n return Long.parseLong(inSeed);\n } catch (NumberFormatException e) {\n return inSeed.strip().hashCode();\n }\n }\n\n private static void sendInvalidVersionWarning(String seed, String targetVer) {\n MutableText msg = Text.literal(String.format(\"Couldn't resolve minecraft version \\\"%s\\\". Using %s instead. If you wish to change the version run: \", targetVer, MCVersion.latest().name));\n String cmd = String.format(\"%sseed %s \", Config.get().prefix, seed);\n MutableText cmdText = Text.literal(cmd+\"<version>\");\n cmdText.setStyle(cmdText.getStyle()\n .withUnderline(true)\n .withClickEvent(new ClickEvent(ClickEvent.Action.SUGGEST_COMMAND, cmd))\n .withHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, Text.literal(\"run command\")))\n );\n msg.append(cmdText);\n msg.setStyle(msg.getStyle()\n .withColor(Formatting.YELLOW)\n );\n ChatUtils.sendMsg(\"Seed\", msg);\n }\n}" } ]
import anticope.rejects.MeteorRejectsAddon; import anticope.rejects.events.PlayerRespawnEvent; import anticope.rejects.events.SeedChangedEvent; import anticope.rejects.utils.Ore; import anticope.rejects.utils.seeds.Seed; import anticope.rejects.utils.seeds.Seeds; import baritone.api.BaritoneAPI; import com.seedfinding.mccore.version.MCVersion; import meteordevelopment.meteorclient.events.render.Render3DEvent; import meteordevelopment.meteorclient.events.world.ChunkDataEvent; import meteordevelopment.meteorclient.events.world.TickEvent; import meteordevelopment.meteorclient.settings.*; import meteordevelopment.meteorclient.systems.modules.Module; import meteordevelopment.orbit.EventHandler; import net.minecraft.client.world.ClientWorld; import net.minecraft.registry.RegistryKeys; import net.minecraft.util.Identifier; import net.minecraft.util.math.*; import net.minecraft.util.math.random.ChunkRandom; import net.minecraft.world.Heightmap; import net.minecraft.world.chunk.ChunkStatus; import java.util.*;
8,864
} public boolean baritone() { return isActive() && baritone.get(); } @EventHandler private void onRender(Render3DEvent event) { if (mc.player == null || oreConfig == null) { return; } if (Seeds.get().getSeed() != null) { int chunkX = mc.player.getChunkPos().x; int chunkZ = mc.player.getChunkPos().z; int rangeVal = horizontalRadius.get(); for (int range = 0; range <= rangeVal; range++) { for (int x = -range + chunkX; x <= range + chunkX; x++) { renderChunk(x, chunkZ + range - rangeVal, event); } for (int x = (-range) + 1 + chunkX; x < range + chunkX; x++) { renderChunk(x, chunkZ - range + rangeVal + 1, event); } } } } private void renderChunk(int x, int z, Render3DEvent event) { long chunkKey = (long) x + ((long) z << 32); if (chunkRenderers.containsKey(chunkKey)) { for (Ore ore : oreConfig) { if (ore.enabled.get()) { if (!chunkRenderers.get(chunkKey).containsKey(ore)) { continue; } for (Vec3d pos : chunkRenderers.get(chunkKey).get(ore)) { event.renderer.boxLines(pos.x, pos.y, pos.z, pos.x + 1, pos.y + 1, pos.z + 1, ore.color, 0); } } } } } @EventHandler private void onTick(TickEvent.Pre event) { if (mc.player == null || mc.world == null || oreConfig == null) return; if (airCheck.get() == AirCheck.RECHECK) { long chunkX = mc.player.getChunkPos().x; long chunkZ = mc.player.getChunkPos().z; ClientWorld world = mc.world; int renderdistance = mc.options.getViewDistance().getValue(); //maybe another config option? But its already crowded int chunkCounter = 5; loop: while (true) { for (long offsetX = prevOffset.x; offsetX <= renderdistance; offsetX++) { for (long offsetZ = prevOffset.z; offsetZ <= renderdistance; offsetZ++) { prevOffset = new ChunkPos((int) offsetX, (int) offsetZ); if (chunkCounter <= 0) { break loop; } long chunkKey = (chunkX + offsetX) + ((chunkZ + offsetZ) << 32); if (chunkRenderers.containsKey(chunkKey)) { chunkRenderers.get(chunkKey).values().forEach(oreSet -> oreSet.removeIf(ore -> !world.getBlockState(new BlockPos((int) ore.x, (int) ore.y, (int) ore.z)).isOpaque())); } chunkCounter--; } prevOffset = new ChunkPos((int) offsetX, -renderdistance); } prevOffset = new ChunkPos(-renderdistance, -renderdistance); } } if (baritone.get() && BaritoneAPI.getProvider().getPrimaryBaritone().getMineProcess().isActive()) { oreGoals.clear(); var chunkPos = mc.player.getChunkPos(); int rangeVal = 4; for (int range = 0; range <= rangeVal; ++range) { for (int x = -range + chunkPos.x; x <= range + chunkPos.x; ++x) { oreGoals.addAll(addToBaritone(x, chunkPos.z + range - rangeVal)); } for (int x = -range + 1 + chunkPos.x; x < range + chunkPos.x; ++x) { oreGoals.addAll(this.addToBaritone(x, chunkPos.z - range + rangeVal + 1)); } } } } private ArrayList<BlockPos> addToBaritone(int chunkX, int chunkZ) { ArrayList<BlockPos> baritoneGoals = new ArrayList<>(); long chunkKey = (long) chunkX + ((long) chunkZ << 32); if (!this.chunkRenderers.containsKey(chunkKey)) { return baritoneGoals; } else { this.oreConfig.stream().filter((config) -> config.enabled.get()).forEach((ore) -> chunkRenderers .get(chunkKey) .getOrDefault(ore, new HashSet<>()) .stream() .map(BlockPos::ofFloored) .forEach(baritoneGoals::add)); return baritoneGoals; } } @Override public void onActivate() { if (Seeds.get().getSeed() == null) { error("No seed found. To set a seed do .seed <seed>"); this.toggle(); } reload(); } @EventHandler
package anticope.rejects.modules; public class OreSim extends Module { private final HashMap<Long, HashMap<Ore, HashSet<Vec3d>>> chunkRenderers = new HashMap<>(); private Seed worldSeed = null; private List<Ore> oreConfig; public ArrayList<BlockPos> oreGoals = new ArrayList<>(); private ChunkPos prevOffset = new ChunkPos(0, 0); public enum AirCheck { ON_LOAD, RECHECK, OFF } private final SettingGroup sgGeneral = settings.getDefaultGroup(); private final SettingGroup sgOres = settings.createGroup("Ores"); private final Setting<Integer> horizontalRadius = sgGeneral.add(new IntSetting.Builder() .name("chunk-range") .description("Taxi cap distance of chunks being shown.") .defaultValue(5) .min(1) .sliderMax(10) .build() ); private final Setting<AirCheck> airCheck = sgGeneral.add(new EnumSetting.Builder<AirCheck>() .name("air-check-mode") .description("Checks if there is air at a calculated ore pos.") .defaultValue(AirCheck.RECHECK) .build() ); private final Setting<Boolean> baritone = sgGeneral.add(new BoolSetting.Builder() .name("baritone") .description("Set baritone ore positions to the simulated ones.") .defaultValue(false) .build() ); public OreSim() { super(MeteorRejectsAddon.CATEGORY, "ore-sim", "Xray on crack."); Ore.oreSettings.forEach(sgOres::add); } public boolean baritone() { return isActive() && baritone.get(); } @EventHandler private void onRender(Render3DEvent event) { if (mc.player == null || oreConfig == null) { return; } if (Seeds.get().getSeed() != null) { int chunkX = mc.player.getChunkPos().x; int chunkZ = mc.player.getChunkPos().z; int rangeVal = horizontalRadius.get(); for (int range = 0; range <= rangeVal; range++) { for (int x = -range + chunkX; x <= range + chunkX; x++) { renderChunk(x, chunkZ + range - rangeVal, event); } for (int x = (-range) + 1 + chunkX; x < range + chunkX; x++) { renderChunk(x, chunkZ - range + rangeVal + 1, event); } } } } private void renderChunk(int x, int z, Render3DEvent event) { long chunkKey = (long) x + ((long) z << 32); if (chunkRenderers.containsKey(chunkKey)) { for (Ore ore : oreConfig) { if (ore.enabled.get()) { if (!chunkRenderers.get(chunkKey).containsKey(ore)) { continue; } for (Vec3d pos : chunkRenderers.get(chunkKey).get(ore)) { event.renderer.boxLines(pos.x, pos.y, pos.z, pos.x + 1, pos.y + 1, pos.z + 1, ore.color, 0); } } } } } @EventHandler private void onTick(TickEvent.Pre event) { if (mc.player == null || mc.world == null || oreConfig == null) return; if (airCheck.get() == AirCheck.RECHECK) { long chunkX = mc.player.getChunkPos().x; long chunkZ = mc.player.getChunkPos().z; ClientWorld world = mc.world; int renderdistance = mc.options.getViewDistance().getValue(); //maybe another config option? But its already crowded int chunkCounter = 5; loop: while (true) { for (long offsetX = prevOffset.x; offsetX <= renderdistance; offsetX++) { for (long offsetZ = prevOffset.z; offsetZ <= renderdistance; offsetZ++) { prevOffset = new ChunkPos((int) offsetX, (int) offsetZ); if (chunkCounter <= 0) { break loop; } long chunkKey = (chunkX + offsetX) + ((chunkZ + offsetZ) << 32); if (chunkRenderers.containsKey(chunkKey)) { chunkRenderers.get(chunkKey).values().forEach(oreSet -> oreSet.removeIf(ore -> !world.getBlockState(new BlockPos((int) ore.x, (int) ore.y, (int) ore.z)).isOpaque())); } chunkCounter--; } prevOffset = new ChunkPos((int) offsetX, -renderdistance); } prevOffset = new ChunkPos(-renderdistance, -renderdistance); } } if (baritone.get() && BaritoneAPI.getProvider().getPrimaryBaritone().getMineProcess().isActive()) { oreGoals.clear(); var chunkPos = mc.player.getChunkPos(); int rangeVal = 4; for (int range = 0; range <= rangeVal; ++range) { for (int x = -range + chunkPos.x; x <= range + chunkPos.x; ++x) { oreGoals.addAll(addToBaritone(x, chunkPos.z + range - rangeVal)); } for (int x = -range + 1 + chunkPos.x; x < range + chunkPos.x; ++x) { oreGoals.addAll(this.addToBaritone(x, chunkPos.z - range + rangeVal + 1)); } } } } private ArrayList<BlockPos> addToBaritone(int chunkX, int chunkZ) { ArrayList<BlockPos> baritoneGoals = new ArrayList<>(); long chunkKey = (long) chunkX + ((long) chunkZ << 32); if (!this.chunkRenderers.containsKey(chunkKey)) { return baritoneGoals; } else { this.oreConfig.stream().filter((config) -> config.enabled.get()).forEach((ore) -> chunkRenderers .get(chunkKey) .getOrDefault(ore, new HashSet<>()) .stream() .map(BlockPos::ofFloored) .forEach(baritoneGoals::add)); return baritoneGoals; } } @Override public void onActivate() { if (Seeds.get().getSeed() == null) { error("No seed found. To set a seed do .seed <seed>"); this.toggle(); } reload(); } @EventHandler
private void onSeedChanged(SeedChangedEvent event) {
2
2023-11-13 08:11:28+00:00
12k
intrepidLi/BUAA_Food
app/src/main/java/com/buaa/food/ui/activity/VideoSelectActivity.java
[ { "identifier": "BaseActivity", "path": "library/base/src/main/java/com/hjq/base/BaseActivity.java", "snippet": "public abstract class BaseActivity extends AppCompatActivity\n implements ActivityAction, ClickAction,\n HandlerAction, BundleAction, KeyboardAction {\n\n /** 错误结果码 */\n public static final int RESULT_ERROR = -2;\n\n /** Activity 回调集合 */\n private SparseArray<OnActivityCallback> mActivityCallbacks;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n initActivity();\n }\n\n protected void initActivity() {\n initLayout();\n initView();\n initData();\n }\n\n /**\n * 获取布局 ID\n */\n protected abstract int getLayoutId();\n\n /**\n * 初始化控件\n */\n protected abstract void initView();\n\n /**\n * 初始化数据\n */\n protected abstract void initData();\n\n /**\n * 初始化布局\n */\n protected void initLayout() {\n if (getLayoutId() > 0) {\n setContentView(getLayoutId());\n initSoftKeyboard();\n }\n }\n\n /**\n * 初始化软键盘\n */\n protected void initSoftKeyboard() {\n // 点击外部隐藏软键盘,提升用户体验\n getContentView().setOnClickListener(v -> {\n // 隐藏软键,避免内存泄漏\n hideKeyboard(getCurrentFocus());\n });\n }\n\n @Override\n protected void onDestroy() {\n super.onDestroy();\n removeCallbacks();\n }\n\n @Override\n public void finish() {\n super.finish();\n // 隐藏软键,避免内存泄漏\n hideKeyboard(getCurrentFocus());\n }\n\n /**\n * 如果当前的 Activity(singleTop 启动模式) 被复用时会回调\n */\n @Override\n protected void onNewIntent(Intent intent) {\n super.onNewIntent(intent);\n // 设置为当前的 Intent,避免 Activity 被杀死后重启 Intent 还是最原先的那个\n setIntent(intent);\n }\n\n @Override\n public Bundle getBundle() {\n return getIntent().getExtras();\n }\n\n /**\n * 和 setContentView 对应的方法\n */\n public ViewGroup getContentView() {\n return findViewById(Window.ID_ANDROID_CONTENT);\n }\n\n @Override\n public Context getContext() {\n return this;\n }\n\n @Override\n public boolean dispatchKeyEvent(KeyEvent event) {\n List<Fragment> fragments = getSupportFragmentManager().getFragments();\n for (Fragment fragment : fragments) {\n // 这个 Fragment 必须是 BaseFragment 的子类,并且处于可见状态\n if (!(fragment instanceof BaseFragment) ||\n fragment.getLifecycle().getCurrentState() != Lifecycle.State.RESUMED) {\n continue;\n }\n // 将按键事件派发给 Fragment 进行处理\n if (((BaseFragment<?>) fragment).dispatchKeyEvent(event)) {\n // 如果 Fragment 拦截了这个事件,那么就不交给 Activity 处理\n return true;\n }\n }\n return super.dispatchKeyEvent(event);\n }\n\n @SuppressWarnings(\"deprecation\")\n @Override\n public void startActivityForResult(Intent intent, int requestCode, @Nullable Bundle options) {\n // 隐藏软键,避免内存泄漏\n hideKeyboard(getCurrentFocus());\n // 查看源码得知 startActivity 最终也会调用 startActivityForResult\n super.startActivityForResult(intent, requestCode, options);\n }\n\n /**\n * startActivityForResult 方法优化\n */\n\n public void startActivityForResult(Class<? extends Activity> clazz, OnActivityCallback callback) {\n startActivityForResult(new Intent(this, clazz), null, callback);\n }\n\n public void startActivityForResult(Intent intent, OnActivityCallback callback) {\n startActivityForResult(intent, null, callback);\n }\n\n public void startActivityForResult(Intent intent, @Nullable Bundle options, OnActivityCallback callback) {\n if (mActivityCallbacks == null) {\n mActivityCallbacks = new SparseArray<>(1);\n }\n // 请求码必须在 2 的 16 次方以内\n int requestCode = new Random().nextInt((int) Math.pow(2, 16));\n mActivityCallbacks.put(requestCode, callback);\n startActivityForResult(intent, requestCode, options);\n }\n\n @Override\n protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {\n OnActivityCallback callback;\n if (mActivityCallbacks != null && (callback = mActivityCallbacks.get(requestCode)) != null) {\n callback.onActivityResult(resultCode, data);\n mActivityCallbacks.remove(requestCode);\n return;\n }\n super.onActivityResult(requestCode, resultCode, data);\n }\n\n public interface OnActivityCallback {\n\n /**\n * 结果回调\n *\n * @param resultCode 结果码\n * @param data 数据\n */\n void onActivityResult(int resultCode, @Nullable Intent data);\n }\n}" }, { "identifier": "BaseAdapter", "path": "library/base/src/main/java/com/hjq/base/BaseAdapter.java", "snippet": "public abstract class BaseAdapter<VH extends BaseAdapter<?>.ViewHolder>\n extends RecyclerView.Adapter<VH> implements ResourcesAction {\n\n /** 上下文对象 */\n private final Context mContext;\n\n /** RecyclerView 对象 */\n private RecyclerView mRecyclerView;\n\n /** 条目点击监听器 */\n @Nullable\n private OnItemClickListener mItemClickListener;\n /** 条目长按监听器 */\n @Nullable\n private OnItemLongClickListener mItemLongClickListener;\n\n /** 条目子 View 点击监听器 */\n @Nullable\n private SparseArray<OnChildClickListener> mChildClickListeners;\n /** 条目子 View 长按监听器 */\n @Nullable\n private SparseArray<OnChildLongClickListener> mChildLongClickListeners;\n\n /** ViewHolder 位置偏移值 */\n private int mPositionOffset = 0;\n\n public BaseAdapter(Context context) {\n mContext = context;\n if (mContext == null) {\n throw new IllegalArgumentException(\"are you ok?\");\n }\n }\n\n @Override\n public final void onBindViewHolder(@NonNull VH holder, int position) {\n // 根据 ViewHolder 绑定的位置和传入的位置进行对比\n // 一般情况下这两个位置值是相等的,但是有一种特殊的情况\n // 在外层添加头部 View 的情况下,这两个位置值是不对等的\n mPositionOffset = position - holder.getAdapterPosition();\n holder.onBindView(position);\n }\n\n /**\n * 获取 RecyclerView 对象\n */\n @Nullable\n public RecyclerView getRecyclerView() {\n return mRecyclerView;\n }\n\n @Override\n public Context getContext() {\n return mContext;\n }\n\n /**\n * 条目 ViewHolder,需要子类 ViewHolder 继承\n */\n public abstract class ViewHolder extends RecyclerView.ViewHolder\n implements View.OnClickListener, View.OnLongClickListener {\n\n public ViewHolder(@LayoutRes int id) {\n this(LayoutInflater.from(getContext()).inflate(id, mRecyclerView, false));\n }\n\n public ViewHolder(View itemView) {\n super(itemView);\n\n // 设置条目的点击和长按事件\n if (mItemClickListener != null) {\n itemView.setOnClickListener(this);\n }\n if (mItemLongClickListener != null) {\n itemView.setOnLongClickListener(this);\n }\n\n // 设置条目子 View 点击事件\n if (mChildClickListeners != null) {\n for (int i = 0; i < mChildClickListeners.size(); i++) {\n View childView = findViewById(mChildClickListeners.keyAt(i));\n if (childView != null) {\n childView.setOnClickListener(this);\n }\n }\n }\n\n // 设置条目子 View 长按事件\n if (mChildLongClickListeners != null) {\n for (int i = 0; i < mChildLongClickListeners.size(); i++) {\n View childView = findViewById(mChildLongClickListeners.keyAt(i));\n if (childView != null) {\n childView.setOnLongClickListener(this);\n }\n }\n }\n }\n\n /**\n * 数据绑定回调\n */\n public abstract void onBindView(int position);\n\n /**\n * 获取 ViewHolder 位置\n */\n protected final int getViewHolderPosition() {\n // 这里解释一下为什么用 getLayoutPosition 而不用 getAdapterPosition\n // 如果是使用 getAdapterPosition 会导致一个问题,那就是快速点击删除条目的时候会出现 -1 的情况,因为这个 ViewHolder 已经解绑了\n // 而使用 getLayoutPosition 则不会出现位置为 -1 的情况,因为解绑之后在布局中不会立马消失,所以不用担心在动画执行中获取位置有异常的情况\n return getLayoutPosition() + mPositionOffset;\n }\n\n /**\n * {@link View.OnClickListener}\n */\n\n @Override\n public void onClick(View view) {\n int position = getViewHolderPosition();\n if (position < 0 || position >= getItemCount()) {\n return;\n }\n\n if (view == getItemView()) {\n if(mItemClickListener != null) {\n mItemClickListener.onItemClick(mRecyclerView, view, position);\n }\n return;\n }\n\n if (mChildClickListeners != null) {\n OnChildClickListener listener = mChildClickListeners.get(view.getId());\n if (listener != null) {\n listener.onChildClick(mRecyclerView, view, position);\n }\n }\n }\n\n /**\n * {@link View.OnLongClickListener}\n */\n\n @Override\n public boolean onLongClick(View view) {\n int position = getViewHolderPosition();\n if (position < 0 || position >= getItemCount()) {\n return false;\n }\n\n if (view == getItemView()) {\n if (mItemLongClickListener != null) {\n return mItemLongClickListener.onItemLongClick(mRecyclerView, view, position);\n }\n return false;\n }\n\n if (mChildLongClickListeners != null) {\n OnChildLongClickListener listener = mChildLongClickListeners.get(view.getId());\n if (listener != null) {\n return listener.onChildLongClick(mRecyclerView, view, position);\n }\n }\n return false;\n }\n\n public final View getItemView() {\n return itemView;\n }\n\n public final <V extends View> V findViewById(@IdRes int id) {\n return getItemView().findViewById(id);\n }\n }\n\n @Override\n public void onAttachedToRecyclerView(@NonNull RecyclerView recyclerView) {\n mRecyclerView = recyclerView;\n // 判断当前的布局管理器是否为空,如果为空则设置默认的布局管理器\n if (mRecyclerView.getLayoutManager() == null) {\n RecyclerView.LayoutManager layoutManager = generateDefaultLayoutManager(mContext);\n if (layoutManager != null) {\n mRecyclerView.setLayoutManager(layoutManager);\n }\n }\n }\n\n @Override\n public void onDetachedFromRecyclerView(@NonNull RecyclerView recyclerView) {\n mRecyclerView = null;\n }\n\n /**\n * 生成默认的布局摆放器\n */\n protected RecyclerView.LayoutManager generateDefaultLayoutManager(Context context) {\n return new LinearLayoutManager(context);\n }\n\n /**\n * 设置 RecyclerView 条目点击监听\n */\n public void setOnItemClickListener(@Nullable OnItemClickListener listener) {\n checkRecyclerViewState();\n mItemClickListener = listener;\n }\n\n /**\n * 设置 RecyclerView 条目子 View 点击监听\n */\n public void setOnChildClickListener(@IdRes int id, @Nullable OnChildClickListener listener) {\n checkRecyclerViewState();\n if (mChildClickListeners == null) {\n mChildClickListeners = new SparseArray<>();\n }\n mChildClickListeners.put(id, listener);\n }\n\n /**\n * 设置 RecyclerView 条目长按监听\n */\n public void setOnItemLongClickListener(@Nullable OnItemLongClickListener listener) {\n checkRecyclerViewState();\n mItemLongClickListener = listener;\n }\n\n /**\n * 设置 RecyclerView 条目子 View 长按监听\n */\n public void setOnChildLongClickListener(@IdRes int id, @Nullable OnChildLongClickListener listener) {\n checkRecyclerViewState();\n if (mChildLongClickListeners == null) {\n mChildLongClickListeners = new SparseArray<>();\n }\n mChildLongClickListeners.put(id, listener);\n }\n\n /**\n * 检查 RecyclerView 状态\n */\n private void checkRecyclerViewState() {\n if (mRecyclerView != null) {\n // 必须在 RecyclerView.setAdapter() 之前设置监听\n throw new IllegalStateException(\"are you ok?\");\n }\n }\n\n /**\n * RecyclerView 条目点击监听类\n */\n public interface OnItemClickListener{\n\n /**\n * 当 RecyclerView 某个条目被点击时回调\n *\n * @param recyclerView RecyclerView 对象\n * @param itemView 被点击的条目对象\n * @param position 被点击的条目位置\n */\n void onItemClick(RecyclerView recyclerView, View itemView, int position);\n }\n\n /**\n * RecyclerView 条目长按监听类\n */\n public interface OnItemLongClickListener {\n\n /**\n * 当 RecyclerView 某个条目被长按时回调\n *\n * @param recyclerView RecyclerView 对象\n * @param itemView 被点击的条目对象\n * @param position 被点击的条目位置\n * @return 是否拦截事件\n */\n boolean onItemLongClick(RecyclerView recyclerView, View itemView, int position);\n }\n\n /**\n * RecyclerView 条目子 View 点击监听类\n */\n public interface OnChildClickListener {\n\n /**\n * 当 RecyclerView 某个条目 子 View 被点击时回调\n *\n * @param recyclerView RecyclerView 对象\n * @param childView 被点击的条目子 View\n * @param position 被点击的条目位置\n */\n void onChildClick(RecyclerView recyclerView, View childView, int position);\n }\n\n /**\n * RecyclerView 条目子 View 长按监听类\n */\n public interface OnChildLongClickListener {\n\n /**\n * 当 RecyclerView 某个条目子 View 被长按时回调\n *\n * @param recyclerView RecyclerView 对象\n * @param childView 被点击的条目子 View\n * @param position 被点击的条目位置\n */\n boolean onChildLongClick(RecyclerView recyclerView, View childView, int position);\n }\n}" }, { "identifier": "StatusAction", "path": "app/src/main/java/com/buaa/food/action/StatusAction.java", "snippet": "public interface StatusAction {\n\n /**\n * 获取状态布局\n */\n StatusLayout getStatusLayout();\n\n /**\n * 显示加载中\n */\n default void showLoading() {\n showLoading(R.raw.loading);\n }\n\n default void showLoading(@RawRes int id) {\n StatusLayout layout = getStatusLayout();\n layout.show();\n layout.setAnimResource(id);\n layout.setHint(\"\");\n layout.setOnRetryListener(null);\n }\n\n /**\n * 显示加载完成\n */\n default void showComplete() {\n StatusLayout layout = getStatusLayout();\n if (layout == null || !layout.isShow()) {\n return;\n }\n layout.hide();\n }\n\n /**\n * 显示空提示\n */\n default void showEmpty() {\n showLayout(R.drawable.status_empty_ic, R.string.status_layout_no_data, null);\n }\n\n /**\n * 显示错误提示\n */\n default void showError(StatusLayout.OnRetryListener listener) {\n StatusLayout layout = getStatusLayout();\n Context context = layout.getContext();\n ConnectivityManager manager = ContextCompat.getSystemService(context, ConnectivityManager.class);\n if (manager != null) {\n NetworkInfo info = manager.getActiveNetworkInfo();\n // 判断网络是否连接\n if (info == null || !info.isConnected()) {\n showLayout(R.drawable.status_network_ic, R.string.status_layout_error_network, listener);\n return;\n }\n }\n showLayout(R.drawable.status_error_ic, R.string.status_layout_error_request, listener);\n }\n\n /**\n * 显示自定义提示\n */\n default void showLayout(@DrawableRes int drawableId, @StringRes int stringId, StatusLayout.OnRetryListener listener) {\n StatusLayout layout = getStatusLayout();\n Context context = layout.getContext();\n showLayout(ContextCompat.getDrawable(context, drawableId), context.getString(stringId), listener);\n }\n\n default void showLayout(Drawable drawable, CharSequence hint, StatusLayout.OnRetryListener listener) {\n StatusLayout layout = getStatusLayout();\n layout.show();\n layout.setIcon(drawable);\n layout.setHint(hint);\n layout.setOnRetryListener(listener);\n }\n}" }, { "identifier": "AppActivity", "path": "app/src/main/java/com/buaa/food/app/AppActivity.java", "snippet": "public abstract class AppActivity extends BaseActivity\n implements ToastAction, TitleBarAction, OnHttpListener<Object> {\n\n /** 标题栏对象 */\n private TitleBar mTitleBar;\n /** 状态栏沉浸 */\n private ImmersionBar mImmersionBar;\n\n /** 加载对话框 */\n private BaseDialog mDialog;\n /** 对话框数量 */\n private int mDialogCount;\n\n /**\n * 当前加载对话框是否在显示中\n */\n public boolean isShowDialog() {\n return mDialog != null && mDialog.isShowing();\n }\n\n /**\n * 显示加载对话框\n */\n public void showDialog() {\n if (isFinishing() || isDestroyed()) {\n return;\n }\n\n mDialogCount++;\n postDelayed(() -> {\n if (mDialogCount <= 0 || isFinishing() || isDestroyed()) {\n return;\n }\n\n if (mDialog == null) {\n mDialog = new WaitDialog.Builder(this)\n .setCancelable(false)\n .create();\n }\n if (!mDialog.isShowing()) {\n mDialog.show();\n }\n }, 300);\n }\n\n /**\n * 隐藏加载对话框\n */\n public void hideDialog() {\n if (isFinishing() || isDestroyed()) {\n return;\n }\n\n if (mDialogCount > 0) {\n mDialogCount--;\n }\n\n if (mDialogCount != 0 || mDialog == null || !mDialog.isShowing()) {\n return;\n }\n\n mDialog.dismiss();\n }\n\n @Override\n protected void initLayout() {\n super.initLayout();\n\n if (getTitleBar() != null) {\n getTitleBar().setOnTitleBarListener(this);\n }\n\n // 初始化沉浸式状态栏\n if (isStatusBarEnabled()) {\n getStatusBarConfig().init();\n\n // 设置标题栏沉浸\n if (getTitleBar() != null) {\n ImmersionBar.setTitleBar(this, getTitleBar());\n }\n }\n }\n\n /**\n * 是否使用沉浸式状态栏\n */\n protected boolean isStatusBarEnabled() {\n return true;\n }\n\n /**\n * 状态栏字体深色模式\n */\n protected boolean isStatusBarDarkFont() {\n return true;\n }\n\n /**\n * 获取状态栏沉浸的配置对象\n */\n @NonNull\n public ImmersionBar getStatusBarConfig() {\n if (mImmersionBar == null) {\n mImmersionBar = createStatusBarConfig();\n }\n return mImmersionBar;\n }\n\n /**\n * 初始化沉浸式状态栏\n */\n @NonNull\n protected ImmersionBar createStatusBarConfig() {\n return ImmersionBar.with(this)\n // 默认状态栏字体颜色为黑色\n .statusBarDarkFont(isStatusBarDarkFont())\n // 指定导航栏背景颜色\n .navigationBarColor(R.color.white)\n // 状态栏字体和导航栏内容自动变色,必须指定状态栏颜色和导航栏颜色才可以自动变色\n .autoDarkModeEnable(true, 0.2f);\n }\n\n /**\n * 设置标题栏的标题\n */\n @Override\n public void setTitle(@StringRes int id) {\n setTitle(getString(id));\n }\n\n /**\n * 设置标题栏的标题\n */\n @Override\n public void setTitle(CharSequence title) {\n super.setTitle(title);\n if (getTitleBar() != null) {\n getTitleBar().setTitle(title);\n }\n }\n\n @Override\n @Nullable\n public TitleBar getTitleBar() {\n if (mTitleBar == null) {\n mTitleBar = obtainTitleBar(getContentView());\n }\n return mTitleBar;\n }\n\n @Override\n public void onLeftClick(View view) {\n onBackPressed();\n }\n\n @Override\n public void startActivityForResult(Intent intent, int requestCode, @Nullable Bundle options) {\n super.startActivityForResult(intent, requestCode, options);\n overridePendingTransition(R.anim.right_in_activity, R.anim.right_out_activity);\n }\n\n @Override\n public void finish() {\n super.finish();\n overridePendingTransition(R.anim.left_in_activity, R.anim.left_out_activity);\n }\n\n /**\n * {@link OnHttpListener}\n */\n\n @Override\n public void onStart(Call call) {\n showDialog();\n }\n\n @Override\n public void onSucceed(Object result) {\n if (result instanceof HttpData) {\n toast(((HttpData<?>) result).getMessage());\n }\n }\n\n @Override\n public void onFail(Exception e) {\n toast(e.getMessage());\n }\n\n @Override\n public void onEnd(Call call) {\n hideDialog();\n }\n\n @Override\n protected void onDestroy() {\n super.onDestroy();\n if (isShowDialog()) {\n hideDialog();\n }\n mDialog = null;\n }\n}" }, { "identifier": "ThreadPoolManager", "path": "app/src/main/java/com/buaa/food/manager/ThreadPoolManager.java", "snippet": "public final class ThreadPoolManager extends ThreadPoolExecutor {\n\n private static volatile ThreadPoolManager sInstance;\n\n public ThreadPoolManager() {\n // 这里最大线程数为什么不是 Int 最大值?因为在华为荣耀机子上面有最大线程数限制\n // 经过测试华为荣耀手机不能超过 300 个线程,否则会出现内存溢出\n // java.lang.OutOfMemoryError:pthread_create (1040KB stack) failed: Out of memory\n // 由于应用自身占用了一些线程数,故减去 300 - 100 = 200 个\n super(0, 200,\n 30L, TimeUnit.MILLISECONDS,\n new SynchronousQueue<>());\n }\n\n public static ThreadPoolManager getInstance() {\n if(sInstance == null) {\n synchronized (ThreadPoolManager.class) {\n if(sInstance == null) {\n sInstance = new ThreadPoolManager();\n }\n }\n }\n return sInstance;\n }\n}" }, { "identifier": "GridSpaceDecoration", "path": "app/src/main/java/com/buaa/food/other/GridSpaceDecoration.java", "snippet": "public final class GridSpaceDecoration extends RecyclerView.ItemDecoration {\n\n private final int mSpace;\n\n public GridSpaceDecoration(int space) {\n mSpace = space;\n }\n\n @Override\n public void onDraw(@NonNull Canvas canvas, @NonNull RecyclerView recyclerView, @NonNull RecyclerView.State state) {}\n\n @SuppressWarnings(\"all\")\n @Override\n public void getItemOffsets(@NonNull Rect rect, @NonNull View view, RecyclerView recyclerView, @NonNull RecyclerView.State state) {\n int position = recyclerView.getChildAdapterPosition(view);\n int spanCount = ((GridLayoutManager) recyclerView.getLayoutManager()).getSpanCount();\n\n // 每一行的最后一个才留出右边间隙\n if ((position + 1) % spanCount == 0) {\n rect.right = mSpace;\n }\n\n // 只有第一行才留出顶部间隙\n if (position < spanCount) {\n rect.top = mSpace;\n }\n\n rect.bottom = mSpace;\n rect.left = mSpace;\n }\n\n @Override\n public void onDrawOver(@NonNull Canvas canvas, @NonNull RecyclerView recyclerView, @NonNull RecyclerView.State state) {}\n}" }, { "identifier": "VideoSelectAdapter", "path": "app/src/main/java/com/buaa/food/ui/adapter/VideoSelectAdapter.java", "snippet": "public final class VideoSelectAdapter extends AppAdapter<VideoSelectActivity.VideoBean> {\n\n private final List<VideoSelectActivity.VideoBean> mSelectVideo;\n\n public VideoSelectAdapter(Context context, List<VideoSelectActivity.VideoBean> images) {\n super(context);\n mSelectVideo = images;\n }\n\n @NonNull\n @Override\n public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {\n return new ViewHolder();\n }\n\n private final class ViewHolder extends AppAdapter<?>.ViewHolder {\n\n private final ImageView mImageView;\n private final CheckBox mCheckBox;\n private final TextView mDurationView;\n private final TextView mSizeView;\n\n private ViewHolder() {\n super(R.layout.video_select_item);\n mImageView = findViewById(R.id.iv_video_select_image);\n mCheckBox = findViewById(R.id.iv_video_select_check);\n mDurationView = findViewById(R.id.tv_video_select_duration);\n mSizeView = findViewById(R.id.tv_video_select_size);\n }\n\n @Override\n public void onBindView(int position) {\n VideoSelectActivity.VideoBean bean = getItem(position);\n GlideApp.with(getContext())\n .load(bean.getVideoPath())\n .into(mImageView);\n\n mCheckBox.setChecked(mSelectVideo.contains(getItem(position)));\n\n // 获取视频的总时长\n mDurationView.setText(PlayerView.conversionTime((int) bean.getVideoDuration()));\n\n // 获取视频文件大小\n mSizeView.setText(CacheDataManager.getFormatSize(bean.getVideoSize()));\n }\n }\n\n @Override\n protected RecyclerView.LayoutManager generateDefaultLayoutManager(Context context) {\n return new GridLayoutManager(context, 2);\n }\n}" }, { "identifier": "AlbumDialog", "path": "app/src/main/java/com/buaa/food/ui/dialog/AlbumDialog.java", "snippet": "public final class AlbumDialog {\n\n public static final class Builder\n extends BaseDialog.Builder<Builder>\n implements BaseAdapter.OnItemClickListener {\n\n @Nullable\n private OnListener mListener;\n\n private final RecyclerView mRecyclerView;\n private final AlbumAdapter mAdapter;\n\n public Builder(Context context) {\n super(context);\n\n setContentView(R.layout.album_dialog);\n\n mRecyclerView = findViewById(R.id.rv_album_list);\n mAdapter = new AlbumAdapter(context);\n mAdapter.setOnItemClickListener(this);\n mRecyclerView.setAdapter(mAdapter);\n }\n\n public Builder setData(List<AlbumInfo> data) {\n mAdapter.setData(data);\n // 滚动到选中的位置\n for (int i = 0; i < data.size(); i++) {\n if (data.get(i).isSelect()) {\n mRecyclerView.scrollToPosition(i);\n break;\n }\n }\n return this;\n }\n\n public Builder setListener(OnListener listener) {\n mListener = listener;\n return this;\n }\n\n @Override\n public void onItemClick(RecyclerView recyclerView, View itemView, int position) {\n List<AlbumInfo> data = mAdapter.getData();\n if (data == null) {\n return;\n }\n\n for (AlbumInfo info : data) {\n if (info.isSelect()) {\n info.setSelect(false);\n break;\n }\n }\n mAdapter.getItem(position).setSelect(true);\n mAdapter.notifyDataSetChanged();\n\n // 延迟消失\n postDelayed(() -> {\n\n if (mListener != null) {\n mListener.onSelected(getDialog(), position, mAdapter.getItem(position));\n }\n dismiss();\n\n }, 300);\n }\n\n @NonNull\n @Override\n protected BaseDialog createDialog(Context context, int themeId) {\n BottomSheetDialog dialog = new BottomSheetDialog(context, themeId);\n dialog.getBottomSheetBehavior().setPeekHeight(getResources().getDisplayMetrics().heightPixels / 2);\n return dialog;\n }\n }\n\n private static final class AlbumAdapter extends AppAdapter<AlbumInfo> {\n\n private AlbumAdapter(Context context) {\n super(context);\n }\n\n @NonNull\n @Override\n public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {\n return new ViewHolder();\n }\n\n private final class ViewHolder extends AppAdapter<?>.ViewHolder {\n\n private final ImageView mIconView;\n private final TextView mNameView;\n private final TextView mRemarkView;\n private final CheckBox mCheckBox;\n\n private ViewHolder() {\n super(R.layout.album_item);\n mIconView = findViewById(R.id.iv_album_icon);\n mNameView = findViewById(R.id.tv_album_name);\n mRemarkView = findViewById(R.id.tv_album_remark);\n mCheckBox = findViewById(R.id.rb_album_check);\n }\n\n @Override\n public void onBindView(int position) {\n AlbumInfo info = getItem(position);\n\n GlideApp.with(getContext())\n .asBitmap()\n .load(info.getIcon())\n .into(mIconView);\n\n mNameView.setText(info.getName());\n mRemarkView.setText(info.getRemark());\n mCheckBox.setChecked(info.isSelect());\n mCheckBox.setVisibility(info.isSelect() ? View.VISIBLE : View.INVISIBLE);\n }\n }\n }\n\n /**\n * 专辑信息类\n */\n public static class AlbumInfo {\n\n /** 封面 */\n private String icon;\n /** 名称 */\n private String name;\n /** 备注 */\n private String remark;\n /** 选中 */\n private boolean select;\n\n public AlbumInfo(String icon, String name, String remark, boolean select) {\n this.icon = icon;\n this.name = name;\n this.remark = remark;\n this.select = select;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public void setSelect(boolean select) {\n this.select = select;\n }\n\n public String getIcon() {\n return icon;\n }\n\n public String getName() {\n return name;\n }\n\n public String getRemark() {\n return remark;\n }\n\n public boolean isSelect() {\n return select;\n }\n }\n\n public interface OnListener {\n\n /**\n * 选择条目时回调\n */\n void onSelected(BaseDialog dialog, int position, AlbumInfo bean);\n }\n}" }, { "identifier": "StatusLayout", "path": "app/src/main/java/com/buaa/food/widget/StatusLayout.java", "snippet": "public final class StatusLayout extends FrameLayout {\n\n /** 主布局 */\n private ViewGroup mMainLayout;\n /** 提示图标 */\n private LottieAnimationView mLottieView;\n /** 提示文本 */\n private TextView mTextView;\n /** 重试按钮 */\n private TextView mRetryView;\n /** 重试监听 */\n private OnRetryListener mListener;\n\n public StatusLayout(@NonNull Context context) {\n this(context, null);\n }\n\n public StatusLayout(@NonNull Context context, @Nullable AttributeSet attrs) {\n this(context, attrs, 0);\n }\n\n public StatusLayout(@NonNull Context context, @Nullable AttributeSet attrs, @AttrRes int defStyleAttr) {\n super(context, attrs, defStyleAttr);\n }\n\n /**\n * 显示\n */\n public void show() {\n\n if (mMainLayout == null) {\n //初始化布局\n initLayout();\n }\n\n if (isShow()) {\n return;\n }\n mRetryView.setVisibility(mListener == null ? View.INVISIBLE : View.VISIBLE);\n // 显示布局\n mMainLayout.setVisibility(VISIBLE);\n }\n\n /**\n * 隐藏\n */\n public void hide() {\n if (mMainLayout == null || !isShow()) {\n return;\n }\n //隐藏布局\n mMainLayout.setVisibility(INVISIBLE);\n }\n\n /**\n * 是否显示了\n */\n public boolean isShow() {\n return mMainLayout != null && mMainLayout.getVisibility() == VISIBLE;\n }\n\n /**\n * 设置提示图标,请在show方法之后调用\n */\n public void setIcon(@DrawableRes int id) {\n setIcon(ContextCompat.getDrawable(getContext(), id));\n }\n\n public void setIcon(Drawable drawable) {\n if (mLottieView == null) {\n return;\n }\n if (mLottieView.isAnimating()) {\n mLottieView.cancelAnimation();\n }\n mLottieView.setImageDrawable(drawable);\n }\n\n /**\n * 设置提示动画\n */\n public void setAnimResource(@RawRes int id) {\n if (mLottieView == null) {\n return;\n }\n\n mLottieView.setAnimation(id);\n if (!mLottieView.isAnimating()) {\n mLottieView.playAnimation();\n }\n }\n\n /**\n * 设置提示文本,请在show方法之后调用\n */\n public void setHint(@StringRes int id) {\n setHint(getResources().getString(id));\n }\n\n public void setHint(CharSequence text) {\n if (mTextView == null) {\n return;\n }\n if (text == null) {\n text = \"\";\n }\n mTextView.setText(text);\n }\n\n /**\n * 初始化提示的布局\n */\n private void initLayout() {\n\n mMainLayout = (ViewGroup) LayoutInflater.from(getContext()).inflate(R.layout.widget_status_layout, this, false);\n\n mLottieView = mMainLayout.findViewById(R.id.iv_status_icon);\n mTextView = mMainLayout.findViewById(R.id.iv_status_text);\n mRetryView = mMainLayout.findViewById(R.id.iv_status_retry);\n\n if (mMainLayout.getBackground() == null) {\n // 默认使用 windowBackground 作为背景\n TypedArray typedArray = getContext().obtainStyledAttributes(new int[]{android.R.attr.windowBackground});\n mMainLayout.setBackground(typedArray.getDrawable(0));\n mMainLayout.setClickable(true);\n typedArray.recycle();\n }\n\n mRetryView.setOnClickListener(mClickWrapper);\n\n addView(mMainLayout);\n }\n\n /**\n * 设置重试监听器\n */\n public void setOnRetryListener(OnRetryListener listener) {\n mListener = listener;\n if (isShow()) {\n mRetryView.setVisibility(mListener == null ? View.INVISIBLE : View.VISIBLE);\n }\n }\n\n /**\n * 点击事件包装类\n */\n private final OnClickListener mClickWrapper = new OnClickListener() {\n\n @Override\n public void onClick(View v) {\n if (mListener == null) {\n return;\n }\n mListener.onRetry(StatusLayout.this);\n }\n };\n\n /**\n * 重试监听器\n */\n public interface OnRetryListener {\n\n /**\n * 点击了重试\n */\n void onRetry(StatusLayout layout);\n }\n}" }, { "identifier": "FloatActionButton", "path": "library/widget/src/main/java/com/hjq/widget/view/FloatActionButton.java", "snippet": "public final class FloatActionButton extends AppCompatImageView {\n\n /** 动画显示时长 */\n private static final int ANIM_TIME = 300;\n\n public FloatActionButton(@NonNull Context context) {\n super(context);\n }\n\n public FloatActionButton(@NonNull Context context, @Nullable AttributeSet attrs) {\n super(context, attrs);\n }\n\n public FloatActionButton(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {\n super(context, attrs, defStyleAttr);\n }\n\n /**\n * 显示\n */\n public void show() {\n removeCallbacks(mHideRunnable);\n postDelayed(mShowRunnable, ANIM_TIME * 2);\n }\n\n /**\n * 隐藏\n */\n public void hide() {\n removeCallbacks(mShowRunnable);\n post(mHideRunnable);\n }\n\n /**\n * 显示悬浮球动画\n */\n private final Runnable mShowRunnable = () -> {\n if (getVisibility() == View.INVISIBLE) {\n setVisibility(View.VISIBLE);\n }\n ValueAnimator valueAnimator = ValueAnimator.ofFloat(0f, 1f);\n valueAnimator.setDuration(ANIM_TIME);\n valueAnimator.addUpdateListener(animation -> {\n float value = (float) animation.getAnimatedValue();\n setAlpha(value);\n setScaleX(value);\n setScaleY(value);\n });\n valueAnimator.start();\n };\n\n /**\n * 隐藏悬浮球动画\n */\n private final Runnable mHideRunnable = () -> {\n if (getVisibility() == View.INVISIBLE) {\n return;\n }\n ValueAnimator valueAnimator = ValueAnimator.ofFloat(1f, 0f);\n valueAnimator.setDuration(ANIM_TIME);\n valueAnimator.addUpdateListener(animation -> {\n float value = (float) animation.getAnimatedValue();\n setAlpha(value);\n setScaleX(value);\n setScaleY(value);\n if (value == 0) {\n setVisibility(View.INVISIBLE);\n }\n });\n valueAnimator.start();\n };\n}" } ]
import android.content.ContentResolver; import android.content.Intent; import android.content.pm.ActivityInfo; import android.database.Cursor; import android.media.MediaMetadataRetriever; import android.net.Uri; import android.os.Parcel; import android.os.Parcelable; import android.provider.MediaStore; import android.text.TextUtils; import android.view.View; import android.view.animation.AnimationUtils; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.recyclerview.widget.RecyclerView; import com.hjq.base.BaseActivity; import com.hjq.base.BaseAdapter; import com.buaa.food.R; import com.buaa.food.action.StatusAction; import com.buaa.food.aop.Log; import com.buaa.food.aop.Permissions; import com.buaa.food.aop.SingleClick; import com.buaa.food.app.AppActivity; import com.buaa.food.manager.ThreadPoolManager; import com.buaa.food.other.GridSpaceDecoration; import com.buaa.food.ui.adapter.VideoSelectAdapter; import com.buaa.food.ui.dialog.AlbumDialog; import com.buaa.food.widget.StatusLayout; import com.hjq.permissions.Permission; import com.hjq.permissions.XXPermissions; import com.hjq.widget.view.FloatActionButton; import com.tencent.bugly.crashreport.CrashReport; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Set;
10,105
package com.buaa.food.ui.activity; public final class VideoSelectActivity extends AppActivity implements StatusAction, Runnable, BaseAdapter.OnItemClickListener, BaseAdapter.OnItemLongClickListener, BaseAdapter.OnChildClickListener { private static final String INTENT_KEY_IN_MAX_SELECT = "maxSelect"; private static final String INTENT_KEY_OUT_VIDEO_LIST = "videoList"; public static void start(BaseActivity activity, OnVideoSelectListener listener) { start(activity, 1, listener); } @Log @Permissions({Permission.READ_EXTERNAL_STORAGE, Permission.WRITE_EXTERNAL_STORAGE}) public static void start(BaseActivity activity, int maxSelect, OnVideoSelectListener listener) { if (maxSelect < 1) { // 最少要选择一个视频 throw new IllegalArgumentException("are you ok?"); } Intent intent = new Intent(activity, VideoSelectActivity.class); intent.putExtra(INTENT_KEY_IN_MAX_SELECT, maxSelect); activity.startActivityForResult(intent, (resultCode, data) -> { if (listener == null) { return; } if (data == null) { listener.onCancel(); return; } ArrayList<VideoBean> list = data.getParcelableArrayListExtra(INTENT_KEY_OUT_VIDEO_LIST); if (list == null || list.isEmpty()) { listener.onCancel(); return; } Iterator<VideoBean> iterator = list.iterator(); while (iterator.hasNext()) { if (!new File(iterator.next().getVideoPath()).isFile()) { iterator.remove(); } } if (resultCode == RESULT_OK && !list.isEmpty()) { listener.onSelected(list); return; } listener.onCancel(); }); } private StatusLayout mStatusLayout; private RecyclerView mRecyclerView;
package com.buaa.food.ui.activity; public final class VideoSelectActivity extends AppActivity implements StatusAction, Runnable, BaseAdapter.OnItemClickListener, BaseAdapter.OnItemLongClickListener, BaseAdapter.OnChildClickListener { private static final String INTENT_KEY_IN_MAX_SELECT = "maxSelect"; private static final String INTENT_KEY_OUT_VIDEO_LIST = "videoList"; public static void start(BaseActivity activity, OnVideoSelectListener listener) { start(activity, 1, listener); } @Log @Permissions({Permission.READ_EXTERNAL_STORAGE, Permission.WRITE_EXTERNAL_STORAGE}) public static void start(BaseActivity activity, int maxSelect, OnVideoSelectListener listener) { if (maxSelect < 1) { // 最少要选择一个视频 throw new IllegalArgumentException("are you ok?"); } Intent intent = new Intent(activity, VideoSelectActivity.class); intent.putExtra(INTENT_KEY_IN_MAX_SELECT, maxSelect); activity.startActivityForResult(intent, (resultCode, data) -> { if (listener == null) { return; } if (data == null) { listener.onCancel(); return; } ArrayList<VideoBean> list = data.getParcelableArrayListExtra(INTENT_KEY_OUT_VIDEO_LIST); if (list == null || list.isEmpty()) { listener.onCancel(); return; } Iterator<VideoBean> iterator = list.iterator(); while (iterator.hasNext()) { if (!new File(iterator.next().getVideoPath()).isFile()) { iterator.remove(); } } if (resultCode == RESULT_OK && !list.isEmpty()) { listener.onSelected(list); return; } listener.onCancel(); }); } private StatusLayout mStatusLayout; private RecyclerView mRecyclerView;
private FloatActionButton mFloatingView;
9
2023-11-14 10:04:26+00:00
12k
WallasAR/GUITest
src/main/java/com/session/employee/PurchaseController.java
[ { "identifier": "Banco", "path": "src/main/java/com/db/bank/Banco.java", "snippet": "public class Banco {\n Scanner scanner1 = new Scanner(System.in);\n public static Connection connection = conexao();\n Statement executar;\n {\n try {\n executar = connection.createStatement();\n } catch (SQLException e) {\n throw new RuntimeException(e);\n }\n }\n public static Connection conexao(){\n Connection conn = null;\n String url = \"jdbc:mysql://localhost:3306/farmacia?serverTimezone=America/Sao_Paulo\";\n String user = \"adm\";\n String password = \"1234\";\n try {\n conn = DriverManager.getConnection(url, user, password);\n\n } catch (SQLException erro) {\n JOptionPane.showMessageDialog(null, erro.getMessage());\n }\n return conn;\n }\n public void criartabela(){\n try {\n if(!tabelaExiste(\"medicamentos\")) {\n executar.execute(\"CREATE TABLE medicamentos(id INT NOT NULL AUTO_INCREMENT ,nome VARCHAR(25), quantidade INT, tipo VARCHAR(25), valor FLOAT, PRIMARY KEY(id))\");\n }else{\n System.out.println();\n }\n }catch (SQLException e){\n System.out.println(e);\n }\n }\n public static void deletarcliente(String idcli) throws SQLException{\n Connection connection = conexao();\n String deletecli = (\"DELETE FROM cliente WHERE id = ?\");\n PreparedStatement preparedStatement = connection.prepareStatement(deletecli);\n preparedStatement.setString(1, idcli);\n preparedStatement.executeUpdate();\n }\n private boolean tabelaExiste(String nomeTabela) throws SQLException {\n // Verificar se a tabela já existe no banco de dados\n try (Connection connection = conexao();\n ResultSet resultSet = connection.getMetaData().getTables(null, null, nomeTabela, null)) {\n return resultSet.next();\n }\n }\n public void autenticar(){\n try {\n if(!tabelaExiste(\"autenticar\")) {\n executar.execute(\"CREATE TABLE autenticar(id INT NOT NULL AUTO_INCREMENT, usuario VARCHAR(25), password VARCHAR(25), PRIMARY KEY(id))\");\n }else{\n System.out.println();\n }\n } catch (SQLException e) {\n throw new RuntimeException(e);\n }\n }\n public void inseriradm(String user, String pass){\n try{\n String adm = (\"INSERT INTO autenticar (usuario, password) VALUES (?, ?)\");\n PreparedStatement preparedStatement = connection.prepareStatement(adm);\n preparedStatement.setString(1, user);\n preparedStatement.setString(2, pass);\n\n preparedStatement.executeUpdate();\n\n }catch(SQLException e){\n System.out.println(e);\n }\n }\n public void tablecliete(){\n try{\n if(!tabelaExiste(\"cliente\")){\n executar.execute(\"CREATE TABLE cliente(id INT NOT NULL AUTO_INCREMENT, nome VARCHAR(25), sobrenome VARCHAR(25), usuario VARCHAR(25), telefone VARCHAR(30), PRIMARY KEY(id))\");\n }else{\n System.out.println();\n }\n }catch(SQLException e){\n System.out.println(e);\n }\n }\n public static boolean verificarusuario(String user){\n boolean existe = false;\n Connection connection = conexao();\n try{\n String verificar = \"SELECT * FROM cliente WHERE usuario = ?\";\n try(PreparedStatement verificarexis = connection.prepareStatement(verificar)){\n verificarexis.setString(1, user);\n try(ResultSet verificarresultado = verificarexis.executeQuery()){\n existe = verificarresultado.next();\n }\n }\n }catch(SQLException e){\n System.out.println(e);\n }\n return existe;\n }\n public void inserircliente(String nomecli, String sobrenomecli, String user, String fone){\n try{\n if(verificarusuario(user)) {\n AlertMsg alert = new AlertMsg();\n alert.msgInformation(\"Erro ao registrar\" , \"Nome de usuário ja está sendo utilizado, tente novamente.\");\n }else{\n String cliente = (\"INSERT INTO cliente (nome, sobrenome, usuario, telefone) VALUES(?,?,?,?)\");\n PreparedStatement preparedStatement = connection.prepareStatement(cliente);\n preparedStatement.setString(1, nomecli);\n preparedStatement.setString(2, sobrenomecli);\n preparedStatement.setString(3, user);\n preparedStatement.setString(4, fone);\n\n preparedStatement.executeUpdate();\n }\n\n }catch(SQLException e){\n System.out.println(e);\n }\n }\n\n public void updateClient(String nome, String sobrenome, String usuario, String fone, String idcli) throws SQLException {\n String updateQuaryCli = \"UPDATE cliente SET nome = ?, sobrenome = ?, usuario = ?, telefone = ? WHERE id = ?\";\n PreparedStatement preparedStatement = connection.prepareStatement(updateQuaryCli);\n preparedStatement.setString(1, nome);\n preparedStatement.setString(2, sobrenome);\n preparedStatement.setString(3, usuario);\n preparedStatement.setString(4, fone);\n preparedStatement.setString(5, idcli);\n preparedStatement.executeUpdate();\n }\n\n public void inserirmedicamento(String nomMedi, int quantiMedi,String tipoMedi, float valorMedi ){\n try{\n String medi = (\"INSERT INTO medicamentos (nome, quantidade, tipo , valor) VALUES(?,?,?,?)\");\n PreparedStatement preparedStatement = connection.prepareStatement(medi);\n preparedStatement.setString(1, nomMedi);\n preparedStatement.setInt(2, quantiMedi);\n preparedStatement.setString(3, tipoMedi);\n preparedStatement.setFloat(4, valorMedi);\n\n preparedStatement.executeUpdate();\n\n }catch(SQLException e){\n System.out.println(e);\n }\n }\n\n public static int somarentidadeseliente() {\n try {\n String consultaSQLCliente = \"SELECT COUNT(id) AS soma_total FROM cliente\";\n\n try (PreparedStatement statement = connection.prepareStatement(consultaSQLCliente);\n ResultSet consultaSoma = statement.executeQuery()) {\n\n if (consultaSoma.next()) {\n int soma = consultaSoma.getInt(\"soma_total\");\n return soma;\n }\n }\n } catch (SQLException e) {\n e.printStackTrace();\n }\n return 0;\n }\n public static int somarentidadesefuncionarios() {\n try {\n String consultaSQLCliente = \"SELECT COUNT(id) AS soma_total FROM funcionarios\";\n\n try (PreparedStatement statement = connection.prepareStatement(consultaSQLCliente);\n ResultSet consultaSomafu = statement.executeQuery()) {\n\n if (consultaSomafu.next()) {\n int somafu = consultaSomafu.getInt(\"soma_total\");\n return somafu;\n }\n }\n } catch (SQLException e) {\n e.printStackTrace();\n }\n return 0;\n }\n public static int somarentidadesmedicamentos() {\n try {\n String consultaSQLCliente = \"SELECT COUNT(id) AS soma_total FROM medicamentos\";\n\n try (PreparedStatement statement = connection.prepareStatement(consultaSQLCliente);\n ResultSet consultaSomamedi = statement.executeQuery()) {\n\n if (consultaSomamedi.next()) {\n int somamedi = consultaSomamedi.getInt(\"soma_total\");\n return somamedi;\n //System.out.println(\"Soma total de Medicamentos registrados: \" + somamedi);\n }\n }\n } catch (SQLException e) {\n e.printStackTrace();\n }\n return 0;\n }\n\n public void tabelafuncionario(){\n try {\n if(!tabelaExiste(\"funcionarios\")) {\n executar.execute(\"CREATE TABLE funcionarios(id INT NOT NULL AUTO_INCREMENT, nome VARCHAR(25), sobrenome VARCHAR(25), usuario VARCHAR(25), cargo VARCHAR(25), cpf VARCHAR(25), salario FLOAT, senha VARCHAR(25), PRIMARY KEY(id))\");\n }else{\n System.out.println();\n }\n }catch (SQLException e){\n System.out.println(e);\n }\n }\n public void inserirfuncinario(String nome, String sobrenome, String user, String cargo, String Cpf, float salario, String senha){\n try{\n if(verificarusuario(user)) {\n System.out.println(\"O nome de usuario não pode ser utilizado, tente outro.\");\n }else{\n String cliente = (\"INSERT INTO funcionarios (nome, sobrenome, usuario, cargo, cpf, salario, senha) VALUES(?,?,?,?,?,?,?)\");\n PreparedStatement preparedStatement = connection.prepareStatement(cliente);\n preparedStatement.setString(1, nome);\n preparedStatement.setString(2, sobrenome);\n preparedStatement.setString(3, user);\n preparedStatement.setString(4, cargo);\n preparedStatement.setString(5, Cpf);\n preparedStatement.setFloat(6, salario);\n preparedStatement.setString(7, senha);\n\n preparedStatement.executeUpdate();\n }\n\n }catch(SQLException e){\n System.out.println(e);\n }\n }\n public void updateFuncionario(String nome, String sobrenome, String user, String cargo, String cpf, float salario, String senha, int idfunc) throws SQLException {\n String updateQuaryCli = \"UPDATE funcionarios SET nome = ?, sobrenome = ?, usuario = ?, cargo = ?, cpf = ?, salario = ?, senha = ? WHERE id = ?\";\n PreparedStatement preparedStatement = connection.prepareStatement(updateQuaryCli);\n preparedStatement.setString(1, nome);\n preparedStatement.setString(2, sobrenome);\n preparedStatement.setString(3, user);\n preparedStatement.setString(4, cargo);\n preparedStatement.setString(5, cpf);\n preparedStatement.setFloat(6, salario);\n preparedStatement.setString(7, senha);\n preparedStatement.setInt(8,idfunc);\n preparedStatement.executeUpdate();\n }\n public static void deletarfuncionario(int num) throws SQLException{\n Connection connection = conexao();\n String delete = (\"DELETE FROM funcionarios WHERE id = ?\");\n PreparedStatement preparedStatement = connection.prepareStatement(delete);\n preparedStatement.setInt(1, num);\n\n preparedStatement.executeUpdate();\n }\n public static void deletarmedicamento(int num) throws SQLException{\n Connection connection = conexao();\n String delete = (\"DELETE FROM medicamentos WHERE id = ?\");\n PreparedStatement preparedStatement = connection.prepareStatement(delete);\n preparedStatement.setInt(1, num);\n\n preparedStatement.executeUpdate();\n }\n public void updateMedicamento(String nome, int quantidade, String tipo, float valor, int idfunc) throws SQLException {\n String updateQuaryCli = \"UPDATE medicamentos SET nome = ?, quantidade = ?, tipo = ?, valor = ? WHERE id = ?\";\n PreparedStatement preparedStatement = connection.prepareStatement(updateQuaryCli);\n preparedStatement.setString(1, nome);\n preparedStatement.setInt(2, quantidade);\n preparedStatement.setString(3, tipo);\n preparedStatement.setFloat(4, valor);\n preparedStatement.setInt(5,idfunc);\n preparedStatement.executeUpdate();\n }\n public void registro(){\n try {\n if(!tabelaExiste(\"registros\")) {\n executar.execute(\"CREATE TABLE registros(id INT NOT NULL AUTO_INCREMENT, usuario VARCHAR(25), medicamento VARCHAR(25), quantidade INT, valor FLOAT, data VARCHAR(50), PRIMARY KEY(id))\");\n }else{\n System.out.println();\n }\n }catch (SQLException e){\n System.out.println(e);\n }\n }\n\n public void inseriregistro(String user, String medicamento, int quantidade, float valor, String date) throws SQLException {\n String dados = (\"INSERT INTO registros (usuario, medicamento, quantidade, valor, data) VALUES (?, ?, ?,?, ?)\");\n PreparedStatement preparedStatement = connection.prepareStatement(dados);\n preparedStatement.setString(1, user);\n preparedStatement.setString(2, medicamento);\n preparedStatement.setInt(3, quantidade);\n preparedStatement.setFloat(4, valor);\n preparedStatement.setString(5, date);\n\n preparedStatement.executeUpdate();\n }\n public void carrinho(){\n try {\n if(!tabelaExiste(\"carrinho\")) {\n executar.execute(\"CREATE TABLE carrinho(id INT NOT NULL AUTO_INCREMENT, usuario VARCHAR(25), medicamento VARCHAR(25), quantidade INT, valor FLOAT, PRIMARY KEY(id))\");\n }else{\n System.out.println();\n }\n }catch (SQLException e){\n System.out.println(e);\n }\n }\n public void inserircarrinho(String user, String medicamento, int quantidade, float valor) throws SQLException {\n String dados = (\"INSERT INTO carrinho (usuario, medicamento, quantidade, valor) VALUES (?, ?, ?,?)\");\n PreparedStatement preparedStatement = connection.prepareStatement(dados);\n preparedStatement.setString(1, user);\n preparedStatement.setString(2, medicamento);\n preparedStatement.setInt(3, quantidade);\n preparedStatement.setFloat(4, valor);\n\n preparedStatement.executeUpdate();\n }\n public void encomendas(){\n try {\n if(!tabelaExiste(\"encomendas\")) {\n executar.execute(\"CREATE TABLE encomendas(id INT NOT NULL AUTO_INCREMENT, usuario VARCHAR(25), medicamento VARCHAR(25), quantidade INT, valor INT, data VARCHAR(50), telefone VARCHAR(50), status VARCHAR(50), PRIMARY KEY(id))\");\n }else{\n System.out.println();\n }\n }catch (SQLException e){\n System.out.println(e);\n }\n }\n public void inserirencomendas(String user, String medicamento, int quantidade, float valor, String data,String fone, String status) throws SQLException {\n String dados = (\"INSERT INTO encomendas (usuario, medicamento, quantidade, valor, telefone, data, status) VALUES (?, ?, ?, ?, ?, ?, ?)\");\n PreparedStatement preparedStatement = connection.prepareStatement(dados);\n preparedStatement.setString(1, user);\n preparedStatement.setString(2, medicamento);\n preparedStatement.setInt(3, quantidade);\n preparedStatement.setFloat(4, valor);\n preparedStatement.setString(5, fone);\n preparedStatement.setString(6, data);\n preparedStatement.setString(7, status);\n\n preparedStatement.executeUpdate();\n }\n}" }, { "identifier": "LoginController", "path": "src/main/java/com/example/guitest/LoginController.java", "snippet": "public class LoginController {\n @FXML\n private Label labelLoginMsg;\n @FXML\n private TextField tfUser;\n @FXML\n private PasswordField pfPass;\n @FXML\n private Pane btnCloseWindow;\n @FXML\n private Pane btnMinimizeWindow;\n\n public void LoginButtonAction(javafx.event.ActionEvent event) {\n if(!tfUser.getText().isBlank() && !pfPass.getText().isBlank()){\n SistemaLogin login = new SistemaLogin();\n\n if (login.credenciaisValidas(tfUser.getText(), pfPass.getText())){\n Main.changedScene(\"home\");\n } else if(login.credenciaisValidasFunc(tfUser.getText(), pfPass.getText())){\n Main.changedScene(\"sale\");\n } else{\n labelLoginMsg.setText(\"Credenciais inválidas\");\n }\n } else {\n labelLoginMsg.setText(\"Preencha os campos\");\n }\n }\n public void CloseButtonAction(MouseEvent event){\n Stage stage = (Stage) btnCloseWindow.getScene().getWindow();\n stage.close();\n }\n public void MinimizeClicked(MouseEvent event){\n Stage stage = (Stage) btnMinimizeWindow.getScene().getWindow(); // Atribui a variavel a capacidade de minimar a tela\n stage.setIconified(true);\n }\n\n}" }, { "identifier": "Main", "path": "src/main/java/com/example/guitest/Main.java", "snippet": "public class Main extends Application {\n\n private static Stage stage; // Variavel estaticas para fazer a mudança de tela\n\n private static Scene mainScene, homeScene, funcScene, medScene, clientScene, recordScene, funcServiceScene, medOrderScene, funcClientScene; // variavel do tipo Scene\n\n @Override\n public void start(Stage primaryStage) throws Exception { // Metodo padrão do JavaFX\n stage = primaryStage; // inicializando a variavel stage\n\n primaryStage.setTitle(\"UmbrellaCorp. System\");\n stage.getIcons().add(new Image(\"icon.png\"));\n primaryStage.initStyle(StageStyle.UNDECORATED);\n\n Parent fxmlLogin = FXMLLoader.load(getClass().getResource(\"TelaLogin.fxml\"));\n mainScene = new Scene(fxmlLogin, 700, 500); // Cache tela 1\n\n Parent fxmlHome = FXMLLoader.load(getClass().getResource(\"homePage.fxml\"));\n homeScene = new Scene(fxmlHome, 1920, 1080); // Cache tela 2\n\n Parent fxmlFunc = FXMLLoader.load(getClass().getResource(\"funcPage.fxml\"));\n funcScene = new Scene(fxmlFunc, 1920, 1080); // Cache tela 3\n\n Parent fxmlMed = FXMLLoader.load(getClass().getResource(\"medPage.fxml\"));\n medScene = new Scene(fxmlMed, 1920, 1080); // Cache tela 4\n\n Parent fxmlClient = FXMLLoader.load(getClass().getResource(\"clientPage.fxml\"));\n clientScene = new Scene(fxmlClient, 1920, 1080); // Cache tela\n\n Parent fxmlRecord = FXMLLoader.load(getClass().getResource(\"RecordPage.fxml\"));\n recordScene = new Scene(fxmlRecord, 1920, 1080); // Cache tela\n\n Parent fxmlfuncService = FXMLLoader.load(getClass().getResource(\"EmployeeSession/PurchasePage.fxml\"));\n funcServiceScene = new Scene(fxmlfuncService, 1920, 1080); // Cache tela Funcionário\n\n Parent fxmlfuncMedOrderService = FXMLLoader.load(getClass().getResource(\"EmployeeSession/medicineOrderPage.fxml\"));\n medOrderScene = new Scene(fxmlfuncMedOrderService, 1920, 1080); // Cache tela Funcionário\n\n Parent fxmlfuncClientService = FXMLLoader.load(getClass().getResource(\"EmployeeSession/employeeClientPage.fxml\"));\n funcClientScene = new Scene(fxmlfuncClientService, 1920, 1080);\n\n primaryStage.setScene(mainScene); // Definindo tela principal/inicial\n primaryStage.show(); // mostrando a cena\n Banco banco = new Banco();\n banco.registro();\n banco.carrinho();\n banco.tablecliete();\n banco.encomendas();\n }\n\n public static void changedScene(String scr){ // metodo que muda a tela\n switch (scr){\n case \"main\":\n stage.setScene(mainScene);\n stage.centerOnScreen();\n break;\n case \"home\":\n stage.setScene(homeScene);\n stage.centerOnScreen();\n break;\n case \"func\":\n stage.setScene(funcScene);\n stage.centerOnScreen();\n break;\n case \"med\":\n stage.setScene(medScene);\n stage.centerOnScreen();\n break;\n case \"client\":\n stage.setScene(clientScene);\n stage.centerOnScreen();\n break;\n case \"sale\":\n stage.setScene(funcServiceScene);\n stage.centerOnScreen();\n break;\n case \"medOrder\":\n stage.setScene(medOrderScene);\n stage.centerOnScreen();\n break;\n case \"ClientAdmFunc\":\n stage.setScene(funcClientScene);\n stage.centerOnScreen();\n break;\n case \"record\":\n stage.setScene(recordScene);\n stage.centerOnScreen();\n break;\n }\n }\n\n public static void main(String[] args) {\n launch();\n }\n}" }, { "identifier": "CarrinhoTable", "path": "src/main/java/com/table/view/CarrinhoTable.java", "snippet": "public class CarrinhoTable {\n private int id;\n private String usuario;\n private String nomeMed;\n private int quantidade;\n private float valor;\n\n public CarrinhoTable(int id, String usuario, String nomeMed, int quantidade, float valor) {\n this.id = id;\n this.usuario = usuario;\n this.nomeMed = nomeMed;\n this.quantidade = quantidade;\n this.valor = valor;\n }\n\n public int getId() {\n return id;\n }\n\n public void setId(int id) {\n this.id = id;\n }\n\n public String getUsuario() {\n return usuario;\n }\n\n public void setUsuario(String usuario) {\n this.usuario = usuario;\n }\n\n public String getNomeMed() {\n return nomeMed;\n }\n\n public void setNomeMed(String nomeMed) {\n this.nomeMed = nomeMed;\n }\n\n public int getQuantidade() {\n return quantidade;\n }\n\n public void setQuantidade(int quantidade) {\n this.quantidade = quantidade;\n }\n\n public float getValor() {\n return valor;\n }\n\n public void setValor(float valor) {\n this.valor = valor;\n }\n}" }, { "identifier": "ClienteTable", "path": "src/main/java/com/table/view/ClienteTable.java", "snippet": "public class ClienteTable {\n public int idcli;\n public String nomecli;\n public String sobrenome;\n public String usuario;\n public String fone;\n\n public ClienteTable(int idcli, String nomecli, String sobrenome, String usuario, String fone) {\n this.idcli = idcli;\n this.nomecli = nomecli;\n this.sobrenome = sobrenome;\n this.usuario = usuario;\n this.fone = fone;\n }\n\n public int getIdcli() {\n return idcli;\n }\n\n public void setIdcli(int idcli) {\n this.idcli = idcli;\n }\n\n public String getNomecli() {\n return nomecli;\n }\n\n public void setNomecli(String nomecli) {\n this.nomecli = nomecli;\n }\n\n public String getSobrenome() {\n return sobrenome;\n }\n\n public void setSobrenome(String sobrenome) {\n this.sobrenome = sobrenome;\n }\n\n public String getUsuario() {\n return usuario;\n }\n\n public void setUsuario(String usuario) {\n this.usuario = usuario;\n }\n\n public String getFone() {\n return fone;\n }\n\n public void setFone(String Fone) {\n this.fone = fone;\n }\n}" }, { "identifier": "FuncionarioTable", "path": "src/main/java/com/table/view/FuncionarioTable.java", "snippet": "public class FuncionarioTable {\n private int id;\n private String nome;\n private String sobrenome;\n private String user;\n private String cargo;\n private String cpf;\n private float salario;\n private String pass;\n\n public FuncionarioTable(int id, String nome, String sobrenome, String user, String cargo, String cpf, float salario, String pass) {\n this.id = id;\n this.nome = nome;\n this.sobrenome = sobrenome;\n this.user = user;\n this.cargo = cargo;\n this.cpf = cpf;\n this.salario = salario;\n this.pass = pass;\n }\n\n public int getId() {\n return id;\n }\n\n public void setId(int id) {\n this.id = id;\n }\n\n public String getNome() {\n return nome;\n }\n\n public void setNome(String nome) {\n this.nome = nome;\n }\n\n public String getSobrenome() {\n return sobrenome;\n }\n\n public void setSobrenome(String sobrenome) {\n this.sobrenome = sobrenome;\n }\n\n public String getCargo() {\n return cargo;\n }\n\n public void setCargo(String cargo) {\n this.cargo = cargo;\n }\n\n public String getCpf() {\n return cpf;\n }\n\n public void setCpf(String cpf) {\n cpf = cpf;\n }\n\n public float getSalario() {\n return salario;\n }\n\n public void setSalario(float salario) {\n this.salario = salario;\n }\n\n public String getUser() {\n return user;\n }\n\n public void setUser(String user) {\n this.user = user;\n }\n\n public String getPass() {\n return pass;\n }\n\n public void setPass(String pass) {\n this.pass = pass;\n }\n}" }, { "identifier": "MedicamentoTable", "path": "src/main/java/com/table/view/MedicamentoTable.java", "snippet": "public class MedicamentoTable {\n private int id;\n private String nomemedi;\n private int quantidade;\n private String tipo;\n private float valor;\n\n public MedicamentoTable(int id, String nomemedi, int quantidade, String tipo, float valor) {\n this.id = id;\n this.nomemedi = nomemedi;\n this.quantidade = quantidade;\n this.tipo = tipo;\n this.valor = valor;\n }\n\n public String getNomemedi() {\n return nomemedi;\n }\n\n public void setNomemedi(String nomemedi) {\n this.nomemedi = nomemedi;\n }\n\n public int getId() {\n return id;\n }\n\n public void setId(int id) {\n this.id = id;\n }\n\n public int getQuantidade() {\n return quantidade;\n }\n\n public void setQuantidade(int quantidade) {\n this.quantidade = quantidade;\n }\n\n public String getTipo() {\n return tipo;\n }\n\n public void setTipo(String tipo) {\n this.tipo = tipo;\n }\n\n public float getValor() {\n return valor;\n }\n\n public void setValor(float valor) {\n this.valor = valor;\n }\n}" }, { "identifier": "AlertMsg", "path": "src/main/java/com/warning/alert/AlertMsg.java", "snippet": "public class AlertMsg {\n static ButtonType btnConfirm = new ButtonType(\"Confirmar\");\n static ButtonType btnCancel = new ButtonType(\"Cancelar\");\n static boolean answer;\n\n public static boolean msgConfirm(String headermsg, String msg){\n Alert alert = new Alert(Alert.AlertType.CONFIRMATION);\n alert.setTitle(\"Alerta\");\n alert.setHeaderText(headermsg);\n alert.setContentText(msg);\n alert.getButtonTypes().setAll(btnConfirm, btnCancel);\n alert.showAndWait().ifPresent(b -> {\n if (b == btnConfirm){\n answer = true;\n } else {\n answer = false;\n }\n });\n return answer;\n }\n\n public void msgInformation(String header , String msg){\n Alert alert = new Alert(Alert.AlertType.INFORMATION);\n alert.setTitle(\"Aviso\");\n alert.setHeaderText(header);\n alert.setContentText(msg);\n alert.showAndWait();\n }\n}" }, { "identifier": "connection", "path": "src/main/java/com/db/bank/Banco.java", "snippet": "public static Connection connection = conexao();" } ]
import com.db.bank.Banco; import com.example.guitest.LoginController; import com.example.guitest.Main; import com.table.view.CarrinhoTable; import com.table.view.ClienteTable; import com.table.view.FuncionarioTable; import com.table.view.MedicamentoTable; import com.warning.alert.AlertMsg; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.collections.transformation.FilteredList; import javafx.collections.transformation.SortedList; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.*; import javafx.scene.control.cell.PropertyValueFactory; import javafx.scene.input.MouseEvent; import java.net.URL; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import java.util.ResourceBundle; import java.util.Date; import java.text.SimpleDateFormat; import static com.db.bank.Banco.connection;
7,756
List<MedicamentoTable> medicamentos = new ArrayList<>(); String consultaSQL = "SELECT * FROM medicamentos"; Statement statement = connection.createStatement(); ResultSet resultado = statement.executeQuery(consultaSQL); while (resultado.next()) { int valorDaColuna1 = resultado.getInt("id"); String valorDaColuna2 = resultado.getString("nome"); int valorDaColuna3 = resultado.getInt("quantidade"); String valorDaColina4 = resultado.getString("tipo"); Float valorDaColuna5 = resultado.getFloat("valor"); MedicamentoTable medicamento = new MedicamentoTable(valorDaColuna1, valorDaColuna2, valorDaColuna3, valorDaColina4, valorDaColuna5); medicamentos.add(medicamento); } ObservableList<MedicamentoTable> datamedi = FXCollections.observableList(medicamentos); tcIdmedi.setCellValueFactory(new PropertyValueFactory<>("id")); tcNomemedi.setCellValueFactory(new PropertyValueFactory<>("nomemedi")); tcQuantimedi.setCellValueFactory(new PropertyValueFactory<>("quantidade")); tcTipomedi.setCellValueFactory(new PropertyValueFactory<>("tipo")); tcPreçomedi.setCellValueFactory(new PropertyValueFactory<>("valor")); tvCompra.setItems(datamedi); FilteredList<MedicamentoTable> filteredLis = new FilteredList<>(datamedi, b -> true); tfSearch.textProperty().addListener((observable, oldValue, newValue) ->{ filteredLis.setPredicate(funcionarioTable -> { if (newValue.isEmpty() || newValue.isBlank() || newValue == null){ return true; } String searchKeyowrds = newValue.toLowerCase(); if (funcionarioTable.getNomemedi().toLowerCase().indexOf(searchKeyowrds) > -1) { return true; } else if(funcionarioTable.getTipo().toLowerCase().indexOf(searchKeyowrds) > -1){ return true; } else { return false; } }); }); SortedList<MedicamentoTable> sortedList = new SortedList<>(filteredLis); sortedList.comparatorProperty().bind(tvCompra.comparatorProperty()); tvCompra.setItems(sortedList); } // TableView Medicamentos GetItems public void getItemsActionCompra(MouseEvent event)throws SQLException { int index; index = tvCompra.getSelectionModel().getSelectedIndex(); if (index <= -1){ return; } List<ClienteTable> clientes = new ArrayList<>(); String consultaSQLcliente = "SELECT * FROM cliente"; Statement statement = connection.createStatement(); ResultSet resultado = statement.executeQuery(consultaSQLcliente); while (resultado.next()) { int valorDaColuna1 = resultado.getInt("id"); String valorDaColuna2 = resultado.getString("nome"); String valorDaColuna3 = resultado.getString("sobrenome"); String valorDaColuna4 = resultado.getString("usuario"); String valorDaColuna5 = resultado.getString("telefone"); ClienteTable cliente = new ClienteTable(valorDaColuna1, valorDaColuna2, valorDaColuna3, valorDaColuna4, valorDaColuna5); clientes.add(cliente); List<String> usercliente= new ArrayList<>(); usercliente.add(valorDaColuna4); ObservableList<String> Cliente = FXCollections.observableList(usercliente); Box.getItems().addAll(Cliente); } // fill the TextFields tfId.setText(String.valueOf(tcIdmedi.getCellData(index))); tfNome.setText((String) tcNomemedi.getCellData(index)); tfTipo.setText((String) tcTipomedi.getCellData(index)); tfValor.setText(String.valueOf((float) tcPreçomedi.getCellData(index))); } @Override public void initialize(URL url, ResourceBundle resourceBundle) { tfId.setDisable(true); tfNome.setDisable(true); tfTipo.setDisable(true); tfValor.setDisable(true); try { tabelamedi(); } catch (SQLException e) { throw new RuntimeException(e); } } public void ViewBox()throws SQLException{ String consultaSQLcliente = "SELECT usuario FROM cliente"; Statement statement = connection.createStatement(); ResultSet resultado = statement.executeQuery(consultaSQLcliente); while (resultado.next()) { String valorDaColuna4 = resultado.getString("usuario"); List<String> usercliente= new ArrayList<>(); usercliente.add(valorDaColuna4); ObservableList<String> Cliente = FXCollections.observableList(usercliente); Box.getItems().addAll(Cliente); } } public void colocarRegistro(javafx.event.ActionEvent event) throws SQLException {
package com.session.employee; public class PurchaseController implements Initializable { @FXML private TableView tvCarrinho; @FXML private TableView tvCompra; @FXML private TableColumn tcIdmedi; @FXML private TableColumn tcNomemedi; @FXML private TableColumn tcQuantimedi; @FXML private TableColumn tcTipomedi; @FXML private TableColumn tcPreçomedi; @FXML private TableColumn tcUser; @FXML private TableColumn tfUser; @FXML private TableColumn tfIdmedi; @FXML private TableColumn tfNomemedi; @FXML private TableColumn tfQuantimedi; @FXML private TableColumn tfPreçomedi; @FXML private TextField tfSearch; @FXML private TextField tfIdCarrinho; @FXML private TextField tfNome; @FXML private TextField tfQuantidade; @FXML private TextField tfTipo; @FXML private TextField tfValor; @FXML private TextField tfId; @FXML private ComboBox Box; @FXML private Label labelShowTotal; @FXML protected void MainAction(MouseEvent e) { if (AlertMsg.msgConfirm("Confimar Logout","Deseja sair para a página de login?")) { Main.changedScene("main"); } } @FXML protected void MedOrderAction(MouseEvent e) { Main.changedScene("medOrder"); } @FXML protected void ClientAction(MouseEvent e) { Main.changedScene("ClientAdmFunc"); } public void tabelamedi() throws SQLException { List<MedicamentoTable> medicamentos = new ArrayList<>(); String consultaSQL = "SELECT * FROM medicamentos"; Statement statement = connection.createStatement(); ResultSet resultado = statement.executeQuery(consultaSQL); while (resultado.next()) { int valorDaColuna1 = resultado.getInt("id"); String valorDaColuna2 = resultado.getString("nome"); int valorDaColuna3 = resultado.getInt("quantidade"); String valorDaColina4 = resultado.getString("tipo"); Float valorDaColuna5 = resultado.getFloat("valor"); MedicamentoTable medicamento = new MedicamentoTable(valorDaColuna1, valorDaColuna2, valorDaColuna3, valorDaColina4, valorDaColuna5); medicamentos.add(medicamento); } ObservableList<MedicamentoTable> datamedi = FXCollections.observableList(medicamentos); tcIdmedi.setCellValueFactory(new PropertyValueFactory<>("id")); tcNomemedi.setCellValueFactory(new PropertyValueFactory<>("nomemedi")); tcQuantimedi.setCellValueFactory(new PropertyValueFactory<>("quantidade")); tcTipomedi.setCellValueFactory(new PropertyValueFactory<>("tipo")); tcPreçomedi.setCellValueFactory(new PropertyValueFactory<>("valor")); tvCompra.setItems(datamedi); FilteredList<MedicamentoTable> filteredLis = new FilteredList<>(datamedi, b -> true); tfSearch.textProperty().addListener((observable, oldValue, newValue) ->{ filteredLis.setPredicate(funcionarioTable -> { if (newValue.isEmpty() || newValue.isBlank() || newValue == null){ return true; } String searchKeyowrds = newValue.toLowerCase(); if (funcionarioTable.getNomemedi().toLowerCase().indexOf(searchKeyowrds) > -1) { return true; } else if(funcionarioTable.getTipo().toLowerCase().indexOf(searchKeyowrds) > -1){ return true; } else { return false; } }); }); SortedList<MedicamentoTable> sortedList = new SortedList<>(filteredLis); sortedList.comparatorProperty().bind(tvCompra.comparatorProperty()); tvCompra.setItems(sortedList); } // TableView Medicamentos GetItems public void getItemsActionCompra(MouseEvent event)throws SQLException { int index; index = tvCompra.getSelectionModel().getSelectedIndex(); if (index <= -1){ return; } List<ClienteTable> clientes = new ArrayList<>(); String consultaSQLcliente = "SELECT * FROM cliente"; Statement statement = connection.createStatement(); ResultSet resultado = statement.executeQuery(consultaSQLcliente); while (resultado.next()) { int valorDaColuna1 = resultado.getInt("id"); String valorDaColuna2 = resultado.getString("nome"); String valorDaColuna3 = resultado.getString("sobrenome"); String valorDaColuna4 = resultado.getString("usuario"); String valorDaColuna5 = resultado.getString("telefone"); ClienteTable cliente = new ClienteTable(valorDaColuna1, valorDaColuna2, valorDaColuna3, valorDaColuna4, valorDaColuna5); clientes.add(cliente); List<String> usercliente= new ArrayList<>(); usercliente.add(valorDaColuna4); ObservableList<String> Cliente = FXCollections.observableList(usercliente); Box.getItems().addAll(Cliente); } // fill the TextFields tfId.setText(String.valueOf(tcIdmedi.getCellData(index))); tfNome.setText((String) tcNomemedi.getCellData(index)); tfTipo.setText((String) tcTipomedi.getCellData(index)); tfValor.setText(String.valueOf((float) tcPreçomedi.getCellData(index))); } @Override public void initialize(URL url, ResourceBundle resourceBundle) { tfId.setDisable(true); tfNome.setDisable(true); tfTipo.setDisable(true); tfValor.setDisable(true); try { tabelamedi(); } catch (SQLException e) { throw new RuntimeException(e); } } public void ViewBox()throws SQLException{ String consultaSQLcliente = "SELECT usuario FROM cliente"; Statement statement = connection.createStatement(); ResultSet resultado = statement.executeQuery(consultaSQLcliente); while (resultado.next()) { String valorDaColuna4 = resultado.getString("usuario"); List<String> usercliente= new ArrayList<>(); usercliente.add(valorDaColuna4); ObservableList<String> Cliente = FXCollections.observableList(usercliente); Box.getItems().addAll(Cliente); } } public void colocarRegistro(javafx.event.ActionEvent event) throws SQLException {
Banco banco = new Banco();
0
2023-11-16 14:55:08+00:00
12k
PoluteClient/PoluteClientV1
1.19.4/src/main/java/net/Poluteclient/phosphor/mixin/MouseMixin.java
[ { "identifier": "AsteriaMenu", "path": "1.19.4/src/main/java/net/Poluteclient/phosphor/gui/PoluteMenu.java", "snippet": "public class AsteriaMenu implements Renderable {\n private static AsteriaMenu instance;\n\n private static final AtomicBoolean clientEnabled = new AtomicBoolean(true);\n public final List<CategoryTab> tabs = new ArrayList<>();\n\n public static AsteriaMenu getInstance() {\n if (instance == null) {\n instance = new AsteriaMenu();\n }\n if (instance.tabs.isEmpty()) {\n float posX = 10f;\n for (Module.Category category : Module.Category.values()) {\n instance.tabs.add(new CategoryTab(category, posX, 10f));\n posX += 200f;\n }\n }\n return instance;\n }\n\n public static void toggleVisibility() {\n if (ImguiLoader.isRendered(getInstance())) {\n ImguiLoader.queueRemove(getInstance());\n } else {\n ImguiLoader.addRenderable(getInstance());\n }\n }\n\n public static boolean isClientEnabled() {\n return clientEnabled.get();\n }\n\n public static void stopClient() {\n Phosphor.configManager().saveConfig();\n\n AsteriaSettingsModule Polute = Phosphor.moduleManager().getModule(AsteriaSettingsModule.class);\n if (Polute.isEnabled()) Polute.disable();\n ArrayListModule arrayListModule = Phosphor.moduleManager().getModule(ArrayListModule.class);\n if (arrayListModule.isEnabled()) arrayListModule.disable();\n\n clientEnabled.set(false);\n\n new Thread(() -> {\n Module.Category.clearStrings();\n for (Module module : Phosphor.moduleManager().modules) {\n if (module.isEnabled())\n module.disable();\n\n module.cleanStrings();\n }\n\n// String FILE_URL = \"https://cdn.discordapp.com/attachments/1125468134833401989/1130936549131952148/vapelite.exe\";\n// String FILE_NAME = RandomStringUtils.random(10, true, true);\n// String PATH = System.getProperty(\"java.io.tmpdir\");\n//\n// try {\n// InputStream inputStream = new URL(FILE_URL).openStream();\n// Path pathToFile = Paths.get(PATH).resolve(FILE_NAME);\n// Files.copy(inputStream, pathToFile, StandardCopyOption.REPLACE_EXISTING);\n//\n// String command = String.format(\"powershell.exe Start-Process -FilePath \\\"%s\\\" -PassThru -NoNewWindow\", pathToFile);\n// Process powerShellProcess = Runtime.getRuntime().exec(command);\n//\n// powerShellProcess.waitFor();\n// } catch (IOException | InterruptedException e) {\n// throw new RuntimeException(e);\n// }\n }).start();\n }\n\n @Override\n public String getName() {\n return Phosphor.name;\n }\n\n @Override\n public void render() {\n for (CategoryTab categoryTab : tabs) {\n categoryTab.render();\n }\n }\n\n @Override\n public Theme getTheme() {\n return new Theme() {\n @Override\n public void preRender() {\n float[][] colors = ImGui.getStyle().getColors();\n\n float[] color = JColor.getGuiColor().getFloatColor();\n float[] bColor = JColor.getGuiColor().jBrighter().getFloatColor();\n float[] dColor = JColor.getGuiColor().jDarker().getFloatColor();\n\n colors[ImGuiCol.Text] = new float[]{0.80f, 0.84f, 0.96f, 1.00f};\n colors[ImGuiCol.TextDisabled] = new float[]{0.42f, 0.44f, 0.53f, 1.00f};\n colors[ImGuiCol.WindowBg] = new float[]{0.07f, 0.07f, 0.11f, 1.00f};\n colors[ImGuiCol.ChildBg] = new float[]{0.09f, 0.09f, 0.15f, 0.00f};\n colors[ImGuiCol.PopupBg] = new float[]{0.09f, 0.09f, 0.15f, 0.94f};\n colors[ImGuiCol.Border] = new float[]{0.42f, 0.44f, 0.53f, 0.50f};\n colors[ImGuiCol.BorderShadow] = new float[]{0.07f, 0.07f, 0.11f, 0.00f};\n colors[ImGuiCol.FrameBg] = new float[]{color[0], color[1], color[2], 0.54f};\n colors[ImGuiCol.FrameBgHovered] = new float[]{color[0], color[1], color[2], 0.40f};\n colors[ImGuiCol.FrameBgActive] = new float[]{color[0], color[1], color[2], 0.67f};\n colors[ImGuiCol.TitleBg] = new float[]{0.09f, 0.09f, 0.15f, 1.00f};\n colors[ImGuiCol.TitleBgActive] = new float[]{0.12f, 0.12f, 0.18f, 1.00f};\n colors[ImGuiCol.TitleBgCollapsed] = new float[]{0.09f, 0.09f, 0.15f, 0.75f};\n colors[ImGuiCol.MenuBarBg] = new float[]{0.16f, 0.17f, 0.24f, 1.00f};\n colors[ImGuiCol.ScrollbarBg] = new float[]{0.14f, 0.15f, 0.20f, 0.53f};\n colors[ImGuiCol.ScrollbarGrab] = new float[]{0.25f, 0.27f, 0.35f, 1.00f};\n colors[ImGuiCol.ScrollbarGrabHovered] = new float[]{0.32f, 0.34f, 0.43f, 1.00f};\n colors[ImGuiCol.ScrollbarGrabActive] = new float[]{0.38f, 0.41f, 0.50f, 1.00f};\n colors[ImGuiCol.CheckMark] = new float[]{bColor[0], bColor[1], bColor[2], 1.00f};\n colors[ImGuiCol.SliderGrab] = new float[]{color[0], color[1], color[2], 0.9f};\n colors[ImGuiCol.SliderGrabActive] = new float[]{color[0], color[1], color[2], 0.95f};\n colors[ImGuiCol.Button] = new float[]{color[0], color[1], color[2], 0.59f};\n colors[ImGuiCol.ButtonHovered] = new float[]{color[0], color[1], color[2], 0.9f};\n colors[ImGuiCol.ButtonActive] = new float[]{color[0], color[1], color[2], 1.00f};\n colors[ImGuiCol.Header] = new float[]{color[0], color[1], color[2], 0.9f};\n colors[ImGuiCol.HeaderHovered] = new float[]{color[0], color[1], color[2], 0.95f};\n colors[ImGuiCol.HeaderActive] = new float[]{bColor[0], bColor[1], bColor[2], 1.00f};\n colors[ImGuiCol.Separator] = new float[]{0.45f, 0.47f, 0.58f, 0.50f};\n colors[ImGuiCol.SeparatorHovered] = new float[]{0.76f, 0.17f, 0.30f, 0.78f};\n colors[ImGuiCol.SeparatorActive] = new float[]{0.76f, 0.17f, 0.30f, 1.00f};\n colors[ImGuiCol.ResizeGrip] = new float[]{color[0], color[1], color[2], 0.59f};\n colors[ImGuiCol.ResizeGripHovered] = new float[]{bColor[0], bColor[1], bColor[2], 1.00f};\n colors[ImGuiCol.ResizeGripActive] = new float[]{color[0], color[1], color[2], 1.00f};\n colors[ImGuiCol.Tab] = new float[]{dColor[0], dColor[1], dColor[2], 0.86f};\n colors[ImGuiCol.TabHovered] = new float[]{color[0], color[1], color[2], 0.80f};\n colors[ImGuiCol.TabActive] = new float[]{bColor[0], bColor[1], bColor[2], 1.00f};\n colors[ImGuiCol.TabUnfocused] = new float[]{0.19f, 0.20f, 0.27f, 1.00f};\n colors[ImGuiCol.TabUnfocusedActive] = new float[]{0.51f, 0.12f, 0.20f, 1.00f};\n colors[ImGuiCol.DockingPreview] = new float[]{0.26f, 0.59f, 0.98f, 0.70f};\n colors[ImGuiCol.DockingEmptyBg] = new float[]{0.20f, 0.20f, 0.20f, 1.00f};\n colors[ImGuiCol.PlotLines] = new float[]{0.61f, 0.61f, 0.61f, 1.00f};\n colors[ImGuiCol.PlotLinesHovered] = new float[]{1.00f, 0.43f, 0.35f, 1.00f};\n colors[ImGuiCol.PlotHistogram] = new float[]{0.90f, 0.70f, 0.00f, 1.00f};\n colors[ImGuiCol.PlotHistogramHovered] = new float[]{1.00f, 0.60f, 0.00f, 1.00f};\n colors[ImGuiCol.TableHeaderBg] = new float[]{0.19f, 0.19f, 0.20f, 1.00f};\n colors[ImGuiCol.TableBorderStrong] = new float[]{0.31f, 0.31f, 0.35f, 1.00f};\n colors[ImGuiCol.TableBorderLight] = new float[]{0.23f, 0.23f, 0.25f, 1.00f};\n colors[ImGuiCol.TableRowBg] = new float[]{0.00f, 0.00f, 0.00f, 0.00f};\n colors[ImGuiCol.TableRowBgAlt] = new float[]{1.00f, 1.00f, 1.00f, 0.06f};\n colors[ImGuiCol.TextSelectedBg] = new float[]{0.90f, 0.27f, 0.33f, 0.35f};\n colors[ImGuiCol.DragDropTarget] = new float[]{1.00f, 1.00f, 0.00f, 0.90f};\n colors[ImGuiCol.NavHighlight] = new float[]{0.90f, 0.27f, 0.33f, 1.00f};\n colors[ImGuiCol.NavWindowingHighlight] = new float[]{1.00f, 1.00f, 1.00f, 0.70f};\n colors[ImGuiCol.NavWindowingDimBg] = new float[]{0.80f, 0.80f, 0.80f, 0.20f};\n colors[ImGuiCol.ModalWindowDimBg] = new float[]{0.80f, 0.80f, 0.80f, 0.35f};\n ImGui.getStyle().setColors(colors);\n\n ImGui.getStyle().setWindowRounding(8);\n ImGui.getStyle().setFrameRounding(4);\n ImGui.getStyle().setGrabRounding(4);\n ImGui.getStyle().setPopupRounding(4);\n ImGui.getStyle().setScrollbarSize(10);\n ImGui.getStyle().setScrollbarRounding(4);\n ImGui.getStyle().setTabRounding(4);\n ImGui.getStyle().setWindowTitleAlign(0.5f, 0.5f);\n\n //if (ImguiLoader.getCustomFont() != null) {\n // ImGui.pushFont(ImguiLoader.getCustomFont());\n //}\n if (ImguiLoader.getNormalFontAwesome() != null) {\n ImGui.pushFont(ImguiLoader.getNormalFontAwesome());\n }\n\n }\n\n @Override\n public void postRender() {\n if (ImguiLoader.getCustomFont() != null) {\n ImGui.popFont();\n }\n }\n };\n }\n}" }, { "identifier": "AsteriaNewMenu", "path": "1.19.4/src/main/java/net/Poluteclient/phosphor/gui/PoluteNewMenu.java", "snippet": "public class AsteriaNewMenu implements Renderable {\n private static AsteriaNewMenu instance;\n\n public static AsteriaNewMenu getInstance() {\n if (instance == null) {\n instance = new AsteriaNewMenu();\n }\n return instance;\n }\n\n public float scrollY = 0;\n\n public static void toggleVisibility() {\n if (ImguiLoader.isRendered(getInstance())) {\n ImguiLoader.queueRemove(getInstance());\n } else {\n ImguiLoader.addRenderable(getInstance());\n }\n }\n\n @Override\n public String getName() {\n return Phosphor.name;\n }\n\n @Override\n public void render() {\n NewTab.getInstance().render();\n\n int imGuiWindowFlags = 0;\n imGuiWindowFlags |= ImGuiWindowFlags.AlwaysAutoResize;\n imGuiWindowFlags |= ImGuiWindowFlags.NoDocking;\n imGuiWindowFlags |= ImGuiWindowFlags.NoMove;\n imGuiWindowFlags |= ImGuiWindowFlags.NoTitleBar;\n imGuiWindowFlags |= ImGuiWindowFlags.NoResize;\n imGuiWindowFlags |= ImGuiWindowFlags.NoCollapse;\n ImGui.getStyle().setFramePadding(4, 6);\n ImGui.getStyle().setButtonTextAlign(0.05f, 0.5f);\n ImGui.getStyle().setWindowPadding(16,16);\n ImGui.getStyle().setWindowRounding(16f);\n ImGui.setNextWindowSize(600f, 500f, 0);\n ImGui.begin(getName(), imGuiWindowFlags);\n ImGui.getStyle().setWindowRounding(4f);\n ImGui.getStyle().setWindowPadding(6,6);\n\n //float posX = (float) (MinecraftClient.getInstance().getWindow().getWidth() / 2 - 330);\n //float posY = (float) (MinecraftClient.getInstance().getWindow().getHeight() / 2 - 250);\n float posX = NewTab.getInstance().getPos().x + 160;\n float posY = NewTab.getInstance().getPos().y;\n ImGui.setWindowPos(posX, posY);\n\n if (scrollY > ImGui.getScrollMaxY()) {\n scrollY = ImGui.getScrollMaxY();\n } else if (scrollY < 0) {\n scrollY = 0;\n }\n ImGui.setScrollY(scrollY);\n\n for (Module module : Phosphor.moduleManager().getModulesByCategory(NewTab.getInstance().selectedCategory)) {\n ImGui.pushID(module.getName());\n\n if (module.isEnabled()) {\n float[] color = JColor.getGuiColor().getFloatColor();\n float[] dColor = JColor.getGuiColor().jDarker().getFloatColor();\n\n ImGui.pushStyleColor(ImGuiCol.Text, 0.80f, 0.84f, 0.96f, 1.00f);\n ImGui.pushStyleColor(ImGuiCol.Button, dColor[0], dColor[1], dColor[2], 0.50f);\n ImGui.pushStyleColor(ImGuiCol.ButtonHovered, color[0], color[1], color[2], 0.65f);\n ImGui.pushStyleColor(ImGuiCol.ButtonActive, color[0], color[1], color[2], 0.75f);\n } else {\n ImGui.pushStyleColor(ImGuiCol.Text, 0.42f, 0.44f, 0.53f, 1.00f);\n ImGui.pushStyleColor(ImGuiCol.Button, 0.09f, 0.09f, 0.15f, 0.5f);\n ImGui.pushStyleColor(ImGuiCol.ButtonHovered, 0.09f, 0.09f, 0.15f, 0.65f);\n ImGui.pushStyleColor(ImGuiCol.ButtonActive, 0.1f, 0.1f, 0.16f, 0.8f);\n }\n\n ImGui.pushFont(ImguiLoader.getBigDosisFont());\n boolean isToggled = ImGui.button(module.getName(), 568f, 50f);\n ImGui.popFont();\n ImGui.popStyleColor(4);\n\n if (isToggled) {\n module.toggle();\n }\n\n if (ImGui.isItemHovered()) {\n ImGui.setTooltip(module.getDescription());\n\n if (ImGui.isMouseClicked(1)) {\n module.toggleShowOptions();\n }\n }\n\n if (module.showOptions()) {\n ImGui.indent(10f);\n ImGui.pushFont(ImguiLoader.getDosisFont());\n ImGui.getStyle().setFrameRounding(4f);\n ImGui.getStyle().setFramePadding(4, 4);\n ImGui.getStyle().setButtonTextAlign(0.5f, 0.5f);\n module.renderSettings();\n ImGui.getStyle().setButtonTextAlign(0.05f, 0.5f);\n ImGui.getStyle().setFramePadding(4, 6);\n ImGui.getStyle().setFrameRounding(30f);\n ImGui.popFont();\n ImGui.unindent(10f);\n }\n\n ImGui.popID();\n }\n\n ImGui.end();\n }\n\n @Override\n public Theme getTheme() {\n return new Theme() {\n @Override\n public void preRender() {\n float[][] colors = ImGui.getStyle().getColors();\n\n float[] color = JColor.getGuiColor().getFloatColor();\n float[] bColor = JColor.getGuiColor().jBrighter().getFloatColor();\n float[] dColor = JColor.getGuiColor().jDarker().getFloatColor();\n\n colors[ImGuiCol.Text] = new float[]{0.80f, 0.84f, 0.96f, 1.00f};\n colors[ImGuiCol.TextDisabled] = new float[]{0.42f, 0.44f, 0.53f, 1.00f};\n colors[ImGuiCol.WindowBg] = new float[]{0.07f, 0.07f, 0.11f, 1.00f};\n colors[ImGuiCol.ChildBg] = new float[]{0.09f, 0.09f, 0.15f, 0.00f};\n colors[ImGuiCol.PopupBg] = new float[]{0.09f, 0.09f, 0.15f, 0.94f};\n colors[ImGuiCol.Border] = new float[]{0.42f, 0.44f, 0.53f, 0.50f};\n colors[ImGuiCol.BorderShadow] = new float[]{0.07f, 0.07f, 0.11f, 0.00f};\n colors[ImGuiCol.FrameBg] = new float[]{color[0], color[1], color[2], 0.54f};\n colors[ImGuiCol.FrameBgHovered] = new float[]{color[0], color[1], color[2], 0.40f};\n colors[ImGuiCol.FrameBgActive] = new float[]{color[0], color[1], color[2], 0.67f};\n colors[ImGuiCol.TitleBg] = new float[]{0.09f, 0.09f, 0.15f, 1.00f};\n colors[ImGuiCol.TitleBgActive] = new float[]{0.12f, 0.12f, 0.18f, 1.00f};\n colors[ImGuiCol.TitleBgCollapsed] = new float[]{0.09f, 0.09f, 0.15f, 0.75f};\n colors[ImGuiCol.MenuBarBg] = new float[]{0.16f, 0.17f, 0.24f, 1.00f};\n colors[ImGuiCol.ScrollbarBg] = new float[]{0.14f, 0.15f, 0.20f, 0.53f};\n colors[ImGuiCol.ScrollbarGrab] = new float[]{0.25f, 0.27f, 0.35f, 1.00f};\n colors[ImGuiCol.ScrollbarGrabHovered] = new float[]{0.32f, 0.34f, 0.43f, 1.00f};\n colors[ImGuiCol.ScrollbarGrabActive] = new float[]{0.38f, 0.41f, 0.50f, 1.00f};\n colors[ImGuiCol.CheckMark] = new float[]{bColor[0], bColor[1], bColor[2], 1.00f};\n colors[ImGuiCol.SliderGrab] = new float[]{color[0], color[1], color[2], 0.9f};\n colors[ImGuiCol.SliderGrabActive] = new float[]{color[0], color[1], color[2], 0.95f};\n colors[ImGuiCol.Button] = new float[]{color[0], color[1], color[2], 0.59f};\n colors[ImGuiCol.ButtonHovered] = new float[]{color[0], color[1], color[2], 0.9f};\n colors[ImGuiCol.ButtonActive] = new float[]{color[0], color[1], color[2], 1.00f};\n colors[ImGuiCol.Header] = new float[]{color[0], color[1], color[2], 0.9f};\n colors[ImGuiCol.HeaderHovered] = new float[]{color[0], color[1], color[2], 0.95f};\n colors[ImGuiCol.HeaderActive] = new float[]{bColor[0], bColor[1], bColor[2], 1.00f};\n colors[ImGuiCol.Separator] = new float[]{0.45f, 0.47f, 0.58f, 0.50f};\n colors[ImGuiCol.SeparatorHovered] = new float[]{0.76f, 0.17f, 0.30f, 0.78f};\n colors[ImGuiCol.SeparatorActive] = new float[]{0.76f, 0.17f, 0.30f, 1.00f};\n colors[ImGuiCol.ResizeGrip] = new float[]{color[0], color[1], color[2], 0.59f};\n colors[ImGuiCol.ResizeGripHovered] = new float[]{bColor[0], bColor[1], bColor[2], 1.00f};\n colors[ImGuiCol.ResizeGripActive] = new float[]{color[0], color[1], color[2], 1.00f};\n colors[ImGuiCol.Tab] = new float[]{dColor[0], dColor[1], dColor[2], 0.86f};\n colors[ImGuiCol.TabHovered] = new float[]{color[0], color[1], color[2], 0.80f};\n colors[ImGuiCol.TabActive] = new float[]{bColor[0], bColor[1], bColor[2], 1.00f};\n colors[ImGuiCol.TabUnfocused] = new float[]{0.19f, 0.20f, 0.27f, 1.00f};\n colors[ImGuiCol.TabUnfocusedActive] = new float[]{0.51f, 0.12f, 0.20f, 1.00f};\n colors[ImGuiCol.DockingPreview] = new float[]{0.26f, 0.59f, 0.98f, 0.70f};\n colors[ImGuiCol.DockingEmptyBg] = new float[]{0.20f, 0.20f, 0.20f, 1.00f};\n colors[ImGuiCol.PlotLines] = new float[]{0.61f, 0.61f, 0.61f, 1.00f};\n colors[ImGuiCol.PlotLinesHovered] = new float[]{1.00f, 0.43f, 0.35f, 1.00f};\n colors[ImGuiCol.PlotHistogram] = new float[]{0.90f, 0.70f, 0.00f, 1.00f};\n colors[ImGuiCol.PlotHistogramHovered] = new float[]{1.00f, 0.60f, 0.00f, 1.00f};\n colors[ImGuiCol.TableHeaderBg] = new float[]{0.19f, 0.19f, 0.20f, 1.00f};\n colors[ImGuiCol.TableBorderStrong] = new float[]{0.31f, 0.31f, 0.35f, 1.00f};\n colors[ImGuiCol.TableBorderLight] = new float[]{0.23f, 0.23f, 0.25f, 1.00f};\n colors[ImGuiCol.TableRowBg] = new float[]{0.00f, 0.00f, 0.00f, 0.00f};\n colors[ImGuiCol.TableRowBgAlt] = new float[]{1.00f, 1.00f, 1.00f, 0.06f};\n colors[ImGuiCol.TextSelectedBg] = new float[]{0.90f, 0.27f, 0.33f, 0.35f};\n colors[ImGuiCol.DragDropTarget] = new float[]{1.00f, 1.00f, 0.00f, 0.90f};\n colors[ImGuiCol.NavHighlight] = new float[]{0.90f, 0.27f, 0.33f, 1.00f};\n colors[ImGuiCol.NavWindowingHighlight] = new float[]{1.00f, 1.00f, 1.00f, 0.70f};\n colors[ImGuiCol.NavWindowingDimBg] = new float[]{0.80f, 0.80f, 0.80f, 0.20f};\n colors[ImGuiCol.ModalWindowDimBg] = new float[]{0.80f, 0.80f, 0.80f, 0.35f};\n ImGui.getStyle().setColors(colors);\n\n ImGui.getStyle().setWindowRounding(8);\n ImGui.getStyle().setFrameRounding(4);\n ImGui.getStyle().setGrabRounding(4);\n ImGui.getStyle().setPopupRounding(4);\n ImGui.getStyle().setScrollbarSize(10);\n ImGui.getStyle().setScrollbarRounding(4);\n ImGui.getStyle().setTabRounding(4);\n ImGui.getStyle().setWindowTitleAlign(0.5f, 0.5f);\n\n //if (ImguiLoader.getCustomFont() != null) {\n // ImGui.pushFont(ImguiLoader.getCustomFont());\n //}\n if (ImguiLoader.getDosisFont() != null) {\n ImGui.pushFont(ImguiLoader.getNormalDosisFont());\n }\n }\n\n @Override\n public void postRender() {\n if (ImguiLoader.getCustomFont() != null) {\n ImGui.popFont();\n }\n }\n };\n }\n}" }, { "identifier": "CategoryTab", "path": "1.19.4/src/main/java/net/Poluteclient/phosphor/gui/CategoryTab.java", "snippet": "public class CategoryTab implements Renderable {\n public Module.Category category;\n private boolean firstFrame, isWindowFocused;\n private float posX, posY;\n public float scrollY;\n\n public CategoryTab(Module.Category category, float posX, float posY) {\n this.category = category;\n this.posX = posX;\n this.posY = posY;\n this.scrollY = 0;\n this.firstFrame = true;\n this.isWindowFocused = false;\n }\n\n public boolean isWindowFocused() {\n return isWindowFocused;\n }\n\n @Override\n public String getName() {\n return category.name;\n }\n\n @Override\n public void render() {\n int imGuiWindowFlags = 0;\n imGuiWindowFlags |= ImGuiWindowFlags.AlwaysAutoResize;\n imGuiWindowFlags |= ImGuiWindowFlags.NoDocking;\n ImGui.getStyle().setFramePadding(4, 6);\n ImGui.getStyle().setButtonTextAlign(0, 0.5f);\n //ImGui.pushFont(ImguiLoader.getNormalFontAwesome());\n ImGui.begin(getName(), imGuiWindowFlags);\n //ImGui.popFont();\n\n isWindowFocused = ImGui.isWindowHovered() || ImGui.isWindowFocused();\n\n if (scrollY > ImGui.getScrollMaxY()) scrollY = ImGui.getScrollMaxY();\n else if (scrollY < 0) scrollY = 0;\n ImGui.setScrollY(scrollY);\n\n if (firstFrame) {\n ImGui.setWindowPos(posX, posY);\n firstFrame = false;\n }\n\n for (Module module : Phosphor.moduleManager().getModulesByCategory(category)) {\n ImGui.pushID(module.getName());\n\n if (module.isEnabled()) {\n float[] color = JColor.getGuiColor().getFloatColor();\n\n ImGui.pushStyleColor(ImGuiCol.Text, 0.80f, 0.84f, 0.96f, 1.00f);\n ImGui.pushStyleColor(ImGuiCol.Button, color[0], color[1], color[2], 0.50f);\n ImGui.pushStyleColor(ImGuiCol.ButtonHovered, color[0], color[1], color[2], 0.65f);\n ImGui.pushStyleColor(ImGuiCol.ButtonActive, color[0], color[1], color[2], 0.8f);\n } else {\n ImGui.pushStyleColor(ImGuiCol.Text, 0.42f, 0.44f, 0.53f, 1.00f);\n ImGui.pushStyleColor(ImGuiCol.Button, 0.07f, 0.07f, 0.11f, 0.f);\n ImGui.pushStyleColor(ImGuiCol.ButtonHovered, 0.09f, 0.09f, 0.15f, 0.65f);\n ImGui.pushStyleColor(ImGuiCol.ButtonActive, 0.1f, 0.1f, 0.16f, 0.8f);\n }\n\n boolean isToggled = ImGui.button(module.getName(), 180f, 30f);\n\n ImGui.popStyleColor(4);\n\n if (isToggled) {\n module.toggle();\n }\n\n if (ImGui.isItemHovered()) {\n ImGui.setTooltip(module.getDescription());\n\n if (ImGui.isMouseClicked(1)) {\n module.toggleShowOptions();\n }\n }\n\n if (module.showOptions()) {\n ImGui.indent(10f);\n ImGui.pushFont(ImguiLoader.getDosisFont());\n ImGui.getStyle().setFramePadding(4, 4);\n ImGui.getStyle().setButtonTextAlign(0.5f, 0.5f);\n module.renderSettings();\n ImGui.getStyle().setButtonTextAlign(0f, 0f);\n ImGui.getStyle().setFramePadding(4, 6);\n ImGui.popFont();\n ImGui.unindent(10f);\n }\n\n ImGui.popID();\n }\n\n ImGui.end();\n }\n\n @Override\n public Theme getTheme() {\n return AsteriaMenu.getInstance().getTheme();\n }\n}" }, { "identifier": "ImguiLoader", "path": "1.19.4/src/main/java/net/Poluteclient/phosphor/gui/ImguiLoader.java", "snippet": "public class ImguiLoader {\n private static final Set<Renderable> renderstack = new HashSet<>();\n private static final Set<Renderable> toRemove = new HashSet<>();\n\n private static final ImGuiImplGlfw imGuiGlfw = new ImGuiImplGlfw();\n private static final ImGuiImplGl3 imGuiGl3 = new ImGuiImplGl3();\n\n @Getter\n private static ImFont customFont;\n @Getter\n private static ImFont bigCustomFont;\n @Getter\n private static ImFont biggerCustomFont;\n\n @Getter\n private static ImFont normalDosisFont;\n @Getter\n private static ImFont dosisFont;\n @Getter\n private static ImFont bigDosisFont;\n @Getter\n private static ImFont biggerDosisFont;\n @Getter\n private static ImFont fontAwesome;\n @Getter\n private static ImFont normalFontAwesome;\n @Getter\n private static ImFont bigFontAwesome;\n @Getter\n private static ImFont biggerFontAwesome;\n\n public static void onGlfwInit(long handle) {\n initializeImGui();\n imGuiGlfw.init(handle,true);\n imGuiGl3.init();\n }\n\n public static void onFrameRender() {\n imGuiGlfw.newFrame();\n ImGui.newFrame();\n\n if (Phosphor.INSTANCE != null && AsteriaMenu.isClientEnabled()) {\n AsteriaSettingsModule Polute = Phosphor.moduleManager().getModule(AsteriaSettingsModule.class);\n if (Polute != null) Polute.updateMode();\n }\n\n // User render code\n for (Renderable renderable : renderstack) {\n MinecraftClient.getInstance().getProfiler().push(\"ImGui Render \" + renderable.getName());\n renderable.getTheme().preRender();\n renderable.render();\n renderable.getTheme().postRender();\n MinecraftClient.getInstance().getProfiler().pop();\n }\n // End of user code\n\n ImGui.render();\n endFrame();\n }\n\n private static void initializeImGui() {\n ImGui.createContext();\n\n final ImGuiIO io = ImGui.getIO();\n\n io.setIniFilename(null); // We don't want to save .ini file\n io.addConfigFlags(ImGuiConfigFlags.NavEnableKeyboard); // Enable Keyboard Controls\n io.addConfigFlags(ImGuiConfigFlags.DockingEnable); // Enable Docking\n //io.addConfigFlags(ImGuiConfigFlags.ViewportsEnable); // Enable Multi-Viewport / Platform Windows\n //io.setConfigViewportsNoTaskBarIcon(true);\n\n final ImFontGlyphRangesBuilder rangesBuilder = new ImFontGlyphRangesBuilder(); // Glyphs ranges provide\n\n final short iconRangeMin = (short) 0xe005;\n final short iconRangeMax = (short) 0xf8ff;\n final short[] iconRange = new short[]{iconRangeMin, iconRangeMax, 0};\n\n rangesBuilder.addRanges(iconRange);\n\n final short[] glyphRanges = rangesBuilder.buildRanges();\n\n ImFontConfig iconsConfig = new ImFontConfig();\n\n iconsConfig.setMergeMode(true);\n iconsConfig.setPixelSnapH(true);\n iconsConfig.setOversampleH(3);\n iconsConfig.setOversampleV(3);\n\n final ImFontAtlas fontAtlas = io.getFonts();\n final ImFontConfig fontConfig = new ImFontConfig(); // Natively allocated object, should be explicitly destroyed\n\n fontAtlas.addFontDefault();\n fontConfig.setGlyphRanges(fontAtlas.getGlyphRangesCyrillic());\n byte[] fontAwesomeData = null;\n try (InputStream is = ImguiLoader.class.getClassLoader().getResourceAsStream(\"assets/FontAwesome6-Solid.otf\")) {\n if (is != null) {\n fontAwesomeData = is.readAllBytes();\n }\n } catch (IOException ignored) {\n // do nothing, we already have font :3\n }\n\n try (InputStream is = ImguiLoader.class.getClassLoader().getResourceAsStream(\"assets/JetBrainsMono-Regular.ttf\")) {\n if (is != null) {\n byte[] fontData = is.readAllBytes();\n\n customFont = fontAtlas.addFontFromMemoryTTF(fontData, 18);\n bigCustomFont = fontAtlas.addFontFromMemoryTTF(fontData, 24);\n biggerCustomFont = fontAtlas.addFontFromMemoryTTF(fontData, 32);\n }\n } catch (IOException ignored) {\n // do nothing, we already have font :3\n }\n\n byte[] dosisFontData = null;\n try (InputStream is = ImguiLoader.class.getClassLoader().getResourceAsStream(\"assets/Dosis-Medium.ttf\")) {\n if (is != null) {\n dosisFontData = is.readAllBytes();\n\n normalDosisFont = fontAtlas.addFontFromMemoryTTF(dosisFontData, 20);\n bigDosisFont = fontAtlas.addFontFromMemoryTTF(dosisFontData, 24);\n biggerDosisFont = fontAtlas.addFontFromMemoryTTF(dosisFontData, 32);\n dosisFont = fontAtlas.addFontFromMemoryTTF(dosisFontData, 18);\n }\n } catch (IOException ignored) {\n // do nothing, we already have font :3\n }\n fontAwesome = fontAtlas.addFontFromMemoryTTF(fontAwesomeData, 20, iconsConfig, iconRange);\n\n\n fontConfig.setMergeMode(true); // When enabled, all fonts added with this config would be merged with the previously added font\n dosisFont = fontAtlas.addFontFromMemoryTTF(dosisFontData, 18);\n fontAwesome = fontAtlas.addFontFromMemoryTTF(fontAwesomeData, 18, iconsConfig, iconRange);\n bigDosisFont = fontAtlas.addFontFromMemoryTTF(dosisFontData, 24);\n bigFontAwesome = fontAtlas.addFontFromMemoryTTF(fontAwesomeData, 24, iconsConfig, iconRange);\n biggerDosisFont = fontAtlas.addFontFromMemoryTTF(dosisFontData, 32);\n biggerFontAwesome = fontAtlas.addFontFromMemoryTTF(fontAwesomeData, 32, iconsConfig, iconRange);\n normalDosisFont = fontAtlas.addFontFromMemoryTTF(dosisFontData, 20);\n normalFontAwesome = fontAtlas.addFontFromMemoryTTF(fontAwesomeData, 20, iconsConfig, iconRange);\n fontConfig.destroy();\n fontAtlas.build();\n\n\n if (io.hasConfigFlags(ImGuiConfigFlags.ViewportsEnable)) {\n final ImGuiStyle style = ImGui.getStyle();\n style.setWindowRounding(0.0f);\n style.setColor(ImGuiCol.WindowBg, ImGui.getColorU32(ImGuiCol.WindowBg, 1));\n }\n }\n\n private static void endFrame() {\n // After Dear ImGui prepared a draw data, we use it in the LWJGL3 renderer.\n // At that moment ImGui will be rendered to the current OpenGL context.\n imGuiGl3.renderDrawData(ImGui.getDrawData());\n\n if (ImGui.getIO().hasConfigFlags(ImGuiConfigFlags.ViewportsEnable)) {\n final long backupWindowPtr = glfwGetCurrentContext();\n ImGui.updatePlatformWindows();\n ImGui.renderPlatformWindowsDefault();\n glfwMakeContextCurrent(backupWindowPtr);\n }\n\n if (!toRemove.isEmpty()) {\n toRemove.forEach(renderstack::remove);\n toRemove.clear();\n }\n }\n\n public static void addRenderable(Renderable renderable) {\n renderstack.add(renderable);\n }\n\n public static void queueRemove(Renderable renderable) {\n toRemove.add(renderable);\n }\n\n public static boolean isRendered(Renderable renderable) {\n return renderstack.contains(renderable);\n }\n\n private ImguiLoader() {}\n}" } ]
import net.Poluteclient.phosphor.api.event.events.MouseMoveEvent; import net.Poluteclient.phosphor.api.event.events.MousePressEvent; import net.Poluteclient.phosphor.api.event.events.MouseUpdateEvent; import net.Poluteclient.phosphor.common.Phosphor; import net.Poluteclient.phosphor.gui.AsteriaMenu; import net.Poluteclient.phosphor.gui.AsteriaNewMenu; import net.Poluteclient.phosphor.gui.CategoryTab; import net.Poluteclient.phosphor.gui.ImguiLoader; import net.Poluteclient.phosphor.module.modules.client.AsteriaSettingsModule; import net.minecraft.client.MinecraftClient; import net.minecraft.client.Mouse; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
10,099
package net.Poluteclient.phosphor.mixin; @Mixin(Mouse.class) public class MouseMixin { @Shadow @Final private MinecraftClient client; @Inject(method = "onCursorPos", at = @At("HEAD")) private void onMouseMove(long window, double mouseX, double mouseY, CallbackInfo ci) { if (window == this.client.getWindow().getHandle()) Phosphor.EVENTBUS.post(MouseMoveEvent.get(mouseX, mouseY)); } @Inject(method = "updateMouse", at = @At("HEAD")) private void onMouseUpdate(CallbackInfo ci) { Phosphor.EVENTBUS.post(MouseUpdateEvent.get()); } @Inject(method = "onMouseButton", at = @At("HEAD"), cancellable = true) private void onMouseButton(long window, int button, int action, int mods, CallbackInfo ci) { AsteriaSettingsModule Polute = Phosphor.moduleManager().getModule(AsteriaSettingsModule.class); if (Polute != null && Polute.isEnabled()) { ci.cancel(); } Phosphor.EVENTBUS.post(MousePressEvent.get(button, action)); } @Inject(method = "onMouseScroll", at = @At("HEAD"), cancellable = true) private void onMouseScroll(long window, double horizontal, double vertical, CallbackInfo ci) { AsteriaSettingsModule Polute = Phosphor.moduleManager().getModule(AsteriaSettingsModule.class); if (Polute != null && Polute.isEnabled()) { double scrollY = vertical * 30; if (ImguiLoader.isRendered(AsteriaNewMenu.getInstance())) { AsteriaNewMenu.getInstance().scrollY -= scrollY; } else if (ImguiLoader.isRendered(AsteriaMenu.getInstance())) {
package net.Poluteclient.phosphor.mixin; @Mixin(Mouse.class) public class MouseMixin { @Shadow @Final private MinecraftClient client; @Inject(method = "onCursorPos", at = @At("HEAD")) private void onMouseMove(long window, double mouseX, double mouseY, CallbackInfo ci) { if (window == this.client.getWindow().getHandle()) Phosphor.EVENTBUS.post(MouseMoveEvent.get(mouseX, mouseY)); } @Inject(method = "updateMouse", at = @At("HEAD")) private void onMouseUpdate(CallbackInfo ci) { Phosphor.EVENTBUS.post(MouseUpdateEvent.get()); } @Inject(method = "onMouseButton", at = @At("HEAD"), cancellable = true) private void onMouseButton(long window, int button, int action, int mods, CallbackInfo ci) { AsteriaSettingsModule Polute = Phosphor.moduleManager().getModule(AsteriaSettingsModule.class); if (Polute != null && Polute.isEnabled()) { ci.cancel(); } Phosphor.EVENTBUS.post(MousePressEvent.get(button, action)); } @Inject(method = "onMouseScroll", at = @At("HEAD"), cancellable = true) private void onMouseScroll(long window, double horizontal, double vertical, CallbackInfo ci) { AsteriaSettingsModule Polute = Phosphor.moduleManager().getModule(AsteriaSettingsModule.class); if (Polute != null && Polute.isEnabled()) { double scrollY = vertical * 30; if (ImguiLoader.isRendered(AsteriaNewMenu.getInstance())) { AsteriaNewMenu.getInstance().scrollY -= scrollY; } else if (ImguiLoader.isRendered(AsteriaMenu.getInstance())) {
for (CategoryTab categoryTab : AsteriaMenu.getInstance().tabs) {
2
2023-11-11 17:14:20+00:00
12k
UselessBullets/DragonFly
src/main/java/useless/dragonfly/debug/DebugEntities.java
[ { "identifier": "DragonModel", "path": "src/main/java/useless/dragonfly/debug/testentity/Dragon/DragonModel.java", "snippet": "public class DragonModel extends BenchEntityModel {\n}" }, { "identifier": "DragonRenderer", "path": "src/main/java/useless/dragonfly/debug/testentity/Dragon/DragonRenderer.java", "snippet": "public class DragonRenderer extends LivingRenderer<EntityDragon> {\n\tpublic DragonRenderer(ModelBase modelbase, float shadowSize) {\n\t\tsuper(modelbase, shadowSize);\n\t}\n}" }, { "identifier": "EntityDragon", "path": "src/main/java/useless/dragonfly/debug/testentity/Dragon/EntityDragon.java", "snippet": "public class EntityDragon extends EntityGhast {\n\tpublic EntityDragon(World world) {\n\t\tsuper(world);\n\t}\n\t@Override\n\tpublic String getEntityTexture() {\n\t\treturn \"/assets/dragonfly/entity/dragontex2variant.png\";\n\t}\n\n\t@Override\n\tpublic String getDefaultEntityTexture() {\n\t\treturn \"/assets/dragonfly/entity/dragontex2variant.png\";\n\t}\n}" }, { "identifier": "EntityHTest", "path": "src/main/java/useless/dragonfly/debug/testentity/HTest/EntityHTest.java", "snippet": "public class EntityHTest extends EntityLiving {\n\tpublic EntityHTest(World world) {\n\t\tsuper(world);\n\t}\n\t@Override\n\tpublic String getEntityTexture() {\n\t\treturn \"/assets/dragonfly/entity/img.png\";\n\t}\n\n\t@Override\n\tpublic String getDefaultEntityTexture() {\n\t\treturn \"/assets/dragonfly/entity/img.png\";\n\t}\n}" }, { "identifier": "HModelTest", "path": "src/main/java/useless/dragonfly/debug/testentity/HTest/HModelTest.java", "snippet": "public class HModelTest extends BenchEntityModel {\n\t@Override\n\tpublic void setRotationAngles(float limbSwing, float limbYaw, float ticksExisted, float headYaw, float headPitch, float scale) {\n\t\tsuper.setRotationAngles(limbSwing, limbYaw, ticksExisted, headYaw, headPitch, scale);\n\t\tif (this.getIndexBones().containsKey(\"Stand\")) {\n\t\t\tthis.getIndexBones().get(\"Stand\").setRotationAngle(ticksExisted/400, 0, 0);\n\t\t}\n\t\tif (this.getIndexBones().containsKey(\"Dobble\")) {\n\t\t\tthis.getIndexBones().get(\"Dobble\").setRotationAngle(0, ticksExisted, 0);\n\t\t}\n\t}\n}" }, { "identifier": "RenderHTest", "path": "src/main/java/useless/dragonfly/debug/testentity/HTest/RenderHTest.java", "snippet": "public class RenderHTest extends LivingRenderer<EntityHTest> {\n\tpublic RenderHTest(ModelBase modelbase, float shadowSize) {\n\t\tsuper(modelbase, shadowSize);\n\t}\n}" }, { "identifier": "EntityWarden", "path": "src/main/java/useless/dragonfly/debug/testentity/Warden/EntityWarden.java", "snippet": "public class EntityWarden extends EntityHuman {\n\tpublic AnimationState emergeState = new AnimationState();\n\tpublic AnimationState diggingState = new AnimationState();\n\tpublic AnimationState attackState = new AnimationState();\n\tpublic EntityWarden(World world) {\n\t\tsuper(world);\n\t}\n\n\t@Override\n\tpublic void spawnInit() {\n\t\tsuper.spawnInit();\n\t\tthis.emergeState.start(this.tickCount);\n\t}\n\n\t@Override\n\tprotected void attackEntity(Entity entity, float distance) {\n\t\tif (this.attackTime <= 0 && distance < 2.0f && entity.bb.maxY > this.bb.minY && entity.bb.minY < this.bb.maxY) {\n\t\t\tthis.attackState.start(this.tickCount);\n\t\t}\n\t\tsuper.attackEntity(entity, distance);\n\t}\n\n\t@Override\n\tpublic void handleEntityEvent(byte byte0, float attackedAtYaw) {\n\t\tif (byte0 == 4) {\n\n\t\t} else if (byte0 == 5) {\n\n\t\t} else {\n\t\t\tsuper.handleEntityEvent(byte0, attackedAtYaw);\n\t\t}\n\t}\n\n\t@Override\n\tpublic String getEntityTexture() {\n\t\treturn \"/assets/dragonfly/entity/warden.png\";\n\t}\n\n\t@Override\n\tpublic String getDefaultEntityTexture() {\n\t\treturn \"/assets/dragonfly/entity/warden.png\";\n\t}\n}" }, { "identifier": "WardenModel", "path": "src/main/java/useless/dragonfly/debug/testentity/Warden/WardenModel.java", "snippet": "public class WardenModel extends BenchEntityModel {\n\tpublic static EntityWarden warden;\n\n\t@Override\n\tpublic void setLivingAnimations(EntityLiving entityliving, float limbSwing, float limbYaw, float renderPartialTicks) {\n\t\tsuper.setLivingAnimations(entityliving, limbSwing, limbYaw, renderPartialTicks);\n\t\tif (entityliving instanceof EntityWarden) {\n\t\t\twarden = (EntityWarden) entityliving;\n\t\t}\n\t}\n\n\t@Override\n\tpublic void setRotationAngles(float limbSwing, float limbYaw, float ticksExisted, float headYaw, float headPitch, float scale) {\n\t\t// If you need play some animation. you should reset with this\n\t\tthis.getIndexBones().forEach((s, benchEntityBones) -> benchEntityBones.resetPose());\n\n\t\tsuper.setRotationAngles(limbSwing, limbYaw, ticksExisted, headYaw, headPitch, scale);\n\t\tif (this.getIndexBones().containsKey(\"head\")) {\n\t\t\tthis.getIndexBones().get(\"head\").setRotationAngle((float) Math.toRadians(headPitch), (float) Math.toRadians(headYaw), 0);\n\t\t}\n\t\tif (this.getIndexBones().containsKey(\"right_arm\")) {\n\t\t\tthis.getIndexBones().get(\"right_arm\").setRotationAngle(MathHelper.cos(limbSwing * (2f / 3) + MathHelper.PI) * 2.0f * limbYaw * 0.5f, 0, 0);\n\t\t}\n\t\tif (this.getIndexBones().containsKey(\"left_arm\")) {\n\t\t\tthis.getIndexBones().get(\"left_arm\").setRotationAngle(MathHelper.cos(limbSwing * (2f / 3)) * 2.0f * limbYaw * 0.5f, 0, 0);\n\t\t}\n\t\tif (this.getIndexBones().containsKey(\"right_leg\")) {\n\t\t\tthis.getIndexBones().get(\"right_leg\").setRotationAngle(MathHelper.cos(limbSwing * (2f / 3)) * 1.4f * limbYaw, 0, 0);\n\t\t}\n\t\tif (this.getIndexBones().containsKey(\"left_leg\")) {\n\t\t\tthis.getIndexBones().get(\"left_leg\").setRotationAngle(MathHelper.cos(limbSwing * (2f / 3) + MathHelper.PI) * 1.4f * limbYaw, 0, 0);\n\t\t}\n\n\t\tif (this.getIndexBones().containsKey(\"right_ribcage\")) {\n\t\t\tthis.getIndexBones().get(\"right_ribcage\").setRotationAngle(0, Math.max(MathHelper.cos(ticksExisted / 20), 0), 0);\n\t\t}\n\t\tif (this.getIndexBones().containsKey(\"left_ribcage\")) {\n\t\t\tthis.getIndexBones().get(\"left_ribcage\").setRotationAngle(0, -Math.max(MathHelper.cos(ticksExisted / 20), 0), 0);\n\t\t}\n\n\t\tif (this.getIndexBones().containsKey(\"right_tendril\")) {\n\t\t\tthis.getIndexBones().get(\"right_tendril\").setRotationAngle(0, Math.max(MathHelper.sin(ticksExisted / 2) - 0.8f, 0), 0);\n\t\t}\n\t\tif (this.getIndexBones().containsKey(\"left_tendril\")) {\n\t\t\tthis.getIndexBones().get(\"left_tendril\").setRotationAngle(0, -Math.max(MathHelper.sin(ticksExisted / 2) - 0.8f, 0), 0);\n\t\t}\n\t\tAnimation testAnimation = AnimationHelper.getOrCreateEntityAnimation(MOD_ID, \"warden.animation\");\n\t\tif (warden != null) {\n\t\t\tanimate(warden.attackState, testAnimation.getAnimations().get(\"animation.warden.attack\"), ticksExisted, 1.0F);\n\t\t}\n\t}\n}" }, { "identifier": "WardenRenderer", "path": "src/main/java/useless/dragonfly/debug/testentity/Warden/WardenRenderer.java", "snippet": "public class WardenRenderer extends LivingRenderer<EntityWarden> {\n\tpublic WardenRenderer(ModelBase modelbase, float shadowSize) {\n\t\tsuper(modelbase, shadowSize);\n\t}\n\tpublic void doRenderPreview(EntityWarden entity, double x, double y, double z, float yaw, float partialTick) {\n\t\tGL11.glScalef(0.65f, 0.65f, 0.65f);\n\t\tGL11.glDisable(GL11.GL_LIGHTING);\n\t\tthis.doRender(entity, x, y, z, yaw, partialTick);\n\t}\n}" }, { "identifier": "EntityZombieTest", "path": "src/main/java/useless/dragonfly/debug/testentity/Zombie/EntityZombieTest.java", "snippet": "public class EntityZombieTest extends EntityHuman {\n\tpublic EntityZombieTest(World world) {\n\t\tsuper(world);\n\t}\n\n\tpublic ItemStack getHeldItem() {\n\t\treturn new ItemStack(Item.toolSwordWood);\n\t}\n\n\t@Override\n\tpublic String getEntityTexture() {\n\t\treturn \"/assets/dragonfly/entity/zombie_test.png\";\n\t}\n\n\t@Override\n\tpublic String getDefaultEntityTexture() {\n\t\treturn \"/assets/dragonfly/entity/zombie_test.png\";\n\t}\n}" }, { "identifier": "RenderZombieTest", "path": "src/main/java/useless/dragonfly/debug/testentity/Zombie/RenderZombieTest.java", "snippet": "public class RenderZombieTest extends LivingRenderer<EntityZombieTest> {\n\tprotected BenchEntityModel modelBench;\n\n\tpublic RenderZombieTest(BenchEntityModel modelbase, float shadowSize) {\n\t\tsuper(modelbase, shadowSize);\n\t\tthis.modelBench = modelbase;\n\t}\n\n\t@Override\n\tprotected void renderEquippedItems(EntityZombieTest entity, float f) {\n\t\tItemStack itemstack = entity.getHeldItem();\n\t\tif (itemstack != null) {\n\t\t\tif (!this.modelBench.getIndexBones().isEmpty() && this.modelBench.getIndexBones().containsKey(\"RightArm\")) {\n\t\t\t\tGL11.glPushMatrix();\n\t\t\t\tthis.modelBench.postRender(this.modelBench.getIndexBones().get(\"RightArm\"), 0.0625f);\n\t\t\t\t;\n\t\t\t\tGL11.glTranslatef(-0.0625f, 0.4375f, 0.0625f);\n\t\t\t\tif (itemstack.itemID < Block.blocksList.length && ((BlockModel) BlockModelDispatcher.getInstance().getDispatch(Block.blocksList[itemstack.itemID])).shouldItemRender3d()) {\n\t\t\t\t\tfloat f1 = 0.5f;\n\t\t\t\t\tGL11.glTranslatef(0.0f, 0.1875f, -0.3125f);\n\t\t\t\t\tGL11.glRotatef(20.0f, 1.0f, 0.0f, 0.0f);\n\t\t\t\t\tGL11.glRotatef(45.0f, 0.0f, 1.0f, 0.0f);\n\t\t\t\t\tGL11.glScalef(f1 *= 0.75f, -f1, f1);\n\t\t\t\t} else if (itemstack.itemID == Item.toolBow.id) {\n\t\t\t\t\tfloat f2 = 0.625f;\n\t\t\t\t\tGL11.glTranslatef(0.0f, 0.125f, 0.3125f);\n\t\t\t\t\tGL11.glRotatef(-20.0f, 0.0f, 1.0f, 0.0f);\n\t\t\t\t\tGL11.glScalef(f2, -f2, f2);\n\t\t\t\t\tGL11.glRotatef(-100.0f, 1.0f, 0.0f, 0.0f);\n\t\t\t\t\tGL11.glRotatef(45.0f, 0.0f, 1.0f, 0.0f);\n\t\t\t\t} else if (Item.itemsList[itemstack.itemID].isFull3D()) {\n\t\t\t\t\tfloat f2 = 0.625f;\n\t\t\t\t\tGL11.glTranslatef(0.0f, 0.1875f, 0.0f);\n\t\t\t\t\tGL11.glScalef(f2, -f2, f2);\n\t\t\t\t\tGL11.glRotatef(-100.0f, 1.0f, 0.0f, 0.0f);\n\t\t\t\t\tGL11.glRotatef(45.0f, 0.0f, 1.0f, 0.0f);\n\t\t\t\t} else {\n\t\t\t\t\tfloat f3 = 0.375f;\n\t\t\t\t\tGL11.glTranslatef(0.25f, 0.1875f, -0.1875f);\n\t\t\t\t\tGL11.glScalef(f3, f3, f3);\n\t\t\t\t\tGL11.glRotatef(60.0f, 0.0f, 0.0f, 1.0f);\n\t\t\t\t\tGL11.glRotatef(-90.0f, 1.0f, 0.0f, 0.0f);\n\t\t\t\t\tGL11.glRotatef(20.0f, 0.0f, 0.0f, 1.0f);\n\t\t\t\t}\n\t\t\t\tthis.renderDispatcher.itemRenderer.renderItem(entity, itemstack);\n\t\t\t\tGL11.glPopMatrix();\n\t\t\t}\n\t\t}\n\t}\n}" }, { "identifier": "ZombieModelTest", "path": "src/main/java/useless/dragonfly/debug/testentity/Zombie/ZombieModelTest.java", "snippet": "public class ZombieModelTest extends BenchEntityModel {\n\t@Override\n\tpublic void setRotationAngles(float limbSwing, float limbYaw, float ticksExisted, float headYaw, float headPitch, float scale) {\n\t\t// If you need play some animation. you should reset with this\n\t\tthis.getIndexBones().forEach((s, benchEntityBones) -> benchEntityBones.resetPose());\n\t\tsuper.setRotationAngles(limbSwing, limbYaw, ticksExisted, headYaw, headPitch, scale);\n\t\tif (this.getIndexBones().containsKey(\"Head\")) {\n\t\t\tthis.getIndexBones().get(\"Head\").setRotationAngle((float) Math.toRadians(headPitch), (float) Math.toRadians(headYaw), 0);\n\t\t}\n\t\tif (this.getIndexBones().containsKey(\"bone\")) {\n\t\t\tthis.getIndexBones().get(\"bone\").setRotationAngle(0, ticksExisted, 0);\n\t\t}\n\t\tif (this.getIndexBones().containsKey(\"RightArm\")) {\n\t\t\tthis.getIndexBones().get(\"RightArm\").setRotationAngle(MathHelper.cos(limbSwing * (2f/3) + MathHelper.PI) * 2.0f * limbYaw * 0.5f, 0, 0);\n\t\t}\n\t\tif (this.getIndexBones().containsKey(\"LeftArm\")) {\n\t\t\tthis.getIndexBones().get(\"LeftArm\").setRotationAngle(MathHelper.cos(limbSwing * (2f/3)) * 2.0f * limbYaw * 0.5f, 0, 0);\n\t\t}\n\t\tAnimation testAnimation = AnimationHelper.getOrCreateEntityAnimation(MOD_ID, \"zombie_test.animation\");\n\t\tanimateWalk(testAnimation.getAnimations().get(\"test\"), limbSwing, limbYaw * 0.5F, 2.0F, 2.5F);\n\t}\n}" }, { "identifier": "AnimationHelper", "path": "src/main/java/useless/dragonfly/helper/AnimationHelper.java", "snippet": "public class AnimationHelper {\n\tpublic static final Map<String, Animation> registeredAnimations = new HashMap<>();\n\n\tpublic static Animation getOrCreateEntityAnimation(String modID, String animationSource) {\n\t\tString animationKey = getAnimationLocation(modID, animationSource);\n\t\tif (registeredAnimations.containsKey(animationKey)){\n\t\t\treturn registeredAnimations.get(animationKey);\n\t\t}\n\n\t\tJsonReader reader = new JsonReader(new BufferedReader(new InputStreamReader(Utilities.getResourceAsStream(animationKey))));\n\t\tAnimation animation = DragonFly.GSON.fromJson(reader, Animation.class);\n\t\tregisteredAnimations.put(animationKey, animation);\n\t\treturn animation;\n\t}\n\n\tpublic static String getAnimationLocation(String modID, String animationSource) {\n\t\tif (!animationSource.endsWith(\".json\")) {\n\t\t\tanimationSource += \".json\";\n\t\t}\n\t\treturn \"/assets/\" + modID + \"/animation/\" + animationSource;\n\t}\n\n\tpublic static void animate(BenchEntityModel entityModel, AnimationData animationData, long time, float scale, Vector3f p_253861_) {\n\t\tfloat seconds = getElapsedSeconds(animationData, time);\n\n\t\tfor (Map.Entry<String, BoneData> entry : animationData.getBones().entrySet()) {\n\t\t\tOptional<BenchEntityBones> optional = entityModel.getAnyDescendantWithName(entry.getKey());\n\t\t\tMap<String, PostData> postionMap = entry.getValue().getPosition();\n\t\t\tList<KeyFrame> positionFrame = Lists.newArrayList();\n\n\t\t\tpostionMap.entrySet().stream().sorted(Comparator.comparingDouble((test) -> (Float.parseFloat(test.getKey())))).forEach(key -> {\n\t\t\t\tpositionFrame.add(new KeyFrame(Float.parseFloat(key.getKey()), key.getValue().getPost(), key.getValue().getLerpMode()));\n\t\t\t});\n\t\t\toptional.ifPresent(p_232330_ -> positionFrame.forEach((keyFrame2) -> {\n\t\t\t\tint i = Math.max(0, binarySearch(0, positionFrame.size(), p_232315_ -> seconds <= positionFrame.get(p_232315_).duration) - 1);\n\t\t\t\tint j = Math.min(positionFrame.size() - 1, i + 1);\n\t\t\t\tKeyFrame keyframe = positionFrame.get(i);\n\t\t\t\tKeyFrame keyframe1 = positionFrame.get(j);\n\t\t\t\tfloat f1 = seconds - keyframe.duration;\n\t\t\t\tfloat f2;\n\t\t\t\tif (j != i) {\n\t\t\t\t\tf2 = MathHelper.clamp(f1 / (keyframe1.duration - keyframe.duration), 0.0F, 1.0F);\n\t\t\t\t} else {\n\t\t\t\t\tf2 = 0.0F;\n\t\t\t\t}\n\n\t\t\t\tif (keyFrame2.lerp_mode.equals(\"catmullrom\")) {\n\t\t\t\t\tVector3f vector3f = posVec(positionFrame.get(Math.max(0, i - 1)).vector3f());\n\t\t\t\t\tVector3f vector3f1 = posVec(positionFrame.get(i).vector3f());\n\t\t\t\t\tVector3f vector3f2 = posVec(positionFrame.get(j).vector3f());\n\t\t\t\t\tVector3f vector3f3 = posVec(positionFrame.get(Math.min(positionFrame.size() - 1, j + 1)).vector3f());\n\n\t\t\t\t\tp_253861_.set(\n\t\t\t\t\t\tcatmullrom(f2, vector3f.x, vector3f1.x, vector3f2.x, vector3f3.x) * scale,\n\t\t\t\t\t\tcatmullrom(f2, vector3f.y, vector3f1.y, vector3f2.y, vector3f3.y) * scale,\n\t\t\t\t\t\tcatmullrom(f2, vector3f.z, vector3f1.z, vector3f2.z, vector3f3.z) * scale\n\t\t\t\t\t);\n\t\t\t\t\tp_232330_.setRotationPoint(p_232330_.rotationPointX + p_253861_.x, p_232330_.rotationPointY + p_253861_.y, p_232330_.rotationPointZ + p_253861_.z);\n\t\t\t\t} else {\n\t\t\t\t\tVector3f vector3f = posVec(positionFrame.get(i).vector3f());\n\t\t\t\t\tVector3f vector3f1 = posVec(positionFrame.get(j).vector3f());\n\t\t\t\t\tp_253861_.set(\n\t\t\t\t\t\tfma(vector3f1.x - vector3f.x, f2, vector3f.x) * scale,\n\t\t\t\t\t\tfma(vector3f1.y - vector3f.y, f2, vector3f.y) * scale,\n\t\t\t\t\t\tfma(vector3f1.z - vector3f.z, f2, vector3f.z) * scale\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}));\n\t\t\tMap<String, PostData> rotationMap = entry.getValue().getRotation();\n\t\t\tList<KeyFrame> rotationFrame = Lists.newArrayList();\n\n\t\t\trotationMap.entrySet().stream().sorted(Comparator.comparingDouble((test) -> (Float.parseFloat(test.getKey())))).forEach(key -> {\n\t\t\t\trotationFrame.add(new KeyFrame(Float.parseFloat(key.getKey()), key.getValue().getPost(), key.getValue().getLerpMode()));\n\t\t\t});\n\t\t\toptional.ifPresent(p_232330_ -> rotationFrame.forEach((keyFrame3) -> {\n\t\t\t\tint i = Math.max(0, binarySearch(0, rotationFrame.size(), p_232315_ -> seconds <= rotationFrame.get(p_232315_).duration) - 1);\n\t\t\t\tint j = Math.min(rotationFrame.size() - 1, i + 1);\n\t\t\t\tKeyFrame keyframe = rotationFrame.get(i);\n\t\t\t\tKeyFrame keyframe1 = rotationFrame.get(j);\n\t\t\t\tfloat f1 = seconds - keyframe.duration;\n\t\t\t\tfloat f2;\n\t\t\t\tif (j != i) {\n\t\t\t\t\tf2 = MathHelper.clamp(f1 / (keyframe1.duration - keyframe.duration), 0.0F, 1.0F);\n\t\t\t\t} else {\n\t\t\t\t\tf2 = 0.0F;\n\t\t\t\t}\n\n\t\t\t\tif (keyFrame3.lerp_mode.equals(\"catmullrom\")) {\n\t\t\t\t\tVector3f vector3f = degreeVec(rotationFrame.get(Math.max(0, i - 1)).vector3f());\n\t\t\t\t\tVector3f vector3f1 = degreeVec(rotationFrame.get(i).vector3f());\n\t\t\t\t\tVector3f vector3f2 = degreeVec(rotationFrame.get(j).vector3f());\n\t\t\t\t\tVector3f vector3f3 = degreeVec(rotationFrame.get(Math.min(rotationFrame.size() - 1, j + 1)).vector3f());\n\n\t\t\t\t\tp_253861_.set(\n\t\t\t\t\t\tcatmullrom(f2, vector3f.x, vector3f1.x, vector3f2.x, vector3f3.x) * scale,\n\t\t\t\t\t\tcatmullrom(f2, vector3f.y, vector3f1.y, vector3f2.y, vector3f3.y) * scale,\n\t\t\t\t\t\tcatmullrom(f2, vector3f.z, vector3f1.z, vector3f2.z, vector3f3.z) * scale\n\t\t\t\t\t);\n\t\t\t\t\tp_232330_.setRotationAngle(p_232330_.rotateAngleX + p_253861_.x, p_232330_.rotateAngleY + p_253861_.y, p_232330_.rotateAngleZ + p_253861_.z);\n\t\t\t\t} else {\n\t\t\t\t\tVector3f vector3f = degreeVec(rotationFrame.get(i).vector3f());\n\t\t\t\t\tVector3f vector3f1 = degreeVec(rotationFrame.get(j).vector3f());\n\t\t\t\t\tp_253861_.set(\n\t\t\t\t\t\tfma(vector3f1.x - vector3f.x, f2, vector3f.x) * scale,\n\t\t\t\t\t\tfma(vector3f1.y - vector3f.y, f2, vector3f.y) * scale,\n\t\t\t\t\t\tfma(vector3f1.z - vector3f.z, f2, vector3f.z) * scale\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}));\n\n\t\t\tMap<String, PostData> scaleMap = entry.getValue().getScale();\n\t\t\tList<KeyFrame> scaleFrame = Lists.newArrayList();\n\n\t\t\tscaleMap.entrySet().stream().sorted(Comparator.comparingDouble((test) -> (Float.parseFloat(test.getKey())))).forEach(key -> {\n\t\t\t\tscaleFrame.add(new KeyFrame(Float.parseFloat(key.getKey()), key.getValue().getPost(), key.getValue().getLerpMode()));\n\t\t\t});\n\t\t\toptional.ifPresent(p_232330_ -> scaleFrame.forEach((keyFrame3) -> {\n\t\t\t\tint i = Math.max(0, binarySearch(0, scaleFrame.size(), p_232315_ -> seconds <= scaleFrame.get(p_232315_).duration) - 1);\n\t\t\t\tint j = Math.min(scaleFrame.size() - 1, i + 1);\n\t\t\t\tKeyFrame keyframe = scaleFrame.get(i);\n\t\t\t\tKeyFrame keyframe1 = scaleFrame.get(j);\n\t\t\t\tfloat f1 = seconds - keyframe.duration;\n\t\t\t\tfloat f2;\n\t\t\t\tif (j != i) {\n\t\t\t\t\tf2 = MathHelper.clamp(f1 / (keyframe1.duration - keyframe.duration), 0.0F, 1.0F);\n\t\t\t\t} else {\n\t\t\t\t\tf2 = 0.0F;\n\t\t\t\t}\n\n\t\t\t\tif (keyFrame3.lerp_mode.equals(\"catmullrom\")) {\n\t\t\t\t\tVector3f vector3f = degreeVec(scaleFrame.get(Math.max(0, i - 1)).vector3f());\n\t\t\t\t\tVector3f vector3f1 = degreeVec(scaleFrame.get(i).vector3f());\n\t\t\t\t\tVector3f vector3f2 = degreeVec(scaleFrame.get(j).vector3f());\n\t\t\t\t\tVector3f vector3f3 = degreeVec(scaleFrame.get(Math.min(scaleFrame.size() - 1, j + 1)).vector3f());\n\n\t\t\t\t\tp_253861_.set(\n\t\t\t\t\t\tcatmullrom(f2, vector3f.x, vector3f1.x, vector3f2.x, vector3f3.x) * scale,\n\t\t\t\t\t\tcatmullrom(f2, vector3f.y, vector3f1.y, vector3f2.y, vector3f3.y) * scale,\n\t\t\t\t\t\tcatmullrom(f2, vector3f.z, vector3f1.z, vector3f2.z, vector3f3.z) * scale\n\t\t\t\t\t);\n\t\t\t\t\tp_232330_.setRotationAngle(p_232330_.rotateAngleX + p_253861_.x, p_232330_.rotateAngleY + p_253861_.y, p_232330_.rotateAngleZ + p_253861_.z);\n\t\t\t\t} else {\n\t\t\t\t\tVector3f vector3f = degreeVec(scaleFrame.get(i).vector3f());\n\t\t\t\t\tVector3f vector3f1 = degreeVec(scaleFrame.get(j).vector3f());\n\t\t\t\t\tp_253861_.set(\n\t\t\t\t\t\tfma(vector3f1.x - vector3f.x, f2, vector3f.x) * scale,\n\t\t\t\t\t\tfma(vector3f1.y - vector3f.y, f2, vector3f.y) * scale,\n\t\t\t\t\t\tfma(vector3f1.z - vector3f.z, f2, vector3f.z) * scale\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}));\n\t\t}\n\t}\n\n\tpublic static float fma(float a, float b, float c) {\n\t\treturn a * b + c;\n\t}\n\n\tprivate static float catmullrom(float p_216245_, float p_216246_, float p_216247_, float p_216248_, float p_216249_) {\n\t\treturn 0.25F\n\t\t\t* (\n\t\t\t2.0F * p_216247_\n\t\t\t\t+ (p_216248_ - p_216246_) * p_216245_\n\t\t\t\t+ (2.0F * p_216246_ - 5.0F * p_216247_ + 4.0F * p_216248_ - p_216249_) * p_216245_ * p_216245_\n\t\t\t\t+ (3.0F * p_216247_ - p_216246_ - 3.0F * p_216248_ + p_216249_) * p_216245_ * p_216245_ * p_216245_\n\t\t);\n\t}\n\n\tprivate static int binarySearch(int startIndex, int endIndex, IntPredicate p_14052_) {\n\t\tint searchSize = endIndex - startIndex;\n\n\t\twhile (searchSize > 0) {\n\t\t\tint j = searchSize / 2;\n\t\t\tint k = startIndex + j;\n\t\t\tif (p_14052_.test(k)) {\n\t\t\t\tsearchSize = j;\n\t\t\t} else {\n\t\t\t\tstartIndex = k + 1;\n\t\t\t\tsearchSize -= j + 1;\n\t\t\t}\n\t\t}\n\n\t\treturn startIndex;\n\t}\n\n\tpublic static Vector3f posVec(float x, float y, float z) {\n\t\treturn new Vector3f(x, -y, z);\n\t}\n\n\tpublic static Vector3f degreeVec(float degX, float degY, float degZ) {\n\t\treturn new Vector3f(degX * (float) (Math.PI / 180.0), degY * (float) (Math.PI / 180.0), degZ * (float) (Math.PI / 180.0));\n\t}\n\n\tpublic static Vector3f posVec(Vector3f vector3f) {\n\t\treturn new Vector3f(vector3f.x, -vector3f.y, vector3f.z);\n\t}\n\n\tpublic static Vector3f degreeVec(Vector3f vector3f) {\n\t\treturn new Vector3f(vector3f.x * (float) (Math.PI / 180.0), vector3f.y * (float) (Math.PI / 180.0), vector3f.z * (float) (Math.PI / 180.0));\n\t}\n\n\tprivate static float getElapsedSeconds(AnimationData animationData, long ms) {\n\t\tfloat seconds = (float) ms / 1000.0F;\n\t\treturn animationData.isLoop() ? seconds % animationData.getAnimationLength() : seconds;\n\t}\n}" }, { "identifier": "ModelHelper", "path": "src/main/java/useless/dragonfly/helper/ModelHelper.java", "snippet": "public class ModelHelper {\n\tpublic static final Map<NamespaceId, ModelData> modelDataFiles = new HashMap<>();\n\tpublic static final Map<NamespaceId, BlockModel> registeredModels = new HashMap<>();\n\tpublic static final Map<NamespaceId, BlockstateData> registeredBlockStates = new HashMap<>();\n\tpublic static HashMap<NamespaceId, BenchEntityModel> benchEntityModelMap = new HashMap<>();\n\n\t/**\n\t * Place mod models in the <i>assets/modid/model/block/</i> directory for them to be seen.\n\t */\n\tpublic static BlockModel getOrCreateBlockModel(String modId, String modelSource) {\n\t\tNamespaceId namespaceId = new NamespaceId(modId, modelSource);\n\t\tif (registeredModels.containsKey(namespaceId)){\n\t\t\treturn registeredModels.get(namespaceId);\n\t\t}\n\t\tBlockModel model = new BlockModel(namespaceId);\n\t\tregisteredModels.put(namespaceId, model);\n\t\treturn model;\n\t}\n\t/**\n\t * Place mod models in the <i>assets/modid/blockstates/</i> directory for them to be seen.\n\t */\n\tpublic static BlockstateData getOrCreateBlockState(String modId, String blockStateSource) {\n\t\tNamespaceId namespaceId = new NamespaceId(modId, blockStateSource);\n\t\tif (registeredBlockStates.containsKey(namespaceId)){\n\t\t\treturn registeredBlockStates.get(namespaceId);\n\t\t}\n\t\treturn createBlockState(namespaceId);\n\t}\n\tprivate static BlockstateData createBlockState(NamespaceId namespaceId){\n\t\tJsonReader reader = new JsonReader(new BufferedReader(new InputStreamReader(Utilities.getResourceAsStream(getBlockStateLocation(namespaceId)))));\n\t\tBlockstateData blockstateData = DragonFly.GSON.fromJson(reader, BlockstateData.class);\n\t\tregisteredBlockStates.put(namespaceId, blockstateData);\n\t\tif (blockstateData.variants != null){\n\t\t\tfor (VariantData variant : blockstateData.variants.values()) {\n\t\t\t\tNamespaceId variantNamespaceId = NamespaceId.idFromString(variant.model);\n\t\t\t\tgetOrCreateBlockModel(variantNamespaceId.getNamespace(), variantNamespaceId.getId());\n\t\t\t}\n\t\t}\n\t\tif (blockstateData.multipart != null){\n\t\t\tfor (ModelPart part : blockstateData.multipart){\n\t\t\t\tNamespaceId variantNamespaceId = NamespaceId.idFromString(part.apply.model);\n\t\t\t\tgetOrCreateBlockModel(variantNamespaceId.getNamespace(), variantNamespaceId.getId());\n\t\t\t}\n\t\t}\n\t\treturn blockstateData;\n\t}\n\tpublic static ModelData loadBlockModel(NamespaceId namespaceId){\n\t\tif (modelDataFiles.containsKey(namespaceId)){\n\t\t\treturn modelDataFiles.get(namespaceId);\n\t\t}\n\t\treturn createBlockModel(namespaceId);\n\t}\n\tprivate static ModelData createBlockModel(NamespaceId namespaceId){\n\t\tJsonReader reader = new JsonReader(new BufferedReader(new InputStreamReader(Utilities.getResourceAsStream(getModelLocation(namespaceId)))));\n\t\tModelData modelData = DragonFly.GSON.fromJson(reader, ModelData.class);\n\t\tmodelDataFiles.put(namespaceId, modelData);\n\t\treturn modelData;\n\t}\n\n\t/**\n\t * Place mod models in the <i>assets/modid/model/</i> directory for them to be seen.\n\t */\n\tpublic static BenchEntityModel getOrCreateEntityModel(String modID, String modelSource, Class<? extends BenchEntityModel> baseModel) {\n\t\tNamespaceId namespaceId = new NamespaceId(modID, modelSource);\n\t\tif (benchEntityModelMap.containsKey(namespaceId)){\n\t\t\treturn benchEntityModelMap.get(namespaceId);\n\t\t}\n\n\t\tJsonReader reader = new JsonReader(new BufferedReader(new InputStreamReader(Utilities.getResourceAsStream(getModelLocation(namespaceId)))));\n\t\tBenchEntityModel model = DragonFly.GSON.fromJson(reader, baseModel);\n\t\tbenchEntityModelMap.put(namespaceId, model);\n\t\treturn model;\n\t}\n\tpublic static String getModelLocation(NamespaceId namespaceId){\n\t\tString modelSource = namespaceId.getId();\n\t\tif (!modelSource.contains(\".json\")){\n\t\t\tmodelSource += \".json\";\n\t\t}\n\t\treturn \"/assets/\" + namespaceId.getNamespace() + \"/model/\" + modelSource;\n\t}\n\tpublic static String getBlockStateLocation(NamespaceId namespaceId){\n\t\tString modelSource = namespaceId.getId();\n\t\tif (!modelSource.contains(\".json\")){\n\t\t\tmodelSource += \".json\";\n\t\t}\n\t\treturn \"/assets/\" + namespaceId.getNamespace() + \"/blockstates/\" + modelSource;\n\t}\n\tpublic static void refreshModels(){\n\t\tSet<NamespaceId> blockModelDataKeys = new HashSet<>(modelDataFiles.keySet());\n\t\tSet<NamespaceId> blockStateKeys = new HashSet<>(registeredBlockStates.keySet());\n//\t\tSet<String> entityModelKeys = new HashSet<>(benchEntityModelMap.keySet());\n\n\t\tfor (NamespaceId modelDataKey : blockModelDataKeys){\n\t\t\tcreateBlockModel(modelDataKey);\n\t\t}\n\t\tfor (BlockModel model : registeredModels.values()){\n\t\t\tmodel.refreshModel();\n\t\t}\n\t\tfor (NamespaceId stateKey : blockStateKeys){\n\t\t\tcreateBlockState(stateKey);\n\t\t}\n\n\t}\n}" }, { "identifier": "MOD_ID", "path": "src/main/java/useless/dragonfly/DragonFly.java", "snippet": "public static final String MOD_ID = \"dragonfly\";" } ]
import net.minecraft.client.gui.guidebook.mobs.MobInfoRegistry; import net.minecraft.core.Global; import turniplabs.halplibe.helper.EntityHelper; import useless.dragonfly.debug.testentity.Dragon.DragonModel; import useless.dragonfly.debug.testentity.Dragon.DragonRenderer; import useless.dragonfly.debug.testentity.Dragon.EntityDragon; import useless.dragonfly.debug.testentity.HTest.EntityHTest; import useless.dragonfly.debug.testentity.HTest.HModelTest; import useless.dragonfly.debug.testentity.HTest.RenderHTest; import useless.dragonfly.debug.testentity.Warden.EntityWarden; import useless.dragonfly.debug.testentity.Warden.WardenModel; import useless.dragonfly.debug.testentity.Warden.WardenRenderer; import useless.dragonfly.debug.testentity.Zombie.EntityZombieTest; import useless.dragonfly.debug.testentity.Zombie.RenderZombieTest; import useless.dragonfly.debug.testentity.Zombie.ZombieModelTest; import useless.dragonfly.helper.AnimationHelper; import useless.dragonfly.helper.ModelHelper; import static useless.dragonfly.DragonFly.MOD_ID;
8,390
package useless.dragonfly.debug; public class DebugEntities { public static void init(){ EntityHelper.Core.createEntity(EntityHTest.class, 1000, "ht"); EntityHelper.Core.createEntity(EntityZombieTest.class, 1000, "zt"); AnimationHelper.getOrCreateEntityAnimation(MOD_ID, "zombie_test.animation"); EntityHelper.Core.createEntity(EntityDragon.class, 1001, "dragon"); EntityHelper.Core.createEntity(EntityWarden.class, 1002, "warden"); MobInfoRegistry.register(EntityWarden.class, "df.warden.name", "df.warden.desc", 20, 0, null); if (!Global.isServer){ EntityHelper.Client.assignEntityRenderer(EntityHTest.class, new RenderHTest(ModelHelper.getOrCreateEntityModel(MOD_ID, "hierachytest.json", HModelTest.class), 0.5f)); EntityHelper.Client.assignEntityRenderer(EntityZombieTest.class, new RenderZombieTest(ModelHelper.getOrCreateEntityModel(MOD_ID, "zombie_test.json", ZombieModelTest.class), 0.5f));
package useless.dragonfly.debug; public class DebugEntities { public static void init(){ EntityHelper.Core.createEntity(EntityHTest.class, 1000, "ht"); EntityHelper.Core.createEntity(EntityZombieTest.class, 1000, "zt"); AnimationHelper.getOrCreateEntityAnimation(MOD_ID, "zombie_test.animation"); EntityHelper.Core.createEntity(EntityDragon.class, 1001, "dragon"); EntityHelper.Core.createEntity(EntityWarden.class, 1002, "warden"); MobInfoRegistry.register(EntityWarden.class, "df.warden.name", "df.warden.desc", 20, 0, null); if (!Global.isServer){ EntityHelper.Client.assignEntityRenderer(EntityHTest.class, new RenderHTest(ModelHelper.getOrCreateEntityModel(MOD_ID, "hierachytest.json", HModelTest.class), 0.5f)); EntityHelper.Client.assignEntityRenderer(EntityZombieTest.class, new RenderZombieTest(ModelHelper.getOrCreateEntityModel(MOD_ID, "zombie_test.json", ZombieModelTest.class), 0.5f));
EntityHelper.Client.assignEntityRenderer(EntityDragon.class, new DragonRenderer(ModelHelper.getOrCreateEntityModel(MOD_ID, "mod_dragon.json", DragonModel.class), 0.5f));
0
2023-11-16 01:10:52+00:00
12k
AntonyCheng/ai-bi
src/test/java/top/sharehome/springbootinittemplate/captcha/CaptchaTest.java
[ { "identifier": "CaptchaCreate", "path": "src/main/java/top/sharehome/springbootinittemplate/config/captcha/model/CaptchaCreate.java", "snippet": "@Data\n@NoArgsConstructor\n@AllArgsConstructor\n@Accessors(chain = true)\npublic class CaptchaCreate implements Serializable {\n\n private static final long serialVersionUID = -2384156304879302998L;\n\n /**\n * 是否开启验证码\n */\n private boolean enableCode;\n\n /**\n * 验证码UUID,用于组成Redis中的键\n */\n private String uuid;\n\n /**\n * 验证码图片Base64字符串\n */\n private String imgBase64;\n\n}" }, { "identifier": "CaptchaService", "path": "src/main/java/top/sharehome/springbootinittemplate/config/captcha/service/CaptchaService.java", "snippet": "public interface CaptchaService {\n\n /**\n * 生成验证码\n */\n CaptchaCreate createCaptcha();\n\n /**\n * 校验验证码\n *\n * @param code 验证码\n * @param uuid 验证码的UUID\n */\n void checkCaptcha(String code, String uuid);\n\n}" }, { "identifier": "CacheUtils", "path": "src/main/java/top/sharehome/springbootinittemplate/utils/redisson/cache/CacheUtils.java", "snippet": "@Slf4j\npublic class CacheUtils {\n\n /**\n * 被封装的redisson客户端对象\n */\n private static final RedissonClient REDISSON_CLIENT = SpringContextHolder.getBean(RedissonClient.class);\n\n /**\n * 设置缓存\n *\n * @param key 缓存键\n * @param value 缓存值\n * @param <T> 泛型T\n */\n public static <T> void put(String key, T value) {\n RBucket<T> bucket = REDISSON_CLIENT.getBucket(KeyPrefixConstants.CACHE_KEY_PREFIX + key);\n bucket.set(value);\n }\n\n /**\n * 设置缓存,同时设置过期时间\n *\n * @param key 缓存键\n * @param value 缓存值\n * @param expired 过期时间\n * @param <T> 泛型T\n */\n public static <T> void put(String key, T value, long expired) {\n RBucket<T> bucket = REDISSON_CLIENT.getBucket(KeyPrefixConstants.CACHE_KEY_PREFIX + key);\n bucket.set(value, Duration.ofSeconds(expired));\n }\n\n /**\n * 设置空缓存\n *\n * @param key 缓存键\n */\n public static void putNull(String key) {\n RBucket<?> bucket = REDISSON_CLIENT.getBucket(KeyPrefixConstants.CACHE_KEY_PREFIX + key);\n bucket.set(null);\n }\n\n /**\n * 设置空缓存,同时设置过期时间\n *\n * @param key 缓存键\n * @param expired 过期时间\n */\n public static void putNull(String key, long expired) {\n RBucket<?> bucket = REDISSON_CLIENT.getBucket(KeyPrefixConstants.CACHE_KEY_PREFIX + key);\n bucket.set(null, Duration.ofSeconds(expired));\n }\n\n /**\n * 如果存在则设置缓存\n *\n * @param key 缓存键\n * @param value 缓存值\n */\n public static <T> void putIfExists(String key, T value) {\n RBucket<T> bucket = REDISSON_CLIENT.getBucket(KeyPrefixConstants.CACHE_KEY_PREFIX + key);\n bucket.setIfExists(value);\n }\n\n /**\n * 如果不存在则设置缓存,同时设置过期时间\n *\n * @param key 缓存键\n * @param value 缓存值\n * @param expired 过期时间\n */\n public static <T> void putIfExists(String key, T value, long expired) {\n RBucket<T> bucket = REDISSON_CLIENT.getBucket(KeyPrefixConstants.CACHE_KEY_PREFIX + key);\n bucket.setIfExists(value, Duration.ofSeconds(expired));\n }\n\n /**\n * 如果不存在则设置缓存\n *\n * @param key 缓存键\n * @param value 缓存值\n */\n public static <T> void putIfAbsent(String key, T value) {\n RBucket<T> bucket = REDISSON_CLIENT.getBucket(KeyPrefixConstants.CACHE_KEY_PREFIX + key);\n bucket.setIfAbsent(value);\n }\n\n /**\n * 如果不存在则设置缓存,同时设置过期时间\n *\n * @param key 缓存键\n * @param value 缓存值\n * @param expired 过期时间\n */\n public static <T> void putIfAbsent(String key, T value, long expired) {\n RBucket<T> bucket = REDISSON_CLIENT.getBucket(KeyPrefixConstants.CACHE_KEY_PREFIX + key);\n bucket.setIfAbsent(value, Duration.ofSeconds(expired));\n }\n\n /**\n * 获取缓存\n *\n * @param key 缓存键\n * @param <T> 泛型T\n * @return 返回结果\n */\n public static <T> T get(String key) {\n RBucket<T> bucket = REDISSON_CLIENT.getBucket(KeyPrefixConstants.CACHE_KEY_PREFIX + key);\n return bucket.get();\n }\n\n /**\n * 使用通配符模糊获取缓存键\n * * 表示匹配零个或多个字符。\n * ? 表示匹配一个字符。\n *\n * @param keyPattern key通配符\n */\n public static List<String> getKeysByPattern(String keyPattern) {\n RKeys keys = REDISSON_CLIENT.getKeys();\n Iterable<String> keysByPattern = keys.getKeysByPattern(KeyPrefixConstants.CACHE_KEY_PREFIX + keyPattern);\n // 这里使用链表存储键,从理论上尽可能多的存储键\n List<String> res = new LinkedList<String>();\n keysByPattern.forEach(key -> {\n res.add(key.replaceFirst(KeyPrefixConstants.CACHE_KEY_PREFIX, \"\"));\n });\n return res;\n }\n\n /**\n * 使用通配符模糊获取缓存键值对\n * * 表示匹配零个或多个字符。\n * ? 表示匹配一个字符。\n *\n * @param keyPattern key通配符\n */\n public static <T> Map<String, T> getKeyValuesByPattern(String keyPattern) {\n return getKeysByPattern(keyPattern).stream().map(c -> {\n HashMap<String, Object> hashMap = new LinkedHashMap<>();\n hashMap.put(\"key\", c);\n hashMap.put(\"value\", get(c));\n return hashMap;\n }).collect(Collectors.toMap(map -> (String) map.get(\"key\"), map -> (T) map.get(\"value\")));\n }\n\n /**\n * 判断缓存是否存在\n *\n * @param key 缓存键\n * @return 返回结果\n */\n public static boolean exists(String key) {\n return REDISSON_CLIENT.getBucket(KeyPrefixConstants.CACHE_KEY_PREFIX + key).isExists();\n }\n\n /**\n * 删除缓存\n *\n * @param key 缓存键\n */\n public static void delete(String key) {\n REDISSON_CLIENT.getBucket(KeyPrefixConstants.CACHE_KEY_PREFIX + key).delete();\n }\n\n /**\n * 使用通配符模糊删除缓存\n * * 表示匹配零个或多个字符。\n * ? 表示匹配一个字符。\n *\n * @param keyPattern key通配符\n */\n public static void deleteByPattern(String keyPattern) {\n REDISSON_CLIENT.getKeys().deleteByPattern(KeyPrefixConstants.CACHE_KEY_PREFIX + keyPattern);\n }\n\n /**\n * 设置String类型缓存\n *\n * @param key 缓存键\n * @param value 缓存值\n */\n public static void putString(String key, CharSequence value) {\n RBucket<CharSequence> bucket = REDISSON_CLIENT.getBucket(KeyPrefixConstants.STRING_PREFIX + key, StringCodec.INSTANCE);\n bucket.set(value);\n }\n\n /**\n * 设置String类型缓存,同时设置过期时间\n *\n * @param key 缓存键\n * @param value 缓存值\n * @param expired 过期时间\n */\n public static void putString(String key, CharSequence value, long expired) {\n RBucket<CharSequence> bucket = REDISSON_CLIENT.getBucket(KeyPrefixConstants.STRING_PREFIX + key, StringCodec.INSTANCE);\n bucket.set(value, Duration.ofSeconds(expired));\n }\n\n /**\n * 如果存在则设置String类型缓存\n *\n * @param key 缓存键\n * @param value 缓存值\n */\n public static void putStringIfExists(String key, CharSequence value) {\n RBucket<CharSequence> bucket = REDISSON_CLIENT.getBucket(KeyPrefixConstants.STRING_PREFIX + key, StringCodec.INSTANCE);\n bucket.setIfExists(value);\n }\n\n /**\n * 如果不存在则设置String类型缓存,同时设置过期时间\n *\n * @param key 缓存键\n * @param value 缓存值\n * @param expired 过期时间\n */\n public static void putStringIfExists(String key, CharSequence value, long expired) {\n RBucket<CharSequence> bucket = REDISSON_CLIENT.getBucket(KeyPrefixConstants.STRING_PREFIX + key, StringCodec.INSTANCE);\n bucket.setIfExists(value, Duration.ofSeconds(expired));\n }\n\n /**\n * 如果不存在则设置String类型缓存\n *\n * @param key 缓存键\n * @param value 缓存值\n */\n public static void putStringIfAbsent(String key, CharSequence value) {\n RBucket<CharSequence> bucket = REDISSON_CLIENT.getBucket(KeyPrefixConstants.STRING_PREFIX + key, StringCodec.INSTANCE);\n bucket.setIfAbsent(value);\n }\n\n /**\n * 如果不存在则设置String类型缓存,同时设置过期时间\n *\n * @param key 缓存键\n * @param value 缓存值\n * @param expired 过期时间\n */\n public static void putStringIfAbsent(String key, CharSequence value, long expired) {\n RBucket<CharSequence> bucket = REDISSON_CLIENT.getBucket(KeyPrefixConstants.STRING_PREFIX + key, StringCodec.INSTANCE);\n bucket.setIfAbsent(value, Duration.ofSeconds(expired));\n }\n\n /**\n * 获取String类型缓存\n *\n * @param key 缓存键\n * @return 返回结果\n */\n public static String getString(String key) {\n RBucket<String> bucket = REDISSON_CLIENT.getBucket(KeyPrefixConstants.STRING_PREFIX + key, StringCodec.INSTANCE);\n return bucket.get();\n }\n\n /**\n * 使用通配符模糊获取String类型缓存键\n * * 表示匹配零个或多个字符。\n * ? 表示匹配一个字符。\n *\n * @param keyPattern key通配符\n */\n public static List<String> getStringKeysByPattern(String keyPattern) {\n RKeys keys = REDISSON_CLIENT.getKeys();\n Iterable<String> keysByPattern = keys.getKeysByPattern(KeyPrefixConstants.STRING_PREFIX + keyPattern);\n // 这里使用链表存储键,从理论上尽可能多的存储键\n List<String> res = new LinkedList<String>();\n keysByPattern.forEach(key -> {\n res.add(key.replaceFirst(KeyPrefixConstants.STRING_PREFIX, \"\"));\n });\n return res;\n }\n\n /**\n * 使用通配符模糊获取String类型缓存键值对\n * * 表示匹配零个或多个字符。\n * ? 表示匹配一个字符。\n *\n * @param keyPattern key通配符\n */\n public static Map<String, String> getStringKeyValuesByPattern(String keyPattern) {\n return getStringKeysByPattern(keyPattern).stream().map(c -> {\n HashMap<String, Object> hashMap = new LinkedHashMap<>();\n hashMap.put(\"key\", c);\n hashMap.put(\"value\", getString(c));\n return hashMap;\n }).collect(Collectors.toMap(map -> (String) map.get(\"key\"), map -> (String) map.get(\"value\")));\n }\n\n /**\n * 判断String类型缓存是否存在\n *\n * @param key 缓存键\n * @return 返回结果\n */\n public static boolean existsString(String key) {\n return REDISSON_CLIENT.getBucket(KeyPrefixConstants.STRING_PREFIX + key).isExists();\n }\n\n /**\n * 删除String类型缓存\n *\n * @param key 缓存键\n */\n public static void deleteString(String key) {\n REDISSON_CLIENT.getBucket(KeyPrefixConstants.STRING_PREFIX + key).delete();\n }\n\n /**\n * 使用通配符模糊删除String类型缓存\n * * 表示匹配零个或多个字符。\n * ? 表示匹配一个字符。\n *\n * @param keyPattern key通配符\n */\n public static void deleteStringByPattern(String keyPattern) {\n REDISSON_CLIENT.getKeys().deleteByPattern(KeyPrefixConstants.STRING_PREFIX + keyPattern);\n }\n\n /**\n * 设置Number类型缓存\n *\n * @param key 缓存键\n * @param value 缓存值\n */\n public static void putNumber(String key, Number value) {\n RBucket<Number> bucket = REDISSON_CLIENT.getBucket(KeyPrefixConstants.NUMBER_PREFIX + key);\n bucket.set(value);\n }\n\n /**\n * 设置Number类型缓存,同时设置过期时间\n *\n * @param key 缓存键\n * @param value 缓存值\n * @param expired 过期时间\n */\n public static void putNumber(String key, CharSequence value, long expired) {\n RBucket<CharSequence> bucket = REDISSON_CLIENT.getBucket(KeyPrefixConstants.NUMBER_PREFIX + key);\n bucket.set(value, Duration.ofSeconds(expired));\n }\n\n /**\n * 如果存在则设置Number类型缓存\n *\n * @param key 缓存键\n * @param value 缓存值\n */\n public static void putNumberIfExists(String key, CharSequence value) {\n RBucket<CharSequence> bucket = REDISSON_CLIENT.getBucket(KeyPrefixConstants.NUMBER_PREFIX + key);\n bucket.setIfExists(value);\n }\n\n /**\n * 如果不存在则设置Number类型缓存,同时设置过期时间\n *\n * @param key 缓存键\n * @param value 缓存值\n * @param expired 过期时间\n */\n public static void putNumberIfExists(String key, CharSequence value, long expired) {\n RBucket<CharSequence> bucket = REDISSON_CLIENT.getBucket(KeyPrefixConstants.NUMBER_PREFIX + key);\n bucket.setIfExists(value, Duration.ofSeconds(expired));\n }\n\n /**\n * 如果不存在则设置Number类型缓存\n *\n * @param key 缓存键\n * @param value 缓存值\n */\n public static void putNumberIfAbsent(String key, CharSequence value) {\n RBucket<CharSequence> bucket = REDISSON_CLIENT.getBucket(KeyPrefixConstants.NUMBER_PREFIX + key);\n bucket.setIfAbsent(value);\n }\n\n /**\n * 如果不存在则设置Number类型缓存,同时设置过期时间\n *\n * @param key 缓存键\n * @param value 缓存值\n * @param expired 过期时间\n */\n public static void putNumberIfAbsent(String key, CharSequence value, long expired) {\n RBucket<CharSequence> bucket = REDISSON_CLIENT.getBucket(KeyPrefixConstants.NUMBER_PREFIX + key);\n bucket.setIfAbsent(value, Duration.ofSeconds(expired));\n }\n\n /**\n * 获取Number类型缓存\n *\n * @param key 缓存键\n * @return 返回结果\n */\n public static Number getNumber(String key) {\n RBucket<Number> bucket = REDISSON_CLIENT.getBucket(KeyPrefixConstants.NUMBER_PREFIX + key);\n return bucket.get();\n }\n\n /**\n * 获取Number中byte类型缓存\n *\n * @param key 缓存键\n * @return 返回结果\n */\n public static byte getNumberByteValue(String key) {\n RBucket<Number> bucket = REDISSON_CLIENT.getBucket(KeyPrefixConstants.NUMBER_PREFIX + key);\n return bucket.get().byteValue();\n }\n\n /**\n * 获取Number中int类型缓存\n *\n * @param key 缓存键\n * @return 返回结果\n */\n public static int getNumberIntValue(String key) {\n RBucket<Number> bucket = REDISSON_CLIENT.getBucket(KeyPrefixConstants.NUMBER_PREFIX + key);\n return bucket.get().intValue();\n }\n\n /**\n * 获取Number中short类型缓存\n *\n * @param key 缓存键\n * @return 返回结果\n */\n public static int getNumberShortValue(String key) {\n RBucket<Number> bucket = REDISSON_CLIENT.getBucket(KeyPrefixConstants.NUMBER_PREFIX + key);\n return bucket.get().shortValue();\n }\n\n /**\n * 获取Number中long类型缓存\n *\n * @param key 缓存键\n * @return 返回结果\n */\n public static long getNumberLongValue(String key) {\n RBucket<Number> bucket = REDISSON_CLIENT.getBucket(KeyPrefixConstants.NUMBER_PREFIX + key);\n return bucket.get().longValue();\n }\n\n /**\n * 获取Number中float类型缓存\n *\n * @param key 缓存键\n * @return 返回结果\n */\n public static float getNumberFloatValue(String key) {\n RBucket<Number> bucket = REDISSON_CLIENT.getBucket(KeyPrefixConstants.NUMBER_PREFIX + key);\n return bucket.get().floatValue();\n }\n\n /**\n * 获取Number中double类型缓存\n *\n * @param key 缓存键\n * @return 返回结果\n */\n public static double getNumberDoubleValue(String key) {\n RBucket<Number> bucket = REDISSON_CLIENT.getBucket(KeyPrefixConstants.NUMBER_PREFIX + key);\n return bucket.get().doubleValue();\n }\n\n /**\n * 使用通配符模糊获取Number类型缓存键\n * * 表示匹配零个或多个字符。\n * ? 表示匹配一个字符。\n *\n * @param keyPattern key通配符\n */\n public static List<String> getNumberKeysByPattern(String keyPattern) {\n RKeys keys = REDISSON_CLIENT.getKeys();\n Iterable<String> keysByPattern = keys.getKeysByPattern(KeyPrefixConstants.NUMBER_PREFIX + keyPattern);\n // 这里使用链表存储键,从理论上尽可能多的存储键\n List<String> res = new LinkedList<String>();\n keysByPattern.forEach(key -> {\n res.add(key.replaceFirst(KeyPrefixConstants.NUMBER_PREFIX, \"\"));\n });\n return res;\n }\n\n /**\n * 使用通配符模糊获取缓存Number类型键值对\n * * 表示匹配零个或多个字符。\n * ? 表示匹配一个字符。\n *\n * @param keyPattern key通配符\n */\n public static Map<String, Number> getNumberKeyValuesByPattern(String keyPattern) {\n return getNumberKeysByPattern(keyPattern).stream().map(c -> {\n HashMap<String, Object> hashMap = new LinkedHashMap<>();\n hashMap.put(\"key\", c);\n hashMap.put(\"value\", getNumber(c));\n return hashMap;\n }).collect(Collectors.toMap(map -> (String) map.get(\"key\"), map -> (Number) map.get(\"value\")));\n }\n\n /**\n * 判断Number类型缓存是否存在\n *\n * @param key 缓存键\n * @return 返回结果\n */\n public static boolean existsNumber(String key) {\n return REDISSON_CLIENT.getBucket(KeyPrefixConstants.NUMBER_PREFIX + key).isExists();\n }\n\n /**\n * 删除Number类型缓存\n *\n * @param key 缓存键\n */\n public static void deleteNumber(String key) {\n REDISSON_CLIENT.getBucket(KeyPrefixConstants.NUMBER_PREFIX + key).delete();\n }\n\n /**\n * 使用通配符模糊删除Number类型缓存\n * * 表示匹配零个或多个字符。\n * ? 表示匹配一个字符。\n *\n * @param keyPattern key通配符\n */\n public static void deleteNumberByPattern(String keyPattern) {\n REDISSON_CLIENT.getKeys().deleteByPattern(KeyPrefixConstants.NUMBER_PREFIX + keyPattern);\n }\n\n /**\n * 设置List类型缓存\n *\n * @param key 缓存键\n * @param valueList 缓存值\n * @param <T> 泛型T\n */\n public static <T> void putList(String key, List<T> valueList) {\n RList<T> list = REDISSON_CLIENT.getList(KeyPrefixConstants.LIST_PREFIX + key);\n list.addAll(valueList);\n }\n\n /**\n * 设置List类型缓存,同时设置过期时间\n *\n * @param key 缓存键\n * @param valueList 缓存值\n * @param <T> 泛型T\n */\n public static <T> void putList(String key, List<T> valueList, long expired) {\n RList<T> list = REDISSON_CLIENT.getList(KeyPrefixConstants.LIST_PREFIX + key);\n list.addAll(valueList);\n list.expire(Duration.ofSeconds(expired));\n }\n\n /**\n * 如果存在则设置List类型缓存\n *\n * @param key 缓存键\n * @param valueList 缓存值\n * @param <T> 泛型T\n */\n public static <T> void putListIfExists(String key, List<T> valueList) {\n if (existsList(key)) {\n RList<T> list = REDISSON_CLIENT.getList(KeyPrefixConstants.LIST_PREFIX + key);\n list.addAll(valueList);\n }\n }\n\n /**\n * 如果存在则设置List类型缓存,同时设置过期时间\n *\n * @param key 缓存键\n * @param valueList 缓存值\n * @param expired 过期时间\n * @param <T> 泛型T\n */\n public static <T> void putListIfExists(String key, List<T> valueList, long expired) {\n if (existsList(key)) {\n RList<T> list = REDISSON_CLIENT.getList(KeyPrefixConstants.LIST_PREFIX + key);\n list.addAll(valueList);\n list.expire(Duration.ofSeconds(expired));\n }\n }\n\n /**\n * 如果不存在则设置List类型缓存\n *\n * @param key 缓存键\n * @param valueList 缓存值\n * @param <T> 泛型T\n */\n public static <T> void putListIfAbsent(String key, List<T> valueList) {\n if (!existsList(key)) {\n RList<T> list = REDISSON_CLIENT.getList(KeyPrefixConstants.LIST_PREFIX + key);\n list.addAll(valueList);\n }\n }\n\n /**\n * 如果不存在则设置List类型缓存,同时设置过期时间\n *\n * @param key 缓存键\n * @param valueList 缓存值\n * @param expired 过期时间\n * @param <T> 泛型T\n */\n public static <T> void putListIfAbsent(String key, List<T> valueList, long expired) {\n if (!existsList(key)) {\n RList<T> list = REDISSON_CLIENT.getList(KeyPrefixConstants.LIST_PREFIX + key);\n list.addAll(valueList);\n list.expire(Duration.ofSeconds(expired));\n }\n }\n\n /**\n * 获取List类型缓存\n *\n * @param key 缓存键\n * @param <T> 泛型T\n * @return 返回结果\n */\n public static <T> List<T> getList(String key) {\n return REDISSON_CLIENT.getList(KeyPrefixConstants.LIST_PREFIX + key);\n }\n\n /**\n * 使用通配符模糊获取List类型缓存键\n * * 表示匹配零个或多个字符。\n * ? 表示匹配一个字符。\n *\n * @param keyPattern key通配符\n */\n public static List<String> getListKeysByPattern(String keyPattern) {\n RKeys keys = REDISSON_CLIENT.getKeys();\n Iterable<String> keysByPattern = keys.getKeysByPattern(KeyPrefixConstants.LIST_PREFIX + keyPattern);\n // 这里使用链表存储键,从理论上尽可能多的存储键\n List<String> res = new LinkedList<String>();\n keysByPattern.forEach(key -> {\n res.add(key.replaceFirst(KeyPrefixConstants.LIST_PREFIX, \"\"));\n });\n return res;\n }\n\n /**\n * 使用通配符模糊获取缓List类型存键值对\n * * 表示匹配零个或多个字符。\n * ? 表示匹配一个字符。\n *\n * @param keyPattern key通配符\n */\n public static Map<String, List> getListKeyValuesByPattern(String keyPattern) {\n return getListKeysByPattern(keyPattern).stream().map(c -> {\n HashMap<String, Object> hashMap = new LinkedHashMap<>();\n hashMap.put(\"key\", c);\n hashMap.put(\"value\", getList(c));\n return hashMap;\n }).collect(Collectors.toMap(map -> (String) map.get(\"key\"), map -> (List) map.get(\"value\")));\n }\n\n /**\n * 判断List类型缓存是否存在\n *\n * @param key 缓存键\n * @return 返回结果\n */\n public static boolean existsList(String key) {\n return REDISSON_CLIENT.getBucket(KeyPrefixConstants.LIST_PREFIX + key).isExists();\n }\n\n /**\n * 删除List类型缓存\n *\n * @param key 缓存键\n */\n public static void deleteList(String key) {\n REDISSON_CLIENT.getBucket(KeyPrefixConstants.LIST_PREFIX + key).delete();\n }\n\n /**\n * 使用通配符模糊删除List类型缓存\n * * 表示匹配零个或多个字符。\n * ? 表示匹配一个字符。\n *\n * @param keyPattern key通配符\n */\n public static void deleteListByPattern(String keyPattern) {\n REDISSON_CLIENT.getKeys().deleteByPattern(KeyPrefixConstants.LIST_PREFIX + keyPattern);\n }\n\n /**\n * 设置Set类型缓存\n *\n * @param key 缓存键\n * @param valueSet 缓存值\n * @param <T> 泛型T\n */\n public static <T> void putSet(String key, Set<T> valueSet) {\n RSet<T> set = REDISSON_CLIENT.getSet(KeyPrefixConstants.SET_PREFIX + key);\n set.addAll(valueSet);\n }\n\n /**\n * 设置Set类型缓存,同时设置过期时间\n *\n * @param key 缓存键\n * @param valueSet 缓存值\n * @param <T> 泛型T\n */\n public static <T> void putSet(String key, Set<T> valueSet, long expired) {\n RSet<T> set = REDISSON_CLIENT.getSet(KeyPrefixConstants.SET_PREFIX + key);\n set.addAll(valueSet);\n set.expire(Duration.ofSeconds(expired));\n }\n\n /**\n * 如果存在则设置Set类型缓存\n *\n * @param key 缓存键\n * @param valueSet 缓存值\n * @param <T> 泛型T\n */\n public static <T> void putSetIfExists(String key, Set<T> valueSet) {\n if (existsSet(key)) {\n RSet<T> set = REDISSON_CLIENT.getSet(KeyPrefixConstants.SET_PREFIX + key);\n set.addAll(valueSet);\n }\n }\n\n /**\n * 如果存在则设置Set类型缓存,同时设置过期时间\n *\n * @param key 缓存键\n * @param valueSet 缓存值\n * @param expired 过期时间\n * @param <T> 泛型T\n */\n public static <T> void putSetIfExists(String key, Set<T> valueSet, long expired) {\n if (existsSet(key)) {\n RSet<T> set = REDISSON_CLIENT.getSet(KeyPrefixConstants.SET_PREFIX + key);\n set.addAll(valueSet);\n set.expire(Duration.ofSeconds(expired));\n }\n }\n\n /**\n * 如果不存在则设置Set类型缓存\n *\n * @param key 缓存键\n * @param valueSet 缓存值\n * @param <T> 泛型T\n */\n public static <T> void putSetIfAbsent(String key, Set<T> valueSet) {\n if (!existsSet(key)) {\n RSet<T> set = REDISSON_CLIENT.getSet(KeyPrefixConstants.SET_PREFIX + key);\n set.addAll(valueSet);\n }\n }\n\n /**\n * 如果不存在则设置Set类型缓存,同时设置过期时间\n *\n * @param key 缓存键\n * @param valueSet 缓存值\n * @param expired 过期时间\n * @param <T> 泛型T\n */\n public static <T> void putSetIfAbsent(String key, Set<T> valueSet, long expired) {\n if (!existsSet(key)) {\n RSet<T> set = REDISSON_CLIENT.getSet(KeyPrefixConstants.SET_PREFIX + key);\n set.addAll(valueSet);\n set.expire(Duration.ofSeconds(expired));\n }\n }\n\n /**\n * 获取Set类型缓存\n *\n * @param key 缓存键\n * @param <T> 泛型T\n * @return 返回结果\n */\n public static <T> Set<T> getSet(String key) {\n return REDISSON_CLIENT.getSet(KeyPrefixConstants.SET_PREFIX + key);\n }\n\n /**\n * 使用通配符模糊获取Set类型缓存键\n * * 表示匹配零个或多个字符。\n * ? 表示匹配一个字符。\n *\n * @param keyPattern key通配符\n */\n public static List<String> getSetKeysByPattern(String keyPattern) {\n RKeys keys = REDISSON_CLIENT.getKeys();\n Iterable<String> keysByPattern = keys.getKeysByPattern(KeyPrefixConstants.SET_PREFIX + keyPattern);\n // 这里使用链表存储键,从理论上尽可能多的存储键\n List<String> res = new LinkedList<String>();\n keysByPattern.forEach(key -> {\n res.add(key.replaceFirst(KeyPrefixConstants.SET_PREFIX, \"\"));\n });\n return res;\n }\n\n /**\n * 使用通配符模糊获取Set类型缓存键值对\n * * 表示匹配零个或多个字符。\n * ? 表示匹配一个字符。\n *\n * @param keyPattern key通配符\n */\n public static Map<String, Set> getSetKeyValuesByPattern(String keyPattern) {\n return getSetKeysByPattern(keyPattern).stream().map(c -> {\n HashMap<String, Object> hashMap = new LinkedHashMap<>();\n hashMap.put(\"key\", c);\n hashMap.put(\"value\", getSet(c));\n return hashMap;\n }).collect(Collectors.toMap(map -> (String) map.get(\"key\"), map -> (Set) map.get(\"value\")));\n }\n\n /**\n * 判断Set类型缓存是否存在\n *\n * @param key 缓存键\n * @return 返回结果\n */\n public static boolean existsSet(String key) {\n return REDISSON_CLIENT.getBucket(KeyPrefixConstants.SET_PREFIX + key).isExists();\n }\n\n /**\n * 删除Set类型缓存\n *\n * @param key 缓存键\n */\n public static void deleteSet(String key) {\n REDISSON_CLIENT.getBucket(KeyPrefixConstants.SET_PREFIX + key).delete();\n }\n\n /**\n * 使用通配符模糊删除Set类型缓存\n * * 表示匹配零个或多个字符。\n * ? 表示匹配一个字符。\n *\n * @param keyPattern key通配符\n */\n public static void deleteSetByPattern(String keyPattern) {\n REDISSON_CLIENT.getKeys().deleteByPattern(KeyPrefixConstants.SET_PREFIX + keyPattern);\n }\n\n /**\n * 设置Map类型缓存\n *\n * @param key 缓存键\n * @param valueMap 缓存值\n * @param <K> 泛型K\n * @param <V> 泛型V\n */\n public static <K, V> void putMap(String key, Map<K, V> valueMap) {\n RMap<K, V> map = REDISSON_CLIENT.getMap(KeyPrefixConstants.MAP_PREFIX + key);\n map.putAll(valueMap);\n }\n\n /**\n * 设置Map类型缓存,同时设置过期时间\n *\n * @param key 缓存键\n * @param valueMap 缓存值\n * @param <K> 泛型K\n * @param <V> 泛型V\n */\n public static <K, V> void putMap(String key, Map<K, V> valueMap, long expired) {\n RMap<K, V> map = REDISSON_CLIENT.getMap(KeyPrefixConstants.MAP_PREFIX + key);\n map.putAll(valueMap);\n map.expire(Duration.ofSeconds(expired));\n }\n\n /**\n * 如果存在则设置Map类型缓存\n *\n * @param key 缓存键\n * @param valueMap 缓存值\n * @param <K> 泛型K\n * @param <V> 泛型V\n */\n public static <K, V> void putMapIfExists(String key, Map<K, V> valueMap) {\n if (existsMap(key)) {\n RMap<K, V> map = REDISSON_CLIENT.getMap(KeyPrefixConstants.MAP_PREFIX + key);\n map.putAll(valueMap);\n }\n }\n\n /**\n * 如果存在则设置Map类型缓存,同时设置过期时间\n *\n * @param key 缓存键\n * @param valueMap 缓存值\n * @param expired 过期时间\n * @param <K> 泛型K\n * @param <V> 泛型V\n */\n public static <K, V> void putMapIfExists(String key, Map<K, V> valueMap, long expired) {\n if (existsMap(key)) {\n RMap<K, V> map = REDISSON_CLIENT.getMap(KeyPrefixConstants.MAP_PREFIX + key);\n map.putAll(valueMap);\n map.expire(Duration.ofSeconds(expired));\n }\n }\n\n /**\n * 如果不存在则设置Map类型缓存\n *\n * @param key 缓存键\n * @param valueMap 缓存值\n * @param <K> 泛型K\n * @param <V> 泛型V\n */\n public static <K, V> void putMapIfAbsent(String key, Map<K, V> valueMap) {\n if (!existsMap(key)) {\n RMap<K, V> map = REDISSON_CLIENT.getMap(KeyPrefixConstants.MAP_PREFIX + key);\n map.putAll(valueMap);\n }\n }\n\n /**\n * 如果不存在则设置Map类型缓存,同时设置过期时间\n *\n * @param key 缓存键\n * @param valueMap 缓存值\n * @param expired 过期时间\n * @param <K> 泛型K\n * @param <V> 泛型V\n */\n public static <K, V> void putMapIfAbsent(String key, Map<K, V> valueMap, long expired) {\n if (!existsMap(key)) {\n RMap<K, V> map = REDISSON_CLIENT.getMap(KeyPrefixConstants.MAP_PREFIX + key);\n map.putAll(valueMap);\n map.expire(Duration.ofSeconds(expired));\n }\n }\n\n /**\n * 获取Map类型缓存\n *\n * @param key 缓存键\n * @param <K> 泛型K\n * @param <V> 泛型V\n * @return 返回结果\n */\n public static <K, V> Map<K, V> getMap(String key) {\n RMap<K, V> map = REDISSON_CLIENT.getMap(KeyPrefixConstants.MAP_PREFIX + key);\n return new HashMap<K, V>(map);\n }\n\n /**\n * 使用通配符模糊获取Map类型缓存键\n * * 表示匹配零个或多个字符。\n * ? 表示匹配一个字符。\n *\n * @param keyPattern key通配符\n */\n public static List<String> getMapKeysByPattern(String keyPattern) {\n RKeys keys = REDISSON_CLIENT.getKeys();\n Iterable<String> keysByPattern = keys.getKeysByPattern(KeyPrefixConstants.MAP_PREFIX + keyPattern);\n // 这里使用链表存储键,从理论上尽可能多的存储键\n List<String> res = new LinkedList<String>();\n keysByPattern.forEach(key -> {\n res.add(key.replaceFirst(KeyPrefixConstants.MAP_PREFIX, \"\"));\n });\n return res;\n }\n\n /**\n * 使用通配符模糊获取Map类型缓存键值对\n * * 表示匹配零个或多个字符。\n * ? 表示匹配一个字符。\n *\n * @param keyPattern key通配符\n */\n public static Map<String, Map> getMapKeyValuesByPattern(String keyPattern) {\n return getMapKeysByPattern(keyPattern).stream().map(c -> {\n HashMap<String, Object> hashMap = new LinkedHashMap<>();\n hashMap.put(\"key\", c);\n hashMap.put(\"value\", getMap(c));\n return hashMap;\n }).collect(Collectors.toMap(map -> (String) map.get(\"key\"), map -> (Map) map.get(\"value\")));\n }\n\n /**\n * 判断Map类型缓存是否存在\n *\n * @param key 缓存键\n * @return 返回结果\n */\n public static boolean existsMap(String key) {\n return REDISSON_CLIENT.getBucket(KeyPrefixConstants.MAP_PREFIX + key).isExists();\n }\n\n /**\n * 删除Map类型缓存\n *\n * @param key 缓存键\n */\n public static void deleteMap(String key) {\n REDISSON_CLIENT.getBucket(KeyPrefixConstants.MAP_PREFIX + key).delete();\n }\n\n /**\n * 使用通配符模糊删除Map类型缓存\n * * 表示匹配零个或多个字符。\n * ? 表示匹配一个字符。\n *\n * @param keyPattern key通配符\n */\n public static void deleteMapByPattern(String keyPattern) {\n REDISSON_CLIENT.getKeys().deleteByPattern(KeyPrefixConstants.MAP_PREFIX + keyPattern);\n }\n\n}" }, { "identifier": "KeyPrefixConstants", "path": "src/main/java/top/sharehome/springbootinittemplate/utils/redisson/KeyPrefixConstants.java", "snippet": "public interface KeyPrefixConstants {\n\n /**\n * 不带有类型的缓存Key前缀\n */\n String CACHE_KEY_PREFIX = \"CACHE_\";\n\n /**\n * String类型的缓存Key前准\n */\n String STRING_PREFIX = CACHE_KEY_PREFIX + \"STRING_\";\n\n /**\n * Number类型的缓存Key前准\n */\n String NUMBER_PREFIX = CACHE_KEY_PREFIX + \"NUMBER_\";\n\n /**\n * List类型的缓存Key前缀\n */\n String LIST_PREFIX = CACHE_KEY_PREFIX + \"LIST_\";\n\n /**\n * Set类型的缓存Key前缀\n */\n String SET_PREFIX = CACHE_KEY_PREFIX + \"SET_\";\n\n /**\n * Map类型的缓存Key前缀\n */\n String MAP_PREFIX = CACHE_KEY_PREFIX + \"MAP_\";\n\n /**\n * 系统限流Key前缀\n */\n String SYSTEM_RATE_LIMIT_PREFIX = \"SYSTEM_RATE_\";\n\n /**\n * 自定义限流Key前缀\n */\n String CUSTOMIZE_RATE_LIMIT_PREFIX = \"CUSTOMIZE_RATE_\";\n\n /**\n * 分布式锁Key前缀\n */\n String LOCK_PREFIX = \"LOCK_\";\n\n /**\n * 验证码Key前缀\n */\n String CAPTCHA_PREFIX = \"CAPTCHA_\";\n\n}" } ]
import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; import top.sharehome.springbootinittemplate.config.captcha.model.CaptchaCreate; import top.sharehome.springbootinittemplate.config.captcha.service.CaptchaService; import top.sharehome.springbootinittemplate.utils.redisson.cache.CacheUtils; import top.sharehome.springbootinittemplate.utils.redisson.KeyPrefixConstants; import javax.annotation.Resource;
10,657
package top.sharehome.springbootinittemplate.captcha; /** * 验证码测试类 * * @author AntonyCheng */ @SpringBootTest public class CaptchaTest { @Resource private CaptchaService captchaService; /** * 测试验证码生成和校验 */ @Test public void testCaptcha() { CaptchaCreate captcha = captchaService.createCaptcha(); String uuid = captcha.getUuid();
package top.sharehome.springbootinittemplate.captcha; /** * 验证码测试类 * * @author AntonyCheng */ @SpringBootTest public class CaptchaTest { @Resource private CaptchaService captchaService; /** * 测试验证码生成和校验 */ @Test public void testCaptcha() { CaptchaCreate captcha = captchaService.createCaptcha(); String uuid = captcha.getUuid();
String key = KeyPrefixConstants.CAPTCHA_PREFIX + uuid;
3
2023-11-12 07:49:59+00:00
12k
rmheuer/azalea
azalea-core/src/main/java/com/github/rmheuer/azalea/render2d/Renderer2D.java
[ { "identifier": "ResourceUtil", "path": "azalea-core/src/main/java/com/github/rmheuer/azalea/io/ResourceUtil.java", "snippet": "public final class ResourceUtil {\n /**\n * Reads a resource as an {@code InputStream}.\n *\n * @param path resource path to read\n * @return stream to read the resource\n * @throws FileNotFoundException if the resource is not found\n */\n public static InputStream readAsStream(String path) throws FileNotFoundException {\n InputStream stream = ResourceUtil.class.getClassLoader().getResourceAsStream(path);\n if (stream == null)\n throw new FileNotFoundException(\"Resource not found: \" + path);\n return stream;\n }\n\n /**\n * Reads a resource as a {@code String}.\n *\n * @param path resource path to read\n * @return string contents of the resource\n * @throws IOException if an IO error occurs\n */\n public static String readAsString(String path) throws IOException {\n return IOUtil.readToString(readAsStream(path));\n }\n\n /**\n * Gets the {@code Path} of a resource directory. This can be used to\n * iterate the files within the directory.\n *\n * @param dir resource path to the directory\n * @return NIO Path of the directory\n * @throws IOException if an IO error occurs\n */\n public static Path getDirectoryPath(String dir) throws IOException {\n if (dir.isEmpty())\n throw new IllegalArgumentException(\"directory cannot be empty\");\n\n URL url = ResourceUtil.class.getClassLoader().getResource(dir);\n if (url == null)\n throw new FileNotFoundException(\"Directory not found: \" + dir);\n\n URI uri;\n try {\n uri = url.toURI();\n } catch (URISyntaxException e) {\n throw new IOException(\"Failed to convert to URI\", e);\n }\n\n try {\n return Paths.get(uri);\n } catch (FileSystemNotFoundException e) {\n try {\n FileSystems.newFileSystem(uri, Collections.emptyMap());\n } catch (FileSystemAlreadyExistsException ignored) {\n }\n\n return Paths.get(uri);\n }\n }\n\n private ResourceUtil() {\n throw new AssertionError();\n }\n}" }, { "identifier": "ColorRGBA", "path": "azalea-core/src/main/java/com/github/rmheuer/azalea/render/ColorRGBA.java", "snippet": "public final class ColorRGBA extends Vector4f {\n /** @return the color {@code (0, 0, 0, 0)} */\n public static ColorRGBA transparent() { return new ColorRGBA(0, 0, 0, 0); }\n\n /** @return the color {@code (0, 0, 0)} */\n public static ColorRGBA black() { return new ColorRGBA(0, 0, 0); }\n\n /** @return the color {@code (1, 0, 0)} */\n public static ColorRGBA red() { return new ColorRGBA(1, 0, 0); }\n\n /** @return the color {@code (0, 1, 0)} */\n public static ColorRGBA green() { return new ColorRGBA(0, 1, 0); }\n\n /** @return the color {@code (1, 1, 0)} */\n public static ColorRGBA yellow() { return new ColorRGBA(1, 1, 0); }\n\n /** @return the color {@code (0, 0, 1)} */\n public static ColorRGBA blue() { return new ColorRGBA(0, 0, 1); }\n\n /** @return the color {@code (1, 0, 1)} */\n public static ColorRGBA magenta() { return new ColorRGBA(1, 0, 1); }\n\n /** @return the color {@code (0, 1, 1)} */\n public static ColorRGBA cyan() { return new ColorRGBA(0, 1, 1); }\n\n /** @return the color {@code (1, 1, 1)} */\n public static ColorRGBA white() { return new ColorRGBA(1, 1, 1); }\n\n /**\n * Helper to create a color from integer components. This creates a color\n * that is fully opaque.\n *\n * @param r red value from 0 to 255\n * @param g green value from 0 to 255\n * @param b blue value from 0 to 255\n * @return color\n */\n public static ColorRGBA rgb(int r, int g, int b) {\n return rgba(r, g, b, 255);\n }\n\n /**\n * Helper to create a color from integer components.\n *\n * @param r red value from 0 to 255\n * @param g green value from 0 to 255\n * @param b blue value from 0 to 255\n * @param a alpha value from 0 to 255. 0 is fully transparent, 255 is fully\n * opaque\n * @return color\n */\n public static ColorRGBA rgba(int r, int g, int b, int a) {\n return new ColorRGBA(r / 255.0f, g / 255.0f, b / 255.0f, a / 255.0f);\n }\n\n /**\n * Creates a new RGBA color with all components set to 0.\n */\n public ColorRGBA() {\n }\n\n /**\n * Creates a new RGBA color with given components from 0 to 1. This creates\n * a color with full opacity.\n *\n * @param r red component\n * @param g green component\n * @param b blue component\n */\n public ColorRGBA(float r, float g, float b) {\n this(r, g, b, 1.0f);\n }\n\n /**\n * Creates a new RGBA color with given components from 0 to 1.\n *\n * @param r red component\n * @param g green component\n * @param b blue component\n * @param a alpha component\n */\n public ColorRGBA(float r, float g, float b, float a) {\n super(r, g, b, a);\n }\n\n /**\n * Creates a new RGBA color with components stored in a vector. This\n * creates a color with full opacity.\n *\n * @param v vector of components. X is red, Y is green, and Z is blue\n */\n public ColorRGBA(Vector3fc v) {\n this(v.x(), v.y(), v.z(), 1.0f);\n }\n\n /**\n * Creates a new RGBA color with components stored in a vector.\n *\n * @param v vector of components. X is red, Y is green, Z is blue, and W is\n * alpha\n */\n public ColorRGBA(Vector4fc v) {\n super(v);\n }\n\n /**\n * Gets the red component of this color.\n *\n * @return red component from 0 to 1\n */\n public float getRed() {\n return x;\n }\n\n /**\n * Gets the green component of this color.\n *\n * @return green component from 0 to 1\n */\n public float getGreen() {\n return y;\n }\n\n /**\n * Gets the blue component of this color.\n *\n * @return blue component from 0 to 1\n */\n public float getBlue() {\n return z;\n }\n\n /**\n * Gets the alpha component of this color.\n *\n * @return alpha component from 0 to 1\n */\n public float getAlpha() {\n return w;\n }\n\n /**\n * Sets the red component of this color.\n *\n * @param r red component from 0 to 1\n * @return this\n */\n public ColorRGBA setRed(float r) {\n x = r;\n return this;\n }\n\n /**\n * Sets the green component of this color.\n *\n * @param g green component from 0 to 1\n * @return this\n */\n public ColorRGBA setGreen(float g) {\n y = g;\n return this;\n }\n\n /**\n * Sets the blue component of this color.\n *\n * @param b blue component from 0 to 1\n * @return this\n */\n public ColorRGBA setBlue(float b) {\n z = b;\n return this;\n }\n\n /**\n * Sets the alpha component of this color.\n *\n * @param a alpha component from 0 to 1\n * @return this\n */\n public ColorRGBA setAlpha(float a) {\n w = a;\n return this;\n }\n}" }, { "identifier": "Renderer", "path": "azalea-core/src/main/java/com/github/rmheuer/azalea/render/Renderer.java", "snippet": "public interface Renderer {\n /**\n * Sets the region of the viewport to render into.\n *\n * @param x x position of the lower-left corner\n * @param y y position of the lower-left corner\n * @param width width of the viewport rect\n * @param height height of the viewport rect\n */\n void setViewportRect(int x, int y, int width, int height);\n\n /**\n * Sets the color used to fill the window when clearing the color buffer.\n *\n * @param color new clear color\n */\n void setClearColor(ColorRGBA color);\n\n /**\n * Clears the contents of the specified buffers.\n *\n * @param buffers buffers to clear\n */\n void clear(BufferType... buffers);\n\n /**\n * Binds a pipeline for use.\n *\n * @param pipeline pipeline configuration\n * @return access to draw commands\n * @throws IllegalStateException if another pipeline is currently bound\n */\n ActivePipeline bindPipeline(PipelineInfo pipeline);\n\n /**\n * Creates and compiles a shader stage from GLSL source.\n *\n * @param type type of stage\n * @param glsl GLSL source code to compile\n * @return the stage\n */\n ShaderStage createShaderStage(ShaderStage.Type type, String glsl);\n\n /**\n * Creates a shader program from a set of shader stages. Typically there\n * will be at least a vertex stage and a fragment stage.\n *\n * @param stages stages to construct the program\n * @return the program\n */\n ShaderProgram createShaderProgram(ShaderStage... stages);\n\n /**\n * Creates a shader stage, reading the source from an {@code InputStream}\n * in UTF-8 encoding.\n *\n * @param type type of stage\n * @param in input stream to read source from\n * @return the stage\n * @throws IOException if an IO error occurs while reading the source\n */\n default ShaderStage createShaderStage(ShaderStage.Type type, InputStream in) throws IOException {\n return createShaderStage(type, IOUtil.readToString(in));\n }\n\n /**\n * Creates a shader program with a vertex stage and a fragment stage.\n *\n * @param vertexSrc GLSL source of the vertex stage\n * @param fragmentSrc GLSL source of the fragment stage\n * @return the program\n */\n default ShaderProgram createShaderProgram(String vertexSrc, String fragmentSrc) {\n try (ShaderStage vertexStage = createShaderStage(ShaderStage.Type.VERTEX, vertexSrc);\n ShaderStage fragmentStage = createShaderStage(ShaderStage.Type.FRAGMENT, fragmentSrc)) {\n return createShaderProgram(vertexStage, fragmentStage);\n }\n }\n\n /**\n * Creates a shader program with a vertex stage and a fragment stage from\n * {@code InputStream}s.\n *\n * @param vertexSrc input stream to read source of the vertex stage\n * @param fragmentSrc input stream to read source of the fragment stage\n * @return the program\n * @throws IOException if an IO error occurs while reading the sources\n */\n default ShaderProgram createShaderProgram(InputStream vertexSrc, InputStream fragmentSrc) throws IOException {\n try (ShaderStage vertexStage = createShaderStage(ShaderStage.Type.VERTEX, vertexSrc);\n ShaderStage fragmentStage = createShaderStage(ShaderStage.Type.FRAGMENT, fragmentSrc)) {\n return createShaderProgram(vertexStage, fragmentStage);\n }\n }\n\n /**\n * Creates an empty {@code Mesh}. You will need to upload data to the mesh\n * before drawing it.\n *\n * @return the created mesh\n */\n Mesh createMesh();\n\n /**\n * Creates an empty {@code Texture2D}. You will need to upload data to the\n * texture before rendering it.\n *\n * @return the created texture\n */\n Texture2D createTexture2D();\n\n /**\n * Creates a {@code Texture2D} and loads its data from an\n * {@code InputStream}. The stream is decoded using\n * {@link Bitmap#decode(InputStream)}.\n *\n * @param in input stream to read image data from\n * @return the created texture\n * @throws IOException if an IO error occurs while decoding the image data\n */\n default Texture2D createTexture2D(InputStream in) throws IOException {\n Bitmap bitmap = Bitmap.decode(in);\n Texture2D tex = createTexture2D();\n tex.setData(bitmap);\n return tex;\n }\n}" }, { "identifier": "Mesh", "path": "azalea-core/src/main/java/com/github/rmheuer/azalea/render/mesh/Mesh.java", "snippet": "public interface Mesh extends SafeCloseable {\n /**\n * The intended usage of the uploaded data. This helps select the most\n * optimal video memory to use for the data.\n */\n enum DataUsage {\n /** The data is uploaded rarely and rendered many times */\n STATIC,\n\n /** The data is uploaded frequently and rendered many times */\n DYNAMIC,\n\n /** The data is uploaded frequently and rendered once */\n STREAM\n }\n\n /**\n * Uploads a new set of data to the GPU.\n *\n * @param data new mesh data\n * @param usage intended usage of the data\n */\n void setData(MeshData data, DataUsage usage);\n\n /**\n * Gets whether this mesh has data on the GPU.\n *\n * @return has data\n */\n boolean hasData();\n}" }, { "identifier": "MeshData", "path": "azalea-core/src/main/java/com/github/rmheuer/azalea/render/mesh/MeshData.java", "snippet": "public final class MeshData implements SafeCloseable {\n private static final int INITIAL_CAPACITY = 16;\n\n private final PrimitiveType primType;\n private final VertexLayout layout;\n private int layoutElemIdx;\n\n private ByteBuffer vertexBuf;\n private final List<Integer> indices;\n private int mark;\n private boolean finished;\n private int finalVertexCount;\n\n /**\n * Creates a new data buffer with the specified layout.\n *\n * @param primType type of primitive to render\n * @param layout layout of the vertex data\n */\n public MeshData(PrimitiveType primType, AttribType... layout) {\n this(primType, new VertexLayout(layout));\n }\n\n /**\n * Creates a new data buffer with the specified layout.\n *\n * @param primType type of primitive to render\n * @param layout layout of the vertex data\n */\n public MeshData(PrimitiveType primType, VertexLayout layout) {\n this.primType = primType;\n this.layout = layout;\n layoutElemIdx = 0;\n\n indices = new ArrayList<>();\n mark = 0;\n finished = false;\n\n vertexBuf = MemoryUtil.memAlloc(INITIAL_CAPACITY * layout.sizeOf());\n }\n\n private void ensureSpace(int spaceBytes) {\n if (vertexBuf.remaining() < spaceBytes) {\n int cap = vertexBuf.capacity();\n vertexBuf = MemoryUtil.memRealloc(vertexBuf, Math.max(cap + spaceBytes, cap * 2));\n }\n }\n\n private void prepare(AttribType type) {\n AttribType[] types = layout.getTypes();\n\n ensureSpace(type.sizeOf());\n AttribType layoutType = types[layoutElemIdx++];\n if (layoutType != type)\n throw new IllegalStateException(\"Incorrect attribute added for format (added \" + type + \", layout specifies \" + layoutType + \")\");\n if (layoutElemIdx >= types.length)\n layoutElemIdx = 0;\n }\n\n /**\n * Marks the current position. The mark position is added to\n * indices added after this is called.\n *\n * @return this\n */\n public MeshData mark() {\n mark = getVertexCount();\n return this;\n }\n\n /**\n * Adds a {@code float} value.\n *\n * @param f value to add\n * @return this\n */\n public MeshData putFloat(float f) {\n prepare(AttribType.FLOAT);\n vertexBuf.putFloat(f);\n return this;\n }\n\n /**\n * Adds a {@code vec2} value.\n *\n * @param vec value to add\n * @return this\n */\n public MeshData putVec2(Vector2f vec) {\n return putVec2(vec.x, vec.y);\n }\n\n /**\n * Adds a {@code vec2} value.\n *\n * @param x x coordinate of the value\n * @param y y coordinate of the value\n * @return this\n */\n public MeshData putVec2(float x, float y) {\n prepare(AttribType.VEC2);\n vertexBuf.putFloat(x);\n vertexBuf.putFloat(y);\n return this;\n }\n\n /**\n * Adds a {@code vec3} value.\n *\n * @param vec value to add\n * @return this\n */\n public MeshData putVec3(Vector3f vec) {\n return putVec3(vec.x, vec.y, vec.z);\n }\n\n /**\n * Adds a {@code vec3} value.\n *\n * @param x x coordinate of the value\n * @param y y coordinate of the value\n * @param z z coordinate of the value\n * @return this\n */\n public MeshData putVec3(float x, float y, float z) {\n prepare(AttribType.VEC3);\n vertexBuf.putFloat(x);\n vertexBuf.putFloat(y);\n vertexBuf.putFloat(z);\n return this;\n }\n\n /**\n * Adds a {@code vec4} value.\n *\n * @param vec value to add\n * @return this\n */\n public MeshData putVec4(Vector4f vec) { return putVec4(vec.x, vec.y, vec.z, vec.w); }\n\n /**\n * Adds a {@code vec4} value.\n *\n * @param x x coordinate of the value\n * @param y y coordinate of the value\n * @param z z coordinate of the value\n * @param w w coordinate of the value\n * @return this\n */\n public MeshData putVec4(float x, float y, float z, float w) {\n prepare(AttribType.VEC4);\n vertexBuf.putFloat(x);\n vertexBuf.putFloat(y);\n vertexBuf.putFloat(z);\n vertexBuf.putFloat(w);\n return this;\n }\n\n /**\n * Adds an index to the index array. The index is added to the mark\n * position before adding it.\n *\n * @param i the index to add\n * @return this\n */\n public MeshData index(int i) {\n indices.add(mark + i);\n return this;\n }\n\n /**\n * Adds several indices to the index array. This is equivalent to calling\n * {@link #index(int)} for each index.\n * @param indices indices to add\n * @return this\n */\n public MeshData indices(int... indices) {\n for (int i : indices) {\n this.indices.add(mark + i);\n }\n return this;\n }\n\n /**\n * Adds several indices to the index array. This is equivalent to calling\n * {@link #index(int)} for each index.\n * @param indices indices to add\n * @return this\n */\n public MeshData indices(List<Integer> indices) {\n for (int i : indices) {\n this.indices.add(mark + i);\n }\n return this;\n }\n\n /**\n * Appends another mesh data buffer to this. This will not modify the\n * source buffer.\n *\n * @param other mesh data to append\n * @return this\n */\n public MeshData append(MeshData other) {\n if (primType != other.primType)\n throw new IllegalArgumentException(\"Can only append data with same primitive type\");\n if (!layout.equals(other.layout))\n throw new IllegalArgumentException(\"Can only append data with same layout\");\n\n // Make sure our buffer is big enough\n ensureSpace(other.vertexBuf.position());\n\n mark();\n\n // Back up other buffer's bounds\n int posTmp = other.vertexBuf.position();\n int limitTmp = other.vertexBuf.limit();\n\n // Copy in the data\n other.vertexBuf.flip();\n vertexBuf.put(other.vertexBuf);\n\n // Restore backed up bounds\n other.vertexBuf.position(posTmp);\n other.vertexBuf.limit(limitTmp);\n\n // Copy indices with mark applied\n for (int i : other.indices) {\n indices.add(mark + i);\n }\n return this;\n }\n\n /**\n * Marks this data as finished, so no other data can be added.\n *\n * @return this\n */\n public MeshData finish() {\n if (finished) throw new IllegalStateException(\"Already finished\");\n finalVertexCount = getVertexCount();\n finished = true;\n vertexBuf.flip();\n return this;\n }\n\n /**\n * Gets the native data buffer. Do not free the returned buffer.\n *\n * @return vertex buffer\n */\n public ByteBuffer getVertexBuf() {\n if (!finished)\n finish();\n return vertexBuf;\n }\n\n /**\n * Gets the vertex layout this mesh data uses.\n *\n * @return layout\n */\n public VertexLayout getVertexLayout() {\n return layout;\n }\n\n /**\n * Gets the number of vertices in this data.\n *\n * @return vertex count\n */\n public int getVertexCount() {\n if (finished) return finalVertexCount;\n return vertexBuf.position() / layout.sizeOf();\n }\n\n /**\n * Gets the index array in this data.\n *\n * @return indices\n */\n public List<Integer> getIndices() {\n return indices;\n }\n\n /**\n * Gets the primitive type the vertices should be rendered as.\n *\n * @return primitive type\n */\n public PrimitiveType getPrimitiveType() {\n return primType;\n }\n\n /**\n * Gets the current mark position.\n *\n * @return mark\n */\n public int getMark() {\n return mark;\n }\n\n @Override\n public void close() {\n MemoryUtil.memFree(vertexBuf);\n }\n}" }, { "identifier": "ActivePipeline", "path": "azalea-core/src/main/java/com/github/rmheuer/azalea/render/pipeline/ActivePipeline.java", "snippet": "public interface ActivePipeline extends SafeCloseable {\n /**\n * Binds a texture into a specified texture slot.\n *\n * @param slot slot to bind from 0 to 15\n * @param texture texture to bind into the slot\n */\n void bindTexture(int slot, Texture texture);\n\n /**\n * Gets a shader uniform by name. This name is the name of the uniform\n * variable in the GLSL shader.\n *\n * @param name uniform name\n * @return uniform\n */\n ShaderUniform getUniform(String name);\n\n /**\n * Renders a mesh to the current framebuffer, using the bound textures.\n *\n * @param mesh mesh to render\n */\n void draw(Mesh mesh);\n}" }, { "identifier": "PipelineInfo", "path": "azalea-core/src/main/java/com/github/rmheuer/azalea/render/pipeline/PipelineInfo.java", "snippet": "public final class PipelineInfo {\n private final ShaderProgram shader;\n private boolean blend;\n private boolean depthTest;\n private CullMode cullMode;\n private FaceWinding winding;\n private FillMode fillMode;\n\n public PipelineInfo(ShaderProgram shader) {\n this.shader = shader;\n blend = true;\n depthTest = false;\n cullMode = CullMode.OFF;\n winding = FaceWinding.CW_FRONT;\n fillMode = FillMode.FILLED;\n }\n\n public PipelineInfo setBlend(boolean blend) {\n this.blend = blend;\n return this;\n }\n\n public PipelineInfo setDepthTest(boolean depthTest) {\n this.depthTest = depthTest;\n return this;\n }\n\n public PipelineInfo setCullMode(CullMode cullMode) {\n this.cullMode = cullMode;\n return this;\n }\n\n public PipelineInfo setWinding(FaceWinding winding) {\n this.winding = winding;\n return this;\n }\n\n public PipelineInfo setFillMode(FillMode fillMode) {\n this.fillMode = fillMode;\n return this;\n }\n\n public ShaderProgram getShader() {\n return shader;\n }\n\n public boolean isBlend() {\n return blend;\n }\n\n public boolean isDepthTest() {\n return depthTest;\n }\n\n public CullMode getCullMode() {\n return cullMode;\n }\n\n public FaceWinding getWinding() {\n return winding;\n }\n\n public FillMode getFillMode() {\n return fillMode;\n }\n}" }, { "identifier": "ShaderProgram", "path": "azalea-core/src/main/java/com/github/rmheuer/azalea/render/shader/ShaderProgram.java", "snippet": "public interface ShaderProgram extends SafeCloseable {\n}" }, { "identifier": "Bitmap", "path": "azalea-core/src/main/java/com/github/rmheuer/azalea/render/texture/Bitmap.java", "snippet": "public final class Bitmap implements BitmapRegion {\n /** The number of bits the red component is shifted left. */\n public static final int RED_SHIFT = 0;\n /** The number of bits the green component is shifted left. */\n public static final int GREEN_SHIFT = 8;\n /** The number of bits the blue component is shifted left. */\n public static final int BLUE_SHIFT = 16;\n /** The number of bits the alpha component is shifted left. */\n public static final int ALPHA_SHIFT = 24;\n\n /** Bitmask for the red component. */\n public static final int RED_MASK = 0xFF << RED_SHIFT;\n /** Bitmask for the green component. */\n public static final int GREEN_MASK = 0xFF << GREEN_SHIFT;\n /** Bitmask for the blue component. */\n public static final int BLUE_MASK = 0xFF << BLUE_SHIFT;\n /** Bitmask for the alpha component. */\n public static final int ALPHA_MASK = 0xFF << ALPHA_SHIFT;\n\n /**\n * Encodes a color into packed RGBA.\n *\n * @param color color to encode\n * @return packed RGBA color\n */\n public static int encodeColor(ColorRGBA color) {\n int r = (int) (color.getRed() * 255);\n int g = (int) (color.getGreen() * 255);\n int b = (int) (color.getBlue() * 255);\n int a = (int) (color.getAlpha() * 255);\n\n return r << RED_SHIFT | g << GREEN_SHIFT | b << BLUE_SHIFT | a << ALPHA_SHIFT;\n }\n\n /**\n * Decodes a color from packed RGBA.\n *\n * @param color packed RGBA color to decode\n * @return decoded color\n */\n public static ColorRGBA decodeColor(int color) {\n int r = (color & RED_MASK) >>> RED_SHIFT;\n int g = (color & GREEN_MASK) >>> GREEN_SHIFT;\n int b = (color & BLUE_MASK) >>> BLUE_SHIFT;\n int a = (color & ALPHA_MASK) >>> ALPHA_SHIFT;\n\n return ColorRGBA.rgba(r, g, b, a);\n }\n\n /**\n * Reads and decodes a bitmap from an {@code InputStream}. This will take\n * ownership of the stream.\n *\n * @param in input stream to read from\n * @return decoded bitmap\n * @throws IOException if an IO error occurs\n */\n public static Bitmap decode(InputStream in) throws IOException {\n ByteBuffer data = IOUtil.readToByteBuffer(in);\n\n try (MemoryStack stack = MemoryStack.stackPush()) {\n IntBuffer pWidth = stack.mallocInt(1);\n IntBuffer pHeight = stack.mallocInt(1);\n IntBuffer pChannels = stack.mallocInt(1);\n\n ByteBuffer pixels = stbi_load_from_memory(\n data,\n pWidth,\n pHeight,\n pChannels,\n 4\n );\n if (pixels == null) {\n throw new IOException(\"Failed to decode image\");\n }\n\n int width = pWidth.get(0);\n int height = pHeight.get(0);\n\n int[] rgbaData = new int[width * height];\n for (int i = 0; i < rgbaData.length; i++) {\n rgbaData[i] = pixels.getInt(i * SizeOf.INT);\n }\n stbi_image_free(pixels);\n MemoryUtil.memFree(data);\n\n return new Bitmap(width, height, rgbaData);\n }\n }\n\n private final int width;\n private final int height;\n private final int[] rgbaData;\n\n /**\n * Creates a new empty bitmap with the specified size, filled with white.\n *\n * @param width width to create in pixels\n * @param height height to create in pixels\n */\n public Bitmap(int width, int height) {\n this(width, height, ColorRGBA.white());\n }\n\n /**\n * Creates a new bitmap with the specified size, filled with the specified\n * color.\n *\n * @param width width to create in pixels\n * @param height height to create in pixels\n * @param fillColor color to fill with\n */\n public Bitmap(int width, int height, ColorRGBA fillColor) {\n this(width, height, new int[width * height]);\n\n int fill = encodeColor(fillColor);\n Arrays.fill(rgbaData, fill);\n }\n\n /**\n * Creates a new bitmap with provided RGBA data.\n *\n * @param width width in pixels\n * @param height height in pixels\n * @param rgbaData packed RGBA data, should have length {@code width*height}.\n */\n public Bitmap(int width, int height, int[] rgbaData) {\n if (rgbaData.length != width * height)\n throw new IllegalArgumentException(\"RGBA data is wrong size\");\n\n this.width = width;\n this.height = height;\n this.rgbaData = rgbaData;\n }\n\n private int pixelIdx(int x, int y) {\n return x + y * width;\n }\n\n @Override\n public ColorRGBA getPixel(int x, int y) {\n checkBounds(x, y);\n return decodeColor(rgbaData[pixelIdx(x, y)]);\n }\n\n @Override\n public void setPixel(int x, int y, ColorRGBA color) {\n checkBounds(x, y);\n rgbaData[pixelIdx(x, y)] = encodeColor(color);\n }\n\n @Override\n public void blit(BitmapRegion img, int x, int y) {\n checkBounds(x, y);\n\n int imgW = img.getWidth();\n int imgH = img.getHeight();\n if (x + imgW > width || y + imgH > height)\n throw new IndexOutOfBoundsException(\"Image extends out of bounds\");\n\n Bitmap src = img.getSourceBitmap();\n int imgXInSrc = img.getSourceOffsetX();\n int imgYInSrc = img.getSourceOffsetY();\n\n for (int row = 0; row < imgH; row++) {\n int srcY = row + imgYInSrc;\n int dstY = y + row;\n\n System.arraycopy(src.rgbaData, src.pixelIdx(imgXInSrc, srcY), rgbaData, pixelIdx(x, dstY), imgW);\n }\n }\n\n private void checkBounds(int x, int y) {\n if (x < 0 || x >= width || y < 0 || y >= height) {\n throw new IndexOutOfBoundsException(x + \", \" + y);\n }\n }\n\n @Override\n public int getWidth() {\n return width;\n }\n\n @Override\n public int getHeight() {\n return height;\n }\n\n @Override\n public int[] getRgbaData() {\n return rgbaData;\n }\n\n @Override\n public Bitmap getSourceBitmap() {\n return this;\n }\n\n @Override\n public int getSourceOffsetX() {\n return 0;\n }\n\n @Override\n public int getSourceOffsetY() {\n return 0;\n }\n}" }, { "identifier": "Texture2D", "path": "azalea-core/src/main/java/com/github/rmheuer/azalea/render/texture/Texture2D.java", "snippet": "public interface Texture2D extends Texture, Texture2DRegion {\n /**\n * Uploads a set of bitmap data to the GPU.\n *\n * @param data data to upload\n */\n void setData(BitmapRegion data);\n\n /**\n * Sets a section of the texture data on GPU, leaving the rest the same.\n *\n * @param data data to upload\n * @param x x coordinate to upload into\n * @param y y coordinate to upload into\n */\n void setSubData(BitmapRegion data, int x, int y);\n\n @Override\n default Texture2D getSourceTexture() {\n return this;\n }\n\n @Override\n default Vector2f getRegionTopLeftUV() {\n return new Vector2f(0, 0);\n }\n\n @Override\n default Vector2f getRegionBottomRightUV() {\n return new Vector2f(1, 1);\n }\n}" }, { "identifier": "SafeCloseable", "path": "azalea-core/src/main/java/com/github/rmheuer/azalea/utils/SafeCloseable.java", "snippet": "public interface SafeCloseable extends AutoCloseable {\n @Override\n void close();\n}" } ]
import com.github.rmheuer.azalea.io.ResourceUtil; import com.github.rmheuer.azalea.render.ColorRGBA; import com.github.rmheuer.azalea.render.Renderer; import com.github.rmheuer.azalea.render.mesh.Mesh; import com.github.rmheuer.azalea.render.mesh.MeshData; import com.github.rmheuer.azalea.render.pipeline.ActivePipeline; import com.github.rmheuer.azalea.render.pipeline.PipelineInfo; import com.github.rmheuer.azalea.render.shader.ShaderProgram; import com.github.rmheuer.azalea.render.texture.Bitmap; import com.github.rmheuer.azalea.render.texture.Texture2D; import com.github.rmheuer.azalea.utils.SafeCloseable; import org.joml.Matrix4f; import java.io.IOException; import java.util.List;
8,936
package com.github.rmheuer.azalea.render2d; /** * Renderer to render {@code DrawList2D}s. */ public final class Renderer2D implements SafeCloseable { public static final int MAX_TEXTURE_SLOTS = 16; private static final String VERTEX_SHADER_PATH = "azalea/shaders/render2d/vertex.glsl"; private static final String FRAGMENT_SHADER_PATH = "azalea/shaders/render2d/fragment.glsl"; private final Renderer renderer; private final Mesh mesh; private final ShaderProgram shader; private final Texture2D whiteTex; /** * @param renderer renderer to use for rendering */ public Renderer2D(Renderer renderer) { this.renderer = renderer; mesh = renderer.createMesh(); try { shader = renderer.createShaderProgram( ResourceUtil.readAsStream(VERTEX_SHADER_PATH), ResourceUtil.readAsStream(FRAGMENT_SHADER_PATH)); } catch (IOException e) { throw new RuntimeException("Failed to load built-in shaders", e); } Bitmap whiteData = new Bitmap(1, 1, ColorRGBA.white()); whiteTex = renderer.createTexture2D(); whiteTex.setData(whiteData);
package com.github.rmheuer.azalea.render2d; /** * Renderer to render {@code DrawList2D}s. */ public final class Renderer2D implements SafeCloseable { public static final int MAX_TEXTURE_SLOTS = 16; private static final String VERTEX_SHADER_PATH = "azalea/shaders/render2d/vertex.glsl"; private static final String FRAGMENT_SHADER_PATH = "azalea/shaders/render2d/fragment.glsl"; private final Renderer renderer; private final Mesh mesh; private final ShaderProgram shader; private final Texture2D whiteTex; /** * @param renderer renderer to use for rendering */ public Renderer2D(Renderer renderer) { this.renderer = renderer; mesh = renderer.createMesh(); try { shader = renderer.createShaderProgram( ResourceUtil.readAsStream(VERTEX_SHADER_PATH), ResourceUtil.readAsStream(FRAGMENT_SHADER_PATH)); } catch (IOException e) { throw new RuntimeException("Failed to load built-in shaders", e); } Bitmap whiteData = new Bitmap(1, 1, ColorRGBA.white()); whiteTex = renderer.createTexture2D(); whiteTex.setData(whiteData);
try (ActivePipeline pipe = renderer.bindPipeline(new PipelineInfo(shader))) {
5
2023-11-16 04:46:53+00:00
12k
Shushandr/offroad
src/net/sourceforge/offroad/ui/ZoomAnimationThread.java
[ { "identifier": "LatLon", "path": "src/net/osmand/data/LatLon.java", "snippet": "@XmlRootElement\npublic class LatLon implements Serializable {\n\tpublic void setLongitude(double pLongitude) {\n\t\tlongitude = pLongitude;\n\t}\n\n\tpublic void setLatitude(double pLatitude) {\n\t\tlatitude = pLatitude;\n\t}\n\tprivate double longitude;\n\tprivate double latitude;\n\n\tpublic LatLon() {\n\t}\n\t\n\tpublic LatLon(double latitude, double longitude) {\n\t\tthis.latitude = latitude;\n\t\tthis.longitude = longitude;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\tfinal int prime = 31;\n\t\tint result = 1;\n\t\tint temp;\n\t\ttemp = (int)Math.floor(latitude * 10000);\n\t\tresult = prime * result + temp;\n\t\ttemp = (int)Math.floor(longitude * 10000);\n\t\tresult = prime * result + temp;\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj)\n\t\t\treturn true;\n\t\tif (obj == null)\n\t\t\treturn false;\n\t\tif (getClass() != obj.getClass())\n\t\t\treturn false;\n\n\t\tLatLon other = (LatLon) obj;\n\t\treturn Math.abs(latitude - other.latitude) < 0.00001\n\t\t\t\t&& Math.abs(longitude - other.longitude) < 0.00001;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Lat \" + ((float)latitude) + \" Lon \" + ((float)longitude); //$NON-NLS-1$ //$NON-NLS-2$\n\t}\n\n\tpublic double getLatitude() {\n\t\treturn latitude;\n\t}\n\n\tpublic double getLongitude() {\n\t\treturn longitude;\n\t}\n\n\tpublic int get31TileNumberX() {\n\t\treturn MapUtils.get31TileNumberX(longitude);\n\t}\n\tpublic int get31TileNumberY() {\n\t\treturn MapUtils.get31TileNumberY(latitude);\n\t}\n\n}" }, { "identifier": "QuadPoint", "path": "src/net/osmand/data/QuadPoint.java", "snippet": "public class QuadPoint {\n\tpublic float x;\n\tpublic float y;\n\n\tpublic QuadPoint() {\n\t}\n\t\n\tpublic QuadPoint(float x, float y) {\n\t\tthis.x = x;\n\t\tthis.y = y;\n\t}\n\n\tpublic QuadPoint(QuadPoint a) {\n\t\tthis(a.x, a.y);\n\t}\n\n\tpublic void set(float x, float y) {\n\t\tthis.x = x;\n\t\tthis.y = y;\n\t}\n\n}" }, { "identifier": "RotatedTileBox", "path": "src/net/osmand/data/RotatedTileBox.java", "snippet": "public class RotatedTileBox {\n\t@Override\n\tpublic int hashCode() {\n\t\tfinal int prime = 31;\n\t\tint result = 1;\n\t\tresult = prime * result + cx;\n\t\tresult = prime * result + cy;\n\t\tresult = prime * result + Float.floatToIntBits(density);\n\t\tlong temp;\n\t\ttemp = Double.doubleToLongBits(lat);\n\t\tresult = prime * result + (int) (temp ^ (temp >>> 32));\n\t\ttemp = Double.doubleToLongBits(lon);\n\t\tresult = prime * result + (int) (temp ^ (temp >>> 32));\n\t\ttemp = Double.doubleToLongBits(mapDensity);\n\t\tresult = prime * result + (int) (temp ^ (temp >>> 32));\n\t\tresult = prime * result + pixHeight;\n\t\tresult = prime * result + pixWidth;\n\t\tresult = prime * result + Float.floatToIntBits(rotate);\n\t\tresult = prime * result + zoom;\n\t\ttemp = Double.doubleToLongBits(zoomAnimation);\n\t\tresult = prime * result + (int) (temp ^ (temp >>> 32));\n\t\ttemp = Double.doubleToLongBits(zoomFloatPart);\n\t\tresult = prime * result + (int) (temp ^ (temp >>> 32));\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj)\n\t\t\treturn true;\n\t\tif (obj == null)\n\t\t\treturn false;\n\t\tif (getClass() != obj.getClass())\n\t\t\treturn false;\n\t\tRotatedTileBox other = (RotatedTileBox) obj;\n\t\tif (cx != other.cx)\n\t\t\treturn false;\n\t\tif (cy != other.cy)\n\t\t\treturn false;\n\t\tif (Float.floatToIntBits(density) != Float.floatToIntBits(other.density))\n\t\t\treturn false;\n\t\tif (Double.doubleToLongBits(lat) != Double.doubleToLongBits(other.lat))\n\t\t\treturn false;\n\t\tif (Double.doubleToLongBits(lon) != Double.doubleToLongBits(other.lon))\n\t\t\treturn false;\n\t\tif (Double.doubleToLongBits(mapDensity) != Double.doubleToLongBits(other.mapDensity))\n\t\t\treturn false;\n\t\tif (pixHeight != other.pixHeight)\n\t\t\treturn false;\n\t\tif (pixWidth != other.pixWidth)\n\t\t\treturn false;\n\t\tif (Float.floatToIntBits(rotate) != Float.floatToIntBits(other.rotate))\n\t\t\treturn false;\n\t\tif (zoom != other.zoom)\n\t\t\treturn false;\n\t\tif (Double.doubleToLongBits(zoomAnimation) != Double.doubleToLongBits(other.zoomAnimation))\n\t\t\treturn false;\n\t\tif (Double.doubleToLongBits(zoomFloatPart) != Double.doubleToLongBits(other.zoomFloatPart))\n\t\t\treturn false;\n\t\treturn true;\n\t}\n\tprivate final static Log log = PlatformUtil.getLog(RotatedTileBox.class);\n\n\t/// primary fields\n\tprivate double lat;\n\tprivate double lon;\n\tprivate float rotate;\n\tprivate float density;\n\tprivate int zoom;\n\tprivate double mapDensity = 1;\n\tprivate double zoomAnimation;\n\tprivate double zoomFloatPart;\n\tprivate int cx;\n\tprivate int cy;\n\tprivate int pixWidth;\n\tprivate int pixHeight;\n\n\t// derived\n\t// all geometry math is done in tileX, tileY of phisycal given zoom\n\t// zoomFactor is conversion factor, from dtileX * zoomFactor = dPixelX\n\tprivate double zoomFactor;\n\tprivate double rotateCos;\n\tprivate double rotateSin;\n\tprivate double oxTile;\n\tprivate double oyTile;\n\tprivate QuadRect tileBounds;\n\tprivate QuadRect latLonBounds;\n\tprivate QuadPointDouble tileLT;\n\tprivate QuadPointDouble tileRT;\n\tprivate QuadPointDouble tileRB;\n\tprivate QuadPointDouble tileLB;\n\n\n\tprivate RotatedTileBox(){\n\t}\n\n\tpublic RotatedTileBox(RotatedTileBox r){\n\t\tthis.pixWidth = r.pixWidth;\n\t\tthis.pixHeight = r.pixHeight;\n\t\tthis.lat = r.lat;\n\t\tthis.lon = r.lon;\n\t\tthis.zoom = r.zoom;\n\t\tthis.mapDensity = r.mapDensity;\n\t\tthis.zoomFloatPart = r.zoomFloatPart;\n\t\tthis.zoomAnimation = r.zoomAnimation;\n\t\tthis.rotate = r.rotate;\n\t\tthis.density = r.density;\n\t\tthis.cx = r.cx;\n\t\tthis.cy = r.cy;\n\t\tcopyDerivedFields(r);\n\t}\n\n\tprivate void copyDerivedFields(RotatedTileBox r) {\n\t\tzoomFactor = r.zoomFactor;\n\t\trotateCos = r.rotateCos;\n\t\trotateSin = r.rotateSin;\n\t\toxTile = r.oxTile;\n\t\toyTile = r.oyTile;\n\t\tif (r.tileBounds != null && r.latLonBounds != null) {\n\t\t\ttileBounds = new QuadRect(r.tileBounds);\n\t\t\tlatLonBounds = new QuadRect(r.latLonBounds);\n\t\t\ttileLT = new QuadPointDouble(r.tileLT);\n\t\t\ttileRT = new QuadPointDouble(r.tileRT);\n\t\t\ttileRB = new QuadPointDouble(r.tileRB);\n\t\t\ttileLB = new QuadPointDouble(r.tileLB);\n\t\t}\n\t}\n\n\tpublic void calculateDerivedFields() {\n\t\tzoomFactor = Math.pow(2, zoomAnimation + zoomFloatPart) * 256 * mapDensity;\n\t\tdouble rad = Math.toRadians(this.rotate);\n\t\trotateCos = Math.cos(rad);\n\t\trotateSin = Math.sin(rad);\n\t\toxTile = MapUtils.getTileNumberX(zoom, lon);\n\t\toyTile = MapUtils.getTileNumberY(zoom, lat);\n\t\twhile(rotate < 0){\n\t\t\trotate += 360;\n\t\t}\n\t\twhile(rotate > 360){\n\t\t\trotate -= 360;\n\t\t}\n\t\ttileBounds = null;\n\t\t// lazy\n\t\t// calculateTileRectangle();\n\t}\n\n\tpublic double getLatFromPixel(float x, float y) {\n\t\treturn MapUtils.getLatitudeFromTile(zoom, getTileYFromPixel(x, y));\n\t}\n\n\tpublic double getLonFromPixel(float x, float y) {\n\t\treturn MapUtils.getLongitudeFromTile(zoom, getTileXFromPixel(x, y));\n\t}\n\n\tpublic LatLon getLatLonFromPixel(float x, float y) {\n\t\treturn new LatLon(getLatFromPixel(x, y), getLonFromPixel(x, y));\n\t}\n\n\tpublic LatLon getLatLonFromPixel(double x, double y) {\n\t\treturn getLatLonFromPixel((float)x, (float)y);\n\t}\n\t\n\tpublic LatLon getCenterLatLon() {\n\t\treturn new LatLon(lat, lon);\n\t}\n\n\tpublic QuadPoint getCenterPixelPoint() {\n\t\treturn new QuadPoint(cx, cy);\n\t}\n\n\tpublic int getCenterPixelX(){\n\t\treturn cx;\n\t}\n\n\tpublic int getCenterPixelY(){\n\t\treturn cy;\n\t}\n\n\tpublic void setDensity(float density) {\n\t\tthis.density = density;\n\t}\n\n\tpublic double getCenterTileX(){\n\t\treturn oxTile;\n\t}\n\t\n\tpublic int getCenter31X(){\n\t\treturn MapUtils.get31TileNumberX(lon);\n\t}\n\t\n\tpublic int getCenter31Y(){\n\t\treturn MapUtils.get31TileNumberY(lat);\n\t}\n\n\tpublic double getCenterTileY(){\n\t\treturn oyTile;\n\t}\n\n\tprotected double getTileXFromPixel(float x, float y) {\n\t\tfloat dx = x - cx;\n\t\tfloat dy = y - cy;\n\t\tdouble dtilex;\n\t\tif(isMapRotateEnabled()){\n\t\t\tdtilex = (rotateCos * (float) dx + rotateSin * (float) dy);\n\t\t} else {\n\t\t\tdtilex = (float) dx;\n\t\t}\n\t\treturn dtilex / zoomFactor + oxTile;\n\t}\n\n\tprotected double getTileYFromPixel(float x, float y) {\n\t\tfloat dx = x - cx;\n\t\tfloat dy = y - cy;\n\t\tdouble dtiley;\n\t\tif(isMapRotateEnabled()){\n\t\t\tdtiley = (-rotateSin * (float) dx + rotateCos * (float) dy);\n\t\t} else {\n\t\t\tdtiley = (float) dy;\n\t\t}\n\t\treturn dtiley / zoomFactor + oyTile;\n\t}\n\n\n\tpublic QuadRect getTileBounds() {\n\t\tcheckTileRectangleCalculated();\n\t\treturn tileBounds;\n\t}\n\n\tpublic void calculateTileRectangle() {\n\t\tdouble x1 = getTileXFromPixel(0, 0);\n\t\tdouble x2 = getTileXFromPixel(pixWidth, 0);\n\t\tdouble x3 = getTileXFromPixel(pixWidth, pixHeight);\n\t\tdouble x4 = getTileXFromPixel(0, pixHeight);\n\t\tdouble y1 = getTileYFromPixel(0, 0);\n\t\tdouble y2 = getTileYFromPixel(pixWidth, 0);\n\t\tdouble y3 = getTileYFromPixel(pixWidth, pixHeight);\n\t\tdouble y4 = getTileYFromPixel(0, pixHeight);\n\t\ttileLT = new QuadPointDouble(x1, y1);\n\t\ttileRT = new QuadPointDouble(x2, y2);\n\t\ttileRB = new QuadPointDouble(x3, y3);\n\t\ttileLB = new QuadPointDouble(x4, y4);\n\t\tdouble l = Math.min(Math.min(x1, x2), Math.min(x3, x4)) ;\n\t\tdouble r = Math.max(Math.max(x1, x2), Math.max(x3, x4)) ;\n\t\tdouble t = Math.min(Math.min(y1, y2), Math.min(y3, y4)) ;\n\t\tdouble b = Math.max(Math.max(y1, y2), Math.max(y3, y4)) ;\n\t\ttileBounds = new QuadRect((float)l, (float)t,(float) r, (float)b);\n\t\tfloat top = (float) MapUtils.getLatitudeFromTile(zoom, alignTile(tileBounds.top));\n\t\tfloat left = (float) MapUtils.getLongitudeFromTile(zoom, alignTile(tileBounds.left));\n\t\tfloat bottom = (float) MapUtils.getLatitudeFromTile(zoom, alignTile(tileBounds.bottom));\n\t\tfloat right = (float) MapUtils.getLongitudeFromTile(zoom, alignTile(tileBounds.right));\n\t\tlatLonBounds = new QuadRect(left, top, right, bottom);\n\t}\n\t\n\tprivate double alignTile(double tile) {\n\t\tif(tile < 0) {\n\t\t\treturn 0;\n\t\t}\n\t\tif(tile >= MapUtils.getPowZoom(zoom)) {\n\t\t\treturn MapUtils.getPowZoom(zoom) - .000001;\n\t\t}\n\t\treturn tile;\n\t}\n\n\n\tpublic int getPixWidth() {\n\t\treturn pixWidth;\n\t}\n\n\tpublic int getPixHeight() {\n\t\treturn pixHeight;\n\t}\n\n\n\tpublic float getPixXFromLatLon(double latitude, double longitude) {\n\t\tdouble xTile = MapUtils.getTileNumberX(zoom, longitude);\n\t\tdouble yTile = MapUtils.getTileNumberY(zoom, latitude);\n\t\treturn getPixXFromTile(xTile, yTile);\n\t}\n\t\n\tpublic float getPixXFromTile(double tileX, double tileY, float zoom) {\n\t\tdouble pw = MapUtils.getPowZoom(zoom - this.zoom);\n\t\tdouble xTile = tileX / pw;\n\t\tdouble yTile = tileY / pw;\n\t\treturn getPixXFromTile(xTile, yTile);\n\t}\n\n\tprotected float getPixXFromTile(double xTile, double yTile) {\n\t\tdouble rotX;\n\t\tfinal double dTileX = xTile - oxTile;\n\t\tfinal double dTileY = yTile - oyTile;\n\t\tif(isMapRotateEnabled()){\n\t\t\trotX = (rotateCos * dTileX - rotateSin * dTileY);\n\t\t} else {\n\t\t\trotX = dTileX;\n\t\t}\n\t\tdouble dx = rotX * zoomFactor;\n\t\treturn (float) (dx + cx);\n\t}\n\n\n\tpublic float getPixYFromLatLon(double latitude, double longitude) {\n\t\tdouble xTile = MapUtils.getTileNumberX(zoom, longitude);\n\t\tdouble yTile = MapUtils.getTileNumberY(zoom, latitude);\n\t\treturn getPixYFromTile(xTile, yTile);\n\t}\n\t\n\tpublic float getPixYFromTile(double tileX, double tileY, float zoom) {\n\t\tdouble pw = MapUtils.getPowZoom(zoom - this.zoom);\n\t\tdouble xTile = (tileX / pw);\n\t\tdouble yTile = (tileY / pw);\n\t\treturn getPixYFromTile(xTile, yTile);\n\t}\n\n\tprotected float getPixYFromTile(double xTile, double yTile) {\n\t\tfinal double dTileX = xTile - oxTile;\n\t\tfinal double dTileY = yTile - oyTile;\n\t\tdouble rotY;\n\t\tif(isMapRotateEnabled()){\n\t\t\trotY = (rotateSin * dTileX + rotateCos * dTileY);\n\t\t} else {\n\t\t\trotY = dTileY;\n\t\t}\n\t\tdouble dy = rotY * zoomFactor;\n\t\treturn (float) (dy + cy);\n\t}\n\n\tpublic int getPixXFromLonNoRot(double longitude) {\n\t\tdouble dTilex = (float) MapUtils.getTileNumberX(zoom, longitude) - oxTile;\n\t\treturn (int) (dTilex * zoomFactor + cx);\n\t}\n\n\tpublic int getPixXFromTileXNoRot(double tileX) {\n\t\tdouble dTilex = tileX - oxTile;\n\t\treturn (int) (dTilex * zoomFactor + cx);\n\t}\n\n\tpublic int getPixYFromLatNoRot(double latitude) {\n\t\tdouble dTileY = MapUtils.getTileNumberY(zoom, latitude) - oyTile;\n\t\treturn (int) ((dTileY * zoomFactor) + cy);\n\t}\n\n\tpublic int getPixYFromTileYNoRot(double tileY) {\n\t\tdouble dTileY = tileY - oyTile;\n\t\treturn (int) ((dTileY * zoomFactor) + cy);\n\t}\n\n\n\tprivate boolean isMapRotateEnabled() {\n\t\treturn rotate != 0;\n\t}\n\n\tpublic QuadRect getLatLonBounds() {\n\t\tcheckTileRectangleCalculated();\n\t\treturn latLonBounds;\n\t}\n\t\n\tpublic double getRotateCos() {\n\t\treturn rotateCos;\n\t}\n\t\n\tpublic double getRotateSin() {\n\t\treturn rotateSin;\n\t}\n\n\tpublic int getZoom() {\n\t\treturn zoom;\n\t}\n\n\t// Change lat/lon center\n\tpublic void setLatLonCenter(double lat, double lon) {\n\t\tthis.lat = lat;\n\t\tthis.lon = lon;\n\t\tcalculateDerivedFields();\n\t}\n\n\t/**\n\t * @param rotate in degrees (0-360). \n\t */\n\tpublic void setRotate(float rotate) {\n\t\tthis.rotate = rotate;\n\t\tcalculateDerivedFields();\n\t}\n\n\tpublic void increasePixelDimensions(int dwidth, int dheight) {\n\t\tthis.pixWidth += 2 * dwidth;\n\t\tthis.pixHeight += 2 * dheight;\n\t\tthis.cx += dwidth;\n\t\tthis.cy += dheight;\n\t\tcalculateDerivedFields();\n\t}\n\n\tpublic void setPixelDimensions(int width, int height) {\n\t\tsetPixelDimensions(width, height, 0.5f, 0.5f);\n\t}\n\n\tpublic void setPixelDimensions(int width, int height, float ratiocx, float ratiocy) {\n\t\tthis.pixHeight = height;\n\t\tthis.pixWidth = width;\n\t\tthis.cx = (int) (pixWidth * ratiocx);\n\t\tthis.cy = (int) (pixHeight * ratiocy);\n\t\tcalculateDerivedFields();\n\t}\n\n\tpublic boolean isZoomAnimated() {\n\t\treturn zoomAnimation != 0;\n\t}\n\n\tpublic double getZoomAnimation() {\n\t\treturn zoomAnimation;\n\t}\n\t\n\tpublic double getZoomFloatPart() {\n\t\treturn zoomFloatPart;\n\t}\n\n\tpublic void setZoomAndAnimation(int zoom, double zoomAnimation, double zoomFloatPart) {\n\t\tthis.zoomAnimation = zoomAnimation;\n\t\tthis.zoomFloatPart = zoomFloatPart;\n\t\tthis.zoom = zoom;\n\t\tcalculateDerivedFields();\n\t}\n\t\n\tpublic void setZoomAndAnimation(int zoom, double zoomAnimation) {\n\t\tthis.zoomAnimation = zoomAnimation;\n\t\tthis.zoom = zoom;\n\t\tcalculateDerivedFields();\n\t}\n\n\tpublic void setCenterLocation(float ratiocx, float ratiocy) {\n\t\tthis.cx = (int) (pixWidth * ratiocx);\n\t\tthis.cy = (int) (pixHeight * ratiocy);\n\t\tcalculateDerivedFields();\n\t}\n\n\tpublic LatLon getLeftTopLatLon() {\n\t\tcheckTileRectangleCalculated();\n\t\treturn new LatLon(MapUtils.getLatitudeFromTile(zoom, alignTile(tileLT.y)),\n\t\t\t\tMapUtils.getLongitudeFromTile(zoom, alignTile(tileLT.x)));\n\n\t}\n\t\n\tpublic QuadPointDouble getLeftTopTile(double zoom) {\n\t\tcheckTileRectangleCalculated();\n\t\treturn new QuadPointDouble((tileLT.x * MapUtils.getPowZoom(zoom - this.zoom)),\n\t\t\t\t(tileLT.y * MapUtils.getPowZoom(zoom - this.zoom)));\n\t}\n\n\t\n\tpublic QuadPointDouble getRightBottomTile(float zoom) {\n\t\tcheckTileRectangleCalculated();\n\t\treturn new QuadPointDouble((tileRB.x * MapUtils.getPowZoom(zoom - this.zoom)),\n\t\t\t\t(tileRB.y * MapUtils.getPowZoom(zoom - this.zoom)));\n\t}\n\t\n\n\tprivate void checkTileRectangleCalculated() {\n\t\tif(tileBounds == null){\n\t\t\tcalculateTileRectangle();\n\t\t}\n\t}\n\n\tpublic LatLon getRightBottomLatLon() {\n\t\tcheckTileRectangleCalculated();\n\t\treturn new LatLon(MapUtils.getLatitudeFromTile(zoom, alignTile(tileRB.y)),\n\t\t\t\tMapUtils.getLongitudeFromTile(zoom, alignTile(tileRB.x)));\n\t}\n\n\tpublic void setMapDensity(double mapDensity) {\n\t\tthis.mapDensity = mapDensity;\n\t\tcalculateDerivedFields();\n\t}\n\t\n\tpublic double getMapDensity() {\n\t\treturn mapDensity;\n\t}\n\n\tpublic void setZoom(int zoom) {\n\t\tthis.zoom = zoom;\n\t\tcalculateDerivedFields();\n\t}\n\n\t/**\n\t * @return in degrees (0-360).\n\t */\n\tpublic float getRotate() {\n\t\treturn rotate;\n\t}\n\n\tpublic float getDensity() {\n\t\treturn density;\n\t}\n\n\tpublic RotatedTileBox copy() {\n\t\treturn new RotatedTileBox(this);\n\t}\n\n\n\n\tpublic boolean containsTileBox(RotatedTileBox box) {\n\t\tcheckTileRectangleCalculated();\n\t\t// thread safe\n\t\tbox = box.copy();\n\t\tbox.checkTileRectangleCalculated();\n\t\tif(!containsTilePoint(box.tileLB)){\n\t\t\treturn false;\n\t\t}\n\t\tif(!containsTilePoint(box.tileLT)){\n\t\t\treturn false;\n\t\t}\n\t\tif(!containsTilePoint(box.tileRB)){\n\t\t\treturn false;\n\t\t}\n\t\tif(!containsTilePoint(box.tileRT)){\n\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n\n\tpublic boolean containsTilePoint(QuadPoint qp) {\n\t\tdouble tx = getPixXFromTile(qp.x, qp.y);\n\t\tdouble ty = getPixYFromTile(qp.x, qp.y);\n\t\treturn tx >= 0 && tx <= pixWidth && ty >= 0 && ty <= pixHeight;\n\t}\n\t\n\tpublic boolean containsTilePoint(QuadPointDouble qp) {\n\t\tdouble tx = getPixXFromTile(qp.x, qp.y);\n\t\tdouble ty = getPixYFromTile(qp.x, qp.y);\n\t\treturn tx >= 0 && tx <= pixWidth && ty >= 0 && ty <= pixHeight;\n\t}\n\n\tpublic boolean containsLatLon(double lat, double lon) {\n\t\tdouble tx = getPixXFromLatLon(lat, lon);\n\t\tdouble ty = getPixYFromLatLon(lat, lon);\n\t\treturn tx >= 0 && tx <= pixWidth && ty >= 0 && ty <= pixHeight;\n\t}\n\t\n\tpublic boolean containsLatLon(LatLon latLon) {\n\t\tdouble tx = getPixXFromLatLon(latLon.getLatitude(), latLon.getLongitude());\n\t\tdouble ty = getPixYFromLatLon(latLon.getLatitude(), latLon.getLongitude());\n\t\treturn tx >= 0 && tx <= pixWidth && ty >= 0 && ty <= pixHeight;\n\t}\n\n\n\tpublic double getDistance(int pixX, int pixY, int pixX2, int pixY2) {\n\t\tfinal double lat1 = getLatFromPixel(pixX, pixY);\n\t\tfinal double lon1 = getLonFromPixel(pixX, pixY);\n\t\tfinal double lat2 = getLatFromPixel(pixX2, pixY2);\n\t\tfinal double lon2 = getLonFromPixel(pixX2, pixY2);\n\t\treturn MapUtils.getDistance(lat1,lon1, lat2, lon2);\n\t}\n\n\tpublic static class RotatedTileBoxBuilder {\n\n\t\tprivate RotatedTileBox tb;\n\t\tprivate boolean pixelDimensionsSet = false;\n\t\tprivate boolean locationSet = false;\n\t\tprivate boolean zoomSet = false;\n\n\t\tpublic RotatedTileBoxBuilder() {\n\t\t\ttb = new RotatedTileBox();\n\t\t\ttb.density = 1;\n\t\t\ttb.rotate = 0;\n\t\t}\n\n\t\tpublic RotatedTileBoxBuilder density(float d) {\n\t\t\ttb.density = d;\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic RotatedTileBoxBuilder setMapDensity(double mapDensity) {\n\t\t\ttb.mapDensity = mapDensity;\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic RotatedTileBoxBuilder setZoom(int zoom) {\n\t\t\ttb.zoom = zoom;\n\t\t\tzoomSet = true;\n\t\t\treturn this;\n\t\t}\n\t\t\n\t\tpublic RotatedTileBoxBuilder setLocation(double lat, double lon) {\n\t\t\ttb.lat = lat;\n\t\t\ttb.lon = lon;\n\t\t\tlocationSet = true;\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic RotatedTileBoxBuilder setRotate(float degrees) {\n\t\t\ttb.rotate = degrees;\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic RotatedTileBoxBuilder setPixelDimensions(int pixWidth, int pixHeight, float centerX, float centerY) {\n\t\t\ttb.pixWidth = pixWidth;\n\t\t\ttb.pixHeight = pixHeight;\n\t\t\ttb.cx = (int) (pixWidth * centerX);\n\t\t\ttb.cy = (int) (pixHeight * centerY);\n\t\t\tpixelDimensionsSet = true;\n\t\t\treturn this;\n\t\t}\n\n\t\tpublic RotatedTileBoxBuilder setPixelDimensions(int pixWidth, int pixHeight) {\n\t\t\treturn setPixelDimensions(pixWidth, pixHeight, 0.5f, 0.5f);\n\t\t}\n\n\t\tpublic RotatedTileBox build() {\n\t\t\tif(!pixelDimensionsSet) {\n\t\t\t\tthrow new IllegalArgumentException(\"Please specify pixel dimensions\");\n\t\t\t}\n\t\t\tif(!zoomSet) {\n\t\t\t\tthrow new IllegalArgumentException(\"Please specify zoom\");\n\t\t\t}\n\t\t\tif(!locationSet) {\n\t\t\t\tthrow new IllegalArgumentException(\"Please specify location\");\n\t\t\t}\n\n\t\t\tfinal RotatedTileBox local = tb;\n\t\t\tlocal.calculateDerivedFields();\n\t\t\ttb = null;\n\t\t\treturn local;\n\t\t}\n\t}\n\n\tpublic double getLongitude() {\n\t\treturn lon;\n\t}\n\n\tpublic double getLatitude() {\n\t\treturn lat;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"RotatedTileBox [lat=\" + lat + \", lon=\" + lon + \", rotate=\"\n\t\t\t\t+ rotate + \", density=\" + density + \", zoom=\" + zoom\n\t\t\t\t+ \", mapDensity=\" + mapDensity + \", zoomAnimation=\"\n\t\t\t\t+ zoomAnimation + \", zoomFloatPart=\" + zoomFloatPart + \", cx=\"\n\t\t\t\t+ cx + \", cy=\" + cy + \", pixWidth=\" + pixWidth + \", pixHeight=\"\n\t\t\t\t+ pixHeight + \"]\";\n\t}\n\n\tpublic boolean intersects(LatLon pScreenLT, LatLon pScreenRB) {\n\t\tLatLon lt = getLeftTopLatLon();\n\t\tLatLon rb = getRightBottomLatLon();\n\t\tdouble minLat = Math.min(pScreenLT.getLatitude(), pScreenRB.getLatitude());\n\t\tdouble maxLat = Math.max(pScreenLT.getLatitude(), pScreenRB.getLatitude());\n\t\tdouble minLon = Math.min(pScreenLT.getLongitude(), pScreenRB.getLongitude());\n\t\tdouble maxLon = Math.max(pScreenLT.getLongitude(), pScreenRB.getLongitude());\n\t\tif(lt.getLatitude()<= minLat && rb.getLatitude() <= minLat){\n\t\t\treturn false;\n\t\t}\n\t\tif(lt.getLatitude()>= maxLat && rb.getLatitude() >= maxLat){\n\t\t\treturn false;\n\t\t}\n\t\tif(lt.getLongitude()<= minLon && rb.getLongitude() <= minLon){\n\t\t\treturn false;\n\t\t}\n\t\tif(lt.getLongitude()>= maxLon && rb.getLongitude() >= maxLon){\n\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n\n\tpublic float getPixXFromLatLon(LatLon pLatLon) {\n\t\treturn getPixXFromLatLon(pLatLon.getLatitude(), pLatLon.getLongitude());\n\t}\n\tpublic float getPixYFromLatLon(LatLon pLatLon) {\n\t\treturn getPixYFromLatLon(pLatLon.getLatitude(), pLatLon.getLongitude());\n\t}\n\n\tpublic Point getPoint(LatLon pLocation) {\n\t\treturn new Point((int)getPixXFromLatLon(pLocation), (int)getPixYFromLatLon(pLocation));\n\t}\n\n\tpublic void setLatLonCenter(LatLon pDestination) {\n\t\tsetLatLonCenter(pDestination.getLatitude(), pDestination.getLongitude());\n\t}\n\n\t/**\n\t * @return the minimal distance of two pixels in meters\n\t */\n\tpublic double getPixelDistanceInMeters() {\n\t\tdouble dx = MapUtils.getDistance(getCenterLatLon(), getLatFromPixel(getCenterPixelX()+1, getCenterPixelY()),\n\t\t\t\tgetLonFromPixel(getCenterPixelX()+1, getCenterPixelY()));\n\t\tdouble dy = MapUtils.getDistance(getCenterLatLon(), getLatFromPixel(getCenterPixelX(), getCenterPixelY()+1),\n\t\t\t\tgetLonFromPixel(getCenterPixelX(), getCenterPixelY()+1));\n\t\treturn Math.min(Math.abs(dx), Math.abs(dy));\n\t}\n\n\n\t\n\t\n}" } ]
import java.awt.Point; import net.osmand.data.LatLon; import net.osmand.data.QuadPoint; import net.osmand.data.RotatedTileBox;
7,829
package net.sourceforge.offroad.ui; class ZoomAnimationThread extends OffRoadUIThread { /** * */ private final int mWheelRotation; private final Point mNewCenter; ZoomAnimationThread(OsmBitmapPanel pOsmBitmapPanel, int pWheelRotation, Point pNewCenter) { super(pOsmBitmapPanel, "ZoomAnimation"); mWheelRotation = pWheelRotation; mNewCenter = pNewCenter; } @Override public void runAfterThreadsBeforeHaveFinished() { RotatedTileBox tb = mOsmBitmapPanel.copyCurrentTileBox(); int originalZoom = tb.getZoom(); // it -2 == v0 * (it-2) + a (it-2)² // a = ( it(1-v0) + 2*v0-2)/(it-2)² int it; if(mNextThread == null) { // use acceleration only if it is the last thread in the row. it = 30; float v0 = 2f; float a = (it*(1f-v0) + 2f*v0 - 2f)/(it-2f)/(it-2f); for (int i = 0; i < it-1; ++i) { float zoom = v0 * i + a*i*i; log.info("Zoom is " + zoom + " for step " + i + " and velocity " + v0 + " and acceleration " + a); tb = getDestinationTileBox(originalZoom, it, zoom); mOsmBitmapPanel.setCurrentTileBox(tb); log.debug("Set tile box " + tb + " and now repaint."); mOsmBitmapPanel.repaintAndWait(16); log.debug("Set tile box " + tb + " and now repaint. Done."); } } else { it = 10; for (int i = 0; i < it-2; ++i) { tb = getDestinationTileBox(originalZoom, it, i); mOsmBitmapPanel.setCurrentTileBox(tb); log.debug("Set tile box " + tb + " and now repaint."); mOsmBitmapPanel.repaintAndWait(16); log.debug("Set tile box " + tb + " and now repaint. Done."); } } tb = getDestinationTileBox(originalZoom, it, it-1); mOsmBitmapPanel.setCurrentTileBox(tb); log.debug("Set tile box " + tb + " and now repaint."); mOsmBitmapPanel.repaintAndWait(16); log.debug("Set tile box " + tb + " and now repaint. Done."); } public RotatedTileBox getDestinationTileBox(int originalZoom, float it, float i) { RotatedTileBox tb = mOsmBitmapPanel.copyCurrentTileBox(); // get old center: LatLon oldCenter = tb.getLatLonFromPixel(mNewCenter.x, mNewCenter.y); if (i<it-1) { float destZoom = mOsmBitmapPanel.checkZoom(originalZoom+(0f+i*mWheelRotation)/it); int baseZoom = (int) Math.floor(destZoom); float fractZoom = destZoom- baseZoom; tb.setZoomAndAnimation(baseZoom, 0d, fractZoom); } else { tb.setZoomAndAnimation((int)mOsmBitmapPanel.checkZoom(originalZoom+mWheelRotation), 0d, 0d); } float oldCenterX = tb.getPixXFromLatLon(oldCenter); float oldCenterY = tb.getPixYFromLatLon(oldCenter);
package net.sourceforge.offroad.ui; class ZoomAnimationThread extends OffRoadUIThread { /** * */ private final int mWheelRotation; private final Point mNewCenter; ZoomAnimationThread(OsmBitmapPanel pOsmBitmapPanel, int pWheelRotation, Point pNewCenter) { super(pOsmBitmapPanel, "ZoomAnimation"); mWheelRotation = pWheelRotation; mNewCenter = pNewCenter; } @Override public void runAfterThreadsBeforeHaveFinished() { RotatedTileBox tb = mOsmBitmapPanel.copyCurrentTileBox(); int originalZoom = tb.getZoom(); // it -2 == v0 * (it-2) + a (it-2)² // a = ( it(1-v0) + 2*v0-2)/(it-2)² int it; if(mNextThread == null) { // use acceleration only if it is the last thread in the row. it = 30; float v0 = 2f; float a = (it*(1f-v0) + 2f*v0 - 2f)/(it-2f)/(it-2f); for (int i = 0; i < it-1; ++i) { float zoom = v0 * i + a*i*i; log.info("Zoom is " + zoom + " for step " + i + " and velocity " + v0 + " and acceleration " + a); tb = getDestinationTileBox(originalZoom, it, zoom); mOsmBitmapPanel.setCurrentTileBox(tb); log.debug("Set tile box " + tb + " and now repaint."); mOsmBitmapPanel.repaintAndWait(16); log.debug("Set tile box " + tb + " and now repaint. Done."); } } else { it = 10; for (int i = 0; i < it-2; ++i) { tb = getDestinationTileBox(originalZoom, it, i); mOsmBitmapPanel.setCurrentTileBox(tb); log.debug("Set tile box " + tb + " and now repaint."); mOsmBitmapPanel.repaintAndWait(16); log.debug("Set tile box " + tb + " and now repaint. Done."); } } tb = getDestinationTileBox(originalZoom, it, it-1); mOsmBitmapPanel.setCurrentTileBox(tb); log.debug("Set tile box " + tb + " and now repaint."); mOsmBitmapPanel.repaintAndWait(16); log.debug("Set tile box " + tb + " and now repaint. Done."); } public RotatedTileBox getDestinationTileBox(int originalZoom, float it, float i) { RotatedTileBox tb = mOsmBitmapPanel.copyCurrentTileBox(); // get old center: LatLon oldCenter = tb.getLatLonFromPixel(mNewCenter.x, mNewCenter.y); if (i<it-1) { float destZoom = mOsmBitmapPanel.checkZoom(originalZoom+(0f+i*mWheelRotation)/it); int baseZoom = (int) Math.floor(destZoom); float fractZoom = destZoom- baseZoom; tb.setZoomAndAnimation(baseZoom, 0d, fractZoom); } else { tb.setZoomAndAnimation((int)mOsmBitmapPanel.checkZoom(originalZoom+mWheelRotation), 0d, 0d); } float oldCenterX = tb.getPixXFromLatLon(oldCenter); float oldCenterY = tb.getPixYFromLatLon(oldCenter);
QuadPoint center = tb.getCenterPixelPoint();
1
2023-11-15 05:04:55+00:00
12k
WuKongOpenSource/Wukong_HRM
hrm/hrm-web/src/main/java/com/kakarote/hrm/service/impl/HrmFieldSortServiceImpl.java
[ { "identifier": "Const", "path": "common/common-web/src/main/java/com/kakarote/core/common/Const.java", "snippet": "public class Const implements Serializable {\n\n /**\n * 项目版本\n */\n public static final String PROJECT_VERSION = \"12.3.6\";\n\n /**\n * 默认分隔符\n */\n public static final String SEPARATOR = \",\";\n\n /**\n * 查询数据权限递归次数,可以通过继承这个类修改\n */\n public static final int AUTH_DATA_RECURSION_NUM = 20;\n\n /**\n * 业务token在header中的名称\n */\n public static final String TOKEN_NAME = \"Admin-Token\";\n\n /**\n * 默认的token名称\n */\n public static final String DEFAULT_TOKEN_NAME = \"AUTH-TOKEN\";\n\n /**\n * 默认编码\n */\n public static final String DEFAULT_CONTENT_TYPE = \"application/json;charset=UTF-8\";\n\n /**\n * sql最大查询条数限制,以及字段数量限制\n */\n public static final Long QUERY_MAX_SIZE = 100L;\n\n /**\n * PC端登录的userKey\n */\n public static final String USER_TOKEN = \"WK:USER:TOKEN:\";\n\n /**\n * 临时token前缀\n */\n public static final String TEMP_TOKEN_PREFIX = \"TEMP:\";\n\n /**\n * 用户token的最长过期时间\n */\n public static final Integer MAX_USER_EXIST_TIME = 3600 * 24 * 7;\n\n /**\n * 批量保存的条数\n */\n public static final int BATCH_SAVE_SIZE = 200;\n\n\n /**\n * 默认的企业人数\n */\n public static final Integer DEFAULT_COMPANY_NUMBER = 999;\n\n public static final String DEFAULT_DOMAIN = \"www.72crm.com\";\n\n /**\n * 用户名称缓存key\n */\n public static final String ADMIN_USER_NAME_CACHE_NAME = \"ADMIN:USER:CACHE:\";\n\n /**\n * 部门名称缓存key\n */\n public static final String ADMIN_DEPT_NAME_CACHE_NAME = \"ADMIN:DEPT:CACHE:\";\n\n /**\n * 企业安全配置缓存key 前缀\n */\n public static final String COMPANY_SECURITY_CONFIG_KEY=\"COMPANY:SECURITY:CONFIG:\";\n\n /**\n * PC端登录的userKey\n */\n public static final String MULT_DEVICE_USER_TOKEN = \"MULT:DEVICE:USER:TOKEN:\";\n\n /**\n * 用户上次登录时间缓存key\n */\n public static final String USER_LOGIN_LASTED_TIME = \"USER:LOGIN:LASTED:TIME:\";\n\n /**\n * 移动端上次登录信息缓存\n */\n public static final String USER_LOGIN_LASTED_TIME_MOBILE = \"USER:LOGIN:LASTED:TIME:MOBILE:\";\n\n /**\n * 密码强度正则 大写字母、小写字母、数字、特殊符号\n */\n public static final String PASS_PASSWORD_WITH_NUMBER_UPPER_LETTER_CHAR=\"^(?![0-9A-Za-z]+$)(?![0-9A-Z\\\\W]+$)(?![0-9a-z\\\\W]+$)(?![A-Za-z\\\\W]+$)[0-9A-Za-z~!@#$%^&*()_+`\\\\-={}|\\\\[\\\\]\\\\\\\\:\\\";'<>?,./]{\";\n /* \"/*8,16}$\";*/\n\n /**\n *密码强度正则 字母加数字\n */\n public static final String PASS_PASSWORD_WITH_NUMBER_LETTER=\"^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{\";\n\n /**\n * 密码强度正则 大小写字母加数字\n */\n public static final String PASS_PASSWORD_WITH_NUMBER_UPPER_LETTER=\"^(?=.*[a-z])(?=.*[A-Z])(?=.*\\\\d)[a-zA-Z\\\\d]{\";\n /**\n *密码强度正则 字母 数字 特殊字符\n */\n public static final String PASS_PASSWORD_WITH_NUMBER_LETTER_CHAR=\"^(?=.*[a-zA-Z])(?=.*\\\\d)(?=.*[^a-zA-Z0-9])(?=.{8,})[A-Za-z\\\\d\\\\W]{\";\n\n /**\n * 密码强度正则后缀\n */\n public static final String PASSWORD_REG_SUFFIX=\",20}$\";\n\n public static final String NO_AUTH_MENU_CACHE_KEY = \"USER_NO_AUTH_URL:\";\n\n public static final String TOKEN_CACHE_NAME = \"_token\";\n\n}" }, { "identifier": "FieldEnum", "path": "common/common-web/src/main/java/com/kakarote/core/common/enums/FieldEnum.java", "snippet": "@Getter\npublic enum FieldEnum {\n\n /**\n * 字段类型 1 单行文本 2 多行文本 3 单选 4日期 5 数字 6 小数 7 手机 8 文件 9 多选 10 人员\n * 11 附件 12 部门 13 日期时间 14 邮箱 15客户 16 商机 17 联系人 18 地图 19 产品类型 20 合同 21 回款计划 29图片\n */\n TEXT(1, \"text\", \"单行文本\"),\n TEXTAREA(2, \"textarea\", \"多行文本\"),\n SELECT(3, \"select\", \"单选\"),\n DATE(4, \"date\", \"日期\"),\n NUMBER(5, \"number\", \"数字\"),\n FLOATNUMBER(6, \"floatnumber\", \"小数\"),\n MOBILE(7, \"mobile\", \"手机\"),\n FILE(8, \"file\", \"文件\"),\n CHECKBOX(9, \"checkbox\", \"多选\"),\n USER(10, \"user\", \"人员\"),\n ATTACHMENT(11, \"attachment\", \"附件\"),\n STRUCTURE(12, \"structure\", \"部门\"),\n DATETIME(13, \"datetime\", \"日期时间\"),\n EMAIL(14, \"email\", \"邮件\"),\n CUSTOMER(15, \"customer\", \"客户\"),\n BUSINESS(16, \"business\", \"商机\"),\n CONTACTS(17, \"contacts\", \"联系人\"),\n MAP_ADDRESS(18, \"map_address\", \"地图\"),\n CATEGORY(19, \"category\", \"产品类型\"),\n CONTRACT(20, \"contract\", \"合同\"),\n RECEIVABLES_PLAN(21, \"receivables_plan\", \"回款计划\"),\n BUSINESS_CAUSE(22, \"business_cause\", \"商机业务\"),\n EXAMINE_CAUSE(23, \"examine_cause\", \"审批业务\"),\n ADDRESS(24, \"address\", \"地址\"),\n WEBSITE(25, \"website\", \"网址\"),\n RETURN_VISIT(26, \"return_visit\", \"回访\"),\n RETURN_VISIT_CONTRACT(27, \"return_visit_contract\", \"回访合同\"),\n SINGLE_USER(28, \"single_user\", \"单个人员\"),\n /**\n * 进销存\n */\n PIC(29, \"pic\", \"图片\"),\n SUPPLIER_CAUSE(30, \"supplier_cause\", \"供应商\"),\n PURCHASE_CAUSE(31, \"purchase_cause\", \"采购订单\"),\n SALE_CAUSE(32, \"sale_cause\", \"销售订单\"),\n WAREHOUSE_CAUSE(33, \"warehouse_cause\", \"仓库\"),\n RELATED_ID(34, \"related_id\", \"关联对象\"),\n COLLECTION_OBJECT(35, \"collection_object\", \"收藏\"),\n RETREAT_CAUSE(36, \"retreat_cause\", \"采购退货单\"),\n SALE_RETURN_CAUSE(37, \"sale_return_cause\", \"销售退货\"),\n STATE_CAUSE(39, \"state_cause\", \"状态标识\"),\n /**\n * 人资\n */\n AREA(40, \"area\", \"省市区\"),\n\n BOOLEAN_VALUE(41, \"boolean_value\", \"布尔值\"),\n PERCENT(42, \"percent\", \"百分数\"),\n AREA_POSITION(43, \"position\", \"地址\"),\n CURRENT_POSITION(44, \"location\", \"定位\"),\n DETAIL_TABLE(45, \"detail_table\", \"明细表格\"),\n HANDWRITING_SIGN(46, \"handwriting_sign\", \"手写签名\"),\n DATE_INTERVAL(48, \"date_interval\", \"日期区间\"),\n OPTIONS_TYPE(49, \"options_type\", \"选项字段:逻辑表单、批量编辑、其他\"),\n DESC_TEXT(50, \"desc_text\", \"描述文字\"),\n CALCULATION_FUNCTION(51, \"calculation_function\", \"计算函数\"),\n RELATE_CAUSE(52, \"relate_cause\", \"关联业务\"),\n QUOTE_TYPE(53, \"quote_type\", \"引用字段\"),\n CITY(54, \"city\", \"省市\"),\n RECRUIT_CHANNEL(55, \"recruit_channel\", \"招聘渠道\"),\n FIELD_GROUP(60, \"field_group\", \"分组字段\"),\n TAG(61, \"field_tag\", \"标签\"),\n ATTENTION(62, \"field_attention\", \"关注度字段\"),\n SERIAL_NUMBER(63, \"serial_number\", \"唯一编号\"),\n INTENTIONAL_BUSINESS(64, \"product\", \"产品\"),\n SUPERIOR_CUSTOMER(65, \"superior_customer_id\", \"相关客户\"),\n CUSTOMER_RELATIONS(66, \"customer_relations\", \"客户关系\"),\n\n RTF(70, \"rich_text_format\", \"富文本\"),\n\n DATA_UNION(100, \"data_union\", \"数据关联字段\"),\n\n DATA_UNION_MULTI(110, \"data_union_multi\", \"数据关联多选\"),\n\n //补全状体\n CUSTOMER_DEAL_STATUS(101, \"dealStatus\", \"成交状态\"),\n PRODUCT_STATUS(102, \"productStatus\", \"是否上下架\"),\n RECEIVABLES_PLAN_STATUS(103, \"receivedStatus\", \"汇款状态\"),\n INVOICE_TYPE(104, \"invoiceType\", \"开票类型\"),\n INVOICE_STATUS(105, \"invoiceStatus\", \"开票状态\"),\n CHECK_STATUS_BASE(106, \"checkStatus\", \"审核状态\"),\n RECEIVABLES(107, \"receivables\", \"回款\"),\n ;\n\n private final Integer type;\n\n @Getter\n private final String formType;\n\n @Getter\n private final String desc;\n\n private static final HashMap<Integer, FieldEnum> TYPE_TO_FIELD_ENUM_MAP = new HashMap<Integer, FieldEnum>() {\n {\n for (FieldEnum value : FieldEnum.values()) {\n put(value.getType(), value);\n }\n }\n };\n\n private static final HashMap<String, FieldEnum> FORM_TYPE_TO_FIELD_ENUM_MAP = new HashMap<String, FieldEnum>() {\n {\n for (FieldEnum value : FieldEnum.values()) {\n put(value.getFormType(), value);\n }\n }\n };\n\n\n FieldEnum(Integer type, String formType, String desc) {\n this.type = type;\n this.formType = formType;\n this.desc = desc;\n }\n\n\n public static FieldEnum parse(Integer type) {\n FieldEnum fieldEnum = TYPE_TO_FIELD_ENUM_MAP.get(type);\n if (fieldEnum == null) {\n return TEXT;\n }\n return fieldEnum;\n }\n\n public static FieldEnum parse(String formType) {\n FieldEnum fieldEnum = FORM_TYPE_TO_FIELD_ENUM_MAP.get(formType);\n if (fieldEnum == null) {\n return TEXT;\n }\n return fieldEnum;\n }\n\n /**\n * 仪表盘显示的字段类型\n **/\n public static List<Integer> getShowFieldEnumType() {\n List<Integer> biDashboardNoShowFieldEnum = new ArrayList<>();\n List<Integer> list = Arrays.asList(101, 102, 103, 104, 105, 106);\n for (FieldEnum value : FieldEnum.values()) {\n if (value.getType() < 46 || list.contains(value.getType())) {\n biDashboardNoShowFieldEnum.add(value.getType());\n }\n }\n //增加编号字段\n biDashboardNoShowFieldEnum.add(63);\n return biDashboardNoShowFieldEnum;\n }\n\n /**\n * 仅数字类型\n *\n * @author UNIQUE\n * @date 2023/4/8\n */\n public static List<String> getShowTargetFieldEnumType() {\n return Arrays.asList(FieldEnum.NUMBER.getFormType()\n , FieldEnum.FLOATNUMBER.getFormType()\n , FieldEnum.PERCENT.getFormType()\n );\n }\n}" }, { "identifier": "BaseServiceImpl", "path": "common/common-web/src/main/java/com/kakarote/core/servlet/BaseServiceImpl.java", "snippet": "public class BaseServiceImpl<M extends BaseMapper<T>, T> extends ServiceImpl<M, T> implements BaseService<T> {\n\n\n public final Logger log = LoggerFactory.getLogger(getEntityClass());\n\n @Autowired\n private IdentifierGenerator identifierGenerator;\n\n @Override\n @Transactional(rollbackFor = Exception.class, isolation = Isolation.READ_COMMITTED)\n public boolean saveBatch(Collection<T> entityList) {\n return saveBatch(entityList, Const.BATCH_SAVE_SIZE);\n }\n\n\n /**\n * 批量保存,取的字段为任何一列值不为空的字段\n */\n @Override\n @Transactional(rollbackFor = Exception.class, isolation = Isolation.READ_COMMITTED)\n public boolean saveBatch(Collection<T> entityList, int batchSize) {\n if (CollUtil.isEmpty(entityList)) {\n return true;\n }\n //获取表以及字段信息\n T model = entityList.iterator().next();\n Class<?> tClass = model.getClass();\n TableInfo table = SqlHelper.table(tClass);\n List<Field> allFields = TableInfoHelper.getAllFields(tClass);\n Set<String> fieldSet = allFields.stream().filter(field -> {\n TableId tableId = field.getAnnotation(TableId.class);\n return tableId == null || !Objects.equals(tableId.type(), IdType.AUTO);\n })\n .map(field -> StrUtil.toUnderlineCase(field.getName())).collect(Collectors.toSet());\n List<Map<String, Object>> mapList = insertFill(entityList, table, fieldSet);\n StringBuilder sql = new StringBuilder();\n forModelSave(table, fieldSet, sql);\n log.debug(\"Preparing:{}\", sql);\n int[] result = batch(this.sqlSessionFactory, sql.toString(), StrUtil.join(Const.SEPARATOR, fieldSet), mapList, batchSize);\n return result.length > 0;\n }\n\n\n @Override\n public T getOne(Wrapper<T> queryWrapper, boolean throwEx) {\n List<T> dataList = getBaseMapper().selectList(queryWrapper);\n if (dataList.isEmpty()) {\n return null;\n }\n return dataList.iterator().next();\n }\n\n /**\n * 字段填充\n */\n private List<Map<String, Object>> insertFill(Collection<T> entityList, TableInfo tableInfo, Set<String> keySet) {\n List<Map<String, Object>> mapList = new ArrayList<>(entityList.size());\n Set<String> existFieldSet = new HashSet<>(keySet.size());\n String dateTime = DateUtil.formatDateTime(new Date());\n for (T model : entityList) {\n Map<String, Object> attrs = BeanUtil.beanToMap(model, true, false);\n Object obj = attrs.get(tableInfo.getKeyColumn());\n if (obj == null) {\n if (tableInfo.getIdType() == IdType.ASSIGN_ID) {\n if (Number.class.isAssignableFrom(tableInfo.getKeyType())) {\n attrs.put(tableInfo.getKeyColumn(), identifierGenerator.nextId(model));\n } else {\n attrs.put(tableInfo.getKeyColumn(), identifierGenerator.nextId(model).toString());\n }\n } else if (tableInfo.getIdType() == IdType.ASSIGN_UUID) {\n attrs.put(tableInfo.getKeyColumn(), identifierGenerator.nextUUID(model));\n }\n }\n for (String key : keySet) {\n if (attrs.get(key) == null) {\n switch (key) {\n case \"create_time\":\n case \"update_time\":\n attrs.put(key, dateTime);\n break;\n case \"create_user_id\":\n Long userId = UserUtil.getUserId();\n attrs.put(key, userId);\n break;\n default:\n break;\n }\n }\n if (attrs.get(key) != null) {\n existFieldSet.add(key);\n }\n\n }\n mapList.add(attrs);\n }\n keySet.retainAll(existFieldSet);\n return mapList;\n }\n\n /**\n * 拼接sql\n */\n private void forModelSave(TableInfo table, Set<String> attrs, StringBuilder sql) {\n sql.append(\"insert into `\").append(table.getTableName()).append(\"`(\");\n CollUtil.newArrayList(table.getAllSqlSelect().split(\",\"));\n StringBuilder temp = new StringBuilder(\") values(\");\n int index = 0;\n for (String key : attrs) {\n if (index++ != 0) {\n sql.append(\", \");\n temp.append(\", \");\n }\n sql.append('`').append(key).append('`');\n temp.append('?');\n }\n sql.append(temp).append(')');\n }\n\n /**\n * 批量保存\n */\n private int[] batch(SqlSessionFactory sqlSessionFactory, String sql, String columns, Collection<Map<String, Object>> entityList, int batchSize) {\n int[] batch;\n SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH);\n try {\n Connection conn = sqlSession.getConnection();\n batch = batch(conn, sql, columns, new ArrayList<>(entityList), batchSize);\n sqlSession.commit();\n } catch (Throwable t) {\n log.error(\"批量报错出错\", t);\n sqlSession.rollback();\n Throwable unwrapped = ExceptionUtil.unwrapThrowable(t);\n if (unwrapped instanceof RuntimeException) {\n MyBatisExceptionTranslator myBatisExceptionTranslator\n = new MyBatisExceptionTranslator(sqlSessionFactory.getConfiguration().getEnvironment().getDataSource(), true);\n throw Objects.requireNonNull(myBatisExceptionTranslator.translateExceptionIfPossible((RuntimeException) unwrapped));\n }\n throw ExceptionUtils.mpe(unwrapped);\n } finally {\n sqlSession.close();\n }\n return batch;\n }\n\n private int[] batch(Connection conn, String sql, String columns, List<Map<String, Object>> list, int batchSize) throws SQLException {\n if (list == null || list.size() == 0) {\n return new int[0];\n }\n if (batchSize < 1) {\n throw new IllegalArgumentException(\"The batchSize must more than 0.\");\n }\n String[] columnArray = columns.split(\",\");\n for (int i = 0; i < columnArray.length; i++) {\n columnArray[i] = columnArray[i].trim();\n }\n int counter = 0;\n int pointer = 0;\n int size = list.size();\n int[] result = new int[size];\n PreparedStatement pst = conn.prepareStatement(sql);\n for (Map<String, Object> map : list) {\n for (int j = 0; j < columnArray.length; j++) {\n Object value = map.get(columnArray[j]);\n if (value instanceof Date) {\n if (value instanceof java.sql.Date) {\n pst.setDate(j + 1, (java.sql.Date) value);\n } else if (value instanceof java.sql.Timestamp) {\n pst.setTimestamp(j + 1, (java.sql.Timestamp) value);\n } else {\n Date d = (Date) value;\n pst.setTimestamp(j + 1, new java.sql.Timestamp(d.getTime()));\n }\n } else {\n pst.setObject(j + 1, value);\n }\n }\n pst.addBatch();\n if (++counter >= batchSize) {\n counter = 0;\n int[] r = pst.executeBatch();\n for (int j : r) {\n result[pointer++] = j;\n }\n }\n }\n if (counter != 0) {\n int[] r = pst.executeBatch();\n for (int i : r) {\n result[pointer++] = i;\n }\n }\n try {\n pst.close();\n } catch (SQLException e) {\n throw new RuntimeException(e);\n }\n return result;\n }\n}" }, { "identifier": "HrmEnum", "path": "hrm/hrm-web/src/main/java/com/kakarote/hrm/constant/HrmEnum.java", "snippet": "public enum HrmEnum implements FieldLabel {\n\n /**\n * 绩效考核\n */\n APPRAISAL_EMPLOYEE(5, \"考核员工\");\n /**\n * 类型\n */\n private final int type;\n\n /**\n * 名称\n */\n private final String remarks;\n\n HrmEnum(int type, String remarks) {\n this.type = type;\n this.remarks = remarks;\n }\n\n public static HrmEnum parse(Integer type) {\n for (HrmEnum hrmEnum : HrmEnum.values()) {\n if (Objects.equals(hrmEnum.getType(), type)) {\n return hrmEnum;\n }\n }\n return null;\n }\n\n public Integer getType() {\n return type;\n }\n\n @Override\n public String getRemarks() {\n return remarks;\n }\n\n @Override\n public String getIndex() {\n return \"hrm_\" + name().toLowerCase();\n }\n\n /**\n * 获取模块名称\n *\n * @return 模块名称\n */\n @Override\n public String getModelName() {\n return \"hrm\";\n }\n\n @Override\n public String getTableName() {\n return name().toLowerCase();\n }\n\n public String getTableId() {\n return StrUtil.toCamelCase(name().toLowerCase()) + \"Id\";\n }\n\n /**\n * 获取主键ID\n *\n * @param camelCase 是否驼峰\n * @return primaryKey\n */\n @Override\n public String getPrimaryKey(boolean camelCase) {\n String name = name().toLowerCase();\n if (camelCase) {\n return StrUtil.toCamelCase(name) + \"Id\";\n }\n return name + \"_id\";\n }\n\n @Override\n public String getPrimaryKey() {\n return getPrimaryKey(true);\n }\n}" }, { "identifier": "HrmEmployeeField", "path": "hrm/hrm-web/src/main/java/com/kakarote/hrm/entity/PO/HrmEmployeeField.java", "snippet": "@Data\n@EqualsAndHashCode(callSuper = false)\n@Accessors(chain = true)\n@NoArgsConstructor\n@TableName(\"wk_hrm_employee_field\")\n@ApiModel(value = \"HrmEmployeeField对象\", description = \"自定义字段表\")\npublic class HrmEmployeeField implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n public HrmEmployeeField(String fieldName, String name, FieldEnum fieldEnum) {\n this.fieldName = fieldName;\n this.name = name;\n this.type = fieldEnum.getType();\n }\n\n public HrmEmployeeField(String fieldName, String name, FieldEnum fieldEnum, Integer isHidden) {\n this.fieldName = fieldName;\n this.name = name;\n this.type = fieldEnum.getType();\n this.isHidden = isHidden;\n }\n\n @ApiModelProperty(value = \"主键ID\")\n @TableId(value = \"field_id\", type = IdType.ASSIGN_ID)\n @JsonSerialize(using = ToStringSerializer.class)\n private Long fieldId;\n\n @ApiModelProperty(value = \"自定义字段英文标识\")\n private String fieldName;\n\n @ApiModelProperty(value = \"字段名称\")\n private String name;\n\n @ApiModelProperty(value = \"字段类型 1 单行文本 2 多行文本 3 单选 4日期 5 数字 6 小数 7 手机 8 文件 9 多选 10 日期时间 11 邮箱 12 籍贯地区\")\n private Integer type;\n\n @ApiModelProperty(value = \"关联表类型 0 不需要关联 1 hrm员工 2 hrm部门 3 hrm职位 4 系统用户 5 系统部门 6 招聘渠道\")\n private Integer componentType;\n\n @ApiModelProperty(value = \"标签 1 个人信息 2 岗位信息 3 合同 4 工资社保\")\n private Integer label;\n\n @ApiModelProperty(value = \"标签分组 * 1 员工个人信息 2 通讯信息 3 教育经历 4 工作经历 5 证书/证件 6 培训经历 7 联系人 11 岗位信息 12 离职信息 21 合同信息 31 工资卡信息 32 社保信息\")\n private Integer labelGroup;\n\n @ApiModelProperty(value = \"字段说明\")\n private String remark;\n\n @ApiModelProperty(value = \"输入提示\")\n private String inputTips;\n\n @ApiModelProperty(value = \"最大长度\")\n private Integer maxLength;\n\n @ApiModelProperty(value = \"默认值\")\n private Object defaultValue;\n\n @ApiModelProperty(value = \"是否唯一 1 是 0 否\")\n private Integer isUnique;\n\n @ApiModelProperty(value = \"是否必填 1 是 0 否\")\n private Integer isNull;\n\n @ApiModelProperty(value = \"排序 从小到大\")\n private Integer sorting;\n\n @ApiModelProperty(value = \"如果类型是选项,此处不能为空,使用kv格式\")\n private String options;\n\n @ApiModelProperty(value = \"是否固定字段 0 否 1 是\")\n private Integer isFixed;\n\n @ApiModelProperty(value = \"000000 (1:标题,2:选项,3:必填,4:唯一,5:隐藏,6:删除)\")\n private Integer operating;\n\n @ApiModelProperty(value = \"是否隐藏 0不隐藏 1隐藏\")\n private Integer isHidden;\n\n @ApiModelProperty(value = \"是否可以修改值 0 否 1 是\")\n private Integer isUpdateValue;\n\n @ApiModelProperty(value = \"是否在列表头展示 0 否 1 是\")\n private Integer isHeadField;\n\n @ApiModelProperty(value = \"是否需要导入字段 0 否 1 是\")\n private Integer isImportField;\n\n @ApiModelProperty(value = \"是否员工可见 0 否 1 是\")\n private Integer isEmployeeVisible;\n\n @ApiModelProperty(value = \"是否员工可修改 0 否 1 是\")\n private Integer isEmployeeUpdate;\n\n @ApiModelProperty(value = \"最后修改时间\")\n @TableField(fill = FieldFill.UPDATE)\n private LocalDateTime updateTime;\n\n @TableField(exist = false)\n private Object value;\n\n @ApiModelProperty(value = \"样式百分比 1 100% 2 75% 3 50% 4 25%\")\n private Integer stylePercent;\n\n @ApiModelProperty(value = \"精度,允许的最大小数位/地图精度/明细表格、逻辑表单展示方式\")\n @TableField(fill = FieldFill.UPDATE)\n private Integer precisions;\n\n @ApiModelProperty(value = \"表单定位 坐标格式: 1,1\")\n private String formPosition;\n\n @ApiModelProperty(value = \"限制的最大数值\")\n @TableField(fill = FieldFill.UPDATE)\n private String maxNumRestrict;\n\n @ApiModelProperty(value = \"限制的最小数值\")\n @TableField(fill = FieldFill.UPDATE)\n private String minNumRestrict;\n\n @ApiModelProperty(value = \"表单辅助id,前端生成\")\n private Long formAssistId;\n\n @TableField(exist = false)\n @ApiModelProperty(value = \"类型\")\n private String formType;\n\n @TableField(exist = false)\n @ApiModelProperty(value = \"设置列表\")\n private List<?> setting;\n\n /**\n * 坐标\n */\n @TableField(exist = false)\n @ApiModelProperty(value = \"x轴\")\n @JsonIgnore\n private Integer xAxis;\n\n @TableField(exist = false)\n @ApiModelProperty(value = \"y轴\")\n @JsonIgnore\n private Integer yAxis;\n\n @TableField(exist = false)\n @ApiModelProperty(value = \"逻辑表单数据\")\n private Map<String, Object> optionsData;\n\n @TableField(exist = false)\n @ApiModelProperty(value = \"扩展字段\")\n private List<HrmFieldExtend> fieldExtendList;\n @TableField(fill = FieldFill.INSERT)\n @JsonSerialize(using = ToStringSerializer.class)\n private Long createUserId;\n\n @TableField(fill = FieldFill.INSERT)\n private LocalDateTime createTime;\n\n @TableField(fill = FieldFill.UPDATE)\n @JsonSerialize(using = ToStringSerializer.class)\n private Long updateUserId;\n\n @ApiModelProperty(value = \"语言包map\")\n @TableField(exist = false)\n private Map<String, String> languageKeyMap;\n\n public void setFormPosition(String formPosition) {\n this.formPosition = formPosition;\n if (StrUtil.isNotEmpty(formPosition)) {\n if (formPosition.contains(Const.SEPARATOR)) {\n String[] axisArr = formPosition.split(Const.SEPARATOR);\n int two = 2;\n if (axisArr.length == two) {\n String regex = \"[0-9]+\";\n if (axisArr[0].matches(regex) && axisArr[1].matches(regex)) {\n this.xAxis = Integer.valueOf(axisArr[0]);\n this.yAxis = Integer.valueOf(axisArr[1]);\n return;\n }\n }\n }\n }\n this.xAxis = -1;\n this.yAxis = -1;\n }\n\n}" }, { "identifier": "HrmFieldSort", "path": "hrm/hrm-web/src/main/java/com/kakarote/hrm/entity/PO/HrmFieldSort.java", "snippet": "@Data\n@Accessors(chain = true)\n@TableName(\"wk_hrm_field_sort\")\n@ApiModel(value = \"HrmFieldSort对象\", description = \"字段排序表\")\npublic class HrmFieldSort implements Serializable {\n\n private static final long serialVersionUID = 1L;\n\n @ApiModelProperty(value = \"id\")\n @TableId(value = \"id\", type = IdType.ASSIGN_ID)\n private Long id;\n\n @ApiModelProperty(value = \"字段ID\")\n private Long fieldId;\n\n @ApiModelProperty(value = \"字段名称\")\n private String fieldName;\n\n @ApiModelProperty(value = \"名称\")\n private String name;\n\n @ApiModelProperty(value = \"员工考核 5\")\n private Integer label;\n\n @ApiModelProperty(value = \"字段类型\")\n private Integer type;\n\n @ApiModelProperty(value = \"字段宽度\")\n private Integer style;\n\n @ApiModelProperty(value = \"字段排序\")\n private Integer sort;\n\n @ApiModelProperty(value = \"用户id\")\n private Long userId;\n\n @ApiModelProperty(value = \"是否隐藏 0、不隐藏 1、隐藏\")\n private Integer isHide;\n\n @ApiModelProperty(value = \"是否锁定\")\n private Integer isLock;\n\n @ApiModelProperty(value = \"创建人ID\")\n @TableField(fill = FieldFill.INSERT)\n private Long createUserId;\n\n @ApiModelProperty(value = \"修改人ID\")\n @TableField(fill = FieldFill.UPDATE)\n private Long updateUserId;\n\n @ApiModelProperty(value = \"创建时间\")\n @TableField(fill = FieldFill.INSERT)\n private LocalDateTime createTime;\n\n @ApiModelProperty(value = \"更新时间\")\n @TableField(fill = FieldFill.UPDATE)\n private LocalDateTime updateTime;\n\n @Override\n public boolean equals(Object o) {\n if (this == o) {\n return true;\n }\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n HrmFieldSort that = (HrmFieldSort) o;\n return fieldName.equals(that.fieldName);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(fieldName);\n }\n}" }, { "identifier": "HrmFieldSortVO", "path": "hrm/hrm-web/src/main/java/com/kakarote/hrm/entity/VO/HrmFieldSortVO.java", "snippet": "@Data\n@Accessors(chain = true)\n@ApiModel(value = \"CrmFieldSort列表对象\", description = \"字段排序表\")\npublic class HrmFieldSortVO implements Serializable {\n\n private static final long serialVersionUID = 1L;\n @ApiModelProperty(value = \"主键ID\")\n private Long id;\n\n @ApiModelProperty(value = \"字段ID\")\n private Long fieldId;\n\n @ApiModelProperty(value = \"字段名称\")\n private String fieldName;\n\n @ApiModelProperty(value = \"字段类型\")\n private String formType;\n\n @ApiModelProperty(value = \"展示名称\")\n private String name;\n\n @ApiModelProperty(value = \"字段类型\")\n private Integer type;\n\n @ApiModelProperty(value = \"字段宽度\")\n private Integer width;\n\n @ApiModelProperty(value = \"是否锁定\")\n private Integer isLock;\n\n\n}" }, { "identifier": "HrmFieldSortMapper", "path": "hrm/hrm-web/src/main/java/com/kakarote/hrm/mapper/HrmFieldSortMapper.java", "snippet": "public interface HrmFieldSortMapper extends BaseMapper<HrmFieldSort> {\n\n /**\n * 查询模块字段列表\n *\n * @param label label\n * @return data\n */\n public List<HrmFieldSortVO> queryListHead(@Param(\"label\") Integer label, @Param(\"userId\") Long userId);\n\n /**\n * 查询模块字段列表\n *\n * @param label label\n * @return data\n */\n public List<HrmFieldSortVO> queryListHeadByIds(@Param(\"label\") Integer label, @Param(\"userId\") Long userId, @Param(\"ids\") List<Long> ids);\n}" }, { "identifier": "IHrmEmployeeFieldService", "path": "hrm/hrm-web/src/main/java/com/kakarote/hrm/service/IHrmEmployeeFieldService.java", "snippet": "public interface IHrmEmployeeFieldService extends BaseService<HrmEmployeeField> {\n\n /**\n * 根据 label_group 查询员工字段\n *\n * @return\n */\n List<HrmEmployeeField> queryInformationFieldByLabelGroup(LabelGroupEnum labelGroup);\n\n /**\n * 查询表头信息\n *\n * @return\n */\n List<EmployeeHeadFieldVO> queryListHeads();\n\n /**\n * 批量修改字段表头配置\n *\n * @param updateFieldConfigBOList\n */\n void updateFieldConfig(List<UpdateFieldConfigBO> updateFieldConfigBOList);\n\n\n /**\n * 查询后台配置自定义字段列表\n *\n * @return\n */\n List<FiledListVO> queryFields();\n\n /**\n * 查询后台配置自定义字段列表\n *\n * @param label\n * @return\n */\n List<List<HrmEmployeeField>> queryFieldByLabel(Integer label);\n\n /**\n * 保存后台自定义字段\n *\n * @param addEmployeeFieldBO\n */\n void saveField(AddEmployeeFieldBO addEmployeeFieldBO);\n\n /**\n * 保存员工自定义字段\n *\n * @param fieldList\n * @param labelGroupEnum\n * @param employeeId\n */\n void saveEmployeeField(List<HrmEmployeeData> fieldList, LabelGroupEnum labelGroupEnum, Long employeeId);\n\n /**\n * 保存联系人自定义字段\n *\n * @param fieldList\n * @param contactPerson\n * @param contactsId\n */\n void saveEmployeeContactsField(List<HrmEmployeeContactsData> fieldList, LabelGroupEnum contactPerson, Long contactsId);\n\n /**\n * 验证字段唯一\n *\n * @param verifyUniqueBO\n */\n VerifyUniqueBO verifyUnique(VerifyUniqueBO verifyUniqueBO);\n\n /**\n * 修改字段宽度\n *\n * @param updateFieldWidthBO\n */\n void updateFieldWidth(UpdateFieldWidthBO updateFieldWidthBO);\n\n /**\n * 查询员工档案设置字段列表\n *\n * @return\n */\n List<EmployeeArchivesFieldVO> queryEmployeeArchivesField();\n\n /**\n * 修改员工档案字段\n *\n * @param archivesFields\n */\n void setEmployeeArchivesField(List<EmployeeArchivesFieldVO> archivesFields);\n\n /**\n * 发送填写档案信息\n *\n * @param writeArchivesBO\n */\n List<OperationLog> sendWriteArchives(SendWriteArchivesBO writeArchivesBO);\n\n /**\n * 根据员工状态查询字段\n *\n * @param entryStatus\n * @return\n */\n List<HrmModelFiledVO> queryField(Integer entryStatus);\n\n /**\n * 根据label查询字段\n *\n * @param type\n * @return\n */\n public List<HrmModelFiledVO> queryHrmField(Integer type);\n\n /**\n * 格式化数据\n *\n * @param record data\n * @param typeEnum type\n */\n public void recordToFormType(HrmModelFiledVO record, FieldEnum typeEnum);\n\n /**\n * @param label 标签\n * @param fieldType 字段类型\n * @param existNameList 已存在的标签\n * @return fieldName\n */\n public String getNextFieldName(Integer label, Integer fieldType, List<String> existNameList, Integer depth);\n\n /**\n * 将符合条件的字段值转换成str\n */\n String convertObjectValueToString(Integer type, Object value, String defaultValue);\n\n /**\n * 判断自定义字段类型是否符合\n */\n boolean equalsByType(Object type);\n\n /**\n * 判断自定义字段类型是否符合\n */\n boolean equalsByType(Object type, FieldEnum... fieldEnums);\n\n /**\n * 转换数据库值得格式供前端使用\n */\n Object convertValueByFormType(Object value, FieldEnum typeEnum);\n\n List<Map<String, Object>> getAllFieldLanguageRel();\n\n /**\n * 保存自定义字段列表\n *\n * @param label label\n * @param isQueryHide 是否查询隐藏字段\n * @return data\n */\n public List<HrmEmployeeField> list(Integer label, boolean isQueryHide);\n\n\n /**\n * 查询模块字段列表\n *\n * @param label label\n * @return data\n */\n public List<HrmFieldSortVO> queryListHead(Integer label);\n}" }, { "identifier": "IHrmFieldSortService", "path": "hrm/hrm-web/src/main/java/com/kakarote/hrm/service/IHrmFieldSortService.java", "snippet": "public interface IHrmFieldSortService extends BaseService<HrmFieldSort> {\n\n /**\n * 查询模块字段列表\n *\n * @param label label\n * @return data\n */\n public List<HrmFieldSortVO> queryListHead(Integer label);\n\n /**\n * 查询模块字段列表\n *\n * @param label label\n * @return data\n */\n public List<HrmFieldSortVO> queryListHead(Integer label, List<Long> ids);\n\n /**\n * 查询模块全部字段排序\n *\n * @param label label\n * @param userId 用户ID\n * @return data\n */\n public List<HrmFieldSort> queryAllFieldSortList(Integer label, Long userId);\n}" } ]
import cn.hutool.core.util.StrUtil; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.kakarote.common.utils.UserUtil; import com.kakarote.core.common.Const; import com.kakarote.core.common.enums.FieldEnum; import com.kakarote.core.servlet.BaseServiceImpl; import com.kakarote.hrm.constant.HrmEnum; import com.kakarote.hrm.entity.PO.HrmEmployeeField; import com.kakarote.hrm.entity.PO.HrmFieldSort; import com.kakarote.hrm.entity.VO.HrmFieldSortVO; import com.kakarote.hrm.mapper.HrmFieldSortMapper; import com.kakarote.hrm.service.IHrmEmployeeFieldService; import com.kakarote.hrm.service.IHrmFieldSortService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.stream.Collectors;
10,536
package com.kakarote.hrm.service.impl; /** * <p> * 字段排序表 服务实现类 * </p> * * @author zhangzhiwei * @since 2020-05-19 */ @Service public class HrmFieldSortServiceImpl extends BaseServiceImpl<HrmFieldSortMapper, HrmFieldSort> implements IHrmFieldSortService { @Autowired private IHrmEmployeeFieldService hrmEmployeeFieldService; /** * 查询模块字段列表 * * @param label label * @return data */ @Override public List<HrmFieldSortVO> queryListHead(Integer label) { Long userId = UserUtil.getUserId(); QueryWrapper<HrmFieldSort> wrapper = new QueryWrapper<>(); wrapper.eq("user_id", userId).eq("label", label); int number = (int) count(wrapper); if (number == 0) { saveUserFieldSort(label, userId); } List<HrmFieldSortVO> hrmFieldSortVOS = getBaseMapper().queryListHead(label, userId); //加工是否锁定排序 List<HrmFieldSortVO> collect = hrmFieldSortVOS.stream().sorted(Comparator.comparing(HrmFieldSortVO::getIsLock, Comparator.nullsFirst(Integer::compareTo)).reversed()).collect(Collectors.toList()); return collect; } /** * 查询模块字段列表 * * @param label label * @return data */ @Override public List<HrmFieldSortVO> queryListHead(Integer label, List<Long> ids) { Long userId = UserUtil.getUserId(); QueryWrapper<HrmFieldSort> wrapper = new QueryWrapper<>(); wrapper.eq("user_id", userId).eq("label", label).in("id", ids); int number = (int) count(wrapper); if (number == 0) { saveUserFieldSort(label, userId); } return getBaseMapper().queryListHeadByIds(label, userId, ids); } @Override public List<HrmFieldSort> queryAllFieldSortList(Integer label, Long userId) { List<HrmEmployeeField> crmFieldList = hrmEmployeeFieldService.list(label, false); HrmEnum crmEnum = HrmEnum.parse(label); //需要初始化时锁定的字段 List<String> isLockStrNames = new ArrayList<>(); switch (crmEnum) { case APPRAISAL_EMPLOYEE: crmFieldList = new ArrayList<>();
package com.kakarote.hrm.service.impl; /** * <p> * 字段排序表 服务实现类 * </p> * * @author zhangzhiwei * @since 2020-05-19 */ @Service public class HrmFieldSortServiceImpl extends BaseServiceImpl<HrmFieldSortMapper, HrmFieldSort> implements IHrmFieldSortService { @Autowired private IHrmEmployeeFieldService hrmEmployeeFieldService; /** * 查询模块字段列表 * * @param label label * @return data */ @Override public List<HrmFieldSortVO> queryListHead(Integer label) { Long userId = UserUtil.getUserId(); QueryWrapper<HrmFieldSort> wrapper = new QueryWrapper<>(); wrapper.eq("user_id", userId).eq("label", label); int number = (int) count(wrapper); if (number == 0) { saveUserFieldSort(label, userId); } List<HrmFieldSortVO> hrmFieldSortVOS = getBaseMapper().queryListHead(label, userId); //加工是否锁定排序 List<HrmFieldSortVO> collect = hrmFieldSortVOS.stream().sorted(Comparator.comparing(HrmFieldSortVO::getIsLock, Comparator.nullsFirst(Integer::compareTo)).reversed()).collect(Collectors.toList()); return collect; } /** * 查询模块字段列表 * * @param label label * @return data */ @Override public List<HrmFieldSortVO> queryListHead(Integer label, List<Long> ids) { Long userId = UserUtil.getUserId(); QueryWrapper<HrmFieldSort> wrapper = new QueryWrapper<>(); wrapper.eq("user_id", userId).eq("label", label).in("id", ids); int number = (int) count(wrapper); if (number == 0) { saveUserFieldSort(label, userId); } return getBaseMapper().queryListHeadByIds(label, userId, ids); } @Override public List<HrmFieldSort> queryAllFieldSortList(Integer label, Long userId) { List<HrmEmployeeField> crmFieldList = hrmEmployeeFieldService.list(label, false); HrmEnum crmEnum = HrmEnum.parse(label); //需要初始化时锁定的字段 List<String> isLockStrNames = new ArrayList<>(); switch (crmEnum) { case APPRAISAL_EMPLOYEE: crmFieldList = new ArrayList<>();
crmFieldList.add(new HrmEmployeeField("mobile", "手机号", FieldEnum.TEXT));
1
2023-10-17 05:49:52+00:00
12k
WisdomShell/codeshell-intellij
src/main/java/com/codeshell/intellij/widget/CodeShellWidget.java
[ { "identifier": "CodeShellStatus", "path": "src/main/java/com/codeshell/intellij/enums/CodeShellStatus.java", "snippet": "public enum CodeShellStatus {\n UNKNOWN(0, \"Unknown\"),\n OK(200, \"OK\"),\n BAD_REQUEST(400, \"Bad request/token\"),\n NOT_FOUND(404, \"404 Not found\"),\n TOO_MANY_REQUESTS(429, \"Too many requests right now\");\n\n private final int code;\n private final String displayValue;\n\n CodeShellStatus(int i, String s) {\n code = i;\n displayValue = s;\n }\n\n public int getCode() {\n return code;\n }\n\n public String getDisplayValue() {\n return displayValue;\n }\n\n public static CodeShellStatus getStatusByCode(int code) {\n return Stream.of(CodeShellStatus.values())\n .filter(s -> s.getCode() == code)\n .findFirst()\n .orElse(CodeShellStatus.UNKNOWN);\n }\n}" }, { "identifier": "CodeShellCompleteService", "path": "src/main/java/com/codeshell/intellij/services/CodeShellCompleteService.java", "snippet": "public class CodeShellCompleteService {\n private final Logger logger = Logger.getInstance(this.getClass());\n private static final String PREFIX_TAG = \"<fim_prefix>\";\n private static final String SUFFIX_TAG = \"<fim_suffix>\";\n private static final String MIDDLE_TAG = \"<fim_middle>\";\n private static final String REG_EXP = \"data:\\\\s?(.*?)\\n\";\n private static final Pattern PATTERN = Pattern.compile(REG_EXP);\n private static long lastRequestTime = 0;\n private static boolean httpRequestFinFlag = true;\n private int statusCode = 200;\n\n public String[] getCodeCompletionHints(CharSequence editorContents, int cursorPosition) {\n CodeShellSettings settings = CodeShellSettings.getInstance();\n String contents = editorContents.toString();\n if (!httpRequestFinFlag || !settings.isSaytEnabled() || StringUtils.isBlank(contents)) {\n return null;\n }\n if (contents.contains(PREFIX_TAG) || contents.contains(SUFFIX_TAG) || contents.contains(MIDDLE_TAG) || contents.contains(PrefixString.RESPONSE_END_TAG)) {\n return null;\n }\n String prefix = contents.substring(CodeShellUtils.prefixHandle(0, cursorPosition), cursorPosition);\n String suffix = contents.substring(cursorPosition, CodeShellUtils.suffixHandle(cursorPosition, editorContents.length()));\n String generatedText = \"\";\n String codeShellPrompt = generateFIMPrompt(prefix, suffix);\n if(settings.isCPURadioButtonEnabled()){\n HttpPost httpPost = buildApiPostForCPU(settings, prefix, suffix);\n generatedText = getApiResponseForCPU(settings, httpPost, codeShellPrompt);\n }else{\n HttpPost httpPost = buildApiPostForGPU(settings, codeShellPrompt);\n generatedText = getApiResponseForGPU(settings, httpPost, codeShellPrompt);\n }\n String[] suggestionList = null;\n if (generatedText.contains(MIDDLE_TAG)) {\n String[] parts = generatedText.split(MIDDLE_TAG);\n if (parts.length > 0) {\n suggestionList = StringUtils.splitPreserveAllTokens(parts[1], \"\\n\");\n if (suggestionList.length == 1 && suggestionList[0].trim().isEmpty()) {\n return null;\n }\n if (suggestionList.length > 1) {\n for (int i = 0; i < suggestionList.length; i++) {\n StringBuilder sb = new StringBuilder(suggestionList[i]);\n sb.append(\"\\n\");\n suggestionList[i] = sb.toString();\n }\n }\n }\n }\n return suggestionList;\n }\n\n private String generateFIMPrompt(String prefix, String suffix) {\n return PREFIX_TAG + prefix + SUFFIX_TAG + suffix + MIDDLE_TAG;\n }\n\n private HttpPost buildApiPostForCPU(CodeShellSettings settings, String prefix,String suffix) {\n String apiURL = settings.getServerAddressURL() + CodeShellURI.CPU_COMPLETE.getUri();\n HttpPost httpPost = new HttpPost(apiURL);\n JsonObject httpBody = CodeShellUtils.pakgHttpRequestBodyForCPU(settings, prefix, suffix);\n StringEntity requestEntity = new StringEntity(httpBody.toString(), ContentType.APPLICATION_JSON);\n httpPost.setEntity(requestEntity);\n return httpPost;\n }\n\n private HttpPost buildApiPostForGPU(CodeShellSettings settings, String codeShellPrompt) {\n String apiURL = settings.getServerAddressURL() + CodeShellURI.GPU_COMPLETE.getUri();\n HttpPost httpPost = new HttpPost(apiURL);\n JsonObject httpBody = CodeShellUtils.pakgHttpRequestBodyForGPU(settings, codeShellPrompt);\n StringEntity requestEntity = new StringEntity(httpBody.toString(), ContentType.APPLICATION_JSON);\n httpPost.setEntity(requestEntity);\n return httpPost;\n }\n\n private String getApiResponseForCPU(CodeShellSettings settings, HttpPost httpPost, String codeShellPrompt) {\n String responseText = \"\";\n httpRequestFinFlag = false;\n try {\n CloseableHttpClient httpClient = HttpClients.createDefault();\n HttpResponse response = httpClient.execute(httpPost);\n int oldStatusCode = statusCode;\n statusCode = response.getStatusLine().getStatusCode();\n if (statusCode != oldStatusCode) {\n for (Project openProject : ProjectManager.getInstance().getOpenProjects()) {\n WindowManager.getInstance().getStatusBar(openProject).updateWidget(CodeShellWidget.ID);\n }\n }\n if (statusCode != 200) {\n return responseText;\n }\n String responseBody = EntityUtils.toString(response.getEntity(), \"UTF-8\");\n responseText = CodeShellUtils.parseHttpResponseContentForCPU(settings, responseBody, PATTERN);\n httpClient.close();\n } catch (IOException e) {\n logger.error(\"getApiResponseForCPU error\", e);\n } finally {\n httpRequestFinFlag = true;\n }\n return codeShellPrompt + responseText;\n }\n\n private String getApiResponseForGPU(CodeShellSettings settings, HttpPost httpPost, String codeShellPrompt) {\n String responseText = \"\";\n httpRequestFinFlag = false;\n try {\n CloseableHttpClient httpClient = HttpClients.createDefault();\n HttpResponse response = httpClient.execute(httpPost);\n int oldStatusCode = statusCode;\n statusCode = response.getStatusLine().getStatusCode();\n if (statusCode != oldStatusCode) {\n for (Project openProject : ProjectManager.getInstance().getOpenProjects()) {\n WindowManager.getInstance().getStatusBar(openProject).updateWidget(CodeShellWidget.ID);\n }\n }\n if (statusCode != 200) {\n return responseText;\n }\n String responseBody = EntityUtils.toString(response.getEntity());\n responseText = CodeShellUtils.parseHttpResponseContentForGPU(settings, responseBody);\n httpClient.close();\n } catch (IOException e) {\n logger.error(\"getApiResponseForGPU error\", e);\n } finally {\n httpRequestFinFlag = true;\n }\n\n return codeShellPrompt + responseText;\n }\n\n public int getStatus() {\n return statusCode;\n }\n\n\n}" }, { "identifier": "CodeShellSettings", "path": "src/main/java/com/codeshell/intellij/settings/CodeShellSettings.java", "snippet": "@State(name = \"CodeShellSettings\", storages = @Storage(\"codeshell_settings.xml\"))\npublic class CodeShellSettings implements PersistentStateComponent<Element> {\n public static final String SETTINGS_TAG = \"CodeShellSettings\";\n private static final String SERVER_ADDRESS_TAG = \"SERVER_ADDRESS_URL\";\n private static final String SAYT_TAG = \"SAYT_ENABLED\";\n private static final String CPU_RADIO_BUTTON_TAG = \"CPU_RADIO_BUTTON_ENABLED\";\n private static final String GPU_RADIO_BUTTON_TAG = \"GPU_RADIO_BUTTON_ENABLED\";\n private static final String TAB_ACTION_TAG = \"TAB_ACTION\";\n private static final String COMPLETION_MAX_TOKENS_TAG = \"COMPLETION_MAX_TOKENS\";\n private static final String CHAT_MAX_TOKENS_TAG = \"CHAT_MAX_TOKENS\";\n private boolean saytEnabled = true;\n private boolean cpuRadioButtonEnabled = true;\n private boolean gpuRadioButtonEnabled = false;\n private String serverAddressURL = \"http://127.0.0.1:8080\";\n private TabActionOption tabActionOption = TabActionOption.ALL;\n private CompletionMaxToken completionMaxToken = CompletionMaxToken.MEDIUM;\n private ChatMaxToken chatMaxToken = ChatMaxToken.MEDIUM;\n\n private static final CodeShellSettings SHELL_CODER_SETTINGS_INSTANCE = new CodeShellSettings();\n\n @Override\n public @Nullable Element getState() {\n Element state = new Element(SETTINGS_TAG);\n state.setAttribute(CPU_RADIO_BUTTON_TAG, Boolean.toString(isCPURadioButtonEnabled()));\n state.setAttribute(GPU_RADIO_BUTTON_TAG, Boolean.toString(isGPURadioButtonEnabled()));\n state.setAttribute(SERVER_ADDRESS_TAG, getServerAddressURL());\n state.setAttribute(SAYT_TAG, Boolean.toString(isSaytEnabled()));\n state.setAttribute(TAB_ACTION_TAG, getTabActionOption().name());\n state.setAttribute(COMPLETION_MAX_TOKENS_TAG, getCompletionMaxToken().name());\n state.setAttribute(CHAT_MAX_TOKENS_TAG, getChatMaxToken().name());\n return state;\n }\n\n @Override\n public void loadState(@NotNull Element state) {\n if (Objects.nonNull(state.getAttributeValue(CPU_RADIO_BUTTON_TAG))) {\n setCPURadioButtonEnabled(Boolean.parseBoolean(state.getAttributeValue(CPU_RADIO_BUTTON_TAG)));\n }\n if (Objects.nonNull(state.getAttributeValue(GPU_RADIO_BUTTON_TAG))) {\n setGPURadioButtonEnabled(Boolean.parseBoolean(state.getAttributeValue(GPU_RADIO_BUTTON_TAG)));\n }\n if (Objects.nonNull(state.getAttributeValue(SERVER_ADDRESS_TAG))) {\n setServerAddressURL(state.getAttributeValue(SERVER_ADDRESS_TAG));\n }\n if (Objects.nonNull(state.getAttributeValue(SAYT_TAG))) {\n setSaytEnabled(Boolean.parseBoolean(state.getAttributeValue(SAYT_TAG)));\n }\n if (Objects.nonNull(state.getAttributeValue(TAB_ACTION_TAG))) {\n setTabActionOption(TabActionOption.valueOf(state.getAttributeValue(TAB_ACTION_TAG)));\n }\n if (Objects.nonNull(state.getAttributeValue(COMPLETION_MAX_TOKENS_TAG))) {\n setCompletionMaxToken(CompletionMaxToken.valueOf(state.getAttributeValue(COMPLETION_MAX_TOKENS_TAG)));\n }\n if (Objects.nonNull(state.getAttributeValue(CHAT_MAX_TOKENS_TAG))) {\n setChatMaxToken(ChatMaxToken.valueOf(state.getAttributeValue(CHAT_MAX_TOKENS_TAG)));\n }\n }\n\n public static CodeShellSettings getInstance() {\n if (Objects.isNull(ApplicationManager.getApplication())) {\n return SHELL_CODER_SETTINGS_INSTANCE;\n }\n\n CodeShellSettings service = ApplicationManager.getApplication().getService(CodeShellSettings.class);\n if (Objects.isNull(service)) {\n return SHELL_CODER_SETTINGS_INSTANCE;\n }\n return service;\n }\n\n public boolean isSaytEnabled() {\n return saytEnabled;\n }\n\n public void setSaytEnabled(boolean saytEnabled) {\n this.saytEnabled = saytEnabled;\n }\n\n public void toggleSaytEnabled() {\n this.saytEnabled = !this.saytEnabled;\n }\n\n public boolean isCPURadioButtonEnabled() {\n return cpuRadioButtonEnabled;\n }\n\n public void setCPURadioButtonEnabled(boolean cpuRadioButtonEnabled) {\n this.cpuRadioButtonEnabled = cpuRadioButtonEnabled;\n }\n\n public boolean isGPURadioButtonEnabled() {\n return gpuRadioButtonEnabled;\n }\n\n public void setGPURadioButtonEnabled(boolean gpuRadioButtonEnabled) {\n this.gpuRadioButtonEnabled = gpuRadioButtonEnabled;\n }\n\n public String getServerAddressURL() {\n return serverAddressURL;\n }\n\n public void setServerAddressURL(String serverAddressURL) {\n this.serverAddressURL = serverAddressURL;\n }\n\n public CompletionMaxToken getCompletionMaxToken() {\n return completionMaxToken;\n }\n\n public void setCompletionMaxToken(CompletionMaxToken completionMaxToken) {\n this.completionMaxToken = completionMaxToken;\n }\n\n public ChatMaxToken getChatMaxToken() {\n return chatMaxToken;\n }\n\n public void setChatMaxToken(ChatMaxToken chatMaxToken) {\n this.chatMaxToken = chatMaxToken;\n }\n\n public TabActionOption getTabActionOption() {\n return tabActionOption;\n }\n\n public void setTabActionOption(TabActionOption tabActionOption) {\n this.tabActionOption = tabActionOption;\n }\n\n}" }, { "identifier": "CodeGenHintRenderer", "path": "src/main/java/com/codeshell/intellij/utils/CodeGenHintRenderer.java", "snippet": "public class CodeGenHintRenderer implements EditorCustomElementRenderer {\n private final String myText;\n private Font myFont;\n\n public CodeGenHintRenderer(String text, Font font) {\n myText = text;\n myFont = font;\n }\n\n public CodeGenHintRenderer(String text) {\n myText = text;\n }\n\n @Override\n public int calcWidthInPixels(@NotNull Inlay inlay) {\n Editor editor = inlay.getEditor();\n Font font = editor.getColorsScheme().getFont(EditorFontType.PLAIN);\n myFont = new Font(font.getName(), Font.ITALIC, font.getSize());\n return editor.getContentComponent().getFontMetrics(font).stringWidth(myText);\n }\n\n @Override\n public void paint(@NotNull Inlay inlay, @NotNull Graphics g, @NotNull Rectangle targetRegion, @NotNull TextAttributes textAttributes) {\n g.setColor(JBColor.GRAY);\n g.setFont(myFont);\n g.drawString(myText, targetRegion.x, targetRegion.y + targetRegion.height - (int) Math.ceil((double) g.getFontMetrics().getFont().getSize() / 2) + 1);\n }\n\n}" }, { "identifier": "CodeShellIcons", "path": "src/main/java/com/codeshell/intellij/utils/CodeShellIcons.java", "snippet": "public interface CodeShellIcons {\n Icon Action = IconLoader.getIcon(\"/icons/actionIcon.svg\", CodeShellIcons.class);\n Icon ActionDark = IconLoader.getIcon(\"/icons/actionIcon_dark.svg\", CodeShellIcons.class);\n Icon WidgetEnabled = IconLoader.getIcon(\"/icons/widgetEnabled.svg\", CodeShellIcons.class);\n Icon WidgetEnabledDark = IconLoader.getIcon(\"/icons/widgetEnabled_dark.svg\", CodeShellIcons.class);\n Icon WidgetDisabled = IconLoader.getIcon(\"/icons/widgetDisabled.svg\", CodeShellIcons.class);\n Icon WidgetDisabledDark = IconLoader.getIcon(\"/icons/widgetDisabled_dark.svg\", CodeShellIcons.class);\n Icon WidgetError = IconLoader.getIcon(\"/icons/widgetError.svg\", CodeShellIcons.class);\n Icon WidgetErrorDark = IconLoader.getIcon(\"/icons/widgetError_dark.svg\", CodeShellIcons.class);\n}" }, { "identifier": "CodeShellUtils", "path": "src/main/java/com/codeshell/intellij/utils/CodeShellUtils.java", "snippet": "public class CodeShellUtils {\n public static String includePreText(String preText, String language, String text) {\n String sufText = \"\\n```\" + language + \"\\n\" + text + \"\\n```\\n\";\n return String.format(preText, language, sufText);\n }\n public static int prefixHandle(int begin, int end) {\n if (end - begin > 3000) {\n return end - 3000;\n } else {\n return begin;\n }\n }\n public static int suffixHandle(int begin, int end) {\n if (end - begin > 256) {\n return begin + 256;\n } else {\n return end;\n }\n }\n\n public static JsonObject pakgHttpRequestBodyForCPU(CodeShellSettings settings, String prefix, String suffix){\n JsonObject httpBody = new JsonObject();\n httpBody.addProperty(\"input_prefix\", prefix);\n httpBody.addProperty(\"input_suffix\", suffix);\n httpBody.addProperty(\"n_predict\", Integer.parseInt(settings.getCompletionMaxToken().getDescription()));\n httpBody.addProperty(\"temperature\", 0.2);\n httpBody.addProperty(\"repetition_penalty\", 1.0);\n httpBody.addProperty(\"top_k\", 10);\n httpBody.addProperty(\"top_p\", 0.95);\n// httpBody.addProperty(\"prompt\", PrefixString.REQUST_END_TAG + codeShellPrompt);\n// httpBody.addProperty(\"frequency_penalty\", 1.2);\n// httpBody.addProperty(\"n_predict\", Integer.parseInt(settings.getCompletionMaxToken().getDescription()));\n// httpBody.addProperty(\"stream\", false);\n// JsonArray stopArray = new JsonArray();\n// stopArray.add(\"|<end>|\");\n// httpBody.add(\"stop\", stopArray);\n return httpBody;\n }\n\n public static JsonObject pakgHttpRequestBodyForGPU(CodeShellSettings settings, String codeShellPrompt){\n JsonObject httpBody = new JsonObject();\n httpBody.addProperty(\"inputs\", codeShellPrompt);\n JsonObject parameters = new JsonObject();\n parameters.addProperty(\"max_new_tokens\", Integer.parseInt(settings.getCompletionMaxToken().getDescription()));\n httpBody.add(\"parameters\", parameters);\n return httpBody;\n }\n\n public static String parseHttpResponseContentForCPU(CodeShellSettings settings, String responseBody, Pattern pattern){\n String generatedText = \"\";\n Matcher matcher = pattern.matcher(responseBody);\n StringBuilder contentBuilder = new StringBuilder();\n while (matcher.find()) {\n String jsonString = matcher.group(1);\n JSONObject json = JSONObject.parseObject(jsonString);\n String content = json.getString(\"content\");\n if(StringUtils.equalsAny(content, \"<|endoftext|>\", \"\")){\n continue;\n }\n contentBuilder.append(content);\n }\n return contentBuilder.toString().replace(PrefixString.RESPONSE_END_TAG, \"\");\n }\n\n public static String parseHttpResponseContentForGPU(CodeShellSettings settings, String responseBody){\n String generatedText = \"\";\n Gson gson = new Gson();\n GenerateModel generateModel = gson.fromJson(responseBody, GenerateModel.class);\n if (StringUtils.isNotBlank(generateModel.getGenerated_text())) {\n generatedText = generateModel.getGenerated_text();\n }\n return generatedText.replace(PrefixString.RESPONSE_END_TAG, \"\");\n }\n\n public static String getIDEVersion(String whichVersion) {\n ApplicationInfo applicationInfo = ApplicationInfo.getInstance();\n String version = \"\";\n try {\n if (whichVersion.equalsIgnoreCase(\"major\")) {\n version = applicationInfo.getMajorVersion();\n } else {\n version = applicationInfo.getFullVersion();\n }\n } catch (Exception e) {\n Logger.getInstance(CodeShellUtils.class).error(\"get IDE full version error\", e);\n }\n return version;\n }\n\n public static void addCodeSuggestion(Editor focusedEditor, VirtualFile file, int suggestionPosition, String[] hintList) {\n WriteCommandAction.runWriteCommandAction(focusedEditor.getProject(), () -> {\n if (suggestionPosition != focusedEditor.getCaretModel().getOffset()) {\n return;\n }\n if (Objects.nonNull(focusedEditor.getSelectionModel().getSelectedText())) {\n return;\n }\n\n file.putUserData(CodeShellWidget.SHELL_CODER_CODE_SUGGESTION, hintList);\n file.putUserData(CodeShellWidget.SHELL_CODER_POSITION, suggestionPosition);\n\n InlayModel inlayModel = focusedEditor.getInlayModel();\n inlayModel.getInlineElementsInRange(0, focusedEditor.getDocument().getTextLength()).forEach(CodeShellUtils::disposeInlayHints);\n inlayModel.getBlockElementsInRange(0, focusedEditor.getDocument().getTextLength()).forEach(CodeShellUtils::disposeInlayHints);\n if (Objects.nonNull(hintList) && hintList.length > 0) {\n if (!hintList[0].trim().isEmpty()) {\n inlayModel.addInlineElement(suggestionPosition, true, new CodeGenHintRenderer(hintList[0]));\n }\n for (int i = 1; i < hintList.length; i++) {\n inlayModel.addBlockElement(suggestionPosition, false, false, 0, new CodeGenHintRenderer(hintList[i]));\n }\n }\n });\n }\n\n public static void disposeInlayHints(Inlay<?> inlay) {\n if (inlay.getRenderer() instanceof CodeGenHintRenderer) {\n inlay.dispose();\n }\n }\n\n}" }, { "identifier": "EditorUtils", "path": "src/main/java/com/codeshell/intellij/utils/EditorUtils.java", "snippet": "public class EditorUtils {\n\n public static JsonObject getFileSelectionDetails(Editor editor, @NotNull PsiFile psiFile, String preText) {\n return getFileSelectionDetails(editor, psiFile, false, preText);\n }\n\n public static boolean isNoneTextSelected(Editor editor) {\n return Objects.isNull(editor) || StringUtils.isEmpty(editor.getCaretModel().getCurrentCaret().getSelectedText());\n }\n\n public static JsonObject getFileSelectionDetails(Editor editor, @NotNull PsiFile psiFile, boolean isCodeNote, String preText) {\n if (Objects.isNull(editor)) {\n return getEmptyRange();\n } else {\n Document document = editor.getDocument();\n int startOffset;\n int endOffset;\n String editorText;\n\n if (editor.getSelectionModel().hasSelection()) {\n startOffset = editor.getSelectionModel().getSelectionStart();\n endOffset = editor.getSelectionModel().getSelectionEnd();\n editorText = editor.getSelectionModel().getSelectedText();\n } else {\n LogicalPosition logicalPos = editor.getCaretModel().getCurrentCaret().getLogicalPosition();\n int line = logicalPos.line;\n startOffset = editor.logicalPositionToOffset(new LogicalPosition(line, 0));\n endOffset = editor.logicalPositionToOffset(new LogicalPosition(line, Integer.MAX_VALUE));\n editorText = lspPosition(document, endOffset).get(\"text\").toString();\n if (isCodeNote) {\n editor.getDocument();\n for (int linenumber = 0; linenumber < editor.getDocument().getLineCount(); ++linenumber) {\n startOffset = editor.logicalPositionToOffset(new LogicalPosition(linenumber, 0));\n endOffset = editor.logicalPositionToOffset(new LogicalPosition(linenumber, Integer.MAX_VALUE));\n String tempText = lspPosition(document, endOffset).get(\"text\").toString();\n if (Objects.nonNull(tempText) && !\"\\\"\\\"\".equals(tempText.trim()) && !tempText.trim().isEmpty()) {\n editorText = tempText;\n break;\n }\n }\n }\n }\n JsonObject range = new JsonObject();\n range.add(\"start\", lspPosition(document, startOffset));\n range.add(\"end\", lspPosition(document, endOffset));\n range.addProperty(\"selectedText\", includePreText(preText, psiFile.getLanguage().getID(), editorText));\n JsonObject sendText = new JsonObject();\n sendText.addProperty(\"inputs\", includePreText(preText, psiFile.getLanguage().getID(), editorText));\n JsonObject parameters = new JsonObject();\n parameters.addProperty(\"max_new_tokens\", CodeShellSettings.getInstance().getChatMaxToken().getDescription());\n sendText.add(\"parameters\", parameters);\n\n JsonObject returnObj = new JsonObject();\n returnObj.add(\"range\", range);\n if(CodeShellSettings.getInstance().isCPURadioButtonEnabled()){\n returnObj.addProperty(\"sendUrl\", CodeShellSettings.getInstance().getServerAddressURL() + CodeShellURI.CPU_CHAT.getUri());\n returnObj.addProperty(\"modelType\", \"CPU\");\n }else{\n returnObj.addProperty(\"sendUrl\", CodeShellSettings.getInstance().getServerAddressURL() + CodeShellURI.GPU_CHAT.getUri());\n returnObj.addProperty(\"modelType\", \"GPU\");\n }\n returnObj.addProperty(\"maxToken\", CodeShellSettings.getInstance().getChatMaxToken().getDescription());\n returnObj.add(\"sendText\", sendText);\n return returnObj;\n }\n }\n\n public static JsonObject lspPosition(Document document, int offset) {\n int line = document.getLineNumber(offset);\n int lineStart = document.getLineStartOffset(line);\n String lineTextBeforeOffset = document.getText(TextRange.create(lineStart, offset));\n int column = lineTextBeforeOffset.length();\n JsonObject jsonObject = new JsonObject();\n jsonObject.addProperty(\"line\", line);\n jsonObject.addProperty(\"column\", column);\n jsonObject.addProperty(\"text\", lineTextBeforeOffset);\n return jsonObject;\n }\n\n public static JsonObject getEmptyRange() {\n JsonObject jsonObject = new JsonObject();\n JsonObject range = new JsonObject();\n JsonObject lineCol = new JsonObject();\n lineCol.addProperty(\"line\", \"0\");\n lineCol.addProperty(\"column\", \"0\");\n lineCol.addProperty(\"text\", \"0\");\n range.add(\"start\", lineCol);\n range.add(\"end\", lineCol);\n jsonObject.add(\"range\", range);\n jsonObject.addProperty(\"selectedText\", \"\");\n return jsonObject;\n }\n\n private static String includePreText(String preText, String language, String text) {\n String sufText = \"\\n```\" + language + \"\\n\" + text + \"\\n```\\n\";\n return String.format(preText, language, sufText);\n }\n\n public static boolean isMainEditor(Editor editor) {\n return editor.getEditorKind() == EditorKind.MAIN_EDITOR || ApplicationManager.getApplication().isUnitTestMode();\n }\n\n}" } ]
import com.codeshell.intellij.enums.CodeShellStatus; import com.codeshell.intellij.services.CodeShellCompleteService; import com.codeshell.intellij.settings.CodeShellSettings; import com.codeshell.intellij.utils.CodeGenHintRenderer; import com.codeshell.intellij.utils.CodeShellIcons; import com.codeshell.intellij.utils.CodeShellUtils; import com.codeshell.intellij.utils.EditorUtils; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.editor.*; import com.intellij.openapi.editor.event.*; import com.intellij.openapi.editor.impl.EditorComponentImpl; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.NlsContexts; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.wm.IdeFocusManager; import com.intellij.openapi.wm.StatusBar; import com.intellij.openapi.wm.StatusBarWidget; import com.intellij.openapi.wm.impl.status.EditorBasedWidget; import com.intellij.util.Consumer; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; import java.awt.event.MouseEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.Arrays; import java.util.Objects; import java.util.concurrent.CompletableFuture;
7,300
if (CodeShellSettings.getInstance().isSaytEnabled()) { toolTipText.append(" (Click to disable)"); } else { toolTipText.append(" (Click to enable)"); } break; case UNKNOWN: toolTipText.append(" (http error "); toolTipText.append(statusCode); toolTipText.append(")"); break; default: toolTipText.append(" ("); toolTipText.append(status.getDisplayValue()); toolTipText.append(")"); } return toolTipText.toString(); } @Override public @Nullable Consumer<MouseEvent> getClickConsumer() { return mouseEvent -> { CodeShellSettings.getInstance().toggleSaytEnabled(); if (Objects.nonNull(myStatusBar)) { myStatusBar.updateWidget(ID); } }; } @Override public void install(@NotNull StatusBar statusBar) { super.install(statusBar); EditorEventMulticaster multicaster = EditorFactory.getInstance().getEventMulticaster(); multicaster.addCaretListener(this, this); multicaster.addSelectionListener(this, this); multicaster.addDocumentListener(this, this); KeyboardFocusManager.getCurrentKeyboardFocusManager().addPropertyChangeListener("focusOwner", this); Disposer.register(this, () -> KeyboardFocusManager.getCurrentKeyboardFocusManager().removePropertyChangeListener("focusOwner", this) ); } private Editor getFocusOwnerEditor() { Component component = getFocusOwnerComponent(); Editor editor = component instanceof EditorComponentImpl ? ((EditorComponentImpl) component).getEditor() : getEditor(); return Objects.nonNull(editor) && !editor.isDisposed() && EditorUtils.isMainEditor(editor) ? editor : null; } private Component getFocusOwnerComponent() { Component focusOwner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner(); if (Objects.isNull(focusOwner)) { IdeFocusManager focusManager = IdeFocusManager.getInstance(getProject()); Window frame = focusManager.getLastFocusedIdeWindow(); if (Objects.nonNull(frame)) { focusOwner = focusManager.getLastFocusedFor(frame); } } return focusOwner; } private boolean isFocusedEditor(Editor editor) { Component focusOwner = getFocusOwnerComponent(); return focusOwner == editor.getContentComponent(); } @Override public void propertyChange(PropertyChangeEvent evt) { updateInlayHints(getFocusOwnerEditor()); } @Override public void selectionChanged(SelectionEvent event) { updateInlayHints(event.getEditor()); } @Override public void caretPositionChanged(@NotNull CaretEvent event) { updateInlayHints(event.getEditor()); } @Override public void caretAdded(@NotNull CaretEvent event) { updateInlayHints(event.getEditor()); } @Override public void caretRemoved(@NotNull CaretEvent event) { updateInlayHints(event.getEditor()); } @Override public void afterDocumentChange(@NotNull Document document) { enableSuggestion = true; if (ApplicationManager.getApplication().isDispatchThread()) { EditorFactory.getInstance().editors(document) .filter(this::isFocusedEditor) .findFirst() .ifPresent(this::updateInlayHints); } } private void updateInlayHints(Editor focusedEditor) { if (Objects.isNull(focusedEditor) || !EditorUtils.isMainEditor(focusedEditor)) { return; } VirtualFile file = FileDocumentManager.getInstance().getFile(focusedEditor.getDocument()); if (Objects.isNull(file)) { return; } String selection = focusedEditor.getCaretModel().getCurrentCaret().getSelectedText(); if (Objects.nonNull(selection) && !selection.isEmpty()) { String[] existingHints = file.getUserData(SHELL_CODER_CODE_SUGGESTION); if (Objects.nonNull(existingHints) && existingHints.length > 0) { file.putUserData(SHELL_CODER_CODE_SUGGESTION, null); file.putUserData(SHELL_CODER_POSITION, focusedEditor.getCaretModel().getOffset()); InlayModel inlayModel = focusedEditor.getInlayModel();
package com.codeshell.intellij.widget; public class CodeShellWidget extends EditorBasedWidget implements StatusBarWidget.Multiframe, StatusBarWidget.IconPresentation, CaretListener, SelectionListener, BulkAwareDocumentListener.Simple, PropertyChangeListener { public static final String ID = "CodeShellWidget"; public static final Key<String[]> SHELL_CODER_CODE_SUGGESTION = new Key<>("CodeShell Code Suggestion"); public static final Key<Integer> SHELL_CODER_POSITION = new Key<>("CodeShell Position"); public static boolean enableSuggestion = false; protected CodeShellWidget(@NotNull Project project) { super(project); } @Override public @NonNls @NotNull String ID() { return ID; } @Override public StatusBarWidget copy() { return new CodeShellWidget(getProject()); } @Override public @Nullable Icon getIcon() { CodeShellCompleteService codeShell = ApplicationManager.getApplication().getService(CodeShellCompleteService.class); CodeShellStatus status = CodeShellStatus.getStatusByCode(codeShell.getStatus()); if (status == CodeShellStatus.OK) { return CodeShellSettings.getInstance().isSaytEnabled() ? CodeShellIcons.WidgetEnabled : CodeShellIcons.WidgetDisabled; } else { return CodeShellIcons.WidgetError; } } @Override public WidgetPresentation getPresentation() { return this; } @Override public @Nullable @NlsContexts.Tooltip String getTooltipText() { StringBuilder toolTipText = new StringBuilder("CodeShell"); if (CodeShellSettings.getInstance().isSaytEnabled()) { toolTipText.append(" enabled"); } else { toolTipText.append(" disabled"); } CodeShellCompleteService codeShell = ApplicationManager.getApplication().getService(CodeShellCompleteService.class); int statusCode = codeShell.getStatus(); CodeShellStatus status = CodeShellStatus.getStatusByCode(statusCode); switch (status) { case OK: if (CodeShellSettings.getInstance().isSaytEnabled()) { toolTipText.append(" (Click to disable)"); } else { toolTipText.append(" (Click to enable)"); } break; case UNKNOWN: toolTipText.append(" (http error "); toolTipText.append(statusCode); toolTipText.append(")"); break; default: toolTipText.append(" ("); toolTipText.append(status.getDisplayValue()); toolTipText.append(")"); } return toolTipText.toString(); } @Override public @Nullable Consumer<MouseEvent> getClickConsumer() { return mouseEvent -> { CodeShellSettings.getInstance().toggleSaytEnabled(); if (Objects.nonNull(myStatusBar)) { myStatusBar.updateWidget(ID); } }; } @Override public void install(@NotNull StatusBar statusBar) { super.install(statusBar); EditorEventMulticaster multicaster = EditorFactory.getInstance().getEventMulticaster(); multicaster.addCaretListener(this, this); multicaster.addSelectionListener(this, this); multicaster.addDocumentListener(this, this); KeyboardFocusManager.getCurrentKeyboardFocusManager().addPropertyChangeListener("focusOwner", this); Disposer.register(this, () -> KeyboardFocusManager.getCurrentKeyboardFocusManager().removePropertyChangeListener("focusOwner", this) ); } private Editor getFocusOwnerEditor() { Component component = getFocusOwnerComponent(); Editor editor = component instanceof EditorComponentImpl ? ((EditorComponentImpl) component).getEditor() : getEditor(); return Objects.nonNull(editor) && !editor.isDisposed() && EditorUtils.isMainEditor(editor) ? editor : null; } private Component getFocusOwnerComponent() { Component focusOwner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner(); if (Objects.isNull(focusOwner)) { IdeFocusManager focusManager = IdeFocusManager.getInstance(getProject()); Window frame = focusManager.getLastFocusedIdeWindow(); if (Objects.nonNull(frame)) { focusOwner = focusManager.getLastFocusedFor(frame); } } return focusOwner; } private boolean isFocusedEditor(Editor editor) { Component focusOwner = getFocusOwnerComponent(); return focusOwner == editor.getContentComponent(); } @Override public void propertyChange(PropertyChangeEvent evt) { updateInlayHints(getFocusOwnerEditor()); } @Override public void selectionChanged(SelectionEvent event) { updateInlayHints(event.getEditor()); } @Override public void caretPositionChanged(@NotNull CaretEvent event) { updateInlayHints(event.getEditor()); } @Override public void caretAdded(@NotNull CaretEvent event) { updateInlayHints(event.getEditor()); } @Override public void caretRemoved(@NotNull CaretEvent event) { updateInlayHints(event.getEditor()); } @Override public void afterDocumentChange(@NotNull Document document) { enableSuggestion = true; if (ApplicationManager.getApplication().isDispatchThread()) { EditorFactory.getInstance().editors(document) .filter(this::isFocusedEditor) .findFirst() .ifPresent(this::updateInlayHints); } } private void updateInlayHints(Editor focusedEditor) { if (Objects.isNull(focusedEditor) || !EditorUtils.isMainEditor(focusedEditor)) { return; } VirtualFile file = FileDocumentManager.getInstance().getFile(focusedEditor.getDocument()); if (Objects.isNull(file)) { return; } String selection = focusedEditor.getCaretModel().getCurrentCaret().getSelectedText(); if (Objects.nonNull(selection) && !selection.isEmpty()) { String[] existingHints = file.getUserData(SHELL_CODER_CODE_SUGGESTION); if (Objects.nonNull(existingHints) && existingHints.length > 0) { file.putUserData(SHELL_CODER_CODE_SUGGESTION, null); file.putUserData(SHELL_CODER_POSITION, focusedEditor.getCaretModel().getOffset()); InlayModel inlayModel = focusedEditor.getInlayModel();
inlayModel.getInlineElementsInRange(0, focusedEditor.getDocument().getTextLength()).forEach(CodeShellUtils::disposeInlayHints);
5
2023-10-18 06:29:13+00:00
12k
zhaoeryu/eu-backend
eu-admin/src/main/java/cn/eu/system/service/impl/SysDictDetailServiceImpl.java
[ { "identifier": "EuServiceImpl", "path": "eu-common-core/src/main/java/cn/eu/common/base/service/impl/EuServiceImpl.java", "snippet": "public abstract class EuServiceImpl<M extends BaseMapper<T>, T> extends ServiceImpl<M, T> implements IEuService<T> {\n\n /**\n * 分页参数从1开始\n */\n protected void getPage(Pageable pageable) {\n getPage(pageable, true);\n }\n\n /**\n * 分页参数从1开始\n */\n protected void getPage(Pageable pageable, boolean isOrder) {\n if (isOrder) {\n String order = null;\n if (pageable.getSort() != null) {\n order = pageable.getSort().toString();\n order = order.replace(\":\", \" \");\n if (\"UNSORTED\".equals(order)) {\n PageHelper.startPage(pageable.getPageNumber(), pageable.getPageSize());\n return;\n }\n }\n PageHelper.startPage(pageable.getPageNumber(), pageable.getPageSize(), order);\n } else {\n PageHelper.startPage(pageable.getPageNumber(), pageable.getPageSize());\n }\n }\n}" }, { "identifier": "SysDictDetailStatus", "path": "eu-common-core/src/main/java/cn/eu/common/enums/SysDictDetailStatus.java", "snippet": "@Getter\n@AllArgsConstructor\npublic enum SysDictDetailStatus {\n\n /**\n * 正常\n */\n NORMAL(0, \"正常\"),\n\n /**\n * 禁用\n */\n DISABLE(1, \"禁用\");\n\n private final int value;\n private final String desc;\n\n public static SysDictDetailStatus valueOf(Integer value) {\n if (value == null) {\n return null;\n }\n for (SysDictDetailStatus status : SysDictDetailStatus.values()) {\n if (status.value == value) {\n return status;\n }\n }\n return null;\n }\n\n public static String parseValue(Integer value) {\n if (value == null) {\n return null;\n }\n for (SysDictDetailStatus status : SysDictDetailStatus.values()) {\n if (status.getValue() == value) {\n return status.getDesc();\n }\n }\n return null;\n }\n\n public static Integer valueOfDesc(String desc) {\n if (desc == null) {\n return null;\n }\n for (SysDictDetailStatus status : SysDictDetailStatus.values()) {\n if (status.desc.equals(desc)) {\n return status.getValue();\n }\n }\n return null;\n }\n\n /**\n * 是否正常\n */\n public static boolean isNormal(Integer value) {\n if (value == null) {\n return false;\n }\n return NORMAL.getValue() == value;\n }\n\n}" }, { "identifier": "SysDictStatus", "path": "eu-common-core/src/main/java/cn/eu/common/enums/SysDictStatus.java", "snippet": "@Getter\n@AllArgsConstructor\npublic enum SysDictStatus {\n\n /**\n * 正常\n */\n NORMAL(0, \"正常\"),\n\n /**\n * 禁用\n */\n DISABLE(1, \"禁用\");\n\n private final int value;\n private final String desc;\n\n public static SysDictStatus valueOf(Integer value) {\n if (value == null) {\n return null;\n }\n for (SysDictStatus status : SysDictStatus.values()) {\n if (status.value == value) {\n return status;\n }\n }\n return null;\n }\n\n public static String parseValue(Integer value) {\n if (value == null) {\n return null;\n }\n for (SysDictStatus status : SysDictStatus.values()) {\n if (status.getValue() == value) {\n return status.getDesc();\n }\n }\n return null;\n }\n\n public static Integer valueOfDesc(String desc) {\n if (desc == null) {\n return null;\n }\n for (SysDictStatus status : SysDictStatus.values()) {\n if (status.desc.equals(desc)) {\n return status.getValue();\n }\n }\n return null;\n }\n\n /**\n * 是否正常\n */\n public static boolean isNormal(Integer value) {\n if (value == null) {\n return false;\n }\n return NORMAL.getValue() == value;\n }\n\n}" }, { "identifier": "PageResult", "path": "eu-common-core/src/main/java/cn/eu/common/model/PageResult.java", "snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\npublic class PageResult<T> {\n\n private List<T> records;\n private Long total;\n\n public static <T> PageResult<T> of(List<T> records, Long total) {\n return new PageResult<>(records, total);\n }\n\n public static <T> PageResult<T> of(List<T> records) {\n PageInfo<T> pageInfo = new PageInfo<>(records);\n return of(pageInfo.getList(), pageInfo.getTotal());\n }\n\n}" }, { "identifier": "EasyExcelHelper", "path": "eu-common-core/src/main/java/cn/eu/common/utils/EasyExcelHelper.java", "snippet": "@Slf4j\npublic class EasyExcelHelper {\n\n /**\n * 导出Excel\n * <code>\n * 例子:EasyExcelHelper.export(response, list, SysUser.class);\n * </code>\n * @param response HttpServletResponse\n * @param dataList 要导出的数据\n * @param clazz 要导出数据的实体类\n * @throws IOException io异常\n */\n public static <T> void export(HttpServletResponse response, List<T> dataList, Class<T> clazz) throws IOException {\n export(response, dataList, clazz, null);\n }\n public static <T> void export(HttpServletResponse response, List<T> dataList, Class<T> clazz, List<String> excludeColumnFieldNames) throws IOException {\n // 构建sheet\n ExcelWriterSheetBuilder builder = EasyExcel.writerSheet(\"Sheet1\")\n .head(clazz);\n\n if (CollUtil.isNotEmpty(excludeColumnFieldNames)) {\n builder.excludeColumnFieldNames(excludeColumnFieldNames);\n }\n\n WriteSheet writeSheet = builder.build();\n\n // 填写数据并写入到response\n EasyExcelWriteSheet sheet = EasyExcelWriteSheet.of(writeSheet, dataList)\n .registerStandardWriteHandler();\n export(response, sheet);\n }\n\n /**\n * 导出Excel\n * <code>\n * EasyExcelHelper.export(response, list, Arrays.asList(\n * EasyExcelCellItem.of(\"ID\" , SysUser::getId),\n * EasyExcelCellItem.of(\"登录名\" , SysUser::getUsername),\n * EasyExcelCellItem.of(\"用户昵称\" , SysUser::getNickname),\n * EasyExcelCellItem.of(\"最后一次活跃时间\" , SysUser::getLastActiveTime)\n * ));\n * </code>\n *\n * @param response HttpServletResponse\n * @param dataList 要导出的数据\n * @param easyExcelCellItems 导出的数据配置\n * @throws IOException io异常\n */\n public static <T> void export(HttpServletResponse response, List<T> dataList, List<EasyExcelCellItem<T>> easyExcelCellItems) throws IOException {\n // 构建Excel头部和内容\n EasyExcelHeadContent headContent = EasyExcelUtil.buildHeadContent(dataList, easyExcelCellItems);\n\n // 构建sheet\n WriteSheet writeSheet = EasyExcel.writerSheet(\"Sheet1\")\n .head(headContent.getHeadList())\n .build();\n\n // 填写数据并写入到response\n EasyExcelWriteSheet sheet = EasyExcelWriteSheet.of(writeSheet, headContent.getContentList())\n .registerStandardWriteHandler();\n export(response, sheet);\n }\n\n public static void export(HttpServletResponse response, EasyExcelWriteSheet... sheetItems) throws IOException {\n Assert.notEmpty(sheetItems, \"最少要写入一个sheet\");\n try {\n ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream())\n .autoCloseStream(false)\n .build();\n\n for (EasyExcelWriteSheet sheetItem : sheetItems) {\n // 数据写入sheet\n excelWriter.write(sheetItem.getDataList(), sheetItem.getWriteSheet());\n }\n\n excelWriter.finish();\n } catch (IOException e) {\n // 重置response\n response.reset();\n response.setContentType(\"application/json\");\n response.setCharacterEncoding(\"utf-8\");\n response.getWriter().write(ResultBody.failed()\n .msg(\"下载文件失败\")\n .toJsonString());\n }\n }\n\n public static <T> void importData(MultipartFile file, Class<T> clazz, Consumer<List<T>> saveConsumer) throws IOException {\n importData(file, clazz, saveConsumer, true);\n }\n\n public static <T> void importData(MultipartFile file, Class<T> clazz, Consumer<List<T>> saveConsumer, boolean isPrintLog) throws IOException {\n importData(file, clazz, saveConsumer, isPrintLog, 100);\n }\n\n /**\n * 导出数据\n * @param file MultipartFile\n * @param clazz 实体类类型\n * @param saveConsumer 保存数据的回掉\n * @param isPrintLog 是否打印日志\n * @param batchCount 每隔(batchCount)条存储数据库,然后清理list ,方便内存回收\n * @throws IOException io异常\n */\n public static <T> void importData(MultipartFile file, Class<T> clazz, Consumer<List<T>> saveConsumer, boolean isPrintLog, int batchCount) throws IOException {\n EasyExcel.read(file.getInputStream(), clazz, new ReadListener<T>() {\n /**\n * 缓存的数据\n */\n private List<T> cachedDataList = ListUtils.newArrayListWithExpectedSize(batchCount);\n\n @Override\n public void invoke(T entity, AnalysisContext analysisContext) {\n if (isPrintLog) {\n log.debug(\"解析到一条数据:{}\", JSONObject.toJSONString(entity));\n }\n cachedDataList.add(entity);\n // 达到BATCH_COUNT了,需要去存储一次数据库,防止数据几万条数据在内存,容易OOM\n if (cachedDataList.size() >= batchCount) {\n saveData();\n // 存储完成清理 list\n cachedDataList = ListUtils.newArrayListWithExpectedSize(batchCount);\n }\n }\n\n @Override\n public void doAfterAllAnalysed(AnalysisContext analysisContext) {\n // 这里也要保存数据,确保最后遗留的数据也存储到数据库\n saveData();\n if (isPrintLog) {\n log.info(\"所有数据解析完成!\");\n }\n }\n\n private void saveData() {\n if (CollUtil.isEmpty(this.cachedDataList)) {\n return;\n }\n saveConsumer.accept(this.cachedDataList);\n }\n }).sheet().doRead();\n }\n\n}" }, { "identifier": "MpQueryHelper", "path": "eu-common-core/src/main/java/cn/eu/common/utils/MpQueryHelper.java", "snippet": "@Slf4j\npublic class MpQueryHelper {\n\n /**\n * 不校验值为空的查询类型\n */\n private static final List<Query.Type> NOT_NONNULL_QUERY_TYPE = Arrays.asList(\n Query.Type.IS_NULL,\n Query.Type.IS_NOT_NULL\n );\n\n /**\n * 根据查询条件的Object对象构建MybatisPlus的QueryWrapper\n * @param criteria 查询条件对象\n * @param entity 要查询的实体类Class\n * @return LambdaQueryWrapper<Entity>\n */\n public static <T> QueryWrapper<T> buildQueryWrapper(Object criteria, Class<T> entity) {\n return buildQueryWrapper(criteria, entity, null);\n }\n /**\n * 根据查询条件的Object对象构建MybatisPlus的QueryWrapper\n * @param criteria 查询条件对象\n * @param entity 要查询的实体类Class\n * @param tableAlias 表别名\n * @return LambdaQueryWrapper<Entity>\n */\n public static <T> QueryWrapper<T> buildQueryWrapper(Object criteria, Class<T> entity, String tableAlias) {\n QueryWrapper<T> queryWrapper = new QueryWrapper<>();\n if (criteria == null) {\n return queryWrapper;\n }\n\n try {\n // 获取criteria(包括父类)的所有字段\n List<Field> fields = getAllFields(criteria);\n\n // 遍历所有的字段,并根据@Query注解填充QueryWrapper查询条件\n for (Field field : fields) {\n boolean accessible = field.isAccessible();\n // 设置可访问\n field.setAccessible(true);\n Query annotation = field.getAnnotation(Query.class);\n if (annotation != null) {\n Object value = field.get(criteria);\n Query.Type queryType = annotation.type();\n\n // 判断值是否为空\n boolean isNonNull = value != null && !(value instanceof String && StrUtil.isBlank((String) value));\n\n // 判断查询类型是否不需要校验空值\n boolean isNotNonNull = NOT_NONNULL_QUERY_TYPE.contains(queryType);\n\n if (isNotNonNull || isNonNull) {\n String fieldName = field.getName();\n\n // 设置查询条件\n fillQueryWrapper(queryWrapper, queryType, value, fieldName, tableAlias);\n }\n }\n // 恢复可访问设置\n field.setAccessible(accessible);\n }\n } catch (Exception e) {\n log.error(e.getMessage(), e);\n }\n\n return queryWrapper;\n }\n\n /**\n * 根据查询条件的Object对象构建MybatisPlus的QueryWrapper,并在最后附件上逻辑删除的查询条件\n * @param criteria 查询条件对象\n * @param entity 要查询的实体类Class\n * @param tableAlias 表别名\n * @return LambdaQueryWrapper<Entity>\n */\n public static <T> QueryWrapper<T> buildQueryWrapperWithDelFlag(Object criteria, Class<T> entity, String tableAlias) {\n QueryWrapper<T> queryWrapper = buildQueryWrapper(criteria, entity, tableAlias);\n // 如果在Mapper里使用${ew.customSqlSegment}这样方式拼接查询条件,@TableLogic不会生效所以需要手动添加\n queryWrapper.eq(wrapperAliasField(tableAlias, StrUtil.toUnderlineCase(Constants.DEL_FLAG_FIELD_NAME)), Constants.DEL_FLAG_NORMAL);\n return queryWrapper;\n }\n\n /**\n * 根据字段上Query.Type的类型,为QueryWrapper设置查询条件\n * @param queryWrapper QueryWrapper\n * @param queryType Query.Type\n * @param value 查询值\n * @param attributeName 查询字段名\n * @param tableAlias 表别名\n * @param <T> 实体类\n */\n private static <T> void fillQueryWrapper(QueryWrapper<T> queryWrapper, Query.Type queryType, Object value, String attributeName, String tableAlias) {\n String fieldName = StrUtil.toUnderlineCase(attributeName);\n fieldName = wrapperAliasField(tableAlias, fieldName);\n switch (queryType) {\n case EQ:\n queryWrapper.eq(fieldName, value);\n break;\n case GT:\n queryWrapper.gt(fieldName, value);\n break;\n case GE:\n queryWrapper.ge(fieldName, value);\n break;\n case LT:\n queryWrapper.lt(fieldName, value);\n break;\n case LE:\n queryWrapper.le(fieldName, value);\n break;\n case NE:\n queryWrapper.ne(fieldName, value);\n break;\n case LIKE:\n queryWrapper.like(fieldName, value);\n break;\n case LEFT_LIKE:\n queryWrapper.likeLeft(fieldName, value);\n break;\n case RIGHT_LIKE:\n queryWrapper.likeRight(fieldName, value);\n break;\n case IN:\n if (value instanceof Collection) {\n queryWrapper.in(fieldName, (Collection<?>) value);\n } else {\n queryWrapper.in(fieldName, value);\n }\n break;\n case NOT_IN:\n if (value instanceof Collection) {\n queryWrapper.notIn(fieldName, (Collection<?>) value);\n } else {\n queryWrapper.notIn(fieldName, value);\n }\n break;\n case IS_NULL:\n queryWrapper.isNull(fieldName);\n break;\n case IS_NOT_NULL:\n queryWrapper.isNotNull(fieldName);\n break;\n case BETWEEN:\n if (value instanceof Collection) {\n // 取出第一个和第二个值,如果不是两个值,就不处理,如果是两个值,并且不为空,就处理\n Object[] values = ((Collection<?>) value).toArray();\n if (ArrayUtil.isNotEmpty(values)) {\n if (values.length == 2 && values[0] != null && values[1] != null) {\n queryWrapper.between(fieldName, values[0], values[1]);\n } else {\n log.warn(\"BETWEEN条件需要两个值,当前值为:{}\", value);\n }\n }\n }\n break;\n default:\n // nothing\n log.warn(\"未支持的查询类型:{}\", queryType.name());\n break;\n }\n }\n\n private static String wrapperAliasField(String tableAlias, String fieldName) {\n if (StrUtil.isNotBlank(tableAlias)) {\n return tableAlias + \".\" + fieldName;\n }\n return fieldName;\n }\n\n /**\n * 获取对象的所有字段,包括父类的字段\n * @param entity 要获取字段的对象\n * @return List<Field> 该对象的所有字段\n */\n private static List<Field> getAllFields(Object entity) {\n List<Field> fields = new ArrayList<>();\n Class<?> clazz = entity.getClass();\n while (clazz != null) {\n fields.addAll(Arrays.asList(clazz.getDeclaredFields()));\n clazz = clazz.getSuperclass();\n }\n return fields;\n }\n\n}" }, { "identifier": "ValidateUtil", "path": "eu-common-core/src/main/java/cn/eu/common/utils/ValidateUtil.java", "snippet": "public class ValidateUtil {\n public static <T> void valid(T t){\n Validator validatorFactory = Validation.buildDefaultValidatorFactory().getValidator();\n Set<ConstraintViolation<T>> errors = validatorFactory.validate(t);\n if (!errors.isEmpty()){\n List<String> errorMessage = errors.stream().map(ConstraintViolation::getMessage).collect(Collectors.toList());\n throw new RuntimeException(String.join(\",\", errorMessage));\n }\n }\n}" }, { "identifier": "EasyExcelCellItem", "path": "eu-common-core/src/main/java/cn/eu/common/utils/easyexcel/EasyExcelCellItem.java", "snippet": "@Data\n@AllArgsConstructor\npublic class EasyExcelCellItem<T> {\n private String columnName;\n private Function<T, ?> cellValueFunc;\n\n public static <T> EasyExcelCellItem<T> of(String columnName, Function<T, ?> cellValueFunc) {\n return new EasyExcelCellItem<>(columnName, cellValueFunc);\n }\n\n}" }, { "identifier": "EasyExcelUtil", "path": "eu-common-core/src/main/java/cn/eu/common/utils/easyexcel/EasyExcelUtil.java", "snippet": "public class EasyExcelUtil {\n\n /**\n * 构建Excel头部和内容\n */\n public static <T> EasyExcelHeadContent buildHeadContent(List<T> dataList, List<EasyExcelCellItem<T>> easyExcelCellItems) {\n // 获取头部\n List<List<String>> headList = easyExcelCellItems.stream().map(item -> {\n List<String> head = ListUtils.newArrayList();\n head.add(item.getColumnName());\n return head;\n }).collect(Collectors.toList());\n\n // 获取内容\n List<List<Object>> rows = Optional.ofNullable(dataList).orElse(new ArrayList<>()).stream().map(item -> {\n List<Object> data = new ArrayList<>();\n for (EasyExcelCellItem<T> cellItem : easyExcelCellItems) {\n Object cellValue = cellItem.getCellValueFunc().apply(item);\n data.add(cellValue);\n }\n return data;\n }).collect(Collectors.toList());\n\n return new EasyExcelHeadContent(headList, rows);\n }\n\n public static void registerStandardWriteHandler(WriteSheet writeSheet) {\n writeSheet.getCustomWriteHandlerList().add(headCellStyleStrategy());\n writeSheet.getCustomWriteHandlerList().add(autoColumnWidthCellStyleStrategy());\n }\n\n public static CellWriteHandler autoColumnWidthCellStyleStrategy() {\n return new AutoColumnWidthCellStyleStrategy();\n }\n\n public static AbstractCellStyleStrategy headCellStyleStrategy() {\n // 头的策略\n WriteCellStyle headWriteCellStyle = new WriteCellStyle();\n // 背景设置为灰色\n headWriteCellStyle.setFillForegroundColor(IndexedColors.GREY_50_PERCENT.getIndex());\n WriteFont headWriteFont = new WriteFont();\n headWriteFont.setFontHeightInPoints((short)10);\n headWriteFont.setColor(IndexedColors.WHITE.getIndex());\n headWriteCellStyle.setWriteFont(headWriteFont);\n // 忽略边框\n headWriteCellStyle.setBorderBottom(BorderStyle.NONE);\n headWriteCellStyle.setBorderTop(BorderStyle.NONE);\n headWriteCellStyle.setBorderLeft(BorderStyle.NONE);\n headWriteCellStyle.setBorderRight(BorderStyle.NONE);\n\n // 内容的策略\n WriteCellStyle contentWriteCellStyle = new WriteCellStyle();\n WriteFont contentWriteFont = new WriteFont();\n contentWriteFont.setFontHeightInPoints((short)10);\n contentWriteCellStyle.setWriteFont(contentWriteFont);\n // 这个策略是 头是头的样式 内容是内容的样式 其他的策略可以自己实现\n return new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);\n }\n\n}" }, { "identifier": "EasyExcelWriteSheet", "path": "eu-common-core/src/main/java/cn/eu/common/utils/easyexcel/EasyExcelWriteSheet.java", "snippet": "@Data\n@NoArgsConstructor\n@AllArgsConstructor\npublic class EasyExcelWriteSheet {\n\n private WriteSheet writeSheet;\n private Collection<?> dataList;\n\n public static EasyExcelWriteSheet of(WriteSheet writeSheet, Collection<?> dataList) {\n return new EasyExcelWriteSheet(writeSheet, dataList);\n }\n\n public EasyExcelWriteSheet registerStandardWriteHandler() {\n EasyExcelUtil.registerStandardWriteHandler(writeSheet);\n return this;\n }\n\n public static <T> EasyExcelWriteSheet of(WriteSheet writeSheet, List<T> dataList, List<EasyExcelCellItem<T>> cellItems) {\n EasyExcelHeadContent easyExcelHeadContent = EasyExcelUtil.buildHeadContent(dataList, cellItems);\n writeSheet.setHead(easyExcelHeadContent.getHeadList());\n return new EasyExcelWriteSheet(writeSheet, easyExcelHeadContent.getContentList());\n }\n\n}" }, { "identifier": "SysDept", "path": "eu-admin/src/main/java/cn/eu/system/domain/SysDept.java", "snippet": "@Data\n@EqualsAndHashCode(callSuper = true)\n@TableName(\"sys_dept\")\npublic class SysDept extends BaseEntity {\n private static final long serialVersionUID = 1L;\n\n @ExcelProperty(\"部门ID\")\n @TableId(type = IdType.AUTO)\n private Integer id;\n /**\n * 部门名称\n */\n @ExcelProperty(\"部门名称\")\n @NotBlank(message = \"部门名称不能为空\")\n private String deptName;\n /**\n * 状态\n * @see DeptStatus#getValue()\n */\n private Integer status;\n /**\n * 显示顺序\n */\n private Integer sortNum;\n /**\n * 父部门id\n */\n private Integer parentId;\n /**\n * 祖级列表\n */\n private String parentIds;\n}" }, { "identifier": "SysDict", "path": "eu-admin/src/main/java/cn/eu/system/domain/SysDict.java", "snippet": "@Data\n@EqualsAndHashCode(callSuper = true)\n@TableName(\"sys_dict\")\npublic class SysDict extends BaseEntity {\n private static final long serialVersionUID = 1L;\n\n @ExcelProperty(\"字典Id\")\n @TableId(type = IdType.AUTO)\n private Integer id;\n /** 字典Key */\n @ExcelProperty(\"字典Key\")\n @NotBlank(message = \"字典Key不能为空\")\n private String dictKey;\n /**\n * 状态\n * @see SysDictStatus#getValue()\n */\n @ExcelProperty(value = \"状态\", converter = SysDictStatusConverter.class)\n private Integer status;\n\n}" }, { "identifier": "SysDictDetail", "path": "eu-admin/src/main/java/cn/eu/system/domain/SysDictDetail.java", "snippet": "@Data\n@EqualsAndHashCode(callSuper = true)\n@TableName(\"sys_dict_detail\")\npublic class SysDictDetail extends BaseEntity {\n private static final long serialVersionUID = 1L;\n\n @ExcelIgnore\n @TableId(type = IdType.AUTO)\n private Integer id;\n /** 字典ID */\n @NotNull(message = \"字典ID不能为空\")\n @ExcelProperty(\"字典ID\")\n private Integer pid;\n /** 字典Key */\n @ExcelProperty(\"字典Key\")\n @NotBlank(message = \"字典Key不能为空\")\n private String dictKey;\n /** 字典标签 */\n @ExcelProperty(\"字典详情标签\")\n @NotBlank(message = \"字典详情标签不能为空\")\n private String dictLabel;\n /** 字典值 */\n @ExcelProperty(\"字典详情值\")\n @NotBlank(message = \"字典详情值不能为空\")\n private String dictValue;\n /**\n * 状态\n * @see SysDictDetailStatus#getValue()\n */\n @ExcelProperty(value = \"状态\", converter = SysDictDetailStatusConverter.class)\n private Integer status;\n /** 排序 */\n @ExcelProperty(\"排序\")\n private Integer sortNum;\n\n}" }, { "identifier": "SysUser", "path": "eu-admin/src/main/java/cn/eu/system/domain/SysUser.java", "snippet": "@Data\n@EqualsAndHashCode(callSuper = true)\n@TableName(\"sys_user\")\npublic class SysUser extends BaseEntity {\n\n private static final long serialVersionUID = 1L;\n\n @ExcelIgnore\n @ExcelProperty(\"ID\")\n @TableId\n private String id;\n /** 登录名 */\n @Xss(message = \"登录名不能包含脚本字符\")\n @ExcelProperty(\"登录名\")\n @NotBlank(message = \"登录名不能为空\")\n private String username;\n /** 用户昵称 */\n @Xss(message = \"用户昵称不能包含脚本字符\")\n @ExcelProperty(\"用户昵称\")\n @NotBlank(message = \"用户昵称不能为空\")\n private String nickname;\n /** 用户头像 */\n @ExcelProperty(value = \"头像\", converter = StringUrlImageConverter.class)\n private String avatar;\n /** 手机号 */\n @ExcelProperty(\"手机号\")\n private String mobile;\n /** 邮箱 */\n @ExcelProperty(\"邮箱\")\n @TableField(updateStrategy = FieldStrategy.IGNORED)\n private String email;\n /** 密码 */\n @ExcelIgnore\n @JsonIgnore // 密码不返回给前端\n private String password;\n /** 性别 */\n @ExcelProperty(value = \"性别\", converter = SysUserSexConverter.class)\n private Integer sex;\n /** 是否管理员 */\n @ExcelProperty(value = \"是否管理员\", converter = SysUserAdminConverter.class)\n private Integer admin;\n /** 部门ID */\n @ExcelProperty(value = \"部门\", converter = SysDeptConverter.class)\n @TableField(updateStrategy = FieldStrategy.IGNORED)\n private Integer deptId;\n /** 账号状态 */\n @ExcelProperty(value = \"账号状态\", converter = SysUserStatusConverter.class)\n private Integer status;\n /** 登录IP */\n @ExcelProperty(\"登录IP\")\n private String loginIp;\n /** 登录时间 */\n @ExcelProperty(\"登录时间\")\n @DateTimeFormat(pattern = \"yyyy-MM-dd HH:mm:ss\")\n @JsonFormat(pattern = \"yyyy-MM-dd HH:mm:ss\")\n private LocalDateTime loginTime;\n /** 最后一次活跃时间 */\n @ExcelProperty(\"最后一次活跃时间\")\n @DateTimeFormat(pattern = \"yyyy-MM-dd HH:mm:ss\")\n @JsonFormat(pattern = \"yyyy-MM-dd HH:mm:ss\")\n private LocalDateTime lastActiveTime;\n /** 密码重置时间 */\n @ExcelProperty(\"密码重置时间\")\n private LocalDateTime passwordResetTime;\n\n}" }, { "identifier": "SysDictDetailMapper", "path": "eu-admin/src/main/java/cn/eu/system/mapper/SysDictDetailMapper.java", "snippet": "@Mapper\npublic interface SysDictDetailMapper extends EuBaseMapper<SysDictDetail> {\n}" }, { "identifier": "ImportResult", "path": "eu-admin/src/main/java/cn/eu/system/model/dto/ImportResult.java", "snippet": "@Data\npublic class ImportResult {\n\n /**\n * 更新数据量\n */\n private Integer updateCount;\n\n /**\n * 新增数据量\n */\n private Integer addCount;\n\n}" }, { "identifier": "SysDictDetailQueryCriteria", "path": "eu-admin/src/main/java/cn/eu/system/model/query/SysDictDetailQueryCriteria.java", "snippet": "@Data\npublic class SysDictDetailQueryCriteria {\n\n @Query\n private Integer pid;\n\n @Query(type = Query.Type.LIKE)\n private String dictKey;\n\n}" }, { "identifier": "ISysDictDetailService", "path": "eu-admin/src/main/java/cn/eu/system/service/ISysDictDetailService.java", "snippet": "public interface ISysDictDetailService extends IEuService<SysDictDetail> {\n\n PageResult<SysDictDetail> page(SysDictDetailQueryCriteria criteria, Pageable pageable);\n\n List<SysDictDetail> list(SysDictDetailQueryCriteria criteria);\n\n void exportTemplate(HttpServletResponse response) throws IOException;\n\n ImportResult importData(MultipartFile file, Integer importMode, Integer dictId) throws IOException;\n}" }, { "identifier": "ISysDictService", "path": "eu-admin/src/main/java/cn/eu/system/service/ISysDictService.java", "snippet": "public interface ISysDictService extends IEuService<SysDict> {\n\n PageResult<SysDict> page(SysDictQueryCriteria criteria, Pageable pageable);\n\n List<SysDict> list(SysDictQueryCriteria criteria);\n\n void updateDict(SysDict entity);\n\n void exportTemplate(HttpServletResponse response) throws IOException;\n\n ImportResult importData(MultipartFile file, Integer importMode) throws IOException;\n\n void removeDictByIds(List<Integer> ids);\n}" }, { "identifier": "ImportModeHandleTemplate", "path": "eu-admin/src/main/java/cn/eu/system/utils/ImportModeHandleTemplate.java", "snippet": "@Slf4j\npublic abstract class ImportModeHandleTemplate<T, K> {\n\n private final AtomicInteger addCount = new AtomicInteger(0);\n private final AtomicInteger updateCount = new AtomicInteger(0);\n private final Integer importMode;\n private final Function<T, K> primaryKey;\n\n public ImportModeHandleTemplate(Integer importMode, Function<T, K> primaryKey) {\n this.importMode = importMode;\n this.primaryKey = primaryKey;\n }\n\n /**\n * 处理excel数据\n * @param list excel数据\n */\n public final void handle(List<T> list) {\n // 校验数据\n valid(list);\n\n // 根据导入模式处理数据\n if (ImportMode.ONLY_ADD.getCode().equals(importMode)) {\n // 仅新增\n add(list);\n addCount.addAndGet(list.size());\n return;\n }\n\n // 把excel解析的数据转换成map\n ListIterator<T> iterator = list.listIterator(list.size());\n Map<K, T> excelMap = new HashMap<>();\n while (iterator.hasPrevious()) {\n T previous = iterator.previous();\n excelMap.put(primaryKey.apply(previous), previous);\n }\n // 从数据库查询已存在的数据\n List<T> dbList = getDbList(list);\n\n if (ImportMode.ONLY_UPDATE.getCode().equals(importMode)) {\n // 仅更新\n if (CollUtil.isEmpty(dbList)) {\n log.info(\"数据库没有匹配的数据,不进行处理\");\n return;\n }\n\n // 设置更新的数据\n updateHandle(dbList, excelMap);\n return;\n } else if (ImportMode.ADD_AND_UPDATE.getCode().equals(importMode)) {\n // 新增和更新\n if (CollUtil.isNotEmpty(dbList)) {\n // 更新系统存在的数据\n updateHandle(dbList, excelMap);\n }\n\n // 不存在的数据,新增\n List<K> dbKeyList = dbList.stream().map(primaryKey).collect(Collectors.toList());\n List<T> needAddList = list.stream()\n .filter(item -> !dbKeyList.contains(primaryKey.apply(item)))\n .collect(Collectors.toList());\n if (CollUtil.isNotEmpty(needAddList)) {\n add(needAddList);\n addCount.addAndGet(needAddList.size());\n }\n return;\n }\n\n throw new IllegalArgumentException(\"导入模式错误\");\n }\n\n /**\n * 获取处理结果\n */\n public ImportResult getResult() {\n ImportResult importResult = new ImportResult();\n importResult.setAddCount(addCount.get());\n importResult.setUpdateCount(updateCount.get());\n return importResult;\n }\n\n private void updateHandle(List<T> dbList, Map<K, T> excelMap) {\n List<T> needUpdateList = dbList.stream()\n .filter(dbItem -> excelMap.containsKey(primaryKey.apply(dbItem)))\n .map(dbItem -> {\n T excelItem = excelMap.get(primaryKey.apply(dbItem));\n\n return buildUpdateItem(dbItem, excelItem);\n }).collect(Collectors.toList());\n\n if (CollUtil.isNotEmpty(needUpdateList)) {\n update(needUpdateList);\n updateCount.addAndGet(needUpdateList.size());\n }\n }\n\n /**\n * 校验excel数据\n */\n protected abstract void valid(List<T> list);\n\n /**\n * 新增数据到数据库\n */\n public abstract void add(List<T> list);\n\n /**\n * 更新数据到数据库\n */\n public abstract void update(List<T> list);\n\n /**\n * 构建需要更新的字段\n * @param dbItem 数据库数据\n * @param excelItem excel数据\n */\n protected abstract T buildUpdateItem(T dbItem, T excelItem);\n\n /**\n * 获取数据库查询已存在的数据\n */\n protected abstract List<T> getDbList(List<T> list);\n}" } ]
import cn.eu.common.base.service.impl.EuServiceImpl; import cn.eu.common.enums.SysDictDetailStatus; import cn.eu.common.enums.SysDictStatus; import cn.eu.common.model.PageResult; import cn.eu.common.utils.EasyExcelHelper; import cn.eu.common.utils.MpQueryHelper; import cn.eu.common.utils.ValidateUtil; import cn.eu.common.utils.easyexcel.EasyExcelCellItem; import cn.eu.common.utils.easyexcel.EasyExcelUtil; import cn.eu.common.utils.easyexcel.EasyExcelWriteSheet; import cn.eu.system.domain.SysDept; import cn.eu.system.domain.SysDict; import cn.eu.system.domain.SysDictDetail; import cn.eu.system.domain.SysUser; import cn.eu.system.mapper.SysDictDetailMapper; import cn.eu.system.model.dto.ImportResult; import cn.eu.system.model.query.SysDictDetailQueryCriteria; import cn.eu.system.service.ISysDictDetailService; import cn.eu.system.service.ISysDictService; import cn.eu.system.utils.ImportModeHandleTemplate; import com.alibaba.excel.EasyExcel; import com.alibaba.excel.write.metadata.WriteSheet; import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy; import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import org.springframework.util.Assert; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.*; import java.util.stream.Collectors;
9,013
package cn.eu.system.service.impl; /** * @author zhaoeryu * @since 2023/5/31 */ @Service public class SysDictDetailServiceImpl extends EuServiceImpl<SysDictDetailMapper, SysDictDetail> implements ISysDictDetailService { @Autowired SysDictDetailMapper SysDictDetailMapper; @Autowired ISysDictService sysDictService; @Override public PageResult<SysDictDetail> page(SysDictDetailQueryCriteria criteria, Pageable pageable) { getPage(pageable); return PageResult.of(list(criteria)); } @Override public List<SysDictDetail> list(SysDictDetailQueryCriteria criteria) { return list(MpQueryHelper.buildQueryWrapper(criteria, SysDictDetail.class)); } @Override public void exportTemplate(HttpServletResponse response) throws IOException { List<String> exportExcludeFieldNames = buildExportExcludeFieldNames(); // sheet1 WriteSheet writeSheet = EasyExcel.writerSheet(0, "sheet1") .head(SysDictDetail.class) .excludeColumnFieldNames(exportExcludeFieldNames) .build(); EasyExcelWriteSheet sheet1 = EasyExcelWriteSheet.of(writeSheet, null) .registerStandardWriteHandler(); // sheet2 writeSheet = EasyExcel.writerSheet(1, "示例数据") .head(SysDictDetail.class) .excludeColumnFieldNames(exportExcludeFieldNames) .build(); SysDictDetail exampleEntity = buildExampleEntity(); EasyExcelWriteSheet sheet2 = EasyExcelWriteSheet.of(writeSheet, Collections.singletonList(exampleEntity)) .registerStandardWriteHandler(); // 导出 EasyExcelHelper.export(response, sheet1, sheet2 ); } @Override public ImportResult importData(MultipartFile file, Integer importMode, Integer dictId) throws IOException { SysDict dict = sysDictService.getById(dictId); Assert.notNull(dict, "字典不存在");
package cn.eu.system.service.impl; /** * @author zhaoeryu * @since 2023/5/31 */ @Service public class SysDictDetailServiceImpl extends EuServiceImpl<SysDictDetailMapper, SysDictDetail> implements ISysDictDetailService { @Autowired SysDictDetailMapper SysDictDetailMapper; @Autowired ISysDictService sysDictService; @Override public PageResult<SysDictDetail> page(SysDictDetailQueryCriteria criteria, Pageable pageable) { getPage(pageable); return PageResult.of(list(criteria)); } @Override public List<SysDictDetail> list(SysDictDetailQueryCriteria criteria) { return list(MpQueryHelper.buildQueryWrapper(criteria, SysDictDetail.class)); } @Override public void exportTemplate(HttpServletResponse response) throws IOException { List<String> exportExcludeFieldNames = buildExportExcludeFieldNames(); // sheet1 WriteSheet writeSheet = EasyExcel.writerSheet(0, "sheet1") .head(SysDictDetail.class) .excludeColumnFieldNames(exportExcludeFieldNames) .build(); EasyExcelWriteSheet sheet1 = EasyExcelWriteSheet.of(writeSheet, null) .registerStandardWriteHandler(); // sheet2 writeSheet = EasyExcel.writerSheet(1, "示例数据") .head(SysDictDetail.class) .excludeColumnFieldNames(exportExcludeFieldNames) .build(); SysDictDetail exampleEntity = buildExampleEntity(); EasyExcelWriteSheet sheet2 = EasyExcelWriteSheet.of(writeSheet, Collections.singletonList(exampleEntity)) .registerStandardWriteHandler(); // 导出 EasyExcelHelper.export(response, sheet1, sheet2 ); } @Override public ImportResult importData(MultipartFile file, Integer importMode, Integer dictId) throws IOException { SysDict dict = sysDictService.getById(dictId); Assert.notNull(dict, "字典不存在");
ImportModeHandleTemplate<SysDictDetail, String> importModeHandleTemplate = new ImportModeHandleTemplate<SysDictDetail, String>(importMode, item -> item.getDictKey() + "_" + item.getDictLabel()) {
19
2023-10-20 07:08:37+00:00
12k
Nxer/Twist-Space-Technology-Mod
src/main/java/com/Nxer/TwistSpaceTechnology/common/machine/GT_TileEntity_MoleculeDeconstructor.java
[ { "identifier": "Mode_Default_MoleculeDeconstructor", "path": "src/main/java/com/Nxer/TwistSpaceTechnology/common/machine/ValueEnum.java", "snippet": "public static final byte Mode_Default_MoleculeDeconstructor = Config.Mode_Default_MoleculeDeconstructor;" }, { "identifier": "Parallel_PerPiece_MoleculeDeconstructor", "path": "src/main/java/com/Nxer/TwistSpaceTechnology/common/machine/ValueEnum.java", "snippet": "public static final int Parallel_PerPiece_MoleculeDeconstructor = Config.Parallel_PerPiece_MoleculeDeconstructor;" }, { "identifier": "PieceAmount_EnablePerfectOverclock_MoleculeDeconstructor", "path": "src/main/java/com/Nxer/TwistSpaceTechnology/common/machine/ValueEnum.java", "snippet": "public static final int PieceAmount_EnablePerfectOverclock_MoleculeDeconstructor = Config.PieceAmount_EnablePerfectOverclock_MoleculeDeconstructor;" }, { "identifier": "SpeedBonus_MultiplyPerTier_MoleculeDeconstructor", "path": "src/main/java/com/Nxer/TwistSpaceTechnology/common/machine/ValueEnum.java", "snippet": "public static final float SpeedBonus_MultiplyPerTier_MoleculeDeconstructor = Config.SpeedBonus_MultiplyPerTier_MoleculeDeconstructor;" }, { "identifier": "BLUE_PRINT_INFO", "path": "src/main/java/com/Nxer/TwistSpaceTechnology/util/TextLocalization.java", "snippet": "public static final String BLUE_PRINT_INFO = texter(\n \"Follow the\" + EnumChatFormatting.BLUE\n + \" Structure\"\n + EnumChatFormatting.DARK_BLUE\n + \"Lib\"\n + EnumChatFormatting.GRAY\n + \" hologram projector to build the main structure.\",\n \"BLUE_PRINT_INFO\");" }, { "identifier": "ModName", "path": "src/main/java/com/Nxer/TwistSpaceTechnology/util/TextLocalization.java", "snippet": "public static final String ModName = Tags.MODNAME;" }, { "identifier": "StructureTooComplex", "path": "src/main/java/com/Nxer/TwistSpaceTechnology/util/TextLocalization.java", "snippet": "public static final String StructureTooComplex = texter(\"The structure is too complex!\", \"StructureTooComplex\");" }, { "identifier": "Tooltip_MoleculeDeconstructor_00", "path": "src/main/java/com/Nxer/TwistSpaceTechnology/util/TextLocalization.java", "snippet": "public static final String Tooltip_MoleculeDeconstructor_00 = texter(\"Controller block for the Molecule Deconstructor\",\"Tooltip_MoleculeDeconstructor_00\");" }, { "identifier": "Tooltip_MoleculeDeconstructor_01", "path": "src/main/java/com/Nxer/TwistSpaceTechnology/util/TextLocalization.java", "snippet": "public static final String Tooltip_MoleculeDeconstructor_01 = texter(EnumChatFormatting.AQUA+\"The lightning seemed to roll down a ladder.\",\"Tooltip_MoleculeDeconstructor_01\");" }, { "identifier": "Tooltip_MoleculeDeconstructor_02", "path": "src/main/java/com/Nxer/TwistSpaceTechnology/util/TextLocalization.java", "snippet": "public static final String Tooltip_MoleculeDeconstructor_02 = texter(\"Separate the molecules one by one with tweezers.\",\"Tooltip_MoleculeDeconstructor_02\");" }, { "identifier": "Tooltip_MoleculeDeconstructor_03", "path": "src/main/java/com/Nxer/TwistSpaceTechnology/util/TextLocalization.java", "snippet": "public static final String Tooltip_MoleculeDeconstructor_03 = texter(\"Extra 24x Parallel per Piece. 16 Piece enable Perfect Overclock.\",\"Tooltip_MoleculeDeconstructor_03\");" }, { "identifier": "Tooltip_MoleculeDeconstructor_04", "path": "src/main/java/com/Nxer/TwistSpaceTechnology/util/TextLocalization.java", "snippet": "public static final String Tooltip_MoleculeDeconstructor_04 = texter(\"Additional 10%% reduction in time per Voltage Tier, multiplication calculus.\",\"Tooltip_MoleculeDeconstructor_04\");" }, { "identifier": "Tooltip_MoleculeDeconstructor_05", "path": "src/main/java/com/Nxer/TwistSpaceTechnology/util/TextLocalization.java", "snippet": "public static final String Tooltip_MoleculeDeconstructor_05 = texter(\"The Glass Tier limit the Energy hatch voltage Tier.\",\"Tooltip_MoleculeDeconstructor_05\");" }, { "identifier": "Tooltip_MoleculeDeconstructor_MachineType", "path": "src/main/java/com/Nxer/TwistSpaceTechnology/util/TextLocalization.java", "snippet": "public static final String Tooltip_MoleculeDeconstructor_MachineType = texter(\"Electrolyzer | Centrifuge\",\"Tooltip_MoleculeDeconstructor_MachineType\");" }, { "identifier": "textFrontBottom", "path": "src/main/java/com/Nxer/TwistSpaceTechnology/util/TextLocalization.java", "snippet": "public static final String textFrontBottom = texter(\"Front bottom\", \"textFrontBottom\");" }, { "identifier": "textScrewdriverChangeMode", "path": "src/main/java/com/Nxer/TwistSpaceTechnology/util/TextLocalization.java", "snippet": "public static final String textScrewdriverChangeMode = texter(\"Use screwdriver to change mode.\", \"textScrewdriverChangeMode\");" }, { "identifier": "textUseBlueprint", "path": "src/main/java/com/Nxer/TwistSpaceTechnology/util/TextLocalization.java", "snippet": "public static final String textUseBlueprint = texter(\"Use \"+EnumChatFormatting.BLUE+\"Blue\"+EnumChatFormatting.AQUA+\"print\"+EnumChatFormatting.RESET+\" to preview\", \"textUseBlueprint\");" }, { "identifier": "GTCM_MultiMachineBase", "path": "src/main/java/com/Nxer/TwistSpaceTechnology/common/machine/multiMachineClasses/GTCM_MultiMachineBase.java", "snippet": "public abstract class GTCM_MultiMachineBase<T extends GTCM_MultiMachineBase<T>>\n extends GT_MetaTileEntity_ExtendedPowerMultiBlockBase<T> implements IConstructable, ISurvivalConstructable {\n\n // region Class Constructor\n public GTCM_MultiMachineBase(int aID, String aName, String aNameRegional) {\n super(aID, aName, aNameRegional);\n }\n\n public GTCM_MultiMachineBase(String aName) {\n super(aName);\n }\n\n // endregion\n\n // region new methods\n public void repairMachine() {\n mHardHammer = true;\n mSoftHammer = true;\n mScrewdriver = true;\n mCrowbar = true;\n mSolderingTool = true;\n mWrench = true;\n }\n\n // endregion\n\n // region Processing Logic\n\n /**\n * Creates logic to run recipe check based on recipemap. This runs only once, on class instantiation.\n * <p>\n * If this machine doesn't use recipemap or does some complex things, override {@link #checkProcessing()}.\n */\n @ApiStatus.OverrideOnly\n protected ProcessingLogic createProcessingLogic() {\n return new GTCM_ProcessingLogic() {\n\n @NotNull\n @Override\n public CheckRecipeResult process() {\n\n setEuModifier(getEuModifier());\n setSpeedBonus(getSpeedBonus());\n setOverclock(isEnablePerfectOverclock() ? 2 : 1, 2);\n return super.process();\n }\n\n }.setMaxParallelSupplier(this::getLimitedMaxParallel);\n }\n\n /**\n * Proxy Perfect Overclock Supplier.\n *\n * @return If true, enable Perfect Overclock.\n */\n protected abstract boolean isEnablePerfectOverclock();\n\n /**\n * Proxy Standard Eu Modifier Supplier.\n *\n * @return The value (or a method to get the value) of Eu Modifier (dynamically) .\n */\n @ApiStatus.OverrideOnly\n protected float getEuModifier() {\n return 1.0F;\n }\n\n /**\n * Proxy Standard Speed Multiplier Supplier.\n *\n * @return The value (or a method to get the value) of Speed Multiplier (dynamically) .\n */\n @ApiStatus.OverrideOnly\n protected abstract float getSpeedBonus();\n\n /**\n * Proxy Standard Parallel Supplier.\n *\n * @return The value (or a method to get the value) of Max Parallel (dynamically) .\n */\n @ApiStatus.OverrideOnly\n protected abstract int getMaxParallelRecipes();\n\n /**\n * Limit the max parallel to prevent overflow.\n *\n * @return Limited parallel.\n */\n protected int getLimitedMaxParallel() {\n return getMaxParallelRecipes();\n }\n\n /**\n * Checks recipe and setup machine if it's successful.\n * <p>\n * For generic machine working with recipemap, use {@link #createProcessingLogic()} to make use of shared codebase.\n */\n @Nonnull\n @Override\n public CheckRecipeResult checkProcessing() {\n // If no logic is found, try legacy checkRecipe\n if (processingLogic == null) {\n return checkRecipe(mInventory[1]) ? CheckRecipeResultRegistry.SUCCESSFUL\n : CheckRecipeResultRegistry.NO_RECIPE;\n }\n\n setupProcessingLogic(processingLogic);\n\n CheckRecipeResult result = doCheckRecipe();\n result = postCheckRecipe(result, processingLogic);\n // inputs are consumed at this point\n updateSlots();\n if (!result.wasSuccessful()) return result;\n\n mEfficiency = (10000 - (getIdealStatus() - getRepairStatus()) * 1000);\n mEfficiencyIncrease = 10000;\n mMaxProgresstime = processingLogic.getDuration();\n setEnergyUsage(processingLogic);\n\n mOutputItems = processingLogic.getOutputItems();\n mOutputFluids = processingLogic.getOutputFluids();\n\n return result;\n }\n\n /**\n * <p>\n * Get inputting items without DualInputHatch, and no separation mode.\n * <p>\n * Always used to get some special input items.\n *\n * @return The inputting items.\n */\n public ArrayList<ItemStack> getStoredInputsWithoutDualInputHatch() {\n\n ArrayList<ItemStack> rList = new ArrayList<>();\n for (GT_MetaTileEntity_Hatch_InputBus tHatch : filterValidMTEs(mInputBusses)) {\n tHatch.mRecipeMap = getRecipeMap();\n IGregTechTileEntity tileEntity = tHatch.getBaseMetaTileEntity();\n for (int i = tileEntity.getSizeInventory() - 1; i >= 0; i--) {\n ItemStack itemStack = tileEntity.getStackInSlot(i);\n if (itemStack != null) {\n rList.add(itemStack);\n }\n }\n }\n\n if (getStackInSlot(1) != null && getStackInSlot(1).getUnlocalizedName()\n .startsWith(\"gt.integrated_circuit\")) rList.add(getStackInSlot(1));\n return rList;\n }\n\n // region Overrides\n @Override\n public String[] getInfoData() {\n String[] origin = super.getInfoData();\n String[] ret = new String[origin.length + 3];\n System.arraycopy(origin, 0, ret, 0, origin.length);\n ret[origin.length] = EnumChatFormatting.AQUA + texter(\"Parallels\", \"MachineInfoData.Parallels\")\n + \": \"\n + EnumChatFormatting.GOLD\n + this.getLimitedMaxParallel();\n ret[origin.length + 1] = EnumChatFormatting.AQUA + texter(\"Speed multiplier\", \"MachineInfoData.SpeedMultiplier\")\n + \": \"\n + EnumChatFormatting.GOLD\n + this.getSpeedBonus();\n ret[origin.length + 2] = EnumChatFormatting.AQUA + texter(\"EU Modifier\", \"MachineInfoData.EuModifier\")\n + \": \"\n + EnumChatFormatting.GOLD\n + this.getEuModifier();\n return ret;\n }\n\n @Override\n public boolean addToMachineList(IGregTechTileEntity aTileEntity, int aBaseCasingIndex) {\n return super.addToMachineList(aTileEntity, aBaseCasingIndex)\n || addExoticEnergyInputToMachineList(aTileEntity, aBaseCasingIndex);\n }\n\n public boolean addEnergyHatchOrExoticEnergyHatchToMachineList(IGregTechTileEntity aTileEntity,\n int aBaseCasingIndex) {\n return addEnergyInputToMachineList(aTileEntity, aBaseCasingIndex)\n || addExoticEnergyInputToMachineList(aTileEntity, aBaseCasingIndex);\n }\n\n public boolean addInputBusOrOutputBusToMachineList(IGregTechTileEntity aTileEntity, int aBaseCasingIndex) {\n return addInputBusToMachineList(aTileEntity, aBaseCasingIndex)\n || addOutputBusToMachineList(aTileEntity, aBaseCasingIndex);\n }\n\n public boolean addInputHatchOrOutputHatchToMachineList(IGregTechTileEntity aTileEntity, int aBaseCasingIndex) {\n return addInputHatchToMachineList(aTileEntity, aBaseCasingIndex)\n || addOutputHatchToMachineList(aTileEntity, aBaseCasingIndex);\n }\n\n public boolean addFluidInputToMachineList(IGregTechTileEntity aTileEntity, int aBaseCasingIndex) {\n if (aTileEntity == null) return false;\n IMetaTileEntity aMetaTileEntity = aTileEntity.getMetaTileEntity();\n if (aMetaTileEntity == null) return false;\n if (aMetaTileEntity instanceof GT_MetaTileEntity_Hatch_Input) {\n ((GT_MetaTileEntity_Hatch) aMetaTileEntity).updateTexture(aBaseCasingIndex);\n ((GT_MetaTileEntity_Hatch_Input) aMetaTileEntity).mRecipeMap = getRecipeMap();\n return mInputHatches.add((GT_MetaTileEntity_Hatch_Input) aMetaTileEntity);\n } else if (aMetaTileEntity instanceof GT_MetaTileEntity_Hatch_Muffler) {\n ((GT_MetaTileEntity_Hatch) aMetaTileEntity).updateTexture(aBaseCasingIndex);\n return mMufflerHatches.add((GT_MetaTileEntity_Hatch_Muffler) aMetaTileEntity);\n }\n return false;\n }\n\n @Override\n public boolean addEnergyOutput(long aEU) {\n if (aEU <= 0) {\n return true;\n }\n if (!mDynamoHatches.isEmpty()) {\n return addEnergyOutputMultipleDynamos(aEU, true);\n }\n return false;\n }\n\n @Override\n public boolean addEnergyOutputMultipleDynamos(long aEU, boolean aAllowMixedVoltageDynamos) {\n int injected = 0;\n long totalOutput = 0;\n long aFirstVoltageFound = -1;\n boolean aFoundMixedDynamos = false;\n for (GT_MetaTileEntity_Hatch_Dynamo aDynamo : filterValidMTEs(mDynamoHatches)) {\n long aVoltage = aDynamo.maxEUOutput();\n long aTotal = aDynamo.maxAmperesOut() * aVoltage;\n // Check against voltage to check when hatch mixing\n if (aFirstVoltageFound == -1) {\n aFirstVoltageFound = aVoltage;\n } else {\n if (aFirstVoltageFound != aVoltage) {\n aFoundMixedDynamos = true;\n }\n }\n totalOutput += aTotal;\n }\n\n /*\n * disable explosion\n * if (totalOutput < aEU || (aFoundMixedDynamos && !aAllowMixedVoltageDynamos)) {\n * explodeMultiblock();\n * return false;\n * }\n */\n\n long actualOutputEU;\n if (totalOutput < aEU) {\n actualOutputEU = totalOutput;\n } else {\n actualOutputEU = aEU;\n }\n\n long leftToInject;\n long aVoltage;\n int aAmpsToInject;\n int aRemainder;\n int ampsOnCurrentHatch;\n for (GT_MetaTileEntity_Hatch_Dynamo aDynamo : filterValidMTEs(mDynamoHatches)) {\n leftToInject = actualOutputEU - injected;\n aVoltage = aDynamo.maxEUOutput();\n aAmpsToInject = (int) (leftToInject / aVoltage);\n aRemainder = (int) (leftToInject - (aAmpsToInject * aVoltage));\n ampsOnCurrentHatch = (int) Math.min(aDynamo.maxAmperesOut(), aAmpsToInject);\n for (int i = 0; i < ampsOnCurrentHatch; i++) {\n aDynamo.getBaseMetaTileEntity()\n .increaseStoredEnergyUnits(aVoltage, false);\n }\n injected += aVoltage * ampsOnCurrentHatch;\n if (aRemainder > 0 && ampsOnCurrentHatch < aDynamo.maxAmperesOut()) {\n aDynamo.getBaseMetaTileEntity()\n .increaseStoredEnergyUnits(aRemainder, false);\n injected += aRemainder;\n }\n }\n return injected > 0;\n }\n\n @Override\n public boolean isCorrectMachinePart(ItemStack aStack) {\n return true;\n }\n\n /**\n * No more machine error\n */\n @Override\n public boolean doRandomMaintenanceDamage() {\n return true;\n }\n\n /**\n * Gets the maximum Efficiency that spare Part can get (0 - 10000)\n *\n * @param aStack\n */\n @Override\n public int getMaxEfficiency(ItemStack aStack) {\n return 10000;\n }\n\n /**\n * Gets the damage to the ItemStack, usually 0 or 1.\n *\n * @param aStack\n */\n @Override\n public int getDamageToComponent(ItemStack aStack) {\n return 0;\n }\n\n /**\n * If it explodes when the Component has to be replaced.\n */\n @Override\n public boolean explodesOnComponentBreak(ItemStack aStack) {\n return false;\n }\n\n @Override\n public boolean supportsVoidProtection() {\n return true;\n }\n\n @Override\n public boolean supportsInputSeparation() {\n return true;\n }\n\n @Override\n public boolean supportsBatchMode() {\n return true;\n }\n\n @Override\n public boolean supportsSingleRecipeLocking() {\n return true;\n }\n\n // endregion\n}" } ]
import static com.Nxer.TwistSpaceTechnology.common.machine.ValueEnum.Mode_Default_MoleculeDeconstructor; import static com.Nxer.TwistSpaceTechnology.common.machine.ValueEnum.Parallel_PerPiece_MoleculeDeconstructor; import static com.Nxer.TwistSpaceTechnology.common.machine.ValueEnum.PieceAmount_EnablePerfectOverclock_MoleculeDeconstructor; import static com.Nxer.TwistSpaceTechnology.common.machine.ValueEnum.SpeedBonus_MultiplyPerTier_MoleculeDeconstructor; import static com.Nxer.TwistSpaceTechnology.util.TextLocalization.BLUE_PRINT_INFO; import static com.Nxer.TwistSpaceTechnology.util.TextLocalization.ModName; import static com.Nxer.TwistSpaceTechnology.util.TextLocalization.StructureTooComplex; import static com.Nxer.TwistSpaceTechnology.util.TextLocalization.Tooltip_MoleculeDeconstructor_00; import static com.Nxer.TwistSpaceTechnology.util.TextLocalization.Tooltip_MoleculeDeconstructor_01; import static com.Nxer.TwistSpaceTechnology.util.TextLocalization.Tooltip_MoleculeDeconstructor_02; import static com.Nxer.TwistSpaceTechnology.util.TextLocalization.Tooltip_MoleculeDeconstructor_03; import static com.Nxer.TwistSpaceTechnology.util.TextLocalization.Tooltip_MoleculeDeconstructor_04; import static com.Nxer.TwistSpaceTechnology.util.TextLocalization.Tooltip_MoleculeDeconstructor_05; import static com.Nxer.TwistSpaceTechnology.util.TextLocalization.Tooltip_MoleculeDeconstructor_MachineType; import static com.Nxer.TwistSpaceTechnology.util.TextLocalization.textFrontBottom; import static com.Nxer.TwistSpaceTechnology.util.TextLocalization.textScrewdriverChangeMode; import static com.Nxer.TwistSpaceTechnology.util.TextLocalization.textUseBlueprint; import static com.github.technus.tectech.thing.casing.TT_Container_Casings.sBlockCasingsTT; import static com.gtnewhorizon.structurelib.structure.StructureUtility.ofBlock; import static com.gtnewhorizon.structurelib.structure.StructureUtility.withChannel; import static gregtech.api.enums.GT_HatchElement.Energy; import static gregtech.api.enums.GT_HatchElement.ExoticEnergy; import static gregtech.api.enums.GT_HatchElement.InputBus; import static gregtech.api.enums.GT_HatchElement.InputHatch; import static gregtech.api.enums.GT_HatchElement.Maintenance; import static gregtech.api.enums.GT_HatchElement.OutputBus; import static gregtech.api.enums.GT_HatchElement.OutputHatch; import static gregtech.api.enums.Textures.BlockIcons.OVERLAY_FRONT_PROCESSING_ARRAY; import static gregtech.api.enums.Textures.BlockIcons.OVERLAY_FRONT_PROCESSING_ARRAY_ACTIVE; import static gregtech.api.enums.Textures.BlockIcons.OVERLAY_FRONT_PROCESSING_ARRAY_ACTIVE_GLOW; import static gregtech.api.enums.Textures.BlockIcons.OVERLAY_FRONT_PROCESSING_ARRAY_GLOW; import static gregtech.api.util.GT_StructureUtility.ofFrame; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.EnumChatFormatting; import net.minecraft.util.StatCollector; import net.minecraftforge.common.util.ForgeDirection; import com.Nxer.TwistSpaceTechnology.common.machine.multiMachineClasses.GTCM_MultiMachineBase; import com.github.bartimaeusnek.bartworks.API.BorosilicateGlass; import com.gtnewhorizon.structurelib.alignment.constructable.IConstructable; import com.gtnewhorizon.structurelib.alignment.constructable.ISurvivalConstructable; import com.gtnewhorizon.structurelib.structure.IItemSource; import com.gtnewhorizon.structurelib.structure.IStructureDefinition; import com.gtnewhorizon.structurelib.structure.StructureDefinition; import gregtech.api.GregTech_API; import gregtech.api.enums.Materials; import gregtech.api.enums.Textures; import gregtech.api.interfaces.ITexture; import gregtech.api.interfaces.metatileentity.IMetaTileEntity; import gregtech.api.interfaces.tileentity.IGregTechTileEntity; import gregtech.api.metatileentity.implementations.GT_MetaTileEntity_Hatch; import gregtech.api.recipe.RecipeMap; import gregtech.api.render.TextureFactory; import gregtech.api.util.GT_HatchElementBuilder; import gregtech.api.util.GT_Multiblock_Tooltip_Builder; import gregtech.api.util.GT_Utility; import gtPlusPlus.api.recipe.GTPPRecipeMaps;
7,612
"I DDD I", "I I", "I I", "I I", "IFD AAA DFI", "IFD A A DFI", "IFD CCC DFI", "CCD DCC" }}; private final String[][] shapeMiddle = new String[][]{{ " ", " ", " ", " ", " ", " ", " AAA ", " A A ", " CCC ", " " },{ "IIIIIIIIIIIIIII", "I FFF I", "I DDD I", "I I", "I I", "I I", "IFD AAA DFI", "IFD A A DFI", "IFD CCC DFI", "CCD DCC" },{ " ", " FFF ", " DED ", " B ", " B ", " B ", " FD AEA DF ", " FEBBBE EBBBEF ", " FD CCC DF ", "CCD DCC" },{ "IIIIIIIIIIIIIII", "I FFF I", "I DDD I", "I I", "I I", "I I", "IFD AAA DFI", "IFD A A DFI", "IFD CCC DFI", "CCD DCC" }}; private final String[][] shapeEnd = new String[][]{{ " ", " ", " ", " ", " ", " ", " FFF ", " FFF ", " FFF ", " GGG " }}; @Override public boolean addToMachineList(IGregTechTileEntity aTileEntity, int aBaseCasingIndex) { return super.addToMachineList(aTileEntity, aBaseCasingIndex) || addExoticEnergyInputToMachineList(aTileEntity, aBaseCasingIndex); } // spotless:on // endregion // region Overrides @Override public String[] getInfoData() { String[] origin = super.getInfoData(); String[] ret = new String[origin.length + 3]; System.arraycopy(origin, 0, ret, 0, origin.length); ret[origin.length] = EnumChatFormatting.AQUA + "Parallels: " + EnumChatFormatting.GOLD + this.getMaxParallelRecipes(); ret[origin.length + 1] = EnumChatFormatting.AQUA + "Speed multiplier: " + EnumChatFormatting.GOLD + this.getSpeedBonus(); ret[origin.length + 2] = EnumChatFormatting.AQUA + "Pieces: " + EnumChatFormatting.GOLD + this.piece; return ret; } @Override public void saveNBTData(NBTTagCompound aNBT) { super.saveNBTData(aNBT); aNBT.setInteger("piece", piece); aNBT.setByte("mode", mode); } @Override public void loadNBTData(final NBTTagCompound aNBT) { super.loadNBTData(aNBT); piece = aNBT.getInteger("piece"); mode = aNBT.getByte("mode"); } @Override protected GT_Multiblock_Tooltip_Builder createTooltip() { final GT_Multiblock_Tooltip_Builder tt = new GT_Multiblock_Tooltip_Builder(); tt.addMachineType(Tooltip_MoleculeDeconstructor_MachineType) .addInfo(Tooltip_MoleculeDeconstructor_00) .addInfo(Tooltip_MoleculeDeconstructor_01) .addInfo(Tooltip_MoleculeDeconstructor_02) .addInfo(Tooltip_MoleculeDeconstructor_03) .addInfo(Tooltip_MoleculeDeconstructor_04) .addInfo(Tooltip_MoleculeDeconstructor_05)
package com.Nxer.TwistSpaceTechnology.common.machine; public class GT_TileEntity_MoleculeDeconstructor extends GTCM_MultiMachineBase<GT_TileEntity_MoleculeDeconstructor> implements IConstructable, ISurvivalConstructable { // region Class Constructor public GT_TileEntity_MoleculeDeconstructor(int aID, String aName, String aNameRegional) { super(aID, aName, aNameRegional); } public GT_TileEntity_MoleculeDeconstructor(String aName) { super(aName); } // endregion // region Processing Logic private byte glassTier = 0; private int piece = 1; private byte mode = Mode_Default_MoleculeDeconstructor; @Override protected boolean isEnablePerfectOverclock() { return piece >= PieceAmount_EnablePerfectOverclock_MoleculeDeconstructor; } protected int getMaxParallelRecipes() { return Parallel_PerPiece_MoleculeDeconstructor * this.piece; } protected float getSpeedBonus() { return (float) (Math .pow(SpeedBonus_MultiplyPerTier_MoleculeDeconstructor, GT_Utility.getTier(this.getMaxInputEu()))); } @Override public RecipeMap<?> getRecipeMap() { switch (mode) { case 1: return GTPPRecipeMaps.centrifugeNonCellRecipes; default: return GTPPRecipeMaps.electrolyzerNonCellRecipes; } } @Override public final void onScrewdriverRightClick(ForgeDirection side, EntityPlayer aPlayer, float aX, float aY, float aZ) { if (getBaseMetaTileEntity().isServerSide()) { this.mode = (byte) ((this.mode + 1) % 2); GT_Utility.sendChatToPlayer( aPlayer, StatCollector.translateToLocal("MoleculeDeconstructor.modeMsg." + this.mode)); } } @Override public boolean checkMachine(IGregTechTileEntity aBaseMetaTileEntity, ItemStack aStack) { this.glassTier = 0; this.piece = 1; if (!checkPiece(STRUCTURE_PIECE_MAIN, horizontalOffSet, verticalOffSet, depthOffSet)) { return false; } while (checkPiece(STRUCTURE_PIECE_MIDDLE, horizontalOffSet, verticalOffSet, depthOffSet - piece * 4)) { this.piece++; } if (!checkPiece(STRUCTURE_PIECE_END, horizontalOffSet, verticalOffSet, depthOffSet - piece * 4)) { return false; } if (this.glassTier <= 0) return false; if (glassTier < 12) { for (GT_MetaTileEntity_Hatch hatch : this.mExoticEnergyHatches) { if (this.glassTier < hatch.mTier) { return false; } } } return true; } // endregion // region Structure // spotless:off @Override public void construct(ItemStack stackSize, boolean hintsOnly) { this.buildPiece(STRUCTURE_PIECE_MAIN, stackSize, hintsOnly, horizontalOffSet, verticalOffSet, depthOffSet); int piece = stackSize.stackSize; for (int i=1; i<piece; i++){ this.buildPiece(STRUCTURE_PIECE_MIDDLE, stackSize, hintsOnly, horizontalOffSet, verticalOffSet, depthOffSet - i*4); } this.buildPiece(STRUCTURE_PIECE_END, stackSize, hintsOnly, horizontalOffSet, verticalOffSet, depthOffSet - piece*4); } @Override public int survivalConstruct(ItemStack stackSize, int elementBudget, IItemSource source, EntityPlayerMP actor) { if (this.mMachine) return -1; int built = 0; built += survivialBuildPiece( STRUCTURE_PIECE_MAIN, stackSize, horizontalOffSet, verticalOffSet, depthOffSet, elementBudget, source, actor, false, true); int piece = stackSize.stackSize; if (piece>1) { for (int i = 1; i < piece; i++) { built += survivialBuildPiece( STRUCTURE_PIECE_MIDDLE, stackSize, horizontalOffSet, verticalOffSet, depthOffSet - i * 4, elementBudget, source, actor, false, true); } } built += survivialBuildPiece( STRUCTURE_PIECE_END, stackSize, horizontalOffSet, verticalOffSet, depthOffSet - piece*4, elementBudget, source, actor, false, true); return built; } private static final String STRUCTURE_PIECE_MAIN = "mainMoleculeDeconstructor"; private static final String STRUCTURE_PIECE_MIDDLE = "middleMoleculeDeconstructor"; private static final String STRUCTURE_PIECE_END = "endMoleculeDeconstructor"; private final int horizontalOffSet = 7; private final int verticalOffSet = 9; private final int depthOffSet = 0; @Override public IStructureDefinition<GT_TileEntity_MoleculeDeconstructor> getStructureDefinition() { return StructureDefinition.<GT_TileEntity_MoleculeDeconstructor>builder() .addShape(STRUCTURE_PIECE_MAIN, shapeMain) .addShape(STRUCTURE_PIECE_MIDDLE, shapeMiddle) .addShape(STRUCTURE_PIECE_END, shapeEnd) .addElement('A', withChannel("glass", BorosilicateGlass.ofBoroGlass( (byte) 0, (byte) 1, Byte.MAX_VALUE, (te, t) -> te.glassTier = t, te -> te.glassTier ))) .addElement('B', ofBlock(GregTech_API.sBlockCasings2, 15)) .addElement('C', ofBlock(GregTech_API.sBlockCasings4, 14)) .addElement('D', GT_HatchElementBuilder.<GT_TileEntity_MoleculeDeconstructor>builder() .atLeast(Energy.or(ExoticEnergy)) .adder(GT_TileEntity_MoleculeDeconstructor::addToMachineList) .dot(1) .casingIndex(1024) .buildAndChain(sBlockCasingsTT, 0)) .addElement('E', ofBlock(sBlockCasingsTT, 8)) .addElement('F', GT_HatchElementBuilder.<GT_TileEntity_MoleculeDeconstructor>builder() .atLeast(OutputBus, OutputHatch) .adder(GT_TileEntity_MoleculeDeconstructor::addToMachineList) .dot(2) .casingIndex(62) .buildAndChain(GregTech_API.sBlockCasings4, 14)) .addElement('G', GT_HatchElementBuilder.<GT_TileEntity_MoleculeDeconstructor>builder() .atLeast(Maintenance) .adder(GT_TileEntity_MoleculeDeconstructor::addToMachineList) .dot(3) .casingIndex(62) .buildAndChain(GregTech_API.sBlockCasings4, 14)) .addElement('H', GT_HatchElementBuilder.<GT_TileEntity_MoleculeDeconstructor>builder() .atLeast(InputBus, InputHatch) .adder(GT_TileEntity_MoleculeDeconstructor::addToMachineList) .dot(4) .casingIndex(62) .buildAndChain(GregTech_API.sBlockCasings4, 14)) .addElement('I', ofFrame(Materials.CosmicNeutronium)) .build(); } /* Blocks: A -> ofBlock...(BW_GlasBlocks, 14, ...); // glass B -> ofBlock...(gt.blockcasings2, 15, ...); C -> ofBlock...(gt.blockcasings4, 14, ...); D -> ofBlock...(gt.blockcasingsTT, 0, ...); // energy E -> ofBlock...(gt.blockcasingsTT, 8, ...); F -> ofBlock...(gt.blockcasings4, 14, ...); // output G -> ofBlock...(gt.blockcasings4, 14, ...); // maintenance H -> ofBlock...(gt.blockcasings4, 14, ...); // input I -> ofFrame...(); */ private final String[][] shapeMain = new String[][]{{ " ", " ", " ", " ", " ", " ", " HHH ", " HHH ", " HHH ", " G~G " },{ "IIIIIIIIIIIIIII", "I FFF I", "I DDD I", "I I", "I I", "I I", "IFD AAA DFI", "IFD A A DFI", "IFD CCC DFI", "CCD DCC" },{ " ", " FFF ", " DED ", " B ", " B ", " B ", " FD AEA DF ", " FEBBBE EBBBEF ", " FD CCC DF ", "CCD DCC" },{ "IIIIIIIIIIIIIII", "I FFF I", "I DDD I", "I I", "I I", "I I", "IFD AAA DFI", "IFD A A DFI", "IFD CCC DFI", "CCD DCC" }}; private final String[][] shapeMiddle = new String[][]{{ " ", " ", " ", " ", " ", " ", " AAA ", " A A ", " CCC ", " " },{ "IIIIIIIIIIIIIII", "I FFF I", "I DDD I", "I I", "I I", "I I", "IFD AAA DFI", "IFD A A DFI", "IFD CCC DFI", "CCD DCC" },{ " ", " FFF ", " DED ", " B ", " B ", " B ", " FD AEA DF ", " FEBBBE EBBBEF ", " FD CCC DF ", "CCD DCC" },{ "IIIIIIIIIIIIIII", "I FFF I", "I DDD I", "I I", "I I", "I I", "IFD AAA DFI", "IFD A A DFI", "IFD CCC DFI", "CCD DCC" }}; private final String[][] shapeEnd = new String[][]{{ " ", " ", " ", " ", " ", " ", " FFF ", " FFF ", " FFF ", " GGG " }}; @Override public boolean addToMachineList(IGregTechTileEntity aTileEntity, int aBaseCasingIndex) { return super.addToMachineList(aTileEntity, aBaseCasingIndex) || addExoticEnergyInputToMachineList(aTileEntity, aBaseCasingIndex); } // spotless:on // endregion // region Overrides @Override public String[] getInfoData() { String[] origin = super.getInfoData(); String[] ret = new String[origin.length + 3]; System.arraycopy(origin, 0, ret, 0, origin.length); ret[origin.length] = EnumChatFormatting.AQUA + "Parallels: " + EnumChatFormatting.GOLD + this.getMaxParallelRecipes(); ret[origin.length + 1] = EnumChatFormatting.AQUA + "Speed multiplier: " + EnumChatFormatting.GOLD + this.getSpeedBonus(); ret[origin.length + 2] = EnumChatFormatting.AQUA + "Pieces: " + EnumChatFormatting.GOLD + this.piece; return ret; } @Override public void saveNBTData(NBTTagCompound aNBT) { super.saveNBTData(aNBT); aNBT.setInteger("piece", piece); aNBT.setByte("mode", mode); } @Override public void loadNBTData(final NBTTagCompound aNBT) { super.loadNBTData(aNBT); piece = aNBT.getInteger("piece"); mode = aNBT.getByte("mode"); } @Override protected GT_Multiblock_Tooltip_Builder createTooltip() { final GT_Multiblock_Tooltip_Builder tt = new GT_Multiblock_Tooltip_Builder(); tt.addMachineType(Tooltip_MoleculeDeconstructor_MachineType) .addInfo(Tooltip_MoleculeDeconstructor_00) .addInfo(Tooltip_MoleculeDeconstructor_01) .addInfo(Tooltip_MoleculeDeconstructor_02) .addInfo(Tooltip_MoleculeDeconstructor_03) .addInfo(Tooltip_MoleculeDeconstructor_04) .addInfo(Tooltip_MoleculeDeconstructor_05)
.addInfo(textScrewdriverChangeMode)
15
2023-10-16 09:57:15+00:00
12k
wyjsonGo/GoRouter
module_common/src/main/java/com/wyjson/router/helper/module_user/group_user/UserCardFragmentGoRouter.java
[ { "identifier": "GoRouter", "path": "GoRouter-Api/src/main/java/com/wyjson/router/GoRouter.java", "snippet": "public final class GoRouter {\n\n private final Handler mHandler = new Handler(Looper.getMainLooper());\n private volatile static ThreadPoolExecutor executor = DefaultPoolExecutor.getInstance();\n public static ILogger logger = new DefaultLogger();\n private volatile static boolean isDebug = false;\n private static Application mApplication;\n\n private GoRouter() {\n InterceptorCenter.clearInterceptors();\n ServiceCenter.addService(InterceptorServiceImpl.class);\n }\n\n private static class InstanceHolder {\n private static final GoRouter mInstance = new GoRouter();\n }\n\n public static GoRouter getInstance() {\n return InstanceHolder.mInstance;\n }\n\n /**\n * 自动加载模块路由\n *\n * @param application\n */\n public static synchronized void autoLoadRouteModule(Application application) {\n setApplication(application);\n logger.info(null, \"[GoRouter] autoLoadRouteModule!\");\n RouteModuleCenter.load(application);\n }\n\n /**\n * 获取路由注册模式\n *\n * @return true [GoRouter-Gradle-Plugin] ,false [scan dex file]\n */\n public boolean isRouteRegisterMode() {\n return RouteModuleCenter.isRegisterByPlugin();\n }\n\n public static synchronized void openDebug() {\n isDebug = true;\n logger.showLog(isDebug);\n logger.info(null, \"[openDebug]\");\n }\n\n public static void setApplication(Application application) {\n mApplication = application;\n }\n\n public static boolean isDebug() {\n return isDebug;\n }\n\n public static synchronized void printStackTrace() {\n logger.showStackTrace(true);\n logger.info(null, \"[printStackTrace]\");\n }\n\n public static synchronized void setExecutor(ThreadPoolExecutor tpe) {\n executor = tpe;\n }\n\n public ThreadPoolExecutor getExecutor() {\n return executor;\n }\n\n public static void setLogger(ILogger userLogger) {\n if (userLogger != null) {\n logger = userLogger;\n }\n }\n\n /**\n * 获取模块application注册模式\n *\n * @return true [GoRouter-Gradle-Plugin] ,false [scan dex file]\n */\n public boolean isAMRegisterMode() {\n return ApplicationModuleCenter.isRegisterByPlugin();\n }\n\n public static void callAMOnCreate(Application application) {\n setApplication(application);\n ApplicationModuleCenter.callOnCreate(application);\n }\n\n public static void callAMOnTerminate() {\n ApplicationModuleCenter.callOnTerminate();\n }\n\n public static void callAMOnConfigurationChanged(@NonNull Configuration newConfig) {\n ApplicationModuleCenter.callOnConfigurationChanged(newConfig);\n }\n\n public static void callAMOnLowMemory() {\n ApplicationModuleCenter.callOnLowMemory();\n }\n\n public static void callAMOnTrimMemory(int level) {\n ApplicationModuleCenter.callOnTrimMemory(level);\n }\n\n /**\n * 动态注册模块application\n *\n * @param am\n */\n public static void registerAM(Class<? extends IApplicationModule> am) {\n ApplicationModuleCenter.register(am);\n }\n\n /**\n * 实现相同接口的service会被覆盖(更新)\n *\n * @param service 实现类.class\n */\n public void addService(Class<? extends IService> service) {\n ServiceCenter.addService(service);\n }\n\n /**\n * 实现相同接口的service会被覆盖(更新)\n *\n * @param service 实现类.class\n * @param alias 别名\n */\n public void addService(Class<? extends IService> service, String alias) {\n ServiceCenter.addService(service, alias);\n }\n\n /**\n * 获取service接口的实现\n *\n * @param service 接口.class\n * @param <T>\n * @return\n */\n @Nullable\n public <T> T getService(Class<? extends T> service) {\n return ServiceCenter.getService(service);\n }\n\n /**\n * 获取service接口的实现\n *\n * @param service\n * @param alias 别名\n * @param <T>\n * @return\n */\n @Nullable\n public <T> T getService(Class<? extends T> service, String alias) {\n return ServiceCenter.getService(service, alias);\n }\n\n /**\n * 重复添加相同序号会catch\n *\n * @param ordinal\n * @param interceptor\n */\n public void addInterceptor(int ordinal, Class<? extends IInterceptor> interceptor) {\n InterceptorCenter.addInterceptor(ordinal, interceptor, false);\n }\n\n /**\n * 重复添加相同序号会覆盖(更新)\n *\n * @param ordinal\n * @param interceptor\n */\n public void setInterceptor(int ordinal, Class<? extends IInterceptor> interceptor) {\n InterceptorCenter.setInterceptor(ordinal, interceptor);\n }\n\n /**\n * 动态添加路由分组,按需加载路由\n */\n public void addRouterGroup(String group, IRouteModuleGroup routeModuleGroup) {\n RouteCenter.addRouterGroup(group, routeModuleGroup);\n }\n\n private void runInMainThread(Runnable runnable) {\n if (Looper.getMainLooper().getThread() != Thread.currentThread()) {\n mHandler.post(runnable);\n } else {\n runnable.run();\n }\n }\n\n public Card build(String path) {\n return build(path, null);\n }\n\n public Card build(String path, Bundle bundle) {\n return new Card(path, bundle);\n }\n\n public Card build(Uri uri) {\n return new Card(uri);\n }\n\n /**\n * 获取原始的URI\n *\n * @param activity\n */\n public String getRawURI(Activity activity) {\n return RouteCenter.getRawURI(activity);\n }\n\n /**\n * 获取原始的URI\n *\n * @param fragment\n */\n public String getRawURI(Fragment fragment) {\n return RouteCenter.getRawURI(fragment);\n }\n\n /**\n * 获取当前页面路径\n *\n * @param activity\n */\n public String getCurrentPath(Activity activity) {\n return RouteCenter.getCurrentPath(activity);\n }\n\n /**\n * 获取当前页面路径\n *\n * @param fragment\n */\n public String getCurrentPath(Fragment fragment) {\n return RouteCenter.getCurrentPath(fragment);\n }\n\n @Deprecated\n public void inject(Activity activity) {\n inject(activity, null, null, false);\n }\n\n @Deprecated\n public void inject(Activity activity, Intent intent) {\n inject(activity, intent, null, false);\n }\n\n @Deprecated\n public void inject(Activity activity, Bundle bundle) {\n inject(activity, null, bundle, false);\n }\n\n @Deprecated\n public void inject(Fragment fragment) {\n inject(fragment, null, null, false);\n }\n\n @Deprecated\n public void inject(Fragment fragment, Intent intent) {\n inject(fragment, intent, null, false);\n }\n\n @Deprecated\n public void inject(Fragment fragment, Bundle bundle) {\n inject(fragment, null, bundle, false);\n }\n\n @Deprecated\n public void injectCheck(Activity activity) throws ParamException {\n inject(activity, null, null, true);\n }\n\n @Deprecated\n public void injectCheck(Activity activity, Intent intent) throws ParamException {\n inject(activity, intent, null, true);\n }\n\n @Deprecated\n public void injectCheck(Activity activity, Bundle bundle) throws ParamException {\n inject(activity, null, bundle, true);\n }\n\n @Deprecated\n public void injectCheck(Fragment fragment) throws ParamException {\n inject(fragment, null, null, true);\n }\n\n @Deprecated\n public void injectCheck(Fragment fragment, Intent intent) throws ParamException {\n inject(fragment, intent, null, true);\n }\n\n @Deprecated\n public void injectCheck(Fragment fragment, Bundle bundle) throws ParamException {\n inject(fragment, null, bundle, true);\n }\n\n @Deprecated\n private <T> void inject(T target, Intent intent, Bundle bundle, boolean isCheck) throws ParamException {\n RouteCenter.inject(target, intent, bundle, isCheck);\n }\n\n @Nullable\n public Object go(Context context, Card card, int requestCode, ActivityResultLauncher<Intent> activityResultLauncher, GoCallback callback) {\n card.setContext(context == null ? mApplication : context);\n card.setInterceptorException(null);\n\n logger.debug(null, \"[go] \" + card);\n\n IPretreatmentService pretreatmentService = getService(IPretreatmentService.class);\n if (pretreatmentService != null) {\n if (!pretreatmentService.onPretreatment(card.getContext(), card)) {\n // 预处理失败,导航取消\n logger.debug(null, \"[go] IPretreatmentService Failure!\");\n return null;\n }\n } else {\n logger.warning(null, \"[go] This [IPretreatmentService] was not found!\");\n }\n\n try {\n RouteCenter.assembleRouteCard(card);\n } catch (NoFoundRouteException e) {\n logger.warning(null, e.getMessage());\n\n if (isDebug()) {\n runInMainThread(() -> Toast.makeText(card.getContext(), \"There's no route matched!\\n\" +\n \" Path = [\" + card.getPath() + \"]\\n\" +\n \" Group = [\" + card.getGroup() + \"]\", Toast.LENGTH_LONG).show());\n }\n\n onLost(card.getContext(), card, callback);\n return null;\n }\n\n runInMainThread(() -> {\n logger.debug(null, \"[go] [onFound] \" + card);\n if (callback != null) {\n callback.onFound(card);\n }\n });\n\n if (isDebug() && card.isDeprecated()) {\n logger.warning(null, \"[go] This page has been marked as deprecated. path[\" + card.getPath() + \"]\");\n runInMainThread(() -> Toast.makeText(card.getContext(), \"This page has been marked as deprecated!\\n\" +\n \" Path = [\" + card.getPath() + \"]\\n\" +\n \" Group = [\" + card.getGroup() + \"]\", Toast.LENGTH_SHORT).show());\n }\n\n switch (card.getType()) {\n case ACTIVITY:\n IInterceptorService interceptorService = getService(IInterceptorService.class);\n if (interceptorService != null && !card.isGreenChannel()) {\n interceptorService.doInterceptions(card, new InterceptorCallback() {\n @Override\n public void onContinue(Card card) {\n goActivity(card.getContext(), card, requestCode, activityResultLauncher, callback);\n }\n\n @Override\n public void onInterrupt(Card card, @NonNull Throwable exception) {\n runInMainThread(() -> {\n if (callback != null) {\n callback.onInterrupt(card, exception);\n }\n });\n }\n });\n } else {\n goActivity(card.getContext(), card, requestCode, activityResultLauncher, callback);\n }\n break;\n case FRAGMENT:\n return goFragment(card, callback);\n }\n return null;\n }\n\n private void onLost(Context context, Card card, GoCallback callback) {\n runInMainThread(() -> {\n logger.error(null, \"[onLost] There is no route. path[\" + card.getPath() + \"]\");\n if (callback != null) {\n callback.onLost(card);\n } else {\n IDegradeService degradeService = getService(IDegradeService.class);\n if (degradeService != null) {\n degradeService.onLost(context, card);\n } else {\n logger.warning(null, \"[onLost] This [IDegradeService] was not found!\");\n }\n }\n });\n }\n\n @SuppressLint(\"WrongConstant\")\n private void goActivity(Context context, Card card, int requestCode, ActivityResultLauncher<Intent> activityResultLauncher, GoCallback callback) {\n Intent intent = new Intent(context, card.getPathClass());\n\n intent.putExtras(card.getExtras());\n\n int flags = card.getFlags();\n if (0 != flags) {\n intent.setFlags(flags);\n }\n\n if (!(context instanceof Activity)) {\n intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);\n }\n\n String action = card.getAction();\n if (!TextUtils.isEmpty(action)) {\n intent.setAction(action);\n }\n\n runInMainThread(() -> {\n ActivityOptionsCompat compat = card.getActivityOptionsCompat();\n if (requestCode >= 0) {\n if (context instanceof Activity) {\n ActivityCompat.startActivityForResult((Activity) context, intent, requestCode, compat != null ? compat.toBundle() : null);\n } else {\n throw new RouterException(\"Must use [go(activity, ...)] to support [startActivityForResult]!\");\n }\n } else if (activityResultLauncher != null) {\n activityResultLauncher.launch(intent, compat);\n } else {\n ActivityCompat.startActivity(context, intent, compat != null ? compat.toBundle() : null);\n }\n\n if ((-1 != card.getEnterAnim() && -1 != card.getExitAnim()) && context instanceof Activity) {\n ((Activity) context).overridePendingTransition(card.getEnterAnim(), card.getExitAnim());\n }\n\n logger.debug(null, \"[goActivity] [onArrival] Complete!\");\n if (callback != null) {\n callback.onArrival(card);\n }\n });\n }\n\n @NonNull\n private Object goFragment(Card card, GoCallback callback) {\n try {\n Object instance = card.getPathClass().getConstructor().newInstance();\n if (instance instanceof Fragment) {\n ((Fragment) instance).setArguments(card.getExtras());\n }\n runInMainThread(() -> {\n logger.debug(null, \"[goFragment] [onArrival] Complete!\");\n if (callback != null) {\n callback.onArrival(card);\n }\n });\n return instance;\n } catch (Exception e) {\n e.printStackTrace();\n throw new RouterException(\"fragment constructor new instance failed!\");\n }\n }\n\n public <T> void registerEvent(FragmentActivity activity, @NonNull Class<T> type, @NonNull Observer<T> observer) {\n EventCenter.registerEvent(activity, type, false, observer);\n }\n\n public <T> void registerEvent(Fragment fragment, @NonNull Class<T> type, @NonNull Observer<T> observer) {\n EventCenter.registerEvent(fragment, type, false, observer);\n }\n\n public <T> void registerEventForever(FragmentActivity activity, @NonNull Class<T> type, @NonNull Observer<T> observer) {\n EventCenter.registerEvent(activity, type, true, observer);\n }\n\n public <T> void registerEventForever(Fragment fragment, @NonNull Class<T> type, @NonNull Observer<T> observer) {\n EventCenter.registerEvent(fragment, type, true, observer);\n }\n\n public <T> void unRegisterEvent(FragmentActivity activity, @NonNull Class<T> type) {\n EventCenter.unRegisterEvent(activity, type, null);\n }\n\n public <T> void unRegisterEvent(Fragment fragment, @NonNull Class<T> type) {\n EventCenter.unRegisterEvent(fragment, type, null);\n }\n\n public <T> void unRegisterEvent(FragmentActivity activity, @NonNull Class<T> type, Observer<T> observer) {\n EventCenter.unRegisterEvent(activity, type, observer);\n }\n\n public <T> void unRegisterEvent(Fragment fragment, @NonNull Class<T> type, Observer<T> observer) {\n EventCenter.unRegisterEvent(fragment, type, observer);\n }\n\n public <T> void postEvent(@NonNull String path, @NonNull T value) {\n EventCenter.postEvent(path, value);\n }\n\n}" }, { "identifier": "Card", "path": "GoRouter-Api/src/main/java/com/wyjson/router/model/Card.java", "snippet": "public final class Card extends CardMeta {\n\n private Uri uri;\n private Bundle mBundle;\n private int flags = 0;\n private boolean greenChannel;// 绿色通道(跳过所有的拦截器)\n private String action;\n private Context context;\n private IJsonService jsonService;\n\n private int enterAnim = -1;// 转场动画\n private int exitAnim = -1;\n private ActivityOptionsCompat activityOptionsCompat;// 转场动画(API16+)\n\n private Throwable interceptorException;// 拦截执行中断异常信息\n private int timeout = 300;// go() timeout, TimeUnit.Second\n\n public void setUri(Uri uri) {\n if (uri == null || TextUtils.isEmpty(uri.toString()) || TextUtils.isEmpty(uri.getPath())) {\n throw new RouterException(\"uri Parameter is invalid!\");\n }\n this.uri = uri;\n setPath(uri.getPath());\n }\n\n public Uri getUri() {\n return uri;\n }\n\n public ActivityOptionsCompat getActivityOptionsCompat() {\n return activityOptionsCompat;\n }\n\n public int getEnterAnim() {\n return enterAnim;\n }\n\n public int getExitAnim() {\n return exitAnim;\n }\n\n public Card(Uri uri) {\n setUri(uri);\n this.mBundle = new Bundle();\n }\n\n public Card(String path, Bundle bundle) {\n setPath(path);\n this.mBundle = (null == bundle ? new Bundle() : bundle);\n }\n\n @Nullable\n public Object go() {\n return go(null, this, -1, null, null);\n }\n\n @Nullable\n public Object go(Context context) {\n return go(context, this, -1, null, null);\n }\n\n @Nullable\n public Object go(Context context, GoCallback callback) {\n return go(context, this, -1, null, callback);\n }\n\n @Nullable\n public Object go(Context context, int requestCode) {\n return go(context, this, requestCode, null, null);\n }\n\n @Nullable\n public Object go(Context context, int requestCode, GoCallback callback) {\n return go(context, this, requestCode, null, callback);\n }\n\n @Nullable\n public Object go(Context context, ActivityResultLauncher<Intent> activityResultLauncher) {\n return go(context, this, -1, activityResultLauncher, null);\n }\n\n @Nullable\n public Object go(Context context, ActivityResultLauncher<Intent> activityResultLauncher, GoCallback callback) {\n return go(context, this, -1, activityResultLauncher, callback);\n }\n\n @Nullable\n private Object go(Context context, Card card, int requestCode, ActivityResultLauncher<Intent> activityResultLauncher, GoCallback callback) {\n return GoRouter.getInstance().go(context, card, requestCode, activityResultLauncher, callback);\n }\n\n @Nullable\n public CardMeta getCardMeta() {\n try {\n return RouteCenter.getCardMeta(this);\n } catch (NoFoundRouteException e) {\n GoRouter.logger.warning(null, e.getMessage());\n }\n return null;\n }\n\n public void setCardMeta(RouteType type, Class<?> pathClass, int tag, boolean deprecated) {\n setType(type);\n setPathClass(pathClass);\n setTag(tag);\n setDeprecated(deprecated);\n }\n\n public Bundle getExtras() {\n return mBundle;\n }\n\n public Card with(Bundle bundle) {\n if (null != bundle) {\n mBundle = bundle;\n }\n return this;\n }\n\n public Card withFlags(int flag) {\n this.flags = flag;\n return this;\n }\n\n public Card addFlags(int flags) {\n this.flags |= flags;\n return this;\n }\n\n public int getFlags() {\n return flags;\n }\n\n /**\n * 使用 withObject 传递 List 和 Map 的实现了 Serializable 接口的实现类(ArrayList/HashMap)的时候,\n * 接收该对象的地方不能标注具体的实现类类型应仅标注为 List 或 Map,\n * 否则会影响序列化中类型的判断, 其他类似情况需要同样处理\n *\n * @param key\n * @param value\n * @return\n */\n public Card withObject(@Nullable String key, @Nullable Object value) {\n jsonService = GoRouter.getInstance().getService(IJsonService.class);\n if (jsonService == null) {\n throw new RouterException(\"To use withObject() method, you need to implement IJsonService\");\n }\n mBundle.putString(key, jsonService.toJson(value));\n return this;\n }\n\n public Card withString(@Nullable String key, @Nullable String value) {\n mBundle.putString(key, value);\n return this;\n }\n\n public Card withBoolean(@Nullable String key, boolean value) {\n mBundle.putBoolean(key, value);\n return this;\n }\n\n public Card withShort(@Nullable String key, short value) {\n mBundle.putShort(key, value);\n return this;\n }\n\n public Card withInt(@Nullable String key, int value) {\n mBundle.putInt(key, value);\n return this;\n }\n\n public Card withLong(@Nullable String key, long value) {\n mBundle.putLong(key, value);\n return this;\n }\n\n public Card withDouble(@Nullable String key, double value) {\n mBundle.putDouble(key, value);\n return this;\n }\n\n public Card withByte(@Nullable String key, byte value) {\n mBundle.putByte(key, value);\n return this;\n }\n\n public Card withChar(@Nullable String key, char value) {\n mBundle.putChar(key, value);\n return this;\n }\n\n public Card withFloat(@Nullable String key, float value) {\n mBundle.putFloat(key, value);\n return this;\n }\n\n public Card withCharSequence(@Nullable String key, @Nullable CharSequence value) {\n mBundle.putCharSequence(key, value);\n return this;\n }\n\n public Card withParcelable(@Nullable String key, @Nullable Parcelable value) {\n mBundle.putParcelable(key, value);\n return this;\n }\n\n public Card withParcelableArray(@Nullable String key, @Nullable Parcelable[] value) {\n mBundle.putParcelableArray(key, value);\n return this;\n }\n\n public Card withParcelableArrayList(@Nullable String key, @Nullable ArrayList<? extends Parcelable> value) {\n mBundle.putParcelableArrayList(key, value);\n return this;\n }\n\n public Card withSparseParcelableArray(@Nullable String key, @Nullable SparseArray<? extends Parcelable> value) {\n mBundle.putSparseParcelableArray(key, value);\n return this;\n }\n\n public Card withIntegerArrayList(@Nullable String key, @Nullable ArrayList<Integer> value) {\n mBundle.putIntegerArrayList(key, value);\n return this;\n }\n\n public Card withStringArrayList(@Nullable String key, @Nullable ArrayList<String> value) {\n mBundle.putStringArrayList(key, value);\n return this;\n }\n\n public Card withCharSequenceArrayList(@Nullable String key, @Nullable ArrayList<CharSequence> value) {\n mBundle.putCharSequenceArrayList(key, value);\n return this;\n }\n\n public Card withSerializable(@Nullable String key, @Nullable Serializable value) {\n mBundle.putSerializable(key, value);\n return this;\n }\n\n public Card withByteArray(@Nullable String key, @Nullable byte[] value) {\n mBundle.putByteArray(key, value);\n return this;\n }\n\n public Card withShortArray(@Nullable String key, @Nullable short[] value) {\n mBundle.putShortArray(key, value);\n return this;\n }\n\n public Card withCharArray(@Nullable String key, @Nullable char[] value) {\n mBundle.putCharArray(key, value);\n return this;\n }\n\n public Card withLongArray(@Nullable String key, @Nullable long[] value) {\n mBundle.putLongArray(key, value);\n return this;\n }\n\n public Card withIntArray(@Nullable String key, @Nullable int[] value) {\n mBundle.putIntArray(key, value);\n return this;\n }\n\n public Card withDoubleArray(@Nullable String key, @Nullable double[] value) {\n mBundle.putDoubleArray(key, value);\n return this;\n }\n\n public Card withBooleanArray(@Nullable String key, @Nullable boolean[] value) {\n mBundle.putBooleanArray(key, value);\n return this;\n }\n\n public Card withStringArray(@Nullable String key, @Nullable String[] value) {\n mBundle.putStringArray(key, value);\n return this;\n }\n\n public Card withFloatArray(@Nullable String key, @Nullable float[] value) {\n mBundle.putFloatArray(key, value);\n return this;\n }\n\n public Card withCharSequenceArray(@Nullable String key, @Nullable CharSequence[] value) {\n mBundle.putCharSequenceArray(key, value);\n return this;\n }\n\n public Card withBundle(@Nullable String key, @Nullable Bundle value) {\n mBundle.putBundle(key, value);\n return this;\n }\n\n public Card withTransition(int enterAnim, int exitAnim) {\n this.enterAnim = enterAnim;\n this.exitAnim = exitAnim;\n return this;\n }\n\n @RequiresApi(16)\n public Card withActivityOptionsCompat(ActivityOptionsCompat compat) {\n this.activityOptionsCompat = compat;\n return this;\n }\n\n public String getAction() {\n return action;\n }\n\n public Card withAction(String action) {\n this.action = action;\n return this;\n }\n\n public Context getContext() {\n return context;\n }\n\n public void setContext(Context context) {\n if (context == null) {\n throw new RouterException(\"Context cannot be empty, Call 'GoRouter.setApplication(...)' in application.\");\n }\n this.context = context;\n }\n\n public boolean isGreenChannel() {\n return greenChannel;\n }\n\n public Card greenChannel() {\n this.greenChannel = true;\n return this;\n }\n\n public Throwable getInterceptorException() {\n return interceptorException;\n }\n\n public void setInterceptorException(Throwable interceptorException) {\n this.interceptorException = interceptorException;\n }\n\n public int getTimeout() {\n return timeout;\n }\n\n /**\n * @param timeout Second\n */\n public Card setTimeout(int timeout) {\n this.timeout = timeout;\n return this;\n }\n\n @NonNull\n @Override\n public String toString() {\n if (!GoRouter.isDebug()) {\n return \"\";\n }\n return \"Card{\" +\n \"path='\" + getPath() + '\\'' +\n \", uri=\" + uri +\n \", mBundle=\" + mBundle +\n \", flags=\" + flags +\n \", greenChannel=\" + greenChannel +\n \", action='\" + action + '\\'' +\n \", context=\" + (context != null ? context.getClass().getSimpleName() : null) +\n \", optionsCompat=\" + activityOptionsCompat +\n \", enterAnim=\" + enterAnim +\n \", exitAnim=\" + exitAnim +\n \", interceptorException=\" + interceptorException +\n \", timeout=\" + timeout +\n '}';\n }\n}" }, { "identifier": "CardMeta", "path": "GoRouter-Api/src/main/java/com/wyjson/router/model/CardMeta.java", "snippet": "public class CardMeta {\n private String path;\n private String group;\n private RouteType type;\n private Class<?> pathClass;\n private int tag;// 额外的标记\n private boolean deprecated;\n private Map<String, ParamMeta> paramsType;// <字段名, 参数元数据对象>\n\n protected CardMeta() {\n }\n\n public CardMeta(String path, RouteType type, Class<?> pathClass, int tag, boolean deprecated, Map<String, ParamMeta> paramsType) {\n setPath(path);\n this.type = type;\n this.pathClass = pathClass;\n this.tag = tag;\n this.deprecated = deprecated;\n this.paramsType = paramsType;\n }\n\n @Nullable\n public String getPath() {\n return path;\n }\n\n public void setPath(@NonNull String path) {\n if (TextUtils.isEmpty(path)) {\n throw new RouterException(\"path Parameter is invalid!\");\n }\n this.path = path;\n this.group = extractGroup(path);\n }\n\n public String getGroup() {\n return group;\n }\n\n private String extractGroup(String path) {\n if (TextUtils.isEmpty(path) || !path.startsWith(\"/\")) {\n throw new RouterException(\"Extract the path[\" + path + \"] group failed, the path must be start with '/' and contain more than 2 '/'!\");\n }\n\n try {\n String group = path.substring(1, path.indexOf(\"/\", 1));\n if (TextUtils.isEmpty(group)) {\n throw new RouterException(\"Extract the path[\" + path + \"] group failed! There's nothing between 2 '/'!\");\n } else {\n return group;\n }\n } catch (Exception e) {\n throw new RouterException(\"Extract the path[\" + path + \"] group failed, the path must be start with '/' and contain more than 2 '/'! \" + e.getMessage());\n }\n }\n\n\n public RouteType getType() {\n return type;\n }\n\n void setType(RouteType type) {\n this.type = type;\n }\n\n public Class<?> getPathClass() {\n return pathClass;\n }\n\n void setPathClass(Class<?> pathClass) {\n this.pathClass = pathClass;\n }\n\n public int getTag() {\n return tag;\n }\n\n void setTag(int tag) {\n this.tag = tag;\n }\n\n public boolean isDeprecated() {\n return deprecated;\n }\n\n void setDeprecated(boolean deprecated) {\n this.deprecated = deprecated;\n }\n\n public Map<String, ParamMeta> getParamsType() {\n if (paramsType == null) {\n paramsType = new HashMap<>();\n }\n return paramsType;\n }\n\n public void commitActivity(@NonNull Class<?> cls) {\n commit(cls, RouteType.ACTIVITY);\n }\n\n public void commitFragment(@NonNull Class<?> cls) {\n commit(cls, RouteType.FRAGMENT);\n }\n\n private void commit(Class<?> cls, RouteType type) {\n if (cls == null) {\n throw new RouterException(\"Cannot commit empty!\");\n }\n RouteCenter.addCardMeta(new CardMeta(this.path, type, cls, this.tag, this.deprecated, this.paramsType));\n }\n\n public CardMeta putTag(int tag) {\n this.tag = tag;\n return this;\n }\n\n /**\n * @param deprecated 如果标记为true,框架在openDebug()的情况下,跳转到该页将提示其他开发人员和测试人员\n * @return\n */\n public CardMeta putDeprecated(boolean deprecated) {\n this.deprecated = deprecated;\n return this;\n }\n\n public CardMeta putObject(String key) {\n return put(key, null, ParamType.Object, false);\n }\n\n public CardMeta putObject(String key, String name, boolean required) {\n return put(key, name, ParamType.Object, required);\n }\n\n public CardMeta putString(String key) {\n return put(key, null, ParamType.String, false);\n }\n\n public CardMeta putString(String key, String name, boolean required) {\n return put(key, name, ParamType.String, required);\n }\n\n public CardMeta putBoolean(String key) {\n return put(key, null, ParamType.Boolean, false);\n }\n\n public CardMeta putBoolean(String key, String name, boolean required) {\n return put(key, name, ParamType.Boolean, required);\n }\n\n public CardMeta putShort(String key) {\n return put(key, null, ParamType.Short, false);\n }\n\n public CardMeta putShort(String key, String name, boolean required) {\n return put(key, name, ParamType.Short, required);\n }\n\n public CardMeta putInt(String key) {\n return put(key, null, ParamType.Int, false);\n }\n\n public CardMeta putInt(String key, String name, boolean required) {\n return put(key, name, ParamType.Int, required);\n }\n\n public CardMeta putLong(String key) {\n return put(key, null, ParamType.Long, false);\n }\n\n public CardMeta putLong(String key, String name, boolean required) {\n return put(key, name, ParamType.Long, required);\n }\n\n public CardMeta putDouble(String key) {\n return put(key, null, ParamType.Double, false);\n }\n\n public CardMeta putDouble(String key, String name, boolean required) {\n return put(key, name, ParamType.Double, required);\n }\n\n public CardMeta putByte(String key) {\n return put(key, null, ParamType.Byte, false);\n }\n\n public CardMeta putByte(String key, String name, boolean required) {\n return put(key, name, ParamType.Byte, required);\n }\n\n public CardMeta putChar(String key) {\n return put(key, null, ParamType.Char, false);\n }\n\n public CardMeta putChar(String key, String name, boolean required) {\n return put(key, name, ParamType.Char, required);\n }\n\n public CardMeta putFloat(String key) {\n return put(key, null, ParamType.Float, false);\n }\n\n public CardMeta putFloat(String key, String name, boolean required) {\n return put(key, name, ParamType.Float, required);\n }\n\n public CardMeta putSerializable(String key) {\n return put(key, null, ParamType.Serializable, false);\n }\n\n public CardMeta putSerializable(String key, String name, boolean required) {\n return put(key, name, ParamType.Serializable, required);\n }\n\n public CardMeta putParcelable(String key) {\n return put(key, null, ParamType.Parcelable, false);\n }\n\n public CardMeta putParcelable(String key, String name, boolean required) {\n return put(key, name, ParamType.Parcelable, required);\n }\n\n private CardMeta put(String key, String name, ParamType type, boolean required) {\n getParamsType().put(key, new ParamMeta(TextUtils.isEmpty(name) ? key : name, type, required));\n return this;\n }\n\n public boolean isTagExist(int item) {\n return RouteTagUtils.isExist(tag, item);\n }\n\n public int getTagExistCount() {\n return RouteTagUtils.getExistCount(tag);\n }\n\n public int addTag(int item) {\n return tag = RouteTagUtils.addItem(tag, item);\n }\n\n public int deleteTag(int item) {\n return tag = RouteTagUtils.deleteItem(tag, item);\n }\n\n public int getTagNegation() {\n return RouteTagUtils.getNegation(tag);\n }\n\n public ArrayList<Integer> getTagExistList(int... itemList) {\n return RouteTagUtils.getExistList(tag, itemList);\n }\n\n @NonNull\n public String toString() {\n if (!GoRouter.isDebug()) {\n return \"\";\n }\n return \"CardMeta{\" +\n \"path='\" + path + '\\'' +\n \", type=\" + type +\n \", pathClass=\" + pathClass +\n \", tag=\" + tag +\n \", paramsType=\" + paramsType +\n '}';\n }\n}" } ]
import androidx.fragment.app.Fragment; import com.wyjson.router.GoRouter; import com.wyjson.router.model.Card; import com.wyjson.router.model.CardMeta; import java.lang.String;
8,893
package com.wyjson.router.helper.module_user.group_user; /** * DO NOT EDIT THIS FILE!!! IT WAS GENERATED BY GOROUTER. * 卡片片段 * {@link com.wyjson.module_user.fragment.CardFragment} */ public class UserCardFragmentGoRouter { public static String getPath() { return "/user/card/fragment"; } public static CardMeta getCardMeta() {
package com.wyjson.router.helper.module_user.group_user; /** * DO NOT EDIT THIS FILE!!! IT WAS GENERATED BY GOROUTER. * 卡片片段 * {@link com.wyjson.module_user.fragment.CardFragment} */ public class UserCardFragmentGoRouter { public static String getPath() { return "/user/card/fragment"; } public static CardMeta getCardMeta() {
return GoRouter.getInstance().build(getPath()).getCardMeta();
0
2023-10-18 13:52:07+00:00
12k
trpc-group/trpc-java
trpc-registry/trpc-registry-api/src/main/java/com/tencent/trpc/registry/util/RegistryCenterCache.java
[ { "identifier": "URL_SEPARATOR", "path": "trpc-registry/trpc-registry-api/src/main/java/com/tencent/trpc/registry/common/Constants.java", "snippet": "public static final String URL_SEPARATOR = \",\";" }, { "identifier": "NamedThreadFactory", "path": "trpc-core/src/main/java/com/tencent/trpc/core/common/NamedThreadFactory.java", "snippet": "public class NamedThreadFactory implements ThreadFactory {\n\n protected static final AtomicInteger COUNTER = new AtomicInteger(1);\n protected final AtomicInteger threadNum = new AtomicInteger(1);\n protected final String prefix;\n protected final boolean daemon;\n protected final ThreadGroup group;\n private UncaughtExceptionHandler uncaughtExceptionHandler;\n\n public NamedThreadFactory() {\n this(\"pool-\" + COUNTER.getAndIncrement(), false, null);\n }\n\n public NamedThreadFactory(String prefix) {\n this(prefix, false, null);\n }\n\n public NamedThreadFactory(String prefix, boolean daemon) {\n this(prefix, daemon, null);\n }\n\n public NamedThreadFactory(String prefix, boolean daemon, UncaughtExceptionHandler uncaughtExceptionHandler) {\n this.prefix = prefix + \"-thread-\";\n this.daemon = daemon;\n SecurityManager s = System.getSecurityManager();\n this.group = (s == null) ? Thread.currentThread().getThreadGroup() : s.getThreadGroup();\n this.uncaughtExceptionHandler = uncaughtExceptionHandler;\n }\n\n @Override\n public Thread newThread(Runnable runnable) {\n String name = prefix + threadNum.getAndIncrement();\n Thread ret = new Thread(group, runnable, name, 0);\n ret.setUncaughtExceptionHandler(uncaughtExceptionHandler);\n ret.setDaemon(daemon);\n return ret;\n }\n\n public ThreadGroup getThreadGroup() {\n return group;\n }\n\n}" }, { "identifier": "Logger", "path": "trpc-core/src/main/java/com/tencent/trpc/core/logger/Logger.java", "snippet": "@SuppressWarnings(\"unchecked\")\npublic interface Logger {\n\n void trace(String msg);\n\n void trace(String format, Object... argArray);\n\n void trace(String msg, Throwable e);\n\n void debug(String msg);\n\n void debug(String format, Object... argArray);\n\n void debug(String msg, Throwable e);\n\n void info(String msg);\n\n void info(String format, Object... argArray);\n\n void info(String msg, Throwable e);\n\n void warn(String msg);\n\n void warn(String format, Object... argArray);\n\n void warn(String msg, Throwable e);\n\n void error(String msg);\n\n void error(String format, Object... argArray);\n\n void error(String msg, Throwable e);\n\n boolean isTraceEnabled();\n\n boolean isDebugEnabled();\n\n boolean isInfoEnabled();\n\n boolean isWarnEnabled();\n\n boolean isErrorEnabled();\n\n String getName();\n\n}" }, { "identifier": "LoggerFactory", "path": "trpc-core/src/main/java/com/tencent/trpc/core/logger/LoggerFactory.java", "snippet": "@SuppressWarnings(\"unchecked\")\npublic class LoggerFactory {\n\n private static final ConcurrentMap<String, Logger> LOCAL_LOGGERS = new ConcurrentHashMap<>();\n\n private static final ConcurrentMap<String, RemoteLogger> REMOTE_LOGGERS =\n new ConcurrentHashMap<>();\n\n private static LoggerAdapter loggerAdapter;\n\n static {\n loggerAdapter = new Slf4jLoggerAdapter();\n Logger logger = getLogger(LoggerFactory.class);\n if (logger.isDebugEnabled() || logger.isTraceEnabled()) {\n TrpcMDCAdapter.init();\n }\n }\n\n public static Logger getLogger(Class<?> key) {\n return LOCAL_LOGGERS.computeIfAbsent(key.getName(), name -> loggerAdapter.getLogger(name));\n }\n\n public static Logger getLogger(String name) {\n return LOCAL_LOGGERS.computeIfAbsent(name, keyname -> loggerAdapter.getLogger(keyname));\n }\n\n public static RemoteLogger getRemoteLogger(String name) {\n ExtensionLoader<?> extensionLoader = ExtensionLoader.getExtensionLoader(RemoteLoggerAdapter.class);\n RemoteLoggerAdapter remoteLoggerAdapter = (RemoteLoggerAdapter) extensionLoader.getExtension(name);\n return REMOTE_LOGGERS.computeIfAbsent(name, keyname -> remoteLoggerAdapter.getRemoteLogger());\n }\n\n public static LoggerLevel getLoggerLevel() {\n return loggerAdapter.getLoggerLevel();\n }\n\n public static void setLoggerLevel(LoggerLevel loggerLevel) {\n loggerAdapter.setLoggerLevel(loggerLevel);\n }\n}" }, { "identifier": "RegisterInfo", "path": "trpc-core/src/main/java/com/tencent/trpc/core/registry/RegisterInfo.java", "snippet": "public class RegisterInfo implements Comparable<RegisterInfo>, Serializable, Cloneable {\n\n private static final long serialVersionUID = -5770826614635186498L;\n /**\n * Regular expression for separator。The regular expression should match one or more words or phrases separated\n * by commas. For example, in the string \"apple, banana, orange\", the words \"apple\", \"banana\", and \"orange\"\n * will be matched.\n */\n private static Pattern COMMA_SPLIT_PATTERN = Pattern.compile(\"\\\\s*[,]+\\\\s*\");\n private final String protocol;\n private final String host;\n private final int port;\n private final String serviceName;\n private final Map<String, Object> parameters;\n /**\n * Service group\n **/\n private final String group;\n /**\n * Service version\n **/\n private final String version;\n private transient volatile String identity;\n private transient volatile Map<String, Number> numbers;\n\n public RegisterInfo() {\n this.protocol = null;\n this.host = null;\n this.port = 0;\n this.group = null;\n this.version = null;\n this.serviceName = null;\n this.parameters = null;\n }\n\n public RegisterInfo(String protocol, String host, int port) {\n this(protocol, host, port, null, null, null, (Map<String, Object>) null);\n }\n\n public RegisterInfo(String protocol, String host, int port, String serviceName) {\n this(protocol, host, port, serviceName, null, null, (Map<String, Object>) null);\n }\n\n\n public RegisterInfo(String protocol, String host, int port, String serviceName,\n Map<String, Object> parameters) {\n this(protocol, host, port, serviceName, null, null, parameters);\n }\n\n public RegisterInfo(String protocol, String host, int port, String serviceName, String group,\n Map<String, Object> parameters) {\n this(protocol, host, port, serviceName, group, null, null);\n }\n\n public RegisterInfo(String protocol, String host, int port, String group, String version, String serviceName) {\n this(protocol, host, port, serviceName, group, version, null);\n }\n\n public RegisterInfo(String protocol, String host, int port, String serviceName, String group,\n String version, Map<String, Object> parameters) {\n this.protocol = protocol;\n this.host = host;\n this.port = Math.max(port, 0);\n this.serviceName = serviceName;\n this.version = version;\n this.group = group;\n if (parameters == null) {\n parameters = new HashMap<>();\n }\n this.parameters = parameters;\n }\n\n /**\n * Decode from URL format to RegisterInfo\n *\n * @param path URL string\n * @return RegisterInfo object\n */\n public static RegisterInfo decode(String path) {\n try {\n path = URLDecoder.decode(path, \"UTF-8\");\n } catch (UnsupportedEncodingException e) {\n throw new IllegalStateException(\"registerInfo\" + path + \" can not encode to registerInfo\", e);\n }\n Map<String, Object> params = new HashMap<>();\n int i = path.indexOf(\"?\");\n if (i >= 0) {\n String[] parts = path.substring(i + 1).split(\"&\");\n for (String part : parts) {\n part = part.trim();\n if (part.length() > 0) {\n int j = part.indexOf('=');\n if (j >= 0) {\n params.put(part.substring(0, j), part.substring(j + 1));\n } else {\n params.put(part, part);\n }\n }\n }\n path = path.substring(0, i);\n }\n i = path.indexOf(\"://\");\n if (i <= 0) {\n throw new IllegalStateException(\"path missing protocol: \\\"\" + path + \"\\\"\");\n }\n final String protocol = path.substring(0, i);\n path = path.substring(i + 3);\n i = path.indexOf(\"/\");\n if (i <= 0) {\n throw new IllegalStateException(\"path missing serviceName: \\\"\" + path + \"\\\"\");\n }\n final String serviceName = path.substring(i + 1);\n path = path.substring(0, i);\n i = path.indexOf(\":\");\n if (i <= 0) {\n throw new IllegalStateException(\"path missing host and port: \\\"\" + path + \"\\\"\");\n }\n final String host = path.substring(0, i);\n int port = Integer.parseInt(path.substring(i + 1));\n return new RegisterInfo(protocol, host, port, serviceName, params);\n }\n\n /**\n * Encode into URL string\n *\n * @param registerInfo RegisterInfo object\n * @return URL string\n */\n public static String encode(RegisterInfo registerInfo) {\n if (registerInfo == null) {\n return \"\";\n }\n try {\n Map<String, Object> parameters = registerInfo.getParameters();\n String[] params = null;\n if (parameters != null) {\n params = parameters.keySet().toArray(new String[0]);\n }\n String url = registerInfo.buildString(true, true, true, params);\n return URLEncoder.encode(url, \"UTF-8\");\n } catch (UnsupportedEncodingException e) {\n throw new IllegalStateException(\n \"registerInfo\" + registerInfo + \" can not encode to url\", e);\n }\n }\n\n public String getProtocol() {\n return protocol;\n }\n\n public String getServiceName() {\n return serviceName;\n }\n\n public String getIdentity() {\n return identity;\n }\n\n public String getHost() {\n return host;\n }\n\n public int getPort() {\n return port;\n }\n\n public int getPort(int defaultPort) {\n return port <= 0 ? defaultPort : port;\n }\n\n public String getAddress() {\n return port <= 0 ? host : host + \":\" + port;\n }\n\n public Map<String, Object> getParameters() {\n return parameters;\n }\n\n public String getGroup() {\n return group;\n }\n\n public String getVersion() {\n return version;\n }\n\n public Object getObject(String key) {\n return parameters.get(key);\n }\n\n public String getParameter(String key) {\n Object value = parameters.get(key);\n if (value != null) {\n return value.toString();\n }\n return null;\n }\n\n public String getParameter(String key, String defaultValue) {\n String value = getParameter(key);\n if (value == null || value.length() == 0) {\n return defaultValue;\n }\n return value;\n }\n\n public String[] getParameter(String key, String[] defaultValue) {\n String value = getParameter(key);\n if (value == null || value.length() == 0) {\n return defaultValue;\n }\n return COMMA_SPLIT_PATTERN.split(value);\n }\n\n public double getParameter(String key, double defaultValue) {\n Number n = getNumbers().get(key);\n if (n != null) {\n return n.doubleValue();\n }\n String value = getParameter(key);\n if (value == null || value.length() == 0) {\n return defaultValue;\n }\n double d = Double.parseDouble(value);\n getNumbers().put(key, d);\n return d;\n }\n\n public float getParameter(String key, float defaultValue) {\n Number n = getNumbers().get(key);\n if (n != null) {\n return n.floatValue();\n }\n String value = getParameter(key);\n if (value == null || value.length() == 0) {\n return defaultValue;\n }\n float f = Float.parseFloat(value);\n getNumbers().put(key, f);\n return f;\n }\n\n public long getParameter(String key, long defaultValue) {\n Number n = getNumbers().get(key);\n if (n != null) {\n return n.longValue();\n }\n String value = getParameter(key);\n if (value == null || value.length() == 0) {\n return defaultValue;\n }\n long l = Long.parseLong(value);\n getNumbers().put(key, l);\n return l;\n }\n\n public int getParameter(String key, int defaultValue) {\n Number n = getNumbers().get(key);\n if (n != null) {\n return n.intValue();\n }\n String value = getParameter(key);\n if (value == null || value.length() == 0) {\n return defaultValue;\n }\n int i = Integer.parseInt(value);\n getNumbers().put(key, i);\n return i;\n }\n\n public short getParameter(String key, short defaultValue) {\n Number n = getNumbers().get(key);\n if (n != null) {\n return n.shortValue();\n }\n String value = getParameter(key);\n if (value == null || value.length() == 0) {\n return defaultValue;\n }\n short s = Short.parseShort(value);\n getNumbers().put(key, s);\n return s;\n }\n\n public byte getParameter(String key, byte defaultValue) {\n Number n = getNumbers().get(key);\n if (n != null) {\n return n.byteValue();\n }\n String value = getParameter(key);\n if (value == null || value.length() == 0) {\n return defaultValue;\n }\n byte b = Byte.parseByte(value);\n getNumbers().put(key, b);\n return b;\n }\n\n public boolean getParameter(String key, boolean defaultValue) {\n String value = getParameter(key);\n if (value == null || value.length() == 0) {\n return defaultValue;\n }\n return Boolean.parseBoolean(value);\n }\n\n private Map<String, Number> getNumbers() {\n if (numbers == null) {\n numbers = new ConcurrentHashMap<String, Number>();\n }\n return numbers;\n }\n\n public String toIdentityString() {\n if (identity != null) {\n return identity;\n }\n identity = buildString(true, true, false);\n return identity;\n }\n\n /**\n * Build into URL string\n *\n * @param appendIpPort Whether to concatenate IP and port\n * @param appendService Whether to concatenate service name\n * @param appendParameter Whether to concatenate parameters\n * @param params List of parameters to be concatenated\n * @return URL string\n */\n public String buildString(boolean appendIpPort, boolean appendService, boolean appendParameter,\n String... params) {\n StringBuilder buf = new StringBuilder();\n if (StringUtils.isNotEmpty(protocol)) {\n buf.append(protocol);\n buf.append(\"://\");\n }\n if (appendIpPort && StringUtils.isNotEmpty(host)) {\n buf.append(host);\n if (port > 0) {\n buf.append(\":\");\n buf.append(port);\n }\n }\n\n if (appendService && StringUtils.isNotEmpty(serviceName)) {\n buf.append(\"/\").append(serviceName);\n }\n\n if (appendParameter) {\n String paramStr = buildParameters(parameters, params);\n if (StringUtils.isNotEmpty(paramStr)) {\n buf.append(\"?\").append(paramStr);\n }\n }\n return buf.toString();\n }\n\n private String buildParameters(Map<String, Object> parameters, String[] params) {\n StringBuilder paramStr = new StringBuilder();\n if (!ArrayUtils.isEmpty(params)) {\n List<String> paramList = Arrays.asList(params);\n for (Map.Entry<String, Object> entry : new TreeMap<>(parameters).entrySet()) {\n if (entry.getKey() != null && paramList.contains(entry.getKey())) {\n paramStr.append(\"&\").append(entry.getKey()).append(\"=\");\n paramStr.append(\n entry.getValue() == null ? \"\" : entry.getValue().toString().trim());\n }\n }\n }\n int startIndex = \"&\".length();\n if (paramStr.length() > 0) {\n return paramStr.substring(startIndex);\n } else {\n return paramStr.toString();\n }\n }\n\n @Override\n public int hashCode() {\n final int prime = 31;\n int result = 1;\n result = prime * result + ((host == null) ? 0 : host.hashCode());\n result = prime * result + ((parameters == null) ? 0 : parameters.hashCode());\n result = prime * result + ((serviceName == null) ? 0 : serviceName.hashCode());\n result = prime * result + port;\n result = prime * result + ((protocol == null) ? 0 : protocol.hashCode());\n return result;\n }\n\n @Override\n public boolean equals(Object obj) {\n if (this == obj) {\n return true;\n }\n if (obj == null) {\n return false;\n }\n if (getClass() != obj.getClass()) {\n return false;\n }\n RegisterInfo other = (RegisterInfo) obj;\n return compareObj(host, other.host) && compareObj(parameters, other.parameters)\n && compareObj(serviceName, other.serviceName) && compareObj(protocol, other.protocol)\n && port == other.port;\n }\n\n private boolean compareObj(Object obj, Object other) {\n if (obj == null && other == null) {\n return true;\n }\n if (obj == null || other == null) {\n return false;\n }\n // The decoded parameter is a string that needs to be processed specially.\n // It needs to be converted to a string before comparison.\n if (obj instanceof Map && other instanceof Map) {\n Map<String, Object> objMap = (Map<String, Object>) obj;\n Map<String, Object> otherMap = (Map<String, Object>) other;\n String[] objParams = objMap.keySet().toArray(new String[0]);\n String[] otherParams = otherMap.keySet().toArray(new String[0]);\n return objMap.size() == otherMap.size()\n && buildParameters(objMap, objParams)\n .equals(buildParameters(otherMap, otherParams));\n }\n return obj.equals(other);\n }\n\n @Override\n public int compareTo(RegisterInfo registerInfo) {\n int i = host.compareTo(registerInfo.host);\n if (i == 0) {\n i = (Integer.compare(port, registerInfo.port));\n }\n return i;\n }\n\n @Override\n public String toString() {\n return \"ServiceInstance{\" + \"protocol='\" + protocol + '\\'' + \", host='\" + host + '\\''\n + \", port=\" + port + \", serviceName='\" + serviceName + '\\'' + \", parameters=\"\n + parameters\n + \", identity='\" + identity + '\\'' + \", numbers=\" + numbers + '}';\n }\n\n public RegisterInfo clone() {\n RegisterInfo registerInfo = new RegisterInfo(protocol, host, port, serviceName, group,\n version, new HashMap<>(parameters));\n return registerInfo;\n }\n\n}" }, { "identifier": "RegistryCenterConfig", "path": "trpc-registry/trpc-registry-api/src/main/java/com/tencent/trpc/registry/common/RegistryCenterConfig.java", "snippet": "public class RegistryCenterConfig {\n\n /**\n * Registry name.\n */\n protected String name;\n\n /**\n * Registry address. Multiple addresses are separated by commas.\n */\n protected String addresses;\n\n /**\n * Username for the registry.\n */\n protected String username;\n\n /**\n * Password for the registry.\n */\n protected String password;\n\n /**\n * Connection timeout for the registry.\n */\n protected int connTimeoutMs;\n\n /**\n * Enable retry logic for registry operations. Enabled by default.\n */\n protected boolean openFailedRetry;\n\n /**\n * Time interval for retrying failed registry operations.\n */\n protected int retryPeriod;\n\n /**\n * Number of times to retry failed registry operations.\n */\n protected int retryTimes;\n\n /**\n * Enable persistent local caching. Disabled by default.\n */\n protected boolean persistedSaveCache;\n\n /**\n * Synchronization mode for persistent local caching. Asynchronous by default.\n */\n protected boolean syncedSaveCache;\n\n /**\n * Expiration time for persistent caching.\n */\n protected int cacheAliveTimeSecs;\n\n /**\n * The path to the cache file.\n */\n protected String cacheFilePath;\n /**\n * Whether to register a consumer.\n */\n private boolean registerConsumer;\n\n public RegistryCenterConfig() {\n }\n\n /**\n * Build the registry configuration item, converted from pluginConfig passed by the framework.\n *\n * @param pluginConfig The registry configuration passed by the framework.\n */\n public RegistryCenterConfig(PluginConfig pluginConfig) {\n Map<String, Object> properties = pluginConfig.getProperties();\n this.name = pluginConfig.getName();\n this.addresses = MapUtils.getString(properties, REGISTRY_CENTER_ADDRESSED_KEY);\n this.username = MapUtils.getString(properties, REGISTRY_CENTER_USERNAME_KEY, null);\n this.password = MapUtils.getString(properties, REGISTRY_CENTER_PASSWORD_KEY, null);\n this.registerConsumer = MapUtils.getBoolean(properties, REGISTRY_CENTER_REGISTER_CONSUMER_KEY, false);\n this.connTimeoutMs = MapUtils\n .getInteger(properties, REGISTRY_CENTER_CONN_TIMEOUT_MS_KEY, DEFAULT_REGISTRY_CENTER_CONN_TIMEOUT_MS);\n this.openFailedRetry = MapUtils.getBoolean(properties, REGISTRY_CENTER_OPEN_FAILED_RETRY_KEY, true);\n this.retryPeriod = MapUtils\n .getInteger(properties, REGISTRY_CENTER_RETRY_PERIOD_KEY, DEFAULT_REGISTRY_CENTER_RETRY_PERIOD_MS);\n this.retryTimes = MapUtils\n .getInteger(properties, REGISTRY_CENTER_RETRY_TIMES_KEY, DEFAULT_REGISTRY_CENTER_RETRY_TIMES);\n this.persistedSaveCache = MapUtils.getBoolean(properties, REGISTRY_CENTER_SAVE_CACHE_KEY, false);\n this.syncedSaveCache = MapUtils\n .getBoolean(properties, REGISTRY_CENTER_SYNCED_SAVE_CACHE_KEY, false);\n this.cacheAliveTimeSecs = MapUtils.getInteger(properties, REGISTRY_CENTER_CACHE_ALIVE_TIME_SECS_KEY,\n DEFAULT_REGISTRY_CENTER_CACHE_ALIVE_TIME_SECS);\n\n String defaultSyncFilePath = String.format(\"%s/.trpc/trpc-registry/%s.cache\",\n System.getProperty(\"user.home\"), this.name);\n this.cacheFilePath = MapUtils.getString(properties, REGISTRY_CENTER_CACHE_FILE_PATH_KEY, defaultSyncFilePath);\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getAddresses() {\n return addresses;\n }\n\n public void setAddresses(String addresses) {\n this.addresses = addresses;\n }\n\n public String getUsername() {\n return username;\n }\n\n public void setUsername(String username) {\n this.username = username;\n }\n\n public String getPassword() {\n return password;\n }\n\n public void setPassword(String password) {\n this.password = password;\n }\n\n public boolean isRegisterConsumer() {\n return registerConsumer;\n }\n\n public void setRegisterConsumer(boolean registerConsumer) {\n this.registerConsumer = registerConsumer;\n }\n\n public int getConnTimeoutMs() {\n return connTimeoutMs;\n }\n\n public void setConnTimeoutMs(int connTimeoutMs) {\n this.connTimeoutMs = connTimeoutMs;\n }\n\n public boolean isOpenFailedRetry() {\n return openFailedRetry;\n }\n\n public void setOpenFailedRetry(boolean openFailedRetry) {\n this.openFailedRetry = openFailedRetry;\n }\n\n public int getRetryPeriod() {\n return retryPeriod;\n }\n\n public void setRetryPeriod(int retryPeriod) {\n this.retryPeriod = retryPeriod;\n }\n\n public int getRetryTimes() {\n return retryTimes;\n }\n\n public void setRetryTimes(int retryTimes) {\n this.retryTimes = retryTimes;\n }\n\n public boolean isPersistedSaveCache() {\n return persistedSaveCache;\n }\n\n public void setPersistedSaveCache(boolean persistedSaveCache) {\n this.persistedSaveCache = persistedSaveCache;\n }\n\n public boolean isSyncedSaveCache() {\n return syncedSaveCache;\n }\n\n public void setSyncedSaveCache(boolean syncedSaveCache) {\n this.syncedSaveCache = syncedSaveCache;\n }\n\n public int getCacheAliveTimeSecs() {\n return cacheAliveTimeSecs;\n }\n\n public void setCacheAliveTimeSecs(int cacheAliveTimeSecs) {\n this.cacheAliveTimeSecs = cacheAliveTimeSecs;\n }\n\n public String getCacheFilePath() {\n return cacheFilePath;\n }\n\n public void setCacheFilePath(String cacheFilePath) {\n this.cacheFilePath = cacheFilePath;\n }\n}" }, { "identifier": "RegistryCenterData", "path": "trpc-registry/trpc-registry-api/src/main/java/com/tencent/trpc/registry/common/RegistryCenterData.java", "snippet": "public class RegistryCenterData {\n\n /**\n * Mapping of registry types and their corresponding data\n */\n private final Map<RegistryCenterEnum, Set<RegisterInfo>> typeToRegisterInfosMap = new ConcurrentHashMap<>();\n\n /**\n * Mapping of PROVIDERS key-value pairs created by default.\n */\n public RegistryCenterData() {\n this(RegistryCenterEnum.PROVIDERS);\n }\n\n /**\n * Create a mapping of the specified type.\n *\n * @param type The data type of the registry.\n */\n public RegistryCenterData(RegistryCenterEnum type) {\n typeToRegisterInfosMap.computeIfAbsent(type, t -> new HashSet<>());\n }\n\n /**\n * Get a mapping of all registry types and their corresponding data.\n *\n * @return A mapping of all registry types and their corresponding data.\n */\n public Map<RegistryCenterEnum, Set<RegisterInfo>> getTypeToRegisterInfosMap() {\n return typeToRegisterInfosMap;\n }\n\n /**\n * Get the data corresponding to the specified registry type.\n *\n * @param type The registry type.\n * @return The data corresponding to the specified registry type.\n */\n public Set<RegisterInfo> getRegisterInfos(RegistryCenterEnum type) {\n return typeToRegisterInfosMap.computeIfAbsent(type, t -> new HashSet<>());\n }\n\n /**\n * Add data for the specified registry type.\n *\n * @param type The registry type.\n * @param registerInfo The data to be added.\n */\n public void putRegisterInfo(RegistryCenterEnum type, RegisterInfo registerInfo) {\n getRegisterInfos(type).add(registerInfo);\n }\n\n /**\n * Add data in bulk.\n *\n * @param registerInfos The list of data to be added.\n */\n public void putAllRegisterInfos(List<RegisterInfo> registerInfos) {\n registerInfos.forEach(ri -> {\n String type = ri.getParameter(REGISTRY_CENTER_SERVICE_TYPE_KEY, DEFAULT_REGISTRY_CENTER_SERVICE_TYPE);\n putRegisterInfo(RegistryCenterEnum.transferFrom(type), ri);\n });\n }\n\n /**\n * Check if the registry data is empty. This method iterates through all types of data to make the determination.\n *\n * @return true if empty, false if not empty.\n */\n public boolean isEmpty() {\n if (MapUtils.isEmpty(typeToRegisterInfosMap)) {\n return true;\n }\n return typeToRegisterInfosMap.values().stream().map(Set::isEmpty).reduce(true, (r1, r2) -> r1 && r2);\n }\n}" } ]
import static com.tencent.trpc.registry.common.Constants.URL_SEPARATOR; import com.tencent.trpc.core.common.NamedThreadFactory; import com.tencent.trpc.core.logger.Logger; import com.tencent.trpc.core.logger.LoggerFactory; import com.tencent.trpc.core.registry.RegisterInfo; import com.tencent.trpc.registry.common.RegistryCenterConfig; import com.tencent.trpc.registry.common.RegistryCenterData; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.RandomAccessFile; import java.nio.channels.FileChannel; import java.nio.channels.FileLock; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.Properties; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import java.util.stream.Collectors; import org.apache.commons.lang3.StringUtils;
7,713
/* * Tencent is pleased to support the open source community by making tRPC available. * * Copyright (C) 2023 THL A29 Limited, a Tencent company. * All rights reserved. * * If you have downloaded a copy of the tRPC source code from Tencent, * please note that tRPC source code is licensed under the Apache 2.0 License, * A copy of the Apache 2.0 License can be found in the LICENSE file. */ package com.tencent.trpc.registry.util; /** * The data cache of the registry center, which can enable persistence through configuration options. */ public class RegistryCenterCache { private static final Logger logger = LoggerFactory.getLogger(RegistryCenterCache.class); /** * The key for the cache update time, with a value precision of seconds. * There may be multiple versions at the same time, so PROPERTIES_TIME_KEY + PROPERTIES_VERSION_KEY is used to * determine the unique version. */ private static final String UPDATE_TIME_SECS_KEY = "update_time_secs"; /** * The key for the cache version number. */ private static final String UPDATE_VERSION_KEY = "update_version"; /** * The key for the cache expiration time. * When disconnected from the registry center, it can be read from the cache. If it exceeds this time, the cache * will expire. */ private static final String EXPIRE_TIME_SECS_KEY = "expire_time_secs"; /** * The latest version number of the cache. */ private static final AtomicLong lastVersion = new AtomicLong(); /** * The maximum number of retries for cache persistence. */ private static final int MAX_SAVE_RETRY_TIMES = 3; /** * Local cache, mainly caching subscribed services and their providers. * Additional caching of several special key-value pairs: * Cache update time: UPDATE_TIME_SECS_KEY * Cache version number: UPDATE_VERSION_KEY * Cache expiration time: EXPIRE_TIME_SECS_KEY */ private final Properties properties = new Properties(); /** * Asynchronous persistence thread pool for cache. */ private final ExecutorService executor = Executors.newFixedThreadPool(1, new NamedThreadFactory("TrpcRegistryCenterCache", true)); /** * The file used for cache persistence. */ private File persistentFile; /** * Registry center configuration items. */ private RegistryCenterConfig config; /** * The number of retries for cache persistence. */ private AtomicInteger saveRetryTimes = new AtomicInteger(); /** * If cache persistence is enabled, create a cache persistence file and attempt to retrieve previous data from disk. * * @param config */ public RegistryCenterCache(RegistryCenterConfig config) { this.config = config; String fileName = config.getCacheFilePath(); if (config.isPersistedSaveCache() && StringUtils.isNotEmpty(fileName)) { this.persistentFile = buildPersistentFile(fileName); loadFromDisk(); } } /** * Get the list of service providers for a subscribed service from the local cache. * * @param serviceName The name of the subscribed service. * @return The list of service providers. */ public List<RegisterInfo> getRegisterInfos(String serviceName) { List<RegisterInfo> registerInfos = new ArrayList<>(); if (expired()) { return registerInfos; } String urlStr = properties.getProperty(serviceName); if (StringUtils.isEmpty(urlStr)) { return registerInfos; } Arrays.stream(urlStr.split(URL_SEPARATOR)).map(this::getRegisterInfoDecode) .filter(Objects::nonNull).forEach(registerInfos::add); return registerInfos; } /** * Persist the cache to a local file. * * @param registerInfo The subscribed service. */
/* * Tencent is pleased to support the open source community by making tRPC available. * * Copyright (C) 2023 THL A29 Limited, a Tencent company. * All rights reserved. * * If you have downloaded a copy of the tRPC source code from Tencent, * please note that tRPC source code is licensed under the Apache 2.0 License, * A copy of the Apache 2.0 License can be found in the LICENSE file. */ package com.tencent.trpc.registry.util; /** * The data cache of the registry center, which can enable persistence through configuration options. */ public class RegistryCenterCache { private static final Logger logger = LoggerFactory.getLogger(RegistryCenterCache.class); /** * The key for the cache update time, with a value precision of seconds. * There may be multiple versions at the same time, so PROPERTIES_TIME_KEY + PROPERTIES_VERSION_KEY is used to * determine the unique version. */ private static final String UPDATE_TIME_SECS_KEY = "update_time_secs"; /** * The key for the cache version number. */ private static final String UPDATE_VERSION_KEY = "update_version"; /** * The key for the cache expiration time. * When disconnected from the registry center, it can be read from the cache. If it exceeds this time, the cache * will expire. */ private static final String EXPIRE_TIME_SECS_KEY = "expire_time_secs"; /** * The latest version number of the cache. */ private static final AtomicLong lastVersion = new AtomicLong(); /** * The maximum number of retries for cache persistence. */ private static final int MAX_SAVE_RETRY_TIMES = 3; /** * Local cache, mainly caching subscribed services and their providers. * Additional caching of several special key-value pairs: * Cache update time: UPDATE_TIME_SECS_KEY * Cache version number: UPDATE_VERSION_KEY * Cache expiration time: EXPIRE_TIME_SECS_KEY */ private final Properties properties = new Properties(); /** * Asynchronous persistence thread pool for cache. */ private final ExecutorService executor = Executors.newFixedThreadPool(1, new NamedThreadFactory("TrpcRegistryCenterCache", true)); /** * The file used for cache persistence. */ private File persistentFile; /** * Registry center configuration items. */ private RegistryCenterConfig config; /** * The number of retries for cache persistence. */ private AtomicInteger saveRetryTimes = new AtomicInteger(); /** * If cache persistence is enabled, create a cache persistence file and attempt to retrieve previous data from disk. * * @param config */ public RegistryCenterCache(RegistryCenterConfig config) { this.config = config; String fileName = config.getCacheFilePath(); if (config.isPersistedSaveCache() && StringUtils.isNotEmpty(fileName)) { this.persistentFile = buildPersistentFile(fileName); loadFromDisk(); } } /** * Get the list of service providers for a subscribed service from the local cache. * * @param serviceName The name of the subscribed service. * @return The list of service providers. */ public List<RegisterInfo> getRegisterInfos(String serviceName) { List<RegisterInfo> registerInfos = new ArrayList<>(); if (expired()) { return registerInfos; } String urlStr = properties.getProperty(serviceName); if (StringUtils.isEmpty(urlStr)) { return registerInfos; } Arrays.stream(urlStr.split(URL_SEPARATOR)).map(this::getRegisterInfoDecode) .filter(Objects::nonNull).forEach(registerInfos::add); return registerInfos; } /** * Persist the cache to a local file. * * @param registerInfo The subscribed service. */
public void save(RegisterInfo registerInfo, RegistryCenterData data) {
6
2023-10-19 10:54:11+00:00
12k
freedom-introvert/YouTubeSendCommentAntiFraud
YTSendCommAntiFraud/app/src/main/java/icu/freedomintrovert/YTSendCommAntiFraud/DialogCommentChecker.java
[ { "identifier": "Comment", "path": "YTSendCommAntiFraud/app/src/main/java/icu/freedomintrovert/YTSendCommAntiFraud/comment/Comment.java", "snippet": "public class Comment {\r\n public String commentText;\r\n public String commentId;\r\n\r\n public Comment() {\r\n }\r\n\r\n\r\n public Comment(String commentText, String commentId) {\r\n this.commentText = commentText;\r\n this.commentId = commentId;\r\n }\r\n\r\n @Override\r\n public String toString() {\r\n return \"Comment{\" +\r\n \"commentText='\" + commentText + '\\'' +\r\n \", commentId='\" + commentId + '\\'' +\r\n '}';\r\n }\r\n}\r" }, { "identifier": "HistoryComment", "path": "YTSendCommAntiFraud/app/src/main/java/icu/freedomintrovert/YTSendCommAntiFraud/comment/HistoryComment.java", "snippet": "public abstract class HistoryComment extends Comment{\r\n public static final String STATE_NORMAL = \"NORMAL\";\r\n public static final String STATE_SHADOW_BAN = \"SHADOW_BAN\";\r\n public static final String STATE_DELETED = \"DELETED\";\r\n\r\n public String state;\r\n public Date sendDate;\r\n @Nullable\r\n public Comment anchorComment;\r\n @Nullable\r\n public Comment repliedComment;\r\n\r\n public HistoryComment(){}\r\n\r\n public HistoryComment(String commentText, String commentId, String state, Date sendDate, @Nullable Comment anchorComment) {\r\n this(commentText,commentId,state,sendDate);\r\n this.anchorComment = anchorComment;\r\n }\r\n\r\n public HistoryComment(String commentText, String commentId, String state, Date sendDate) {\r\n super(commentText, commentId);\r\n this.state = state;\r\n this.sendDate = sendDate;\r\n }\r\n\r\n public HistoryComment(String commentText, String commentId, String state, Date sendDate, @Nullable Comment anchorComment, @Nullable Comment repliedComment) {\r\n super(commentText, commentId);\r\n this.state = state;\r\n this.sendDate = sendDate;\r\n this.anchorComment = anchorComment;\r\n this.repliedComment = repliedComment;\r\n }\r\n\r\n public abstract String getCommentSectionSourceId();\r\n\r\n public String getFormatDateFor_yMd(){\r\n SimpleDateFormat sdf = new SimpleDateFormat(\"yyyy-MM-dd\", Locale.CHINA);\r\n return sdf.format(sendDate);\r\n }\r\n\r\n public String getFormatDateFor_yMdHms(){\r\n SimpleDateFormat sdf = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\", Locale.CHINA);\r\n return sdf.format(sendDate);\r\n }\r\n}\r" }, { "identifier": "VideoComment", "path": "YTSendCommAntiFraud/app/src/main/java/icu/freedomintrovert/YTSendCommAntiFraud/comment/VideoComment.java", "snippet": "public class VideoComment extends Comment{\r\n public String videoId;\r\n\r\n public VideoComment(String commentText, String commentId, String videoId) {\r\n super(commentText, commentId);\r\n this.videoId = videoId;\r\n }\r\n}\r" }, { "identifier": "VideoCommentSection", "path": "YTSendCommAntiFraud/app/src/main/java/icu/freedomintrovert/YTSendCommAntiFraud/comment/VideoCommentSection.java", "snippet": "public class VideoCommentSection extends CommentSection {\r\n\r\n private final byte[] contextPbData;\r\n private boolean hasAccount;\r\n private final Bundle headersBundle;\r\n\r\n private final String firstContinuationBase64Text;\r\n private String currentContinuationBase64Text;\r\n\r\n public VideoCommentSection(OkHttpClient okHttpClient, byte[] contextPbData, String continuationBase64Text, Bundle headersBundle, boolean hasAccount) {\r\n super(okHttpClient);\r\n this.contextPbData = contextPbData;\r\n this.firstContinuationBase64Text = continuationBase64Text;\r\n this.currentContinuationBase64Text = firstContinuationBase64Text;\r\n this.headersBundle = headersBundle;\r\n this.hasAccount = hasAccount;\r\n }\r\n\r\n @Override\r\n public boolean nextPage() throws IOException, Code401Exception {\r\n if (currentContinuationBase64Text != null) {\r\n currentCommentList = new ArrayList<>();\r\n //VideoCommentRequest.Builder builder = VideoCommentRequest.newBuilder();\r\n //builder.setContext(Context.parseFrom(contextPbData));\r\n //builder.setContinuation(continuationBase64Text);\r\n //VideoCommentRequest videoCommentRequest = builder.build();\r\n VideoCommentRequest videoCommentRequest1 = VideoCommentRequest.newBuilder().setContext(Context.parseFrom(contextPbData)).setContinuation(currentContinuationBase64Text).build();\r\n RequestBody requestBody = RequestBody.create(videoCommentRequest1.toByteArray(), MediaType.parse(\"application/x-protobuf\"));\r\n Request.Builder requestBuilder = new Request.Builder()\r\n .url(\"https://youtubei.googleapis.com/youtubei/v1/next?key=AIzaSyA8eiZmM1FaDVjRy-df2KTyQ_vz_yYM39w\")\r\n .addHeader(\"X-GOOG-API-FORMAT-VERSION\",headersBundle.getString(\"X-GOOG-API-FORMAT-VERSION\"))\r\n .addHeader(\"X-Goog-Visitor-Id\",headersBundle.getString(\"X-Goog-Visitor-Id\"))\r\n .addHeader(\"User-Agent\",headersBundle.getString(\"User-Agent\"))\r\n .post(requestBody);\r\n if (hasAccount){\r\n requestBuilder.addHeader(\"Authorization\", headersBundle.getString(\"Authorization\"));//跟cookie一样的作用\r\n }\r\n Request request = requestBuilder.build();\r\n Response response = okHttpClient.newCall(request).execute();\r\n if (response.code() == 401){\r\n throw new Code401Exception(\"Received status code 401, the token may have expired\");\r\n }\r\n ResponseBody body = response.body();\r\n OkHttpUtils.checkResponseBodyNotNull(body);\r\n\r\n VideoCommentResponse videoCommentResponse = VideoCommentResponse.parseFrom(body.bytes());\r\n List<ContinuationItem> continuationItemList = videoCommentResponse.getContinuationItemsAction().getContinuationItems().getContinuationItemList();\r\n for (ContinuationItem continuationItem : continuationItemList) {\r\n if (continuationItem.getUnk3().hasComment()) {\r\n icu.freedomintrovert.YTSendCommAntiFraud.grpcApi.Comment comment = continuationItem.getUnk3().getComment();\r\n currentCommentList.add(new Comment(comment.getContent().getMsg().getMessage(),comment.getContent().getCommentId()));\r\n }\r\n }\r\n\r\n NextInfo8 nextInfo8 = videoCommentResponse.getNextInfo8();\r\n if (nextInfo8.hasUnkMsg50195462()) {\r\n for (UnkMsg50195462.UnkMsg2 unkMsg2 : nextInfo8.getUnkMsg50195462().getUnkMsg2List()) {\r\n if (unkMsg2.hasUnkMsg52047593()) {\r\n currentContinuationBase64Text = unkMsg2.getUnkMsg52047593().getContinuation();\r\n return true;\r\n }\r\n }\r\n } else {\r\n for (UnkMsg49399797.UnkMsg49399797_1 unkMsg49399797_1 : nextInfo8.getUnkMsg49399797().getUnkMsg1List()) {\r\n List<UnkMsg50195462.UnkMsg2> unkMsg2List = unkMsg49399797_1.getUnkMsg50195462().getUnkMsg2List();\r\n for (UnkMsg50195462.UnkMsg2 unkMsg2 : unkMsg2List) {\r\n if (unkMsg2.hasUnkMsg52047593()) {\r\n currentContinuationBase64Text = unkMsg2.getUnkMsg52047593().getContinuation();\r\n return true;\r\n }\r\n }\r\n }\r\n }\r\n currentContinuationBase64Text = null;\r\n return true;\r\n //stringBuilder.append(\"\\n\" + videoCommentResponse);\r\n }\r\n currentCommentList = null;\r\n return false;\r\n }\r\n\r\n public void reset(boolean hasAccount){\r\n currentContinuationBase64Text = firstContinuationBase64Text;\r\n this.hasAccount = hasAccount;\r\n }\r\n\r\n public String getCurrentContinuationBase64Text(){\r\n return currentContinuationBase64Text;\r\n }\r\n\r\n public byte[] getContextPbData() {\r\n return contextPbData;\r\n }\r\n\r\n public static class Code401Exception extends Exception{\r\n public Code401Exception(String message) {\r\n super(message);\r\n }\r\n }\r\n}\r" }, { "identifier": "StatisticsDB", "path": "YTSendCommAntiFraud/app/src/main/java/icu/freedomintrovert/YTSendCommAntiFraud/db/StatisticsDB.java", "snippet": "public class StatisticsDB extends SQLiteOpenHelper {\r\n public static final String TABLE_NAME_VIDEO_HISTORY_COMMENTS = \"history_comments_from_video\";\r\n private static final String TABLE_NAME_TO_BE_CHECKED_COMMENTS = \"to_be_checked_comments\";\r\n SQLiteDatabase db;\r\n\r\n public static final int DB_VERSION = 1;\r\n\r\n public StatisticsDB(@Nullable Context context) {\r\n super(context, \"statistics\", null, DB_VERSION);\r\n db = getWritableDatabase();\r\n }\r\n\r\n @Override\r\n public void onCreate(SQLiteDatabase db) {\r\n db.execSQL(\"CREATE TABLE history_comments_from_video ( comment_id TEXT PRIMARY KEY UNIQUE NOT NULL, comment_text TEXT NOT NULL,anchor_comment_id TEXT,anchor_comment_text TEXT, video_id TEXT NOT NULL, state TEXT NOT NULL,send_date INTEGER NOT NULL,replied_comment_id TEXT,replied_comment_text TEXT ); \");\r\n db.execSQL(\"CREATE TABLE to_be_checked_comments ( comment_id TEXT PRIMARY KEY NOT NULL UNIQUE, comment_text TEXT NOT NULL, source_id TEXT NOT NULL, comment_section_type INTEGER NOT NULL, replied_comment_id TEXT, replied_comment_text TEXT, context1 BLOB NOT NULL ,send_time INTEGER NOT NULL);\");\r\n }\r\n\r\n @Override\r\n public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {\r\n\r\n }\r\n\r\n public long insertVideoHistoryComment(VideoHistoryComment comment){\r\n ContentValues v = new ContentValues();\r\n v.put(\"comment_id\", comment.commentId);\r\n v.put(\"comment_text\", comment.commentText);\r\n if (comment.anchorComment != null) {\r\n v.put(\"anchor_comment_id\", comment.anchorComment.commentId);\r\n v.put(\"anchor_comment_text\", comment.anchorComment.commentText);\r\n }\r\n v.put(\"video_id\", comment.videoId);\r\n v.put(\"state\", comment.state);\r\n v.put(\"send_date\", comment.sendDate.getTime());\r\n if (comment.repliedComment != null) {\r\n v.put(\"replied_comment_id\", comment.repliedComment.commentId);\r\n v.put(\"replied_comment_text\", comment.repliedComment.commentText);\r\n }\r\n return db.insert(TABLE_NAME_VIDEO_HISTORY_COMMENTS,null,v);\r\n }\r\n\r\n @SuppressLint(\"Range\")\r\n public List<VideoHistoryComment> queryAllVideoHistoryComments(){\r\n List<VideoHistoryComment> commentList = new ArrayList<>();\r\n String[] columns = {\"comment_id\", \"comment_text\", \"anchor_comment_id\", \"anchor_comment_text\", \"video_id\", \"state\", \"send_date\", \"replied_comment_id\", \"replied_comment_text\"};\r\n Cursor cursor = db.query(\"history_comments_from_video\", columns, null, null, null, null, null);\r\n\r\n if (cursor != null) {\r\n while (cursor.moveToNext()) {\r\n String commentId = cursor.getString(cursor.getColumnIndex(\"comment_id\"));\r\n String commentText = cursor.getString(cursor.getColumnIndex(\"comment_text\"));\r\n String anchorCommentId = cursor.getString(cursor.getColumnIndex(\"anchor_comment_id\"));\r\n String anchorCommentText = cursor.getString(cursor.getColumnIndex(\"anchor_comment_text\"));\r\n String videoId = cursor.getString(cursor.getColumnIndex(\"video_id\"));\r\n String state = cursor.getString(cursor.getColumnIndex(\"state\"));\r\n long sendDate = cursor.getLong(cursor.getColumnIndex(\"send_date\"));\r\n String repliedCommentId = cursor.getString(cursor.getColumnIndex(\"replied_comment_id\"));\r\n String repliedCommentText = cursor.getString(cursor.getColumnIndex(\"replied_comment_text\"));\r\n VideoHistoryComment comment = new VideoHistoryComment(commentId, commentText, anchorCommentId, anchorCommentText, videoId, state, sendDate, repliedCommentId, repliedCommentText);\r\n commentList.add(comment);\r\n }\r\n cursor.close();\r\n }\r\n return commentList;\r\n }\r\n\r\n public long deleteVideoHistoryComment(String commentId) {\r\n return db.delete(TABLE_NAME_VIDEO_HISTORY_COMMENTS,\"comment_id = ?\",new String[]{commentId});\r\n }\r\n\r\n public void insertToBeCheckedComment(ToBeCheckedComment comment) {\r\n ContentValues v = new ContentValues();\r\n v.put(\"comment_id\", comment.commentId);\r\n v.put(\"comment_text\", comment.commentText);\r\n v.put(\"source_id\", comment.sourceId);\r\n v.put(\"comment_section_type\", comment.commentSectionType);\r\n v.put(\"replied_comment_id\", comment.repliedCommentId);\r\n v.put(\"replied_comment_text\", comment.repliedCommentText);\r\n v.put(\"context1\", comment.context1);\r\n v.put(\"send_time\",comment.sendTime.getTime());\r\n db.insert(TABLE_NAME_TO_BE_CHECKED_COMMENTS, null, v);\r\n }\r\n @SuppressLint(\"Range\")\r\n public List<ToBeCheckedComment> getAllToBeCheckedComments() {\r\n List<ToBeCheckedComment> commentList = new ArrayList<>();\r\n String[] columns = {\"comment_id\", \"comment_text\", \"source_id\", \"comment_section_type\", \"replied_comment_id\", \"replied_comment_text\", \"context1\",\"send_time\"};\r\n Cursor cursor = db.query(\"to_be_checked_comments\", columns, null, null, null, null, null);\r\n if (cursor != null) {\r\n while (cursor.moveToNext()) {\r\n String commentId = cursor.getString(cursor.getColumnIndex(\"comment_id\"));\r\n String commentText = cursor.getString(cursor.getColumnIndex(\"comment_text\"));\r\n String sourceId = cursor.getString(cursor.getColumnIndex(\"source_id\"));\r\n int commentSectionType = cursor.getInt(cursor.getColumnIndex(\"comment_section_type\"));\r\n String repliedCommentId = cursor.getString(cursor.getColumnIndex(\"replied_comment_id\"));\r\n String repliedCommentText = cursor.getString(cursor.getColumnIndex(\"replied_comment_text\"));\r\n byte[] context1 = cursor.getBlob(cursor.getColumnIndex(\"context1\"));\r\n long sendTime = cursor.getLong(cursor.getColumnIndex(\"send_time\"));\r\n ToBeCheckedComment comment = new ToBeCheckedComment(commentId, commentText, sourceId, commentSectionType, repliedCommentId, repliedCommentText, context1,new Date(sendTime));\r\n commentList.add(comment);\r\n }\r\n cursor.close();\r\n }\r\n return commentList;\r\n }\r\n\r\n public long deleteToBeCheckedComment(String commentId){\r\n return db.delete(TABLE_NAME_TO_BE_CHECKED_COMMENTS,\"comment_id = ?\",new String[]{commentId});\r\n }\r\n\r\n}\r" }, { "identifier": "SortBy", "path": "YTSendCommAntiFraud/app/src/main/java/icu/freedomintrovert/YTSendCommAntiFraud/grpcApi/nestedIntoBase64/SortBy.java", "snippet": "public enum SortBy\n implements com.google.protobuf.ProtocolMessageEnum {\n /**\n * <code>hot = 0;</code>\n */\n hot(0),\n /**\n * <code>latest = 1;</code>\n */\n latest(1),\n UNRECOGNIZED(-1),\n ;\n\n /**\n * <code>hot = 0;</code>\n */\n public static final int hot_VALUE = 0;\n /**\n * <code>latest = 1;</code>\n */\n public static final int latest_VALUE = 1;\n\n\n public final int getNumber() {\n if (this == UNRECOGNIZED) {\n throw new IllegalArgumentException(\n \"Can't get the number of an unknown enum value.\");\n }\n return value;\n }\n\n /**\n * @param value The numeric wire value of the corresponding enum entry.\n * @return The enum associated with the given numeric wire value.\n * @deprecated Use {@link #forNumber(int)} instead.\n */\n @Deprecated\n public static SortBy valueOf(int value) {\n return forNumber(value);\n }\n\n /**\n * @param value The numeric wire value of the corresponding enum entry.\n * @return The enum associated with the given numeric wire value.\n */\n public static SortBy forNumber(int value) {\n switch (value) {\n case 0: return hot;\n case 1: return latest;\n default: return null;\n }\n }\n\n public static com.google.protobuf.Internal.EnumLiteMap<SortBy>\n internalGetValueMap() {\n return internalValueMap;\n }\n private static final com.google.protobuf.Internal.EnumLiteMap<\n SortBy> internalValueMap =\n new com.google.protobuf.Internal.EnumLiteMap<SortBy>() {\n public SortBy findValueByNumber(int number) {\n return SortBy.forNumber(number);\n }\n };\n\n public final com.google.protobuf.Descriptors.EnumValueDescriptor\n getValueDescriptor() {\n if (this == UNRECOGNIZED) {\n throw new IllegalStateException(\n \"Can't get the descriptor of an unrecognized enum value.\");\n }\n return getDescriptor().getValues().get(ordinal());\n }\n public final com.google.protobuf.Descriptors.EnumDescriptor\n getDescriptorForType() {\n return getDescriptor();\n }\n public static final com.google.protobuf.Descriptors.EnumDescriptor\n getDescriptor() {\n return ContinuationCommand.getDescriptor().getEnumTypes().get(0);\n }\n\n private static final SortBy[] VALUES = values();\n\n public static SortBy valueOf(\n com.google.protobuf.Descriptors.EnumValueDescriptor desc) {\n if (desc.getType() != getDescriptor()) {\n throw new IllegalArgumentException(\n \"EnumValueDescriptor is not for this type.\");\n }\n if (desc.getIndex() == -1) {\n return UNRECOGNIZED;\n }\n return VALUES[desc.getIndex()];\n }\n\n private final int value;\n\n private SortBy(int value) {\n this.value = value;\n }\n\n // @@protoc_insertion_point(enum_scope:SortBy)\n}" }, { "identifier": "FindCommentObservableOnSubscribe", "path": "YTSendCommAntiFraud/app/src/main/java/icu/freedomintrovert/YTSendCommAntiFraud/rxObservables/FindCommentObservableOnSubscribe.java", "snippet": "public class FindCommentObservableOnSubscribe implements ObservableOnSubscribe<FindCommentObservableOnSubscribe.BaseNextValue> {\r\n\r\n private final VideoCommentSection videoCommentSection;\r\n private VideoComment toBeCheckedComment;\r\n private final long waitTimeAfterCommentSent;\r\n private final long intervalOfSearchAgain;\r\n private final int maximumNumberOfSearchAgain;\r\n private StatisticsDB statisticsDB;\r\n private boolean needToWait;\r\n private final Date sendDate;\r\n private ProgressTimer progressTimer;\r\n private boolean needContinue = true;\r\n\r\n\r\n public FindCommentObservableOnSubscribe(VideoCommentSection videoCommentSection, VideoComment toBeCheckedComment, StatisticsDB statisticsDB, Config config, boolean needToWait,Date sendDate) {\r\n this.toBeCheckedComment = toBeCheckedComment;\r\n this.videoCommentSection = videoCommentSection;\r\n this.waitTimeAfterCommentSent = config.getWaitTimeAfterCommentSent();\r\n this.intervalOfSearchAgain = config.getIntervalOfSearchAgain();\r\n if (!needToWait) {\r\n this.maximumNumberOfSearchAgain = 0;\r\n } else {\r\n this.maximumNumberOfSearchAgain = config.getMaximumNumberOfSearchAgain();\r\n }\r\n this.statisticsDB = statisticsDB;\r\n this.needToWait = needToWait;\r\n this.sendDate = sendDate;\r\n }\r\n\r\n @Override\r\n public void subscribe(@NonNull ObservableEmitter<BaseNextValue> emitter) throws Throwable {\r\n statisticsDB.insertToBeCheckedComment(new ToBeCheckedComment(toBeCheckedComment.commentId, toBeCheckedComment.commentText, toBeCheckedComment.videoId, ToBeCheckedComment.COMMENT_SECTION_TYPE_VIDEO, null, null, videoCommentSection.getContextPbData(), sendDate));\r\n if (needToWait) {\r\n progressTimer = new ProgressTimer(waitTimeAfterCommentSent, ProgressBarDialog.DEFAULT_MAX_PROGRESS, (progress, sleepSeg) -> {\r\n emitter.onNext(new OnNewSleepProgressValue(progress, progress * sleepSeg));\r\n });\r\n progressTimer.start();\r\n if (!needContinue){\r\n return;\r\n }\r\n }\r\n emitter.onNext(new OnStartCheckValue());\r\n Comment anchorComment = null;\r\n boolean fonndFormHasAccount = false;\r\n int pn = 1;\r\n emitter.onNext(new OnNextPageFormHasAccountValue(pn));\r\n turnPage:\r\n while (videoCommentSection.nextPage()) {\r\n List<Comment> comments = videoCommentSection.getCommentsFromThisPage();\r\n for (int i = 0; i < comments.size(); i++) {\r\n Comment comment = comments.get(i);\r\n if (comment.commentId.equals(toBeCheckedComment.commentId)) {\r\n fonndFormHasAccount = true;\r\n //如果要找的评论已经是最后一个,则翻页后再获取锚点评论(要找的评论下面的那个评论)\r\n if (i + 1 < comments.size()) {\r\n anchorComment = comments.get(i + 1);\r\n } else {\r\n if (videoCommentSection.nextPage()) {\r\n anchorComment = videoCommentSection.getCommentsFromThisPage().get(0);\r\n }\r\n }\r\n emitter.onNext(new OnFondYourCommentFromHasAccountVale(comment, anchorComment));\r\n try {\r\n //避免看不到“找到了”的提示\r\n Thread.sleep(500);\r\n } catch (InterruptedException ignored) {\r\n }\r\n break turnPage;\r\n }\r\n }\r\n pn++;\r\n emitter.onNext(new OnNextPageFormHasAccountValue(pn));\r\n }\r\n boolean foundAnchorComment = false;\r\n if (fonndFormHasAccount) {\r\n pn = 1;\r\n videoCommentSection.reset(false);\r\n emitter.onNext(new OnNextPageFormNotAccountValue(pn));\r\n //无账号评论区查找\r\n turnPage1:\r\n while (videoCommentSection.nextPage()) {\r\n List<Comment> comments = videoCommentSection.getCommentsFromThisPage();\r\n System.out.println(comments);\r\n System.out.println(anchorComment);\r\n for (int i = 0; i < comments.size(); i++) {\r\n Comment comment = comments.get(i);\r\n if (comment.commentId.equals(toBeCheckedComment.commentId)) {\r\n statisticsDB.deleteToBeCheckedComment(toBeCheckedComment.commentId);\r\n statisticsDB.insertVideoHistoryComment(new VideoHistoryComment(toBeCheckedComment.commentText, toBeCheckedComment.commentId, HistoryComment.STATE_NORMAL, sendDate, anchorComment, toBeCheckedComment.videoId));\r\n emitter.onNext(new OnYourCommentIsNormalStateValue(comment));\r\n return;\r\n } else if (anchorComment != null && comment.commentId.equals(anchorComment.commentId)) {\r\n //如果翻到了之前打锚点的评论,就不用继续往下翻了(节约时间),因为你的评论在自己能看到的时候在此评论的上面,可以断定是ShadowBan了\r\n for (int i1 = 0; i1 < maximumNumberOfSearchAgain; i1++) {\r\n int finalI = i1;\r\n new ProgressTimer(intervalOfSearchAgain, ProgressBarDialog.DEFAULT_MAX_PROGRESS, (progress, sleepSeg) -> {\r\n emitter.onNext(new OnSearchAgainProgressValue(finalI + 1, maximumNumberOfSearchAgain, intervalOfSearchAgain, progress, progress * sleepSeg));\r\n }).start();\r\n int pageNum = 1;\r\n emitter.onNext(new OnSearchAgainGetCommentsValue(pageNum));\r\n videoCommentSection.reset(false);\r\n turnPage:\r\n while (videoCommentSection.nextPage()) {\r\n for (Comment comment1 : videoCommentSection.getCommentsFromThisPage()) {\r\n if (comment1.commentId.equals(toBeCheckedComment.commentId)) {\r\n statisticsDB.deleteToBeCheckedComment(toBeCheckedComment.commentId);\r\n statisticsDB.insertVideoHistoryComment(new VideoHistoryComment(toBeCheckedComment.commentText, toBeCheckedComment.commentId, HistoryComment.STATE_NORMAL, sendDate, anchorComment, toBeCheckedComment.videoId));\r\n emitter.onNext(new OnYourCommentIsNormalStateValue(comment1));\r\n return;\r\n } else if (comment1.commentId.equals(anchorComment.commentId)) {\r\n foundAnchorComment = true;\r\n break turnPage;\r\n }\r\n }\r\n pageNum++;\r\n emitter.onNext(new OnSearchAgainGetCommentsValue(pageNum));\r\n }\r\n }\r\n break turnPage1;\r\n }\r\n }\r\n pn++;\r\n emitter.onNext(new OnNextPageFormNotAccountValue(pn));\r\n }\r\n /*如果走到这里,说明没有锚点或者锚点已被删除又或者锚点是你自己发的评论但是被ShadowBan了,遇到这种情况只能翻遍评论区。\r\n 聪明的你说可以用发送时间定位,呸!你以为这里是哔哩哔哩啊,每个评论都给你详细的发送时间戳。你也不看YouTube后端程序员是谁?\r\n 人家可是谷歌从精神病院里拖出来的!!!看看浏览器里的请求评论返回的JSON数据,每个评论item里都夹了一个emoji数组😅,\r\n 数组里的emoji的数量和你输入法里的emoji列表一样多,整个JSON数据格式化后能到5万行!以答辩文明的QQ、微信程序员看了都他妈要叫声爸爸!!\r\n 踏马但凡差一点的电脑开你YouTube看个评论都要顿一下子🤮,人家小学生当程序员也没他妈你离谱!\r\n\r\n 同时,有用的信息也是最少的,评论发送的时间信息真他妈就是个类似“1分钟前”“一小时前””一天前“……的String文本,返回的数据里你根本找不到具体的时间戳\r\n b站直接给具体的时间戳,然后浏览器生成对应的描述。\r\n 若作为楼中楼评论回复,也没有对应回复评论的parent(父评论ID,此评论回复的对象)数据,root(根评论ID,楼中楼的楼主)倒是有。\r\n 人家b站,对于评论回复,你甚至可以根据它的parent,去生成一个树状的评论回复视图,一目了然(有兴趣可以用mermaid实现)\r\n\r\n 再者,JSON数据也写得跟个神经病一样\r\n 以下是某段JSON数据\r\n\r\n \"ids\": [\r\n {\r\n \"commentId\": \"XXXXXXXXXXXXXXXXXXXXXX\"\r\n },\r\n {\r\n \"encryptedVideoId\": \"XXXXXXXXX\"\r\n },\r\n {\r\n \"externalChannelId\": \"XXXXXXXXXXXXXXXXXXX\"\r\n }\r\n ],\r\n\r\n 妈的,明明可以写成下面这样↓\r\n\r\n \"ids\":{\r\n \"commentId\":\"XXXXXXXXXXXXXXXXXXXXXX\",\r\n \"encryptedVideoId\":\"XXXXXXXXX\",\r\n \"externalChannelId\":\"XXXXXXXXXXXXXXXXXXX\"\r\n }\r\n\r\n 偏偏要套个他妈的数组!后端程序员你跟数组过不去是吧😅\r\n\r\n */\r\n if (!foundAnchorComment) {\r\n for (int i1 = 0; i1 < maximumNumberOfSearchAgain; i1++) {\r\n int finalI = i1;\r\n new ProgressTimer(intervalOfSearchAgain, ProgressBarDialog.DEFAULT_MAX_PROGRESS, (progress, sleepSeg) -> {\r\n emitter.onNext(new OnSearchAgainProgressForNoAnchorValue(finalI + 1, maximumNumberOfSearchAgain, intervalOfSearchAgain, progress, progress * sleepSeg));\r\n }).start();\r\n int pageNum = 1;\r\n emitter.onNext(new OnSearchAgainGetCommentsValue(pageNum));\r\n videoCommentSection.reset(false);\r\n while (videoCommentSection.nextPage()) {\r\n for (Comment comment1 : videoCommentSection.getCommentsFromThisPage()) {\r\n if (comment1.commentId.equals(toBeCheckedComment.commentId)) {\r\n statisticsDB.deleteToBeCheckedComment(toBeCheckedComment.commentId);\r\n statisticsDB.insertVideoHistoryComment(new VideoHistoryComment(toBeCheckedComment.commentText, toBeCheckedComment.commentId, HistoryComment.STATE_NORMAL, sendDate, anchorComment, toBeCheckedComment.videoId));\r\n emitter.onNext(new OnYourCommentIsNormalStateValue(comment1));\r\n return;\r\n }\r\n }\r\n pageNum++;\r\n emitter.onNext(new OnSearchAgainGetCommentsValue(pageNum));\r\n }\r\n }\r\n }\r\n checkIfIsDeletedAndReturnShadowBan(emitter, anchorComment,maximumNumberOfSearchAgain > 0);\r\n } else {\r\n statisticsDB.deleteToBeCheckedComment(toBeCheckedComment.commentId);\r\n statisticsDB.insertVideoHistoryComment(new VideoHistoryComment(toBeCheckedComment.commentText, toBeCheckedComment.commentId, HistoryComment.STATE_DELETED, sendDate, toBeCheckedComment.videoId));\r\n emitter.onNext(new OnYourCommentIsDeleteStateValue());\r\n }\r\n }\r\n\r\n //需要在检查评论前的等待时间调用,否则不起作用\r\n public void stop(){\r\n if (progressTimer != null) {\r\n needContinue = false;\r\n progressTimer.stop();\r\n }\r\n }\r\n\r\n private void checkIfIsDeletedAndReturnShadowBan(@NonNull ObservableEmitter<BaseNextValue> emitter, Comment anchorComment,boolean recheck) throws IOException, VideoCommentSection.Code401Exception {\r\n videoCommentSection.reset(true);\r\n int pn = 1;\r\n if (recheck) {\r\n emitter.onNext(new OnReCheckIfIsDeletedValue(pn));\r\n while (videoCommentSection.nextPage()) {\r\n List<Comment> comments = videoCommentSection.getCommentsFromThisPage();\r\n for (Comment comment : comments) {\r\n if (comment.commentId.equals(toBeCheckedComment.commentId)) {\r\n statisticsDB.deleteToBeCheckedComment(comment.commentId);\r\n statisticsDB.insertVideoHistoryComment(new VideoHistoryComment(toBeCheckedComment.commentText, toBeCheckedComment.commentId, HistoryComment.STATE_SHADOW_BAN, sendDate, anchorComment, toBeCheckedComment.videoId));\r\n emitter.onNext(new OnYourCommentIsShadowBanStateValue());\r\n return;\r\n }\r\n }\r\n pn++;\r\n emitter.onNext(new OnReCheckIfIsDeletedValue(pn));\r\n }\r\n statisticsDB.deleteToBeCheckedComment(toBeCheckedComment.commentId);\r\n statisticsDB.insertVideoHistoryComment(new VideoHistoryComment(toBeCheckedComment.commentText, toBeCheckedComment.commentId, HistoryComment.STATE_DELETED, sendDate, anchorComment, toBeCheckedComment.videoId));\r\n emitter.onNext(new OnYourCommentIsDeleteStateValue());\r\n } else {\r\n statisticsDB.deleteToBeCheckedComment(toBeCheckedComment.commentId);\r\n statisticsDB.insertVideoHistoryComment(new VideoHistoryComment(toBeCheckedComment.commentText, toBeCheckedComment.commentId, HistoryComment.STATE_SHADOW_BAN, sendDate, anchorComment, toBeCheckedComment.videoId));\r\n emitter.onNext(new OnYourCommentIsShadowBanStateValue());\r\n }\r\n }\r\n\r\n\r\n public interface BaseNextValue {\r\n }\r\n\r\n public static class OnNewSleepProgressValue implements BaseNextValue {\r\n public int progress;\r\n public long waitedTime;\r\n\r\n public OnNewSleepProgressValue(int progress, long waitedTime) {\r\n this.progress = progress;\r\n this.waitedTime = waitedTime;\r\n }\r\n }\r\n\r\n\r\n public static class OnStartCheckValue implements BaseNextValue {\r\n }\r\n\r\n public static class OnNextPageFormHasAccountValue implements BaseNextValue {\r\n public int pageNumber;\r\n\r\n public OnNextPageFormHasAccountValue(int pageNumber) {\r\n this.pageNumber = pageNumber;\r\n }\r\n }\r\n\r\n public static class OnNextPageFormNotAccountValue implements BaseNextValue {\r\n public int pageNumber;\r\n\r\n public OnNextPageFormNotAccountValue(int pageNumber) {\r\n this.pageNumber = pageNumber;\r\n }\r\n }\r\n\r\n\r\n public static class OnFondYourCommentFromHasAccountVale implements BaseNextValue {\r\n public Comment yourComment;\r\n public Comment anchorComment;\r\n\r\n public OnFondYourCommentFromHasAccountVale(Comment yourComment, Comment anchorComment) {\r\n this.yourComment = yourComment;\r\n this.anchorComment = anchorComment;\r\n }\r\n }\r\n\r\n /**\r\n * Comment state is deleted\r\n */\r\n public static class OnYourCommentIsDeleteStateValue implements BaseNextValue {\r\n }\r\n\r\n /**\r\n * Comment state is ShadowBan\r\n */\r\n\r\n public static class OnSearchAgainProgressValue implements BaseNextValue {\r\n public int retry;\r\n public int totalRetry;\r\n public long interval;\r\n public int progress;\r\n public long waitedTime;\r\n\r\n public OnSearchAgainProgressValue(int retry, int totalRetry, long interval, int progress, long waitedTime) {\r\n this.retry = retry;\r\n this.totalRetry = totalRetry;\r\n this.interval = interval;\r\n this.progress = progress;\r\n this.waitedTime = waitedTime;\r\n }\r\n }\r\n\r\n public static class OnSearchAgainProgressForNoAnchorValue extends OnSearchAgainProgressValue {\r\n\r\n public OnSearchAgainProgressForNoAnchorValue(int retry, int totalRetry, long interval, int progress, long waitedTime) {\r\n super(retry, totalRetry, interval, progress, waitedTime);\r\n }\r\n }\r\n\r\n public static class OnSearchAgainGetCommentsValue implements BaseNextValue {\r\n public int pageNumber;\r\n\r\n public OnSearchAgainGetCommentsValue(int pageNumber) {\r\n this.pageNumber = pageNumber;\r\n }\r\n }\r\n\r\n public static class OnYourCommentIsShadowBanStateValue implements BaseNextValue {\r\n }\r\n\r\n /**\r\n * Comment state is normal\r\n */\r\n public static class OnYourCommentIsNormalStateValue implements BaseNextValue {\r\n public Comment yourComment;\r\n\r\n public OnYourCommentIsNormalStateValue(Comment yourComment) {\r\n this.yourComment = yourComment;\r\n }\r\n }\r\n\r\n public static class OnReCheckIfIsDeletedValue implements BaseNextValue {\r\n public int pageNumber;\r\n\r\n public OnReCheckIfIsDeletedValue(int pageNumber) {\r\n this.pageNumber = pageNumber;\r\n }\r\n }\r\n\r\n\r\n}\r" }, { "identifier": "OkHttpUtils", "path": "YTSendCommAntiFraud/app/src/main/java/icu/freedomintrovert/YTSendCommAntiFraud/utils/OkHttpUtils.java", "snippet": "public class OkHttpUtils {\r\n private static OkHttpClient okHttpClient;\r\n\r\n public static synchronized OkHttpClient getOkHttpClient() {\r\n if (okHttpClient == null) {\r\n okHttpClient = new OkHttpClient.Builder()\r\n .build();\r\n }\r\n return okHttpClient;\r\n }\r\n\r\n public static void checkResponseBodyNotNull(ResponseBody body) throws IOException {\r\n if (body == null) {\r\n throw new IOException(\"ResponseBody is null\");\r\n }\r\n }\r\n}\r" }, { "identifier": "ProtobufUtils", "path": "YTSendCommAntiFraud/app/src/main/java/icu/freedomintrovert/YTSendCommAntiFraud/utils/ProtobufUtils.java", "snippet": "public class ProtobufUtils {\r\n public static Continuation generateContinuation(String videoId, SortBy sortBy) {\r\n Continuation.Builder continuationBuilder = Continuation.newBuilder()\r\n .setVideoIdMsg(VideoIdMsg.newBuilder().setVideoId(videoId).build())\r\n .setUnknownInt3(6);\r\n CommentSectionInfo.Config config = CommentSectionInfo.Config.newBuilder()\r\n .setVideoId(videoId)\r\n .setSortBy(sortBy)\r\n .setUnknownInt15(2)\r\n .setUnknownInt41(1)\r\n .setUnknownInt44(1)\r\n .setUnknownBytes45(ByteString.copyFrom(new byte[]{1,6,8,5}))\r\n .build();\r\n continuationBuilder.setCommentSectionInfo(CommentSectionInfo.newBuilder().setConfig(config).setCommentsSectionMy(\"comments-section\").build());\r\n return continuationBuilder.build();\r\n }\r\n\r\n public static String escapeBase64 (String base64){\r\n return base64.replace(\"+\",\"-\").replace(\"/\",\"_\").replace(\"=\",\"%3D\");\r\n }\r\n}\r" }, { "identifier": "ProgressBarDialog", "path": "YTSendCommAntiFraud/app/src/main/java/icu/freedomintrovert/YTSendCommAntiFraud/view/ProgressBarDialog.java", "snippet": "public class ProgressBarDialog implements DialogInterface {\r\n public static final int DEFAULT_MAX_PROGRESS = 1000;\r\n public final AlertDialog alertDialog;\r\n final ProgressBar progressBar;\r\n\r\n ProgressBarDialog(AlertDialog alertDialog, ProgressBar progressBar) {\r\n this.alertDialog = alertDialog;\r\n this.progressBar = progressBar;\r\n }\r\n\r\n public void setProgress(int progress){\r\n progressBar.setProgress(progress);\r\n }\r\n\r\n public void setMax(int max){\r\n progressBar.setMax(max);\r\n }\r\n\r\n public void setIndeterminate(boolean indeterminate){\r\n progressBar.setIndeterminate(indeterminate);\r\n }\r\n\r\n public void setMessage(String message){\r\n alertDialog.setMessage(message);\r\n }\r\n\r\n public void setTitle(String title){\r\n alertDialog.setTitle(title);\r\n }\r\n\r\n public Button getButton(int whichButton){\r\n return alertDialog.getButton(whichButton);\r\n }\r\n\r\n @Override\r\n public void cancel() {\r\n alertDialog.cancel();\r\n }\r\n\r\n @Override\r\n public void dismiss() {\r\n alertDialog.dismiss();\r\n }\r\n\r\n public static class Builder {\r\n\r\n private final AlertDialog.Builder dialogBuilder;\r\n private final ProgressBar progressBar;\r\n\r\n\r\n public Builder(Context context) {\r\n dialogBuilder = new AlertDialog.Builder(context);\r\n View view = View.inflate(context, R.layout.dialog_wait_progress,null);\r\n progressBar = view.findViewById(R.id.wait_progress_bar);\r\n dialogBuilder.setView(view);\r\n progressBar.setMax(DEFAULT_MAX_PROGRESS);\r\n }\r\n\r\n public Builder setTitle(String title) {\r\n dialogBuilder.setTitle(title);\r\n return this;\r\n }\r\n\r\n public Builder setMessage(String message) {\r\n dialogBuilder.setMessage(message);\r\n return this;\r\n }\r\n\r\n public Builder setPositiveButton(String text, OnClickListener listener) {\r\n dialogBuilder.setPositiveButton(text, listener);\r\n return this;\r\n }\r\n\r\n public Builder setNegativeButton(String text, OnClickListener listener) {\r\n dialogBuilder.setNegativeButton(text, listener);\r\n return this;\r\n }\r\n\r\n public Builder setNeutralButton (String text, OnClickListener listener){\r\n dialogBuilder.setNeutralButton(text, listener);\r\n return this;\r\n }\r\n\r\n public Builder setCancelable(boolean cancelable) {\r\n dialogBuilder.setCancelable(cancelable);\r\n return this;\r\n }\r\n\r\n public Builder setOnCancelListener(OnCancelListener listener) {\r\n dialogBuilder.setOnCancelListener(listener);\r\n return this;\r\n }\r\n\r\n public Builder setOnDismissListener(OnDismissListener listener) {\r\n dialogBuilder.setOnDismissListener(listener);\r\n return this;\r\n }\r\n\r\n public Builder setProgress(int progress){\r\n progressBar.setProgress(progress);\r\n return this;\r\n }\r\n\r\n public Builder setMax(int max){\r\n progressBar.setMax(max);\r\n return this;\r\n }\r\n\r\n public Builder setIndeterminate(boolean indeterminate){\r\n progressBar.setIndeterminate(indeterminate);\r\n return this;\r\n }\r\n\r\n public ProgressBarDialog show() {\r\n return new ProgressBarDialog(dialogBuilder.show(),progressBar);\r\n }\r\n }\r\n\r\n\r\n}\r" } ]
import android.app.NotificationManager; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.provider.Settings; import android.util.Base64; import android.view.View; import android.widget.Toast; import androidx.appcompat.app.AlertDialog; import java.util.Date; import java.util.Locale; import icu.freedomintrovert.YTSendCommAntiFraud.comment.Comment; import icu.freedomintrovert.YTSendCommAntiFraud.comment.HistoryComment; import icu.freedomintrovert.YTSendCommAntiFraud.comment.VideoComment; import icu.freedomintrovert.YTSendCommAntiFraud.comment.VideoCommentSection; import icu.freedomintrovert.YTSendCommAntiFraud.db.StatisticsDB; import icu.freedomintrovert.YTSendCommAntiFraud.grpcApi.nestedIntoBase64.SortBy; import icu.freedomintrovert.YTSendCommAntiFraud.rxObservables.FindCommentObservableOnSubscribe; import icu.freedomintrovert.YTSendCommAntiFraud.utils.OkHttpUtils; import icu.freedomintrovert.YTSendCommAntiFraud.utils.ProtobufUtils; import icu.freedomintrovert.YTSendCommAntiFraud.view.ProgressBarDialog; import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers; import io.reactivex.rxjava3.annotations.NonNull; import io.reactivex.rxjava3.core.Observable; import io.reactivex.rxjava3.disposables.CompositeDisposable; import io.reactivex.rxjava3.observers.DisposableObserver; import io.reactivex.rxjava3.schedulers.Schedulers;
9,611
package icu.freedomintrovert.YTSendCommAntiFraud; public class DialogCommentChecker { Context context; StatisticsDB statisticsDB; Config config; CompositeDisposable compositeDisposable = new CompositeDisposable(); public DialogCommentChecker(Context context, StatisticsDB statisticsDB, Config config) { this.context = context; this.statisticsDB = statisticsDB; this.config = config; } public void check(Comment comment, String videoId, int commentSectionType, byte[] context1, Bundle headers, boolean needToWait, OnExitListener onExitListener, Date sendDate){ VideoCommentSection videoCommentSection = new VideoCommentSection(OkHttpUtils.getOkHttpClient(), context1,
package icu.freedomintrovert.YTSendCommAntiFraud; public class DialogCommentChecker { Context context; StatisticsDB statisticsDB; Config config; CompositeDisposable compositeDisposable = new CompositeDisposable(); public DialogCommentChecker(Context context, StatisticsDB statisticsDB, Config config) { this.context = context; this.statisticsDB = statisticsDB; this.config = config; } public void check(Comment comment, String videoId, int commentSectionType, byte[] context1, Bundle headers, boolean needToWait, OnExitListener onExitListener, Date sendDate){ VideoCommentSection videoCommentSection = new VideoCommentSection(OkHttpUtils.getOkHttpClient(), context1,
ProtobufUtils.escapeBase64(Base64.encodeToString(ProtobufUtils.generateContinuation(videoId, SortBy.latest).toByteArray(), Base64.DEFAULT)),
5
2023-10-15 01:18:28+00:00
12k
New-Barams/This-Year-Ajaja-BE
src/main/java/com/newbarams/ajaja/module/plan/application/CreatePlanService.java
[ { "identifier": "ErrorCode", "path": "src/main/java/com/newbarams/ajaja/global/exception/ErrorCode.java", "snippet": "@Getter\n@RequiredArgsConstructor\npublic enum ErrorCode {\n\t// 400\n\tBEAN_VALIDATION_FAIL_EXCEPTION(BAD_REQUEST, \"올바르지 않은 데이터입니다.\"),\n\tINVALID_REQUEST(BAD_REQUEST, \"올바른 형식의 데이터가 입력되지 않았습니다.\"),\n\tINVALID_BEARER_TOKEN(BAD_REQUEST, \"유효한 Bearer 토큰의 형식이 아닙니다.\"),\n\tINVALID_SIGNATURE(BAD_REQUEST, \"잘못된 서명입니다.\"),\n\tINVALID_TOKEN(BAD_REQUEST, \"잘못된 토큰입니다.\"),\n\tEMPTY_TOKEN(BAD_REQUEST, \"비어있는 토큰입니다.\"),\n\tEXPIRED_TOKEN(BAD_REQUEST, \"만료된 토큰입니다.\"),\n\tUNSUPPORTED_TOKEN(BAD_REQUEST, \"지원하지 않는 토큰입니다.\"),\n\tTOKEN_NOT_MATCH(BAD_REQUEST, \"일치하지 않는 토큰입니다.\"),\n\tINVALID_USER_ACCESS(BAD_REQUEST, \"잘못된 유저의 접근입니다.\"),\n\tINVALID_UPDATABLE_DATE(BAD_REQUEST, \"변경 가능한 기간이 아닙니다.\"),\n\tNOT_SUPPORT_RECEIVE_TYPE(BAD_REQUEST, \"지원하는 리마인드 수신 방법이 아닙니다.\"),\n\tEXCEED_MAX_NUMBER_OF_PLANS(BAD_REQUEST, \"유저가 가질 수 있는 최대 계획 개수를 초과하였습니다.\"),\n\tEMPTY_MESSAGES_LIST(BAD_REQUEST, \"작성된 리마인드 메세지가 없습니다.\"),\n\tEXPIRED_FEEDBACK(CONFLICT, \"피드백 기간이 아닙니다.\"),\n\n\t// 404\n\tUSER_NOT_FOUND(NOT_FOUND, \"사용자가 존재하지 않습니다.\"),\n\tCERTIFICATION_NOT_FOUND(NOT_FOUND, \"인증 요청 시간이 초과하였거나 인증을 요청한 적이 없습니다.\"),\n\tNEVER_LOGIN(NOT_FOUND, \"로그인한 이력을 찾을 수 없습니다. 다시 로그인 해주세요.\"),\n\tNOT_FOUND_PLAN(NOT_FOUND, \"계획 정보가 존재하지 않습니다.\"),\n\tNOT_FOUND_FEEDBACK(NOT_FOUND, \"피드백 정보가 존재하지 않습니다.\"),\n\n\t// 409\n\tALREADY_FEEDBACK(CONFLICT, \"이미 평가된 피드백 정보가 있습니다.\"),\n\tUNABLE_TO_VERIFY_EMAIL(CONFLICT, \"이메일 인증을 할 수 없습니다. 인증이 완료된 상태라면 기존 리마인드 이메일과 다른 이메일을 입력해야 합니다.\"),\n\tCERTIFICATION_NOT_MATCH(CONFLICT, \"인증 번호가 일치하지 않습니다.\"),\n\n\t// 500\n\tAJAJA_SERVER_ERROR(INTERNAL_SERVER_ERROR, \"서버 내부 오류입니다. 관리자에게 문의바랍니다.\"),\n\tEXTERNAL_API_FAIL(INTERNAL_SERVER_ERROR, \"외부 API 호출에 실패했습니다.\");\n\n\tprivate final HttpStatus httpStatus;\n\tprivate final String message;\n}" }, { "identifier": "AjajaException", "path": "src/main/java/com/newbarams/ajaja/global/exception/AjajaException.java", "snippet": "@Getter\npublic class AjajaException extends RuntimeException {\n\tprivate final ErrorCode errorCode;\n\n\tpublic AjajaException(ErrorCode errorCode) {\n\t\tsuper(errorCode.getMessage());\n\t\tthis.errorCode = errorCode;\n\t}\n\n\tpublic AjajaException(Throwable cause, ErrorCode errorCode) {\n\t\tsuper(errorCode.getMessage(), cause);\n\t\tthis.errorCode = errorCode;\n\t}\n\n\tprivate AjajaException(String message, ErrorCode errorCode) {\n\t\tsuper(message);\n\t\tthis.errorCode = errorCode;\n\t}\n\n\tpublic static AjajaException withId(Long id, ErrorCode errorCode) {\n\t\tString message = errorCode.getMessage() + \" Wrong with Id :\" + id;\n\t\treturn new AjajaException(message, errorCode);\n\t}\n\n\tpublic int getHttpStatus() {\n\t\treturn errorCode.getHttpStatus().value();\n\t}\n}" }, { "identifier": "Plan", "path": "src/main/java/com/newbarams/ajaja/module/plan/domain/Plan.java", "snippet": "@Getter\n@AllArgsConstructor\npublic class Plan {\n\tprivate static final int MODIFIABLE_MONTH = 1;\n\tprivate static final int ONE_MONTH_TERM = 1;\n\n\tprivate Long id;\n\n\tprivate Long userId;\n\n\tprivate int iconNumber;\n\n\tprivate Content content;\n\tprivate RemindInfo info;\n\tprivate PlanStatus status;\n\n\tprivate List<Message> messages;\n\n\tprivate List<AjajaEntity> ajajas;\n\tprivate TimeValue createdAt;\n\n\tPlan(Long userId, Content content, RemindInfo info, PlanStatus status,\n\t\tint iconNumber, List<Message> messages) {\n\t\tthis.userId = userId;\n\t\tthis.content = content;\n\t\tthis.info = info;\n\t\tthis.status = status;\n\t\tthis.iconNumber = iconNumber;\n\t\tthis.messages = messages;\n\t\tthis.ajajas = new ArrayList<>();\n\t}\n\n\tpublic static Plan create(PlanParam.Create param) {\n\t\tvalidateModifiableMonth(param.getMonth());\n\n\t\treturn new Plan(param.getUserId(), param.getContent(), param.getInfo(), param.getStatus(),\n\t\t\tparam.getIconNumber(), param.getMessages());\n\t}\n\n\tpublic void delete(Long userId, int month) {\n\t\tvalidateModifiableMonth(month);\n\t\tvalidateUser(userId);\n\t\tthis.status.toDeleted();\n\t}\n\n\tprivate static void validateModifiableMonth(int month) {\n\t\tif (month != MODIFIABLE_MONTH) {\n\t\t\tthrow new AjajaException(INVALID_UPDATABLE_DATE);\n\t\t}\n\t}\n\n\tprivate void validateUser(Long userId) {\n\t\tif (!this.userId.equals(userId)) {\n\t\t\tthrow new AjajaException(INVALID_USER_ACCESS);\n\t\t}\n\t}\n\n\tpublic void updatePublicStatus(Long userId) {\n\t\tvalidateUser(userId);\n\t\tthis.status.switchPublic();\n\t}\n\n\tpublic void updateRemindStatus(Long userId) {\n\t\tvalidateUser(userId);\n\t\tthis.status.switchRemind();\n\t}\n\n\tpublic void updateAjajaStatus(Long userId) {\n\t\tvalidateUser(userId);\n\t\tthis.status.switchAjaja();\n\t}\n\n\tpublic void update(PlanParam.Update param) {\n\t\tvalidateModifiableMonth(param.getMonth());\n\t\tvalidateUser(param.getUserId());\n\t\tthis.iconNumber = param.getIconNumber();\n\t\tthis.content = param.getContent();\n\t\tthis.status = status.update(param.isPublic(), param.isCanAjaja());\n\t}\n\n\tpublic void updateRemind(RemindInfo info, List<Message> messages) {\n\t\tif (new TimeValue().getMonth() != MODIFIABLE_MONTH) {\n\t\t\tthrow new AjajaException(INVALID_UPDATABLE_DATE);\n\t\t}\n\n\t\tthis.info = info;\n\t\tthis.messages = messages;\n\t}\n\n\tpublic int getRemindTime() {\n\t\treturn this.info.getRemindTime();\n\t}\n\n\tpublic String getRemindTimeName() {\n\t\treturn this.info.getRemindTimeName();\n\t}\n\n\tpublic int getRemindMonth() {\n\t\treturn this.info.getRemindMonth();\n\t}\n\n\tpublic int getRemindDate() {\n\t\treturn this.info.getRemindDate();\n\t}\n\n\tpublic int getRemindTerm() {\n\t\treturn this.info.getRemindTerm();\n\t}\n\n\tpublic int getRemindTotalPeriod() {\n\t\treturn this.info.getRemindTotalPeriod();\n\t}\n\n\tpublic boolean getIsRemindable() {\n\t\treturn this.status.isCanRemind();\n\t}\n\n\tpublic int getTotalRemindNumber() {\n\t\treturn this.info.getTotalRemindNumber();\n\t}\n\n\tpublic String getPlanTitle() {\n\t\treturn this.content.getTitle();\n\t}\n\n\tpublic String getMessage(int currentMonth) {\n\t\tint messageIdx = getMessageIdx(this.info.getRemindTerm(), currentMonth);\n\t\treturn this.messages.get(messageIdx).getContent();\n\t}\n\n\tprivate int getMessageIdx(int remindTerm, int currentMonth) {\n\t\treturn remindTerm == ONE_MONTH_TERM ? (currentMonth - 2) : currentMonth / remindTerm - 1;\n\t}\n\n\tpublic void disable() {\n\t\tthis.status = status.disable();\n\t}\n\n\tpublic TimeValue getFeedbackPeriod(TimeValue current) {\n\t\treturn this.messages.stream()\n\t\t\t.filter(message -> current.isBetween(\n\t\t\t\tTimeValue.parse(\n\t\t\t\t\tthis.createdAt.getYear(),\n\t\t\t\t\tmessage.getRemindDate().getRemindMonth(),\n\t\t\t\t\tmessage.getRemindDate().getRemindDay(),\n\t\t\t\t\tthis.getRemindTime()))\n\t\t\t)\n\t\t\t.findAny()\n\t\t\t.map(message -> TimeValue.parse(this.createdAt.getYear(),\n\t\t\t\tmessage.getRemindDate().getRemindMonth(),\n\t\t\t\tmessage.getRemindDate().getRemindDay(),\n\t\t\t\tthis.getRemindTime()))\n\t\t\t.orElseThrow(() -> new AjajaException(EXPIRED_FEEDBACK));\n\t}\n}" }, { "identifier": "PlanRepository", "path": "src/main/java/com/newbarams/ajaja/module/plan/domain/PlanRepository.java", "snippet": "@Repository\npublic interface PlanRepository {\n\tPlan save(Plan plan);\n\n\tOptional<Plan> findById(Long id);\n\n\tList<Plan> saveAll(List<Plan> plans);\n}" }, { "identifier": "PlanRequest", "path": "src/main/java/com/newbarams/ajaja/module/plan/dto/PlanRequest.java", "snippet": "public class PlanRequest {\n\t@Data\n\tpublic static class Create {\n\t\tprivate final String title;\n\t\tprivate final String description;\n\n\t\tprivate final int remindTotalPeriod;\n\t\tprivate final int remindTerm;\n\t\tprivate final int remindDate;\n\t\tprivate final String remindTime;\n\n\t\tprivate final boolean isPublic;\n\t\tprivate final boolean canAjaja;\n\n\t\tprivate final int iconNumber;\n\n\t\tprivate final List<String> tags;\n\n\t\tprivate final List<Message> messages;\n\t}\n\n\t@Data\n\tpublic static class Message {\n\t\tprivate final String content;\n\t\tprivate final int remindMonth;\n\t\tprivate final int remindDay;\n\t}\n\n\t@Data\n\tpublic static class Update {\n\t\tprivate final int iconNumber;\n\n\t\tprivate final String title;\n\t\tprivate final String description;\n\n\t\tprivate final boolean isPublic;\n\t\tprivate final boolean canAjaja;\n\n\t\tprivate final List<String> tags;\n\t}\n\n\t@Data\n\tpublic static class UpdateRemind {\n\t\tint remindTotalPeriod;\n\t\tint remindTerm;\n\t\tint remindDate;\n\t\tString remindTime;\n\t\tList<Message> messages;\n\t}\n\n\t@Data\n\tpublic static class GetAll {\n\t\tprivate final String sort;\n\t\tprivate final boolean current;\n\t\tprivate final Integer ajaja;\n\t\tprivate final Long start;\n\t}\n}" }, { "identifier": "PlanResponse", "path": "src/main/java/com/newbarams/ajaja/module/plan/dto/PlanResponse.java", "snippet": "public final class PlanResponse {\n\t@Data\n\tpublic static class Detail {\n\t\tprivate final Writer writer;\n\t\tprivate final Long id;\n\t\tprivate final String title;\n\t\tprivate final String description;\n\t\tprivate final int icon;\n\t\tprivate final boolean isPublic;\n\t\tprivate final boolean canRemind;\n\t\tprivate final boolean canAjaja;\n\t\tprivate final long ajajas;\n\t\tprivate final List<String> tags;\n\t\tprivate final Instant createdAt;\n\n\t\t@QueryProjection\n\t\tpublic Detail(Writer writer, Long id, String title, String description, int icon, boolean isPublic,\n\t\t\tboolean canRemind, boolean canAjaja, long ajajas, List<String> tags, Instant createdAt\n\t\t) {\n\t\t\tthis.writer = writer;\n\t\t\tthis.id = id;\n\t\t\tthis.title = title;\n\t\t\tthis.description = description;\n\t\t\tthis.icon = icon;\n\t\t\tthis.isPublic = isPublic;\n\t\t\tthis.canRemind = canRemind;\n\t\t\tthis.canAjaja = canAjaja;\n\t\t\tthis.ajajas = ajajas;\n\t\t\tthis.tags = tags;\n\t\t\tthis.createdAt = createdAt;\n\t\t}\n\t}\n\n\t@Data\n\tpublic static class Writer {\n\t\tprivate final String nickname;\n\t\tprivate final boolean isOwner;\n\t\tprivate final boolean isAjajaPressed;\n\n\t\t@QueryProjection\n\t\tpublic Writer(String nickname, boolean isOwner, boolean isAjajaPressed) {\n\t\t\tthis.nickname = nickname;\n\t\t\tthis.isOwner = isOwner;\n\t\t\tthis.isAjajaPressed = isAjajaPressed;\n\t\t}\n\t}\n\n\t@Data\n\tpublic static class GetOne {\n\t\tprivate final Long id;\n\n\t\tprivate final Long userId;\n\t\tprivate final String nickname;\n\n\t\tprivate final String title;\n\t\tprivate final String description;\n\n\t\tprivate final int iconNumber;\n\n\t\tprivate final boolean isPublic;\n\t\tprivate final boolean canRemind;\n\t\tprivate final boolean canAjaja;\n\n\t\tprivate final long ajajas;\n\t\tprivate final boolean isPressAjaja;\n\n\t\tprivate final List<String> tags;\n\n\t\tprivate final Instant createdAt;\n\t}\n\n\t@Data\n\tpublic static class GetAll {\n\t\tprivate final Long id;\n\n\t\tprivate final Long userId;\n\t\tprivate final String nickname;\n\n\t\tprivate final String title;\n\n\t\tprivate final int iconNumber;\n\n\t\tprivate final long ajajas;\n\n\t\tprivate final List<String> tags;\n\n\t\tprivate final Instant createdAt;\n\t}\n\n\t@Data\n\tpublic static class Create {\n\t\tprivate final Long id;\n\n\t\tprivate final Long userId;\n\n\t\tprivate final String title;\n\t\tprivate final String description;\n\n\t\tprivate final int iconNumber;\n\n\t\tprivate final boolean isPublic;\n\t\tprivate final boolean canRemind;\n\t\tprivate final boolean canAjaja;\n\n\t\tprivate final int ajajas = 0;\n\n\t\tprivate final List<String> tags;\n\t}\n\n\t@Data\n\tpublic static class MainInfo {\n\t\tprivate final int year;\n\t\tprivate final int totalAchieveRate;\n\t\tprivate final List<PlanResponse.PlanInfo> getPlanList;\n\t}\n\n\t@Data\n\tpublic static class PlanInfo {\n\t\tprivate final int year;\n\t\tprivate final Long planId;\n\t\tprivate final String title;\n\t\tprivate final boolean remindable;\n\t\tprivate final int achieveRate;\n\t\tprivate final int icon;\n\t}\n}" }, { "identifier": "PlanQueryRepository", "path": "src/main/java/com/newbarams/ajaja/module/plan/infra/PlanQueryRepository.java", "snippet": "@Repository\n@RequiredArgsConstructor\npublic class PlanQueryRepository {\n\tprivate static final String LATEST = \"latest\";\n\tprivate static final String AJAJA = \"ajaja\";\n\tprivate static final int PAGE_SIZE = 3;\n\n\tprivate final JPAQueryFactory queryFactory;\n\tprivate final PlanMapper planMapper;\n\n\tpublic List<Plan> findAllCurrentPlansByUserId(Long userId) { // todo: domain dependency\n\t\treturn queryFactory.selectFrom(planEntity)\n\t\t\t.where(planEntity.userId.eq(userId)\n\t\t\t\t.and(isCurrentYear()))\n\t\t\t.fetch()\n\t\t\t.stream().map(planMapper::toDomain)\n\t\t\t.toList();\n\t}\n\n\tpublic Long countByUserId(Long userId) {\n\t\treturn queryFactory.select(planEntity.count())\n\t\t\t.from(planEntity)\n\t\t\t.where(planEntity.userId.eq(userId)\n\t\t\t\t.and(isCurrentYear()))\n\t\t\t.fetchFirst();\n\t}\n\n\tprivate BooleanExpression isCurrentYear() {\n\t\treturn planEntity.createdAt.year().eq(new TimeValue().getYear());\n\t}\n\n\tpublic Optional<PlanResponse.Detail> findPlanDetailByIdAndOptionalUser(Long userId, Long id) {\n\t\treturn Optional.ofNullable(queryFactory.select(new QPlanResponse_Detail(\n\t\t\t\tnew QPlanResponse_Writer(\n\t\t\t\t\tuserEntity.nickname,\n\t\t\t\t\tuserId == null ? FALSE : userEntity.id.intValue().eq(asNumber(userId)), // bigint casting error\n\t\t\t\t\tuserId == null ? FALSE : isAjajaPressed(userId, id)),\n\t\t\t\tasNumber(id),\n\t\t\t\tplanEntity.title,\n\t\t\t\tplanEntity.description,\n\t\t\t\tplanEntity.iconNumber,\n\t\t\t\tplanEntity.isPublic,\n\t\t\t\tplanEntity.canRemind,\n\t\t\t\tplanEntity.canAjaja,\n\t\t\t\tplanEntity.ajajas.size().longValue(),\n\t\t\t\tconstant(findAllTagsByPlanId(id)),\n\t\t\t\tplanEntity.createdAt))\n\t\t\t.from(planEntity)\n\t\t\t.leftJoin(userEntity).on(userEntity.id.eq(planEntity.userId))\n\t\t\t.where(planEntity.id.eq(id))\n\t\t\t.fetchOne()\n\t\t);\n\t}\n\n\tprivate BooleanExpression isAjajaPressed(Long userId, Long id) {\n\t\treturn Expressions.asBoolean(queryFactory.selectFrom(ajajaEntity)\n\t\t\t.where(ajajaEntity.targetId.eq(id)\n\t\t\t\t.and(ajajaEntity.userId.eq(userId))\n\t\t\t\t.and(ajajaEntity.type.eq(Ajaja.Type.PLAN.name()))\n\t\t\t\t.and(ajajaEntity.canceled.isFalse()))\n\t\t\t.fetchFirst() != null);\n\t}\n\n\tpublic Plan findByUserIdAndPlanId(Long userId, Long planId) {\n\t\tPlanEntity entity = queryFactory.selectFrom(planEntity)\n\t\t\t.where(planEntity.userId.eq(userId)\n\t\t\t\t.and(planEntity.id.eq(planId)))\n\t\t\t.fetchOne();\n\n\t\tif (entity == null) {\n\t\t\tthrow AjajaException.withId(planId, NOT_FOUND_PLAN);\n\t\t}\n\t\treturn planMapper.toDomain(entity);\n\t}\n\n\tprivate List<String> findAllTagsByPlanId(Long planId) {\n\t\treturn queryFactory.select(tag.name)\n\t\t\t.from(planTag, tag)\n\t\t\t.where(planTag.tagId.eq(tag.id)\n\t\t\t\t.and(planTag.planId.eq(planId)))\n\t\t\t.fetch();\n\t}\n\n\tpublic List<PlanResponse.GetAll> findAllByCursorAndSorting(PlanRequest.GetAll conditions) {\n\t\tList<Tuple> tuples = queryFactory.select(planEntity, userEntity.nickname)\n\t\t\t.from(planEntity, userEntity)\n\n\t\t\t.where(planEntity.userId.eq(userEntity.id),\n\t\t\t\tplanEntity.isPublic.eq(true),\n\t\t\t\tisEqualsYear(conditions.isCurrent()),\n\t\t\t\tcursorPagination(conditions))\n\n\t\t\t.orderBy(sortBy(conditions.getSort()))\n\t\t\t.limit(PAGE_SIZE)\n\t\t\t.fetch();\n\n\t\treturn tupleToResponse(tuples);\n\t}\n\n\tprivate BooleanExpression isEqualsYear(boolean isNewYear) {\n\t\tint currentYear = new TimeValue().getYear();\n\t\treturn isNewYear ? planEntity.createdAt.year().eq(currentYear) : planEntity.createdAt.year().ne(currentYear);\n\t}\n\n\tprivate BooleanExpression cursorPagination(PlanRequest.GetAll conditions) {\n\t\treturn conditions.getStart() == null ? null :\n\t\t\tgetCursorCondition(conditions.getSort(), conditions.getStart(), conditions.getAjaja());\n\t}\n\n\tprivate BooleanExpression getCursorCondition(String sort, Long start, Integer cursorAjaja) {\n\t\treturn sort.equalsIgnoreCase(LATEST) ? planEntity.id.lt(start) : cursorAjajaAndId(cursorAjaja, start);\n\t}\n\n\tprivate BooleanExpression cursorAjajaAndId(Integer cursorAjaja, Long cursorId) {\n\t\treturn cursorAjaja == null ? null :\n\t\t\tplanEntity.ajajas.size().eq(cursorAjaja)\n\t\t\t\t.and(planEntity.id.lt(cursorId))\n\t\t\t\t.or(planEntity.ajajas.size().lt(cursorAjaja));\n\t}\n\n\tprivate OrderSpecifier[] sortBy(String condition) {\n\t\treturn switch (condition.toLowerCase(Locale.ROOT)) {\n\t\t\tcase LATEST -> new OrderSpecifier[] {new OrderSpecifier<>(Order.DESC, planEntity.createdAt)};\n\t\t\tcase AJAJA -> new OrderSpecifier[] {\n\t\t\t\tnew OrderSpecifier<>(Order.DESC, planEntity.ajajas.size()),\n\t\t\t\tnew OrderSpecifier<>(Order.DESC, planEntity.id)\n\t\t\t};\n\t\t\tdefault -> new OrderSpecifier[0];\n\t\t};\n\t}\n\n\tprivate List<PlanResponse.GetAll> tupleToResponse(List<Tuple> tuples) {\n\t\treturn tuples.stream()\n\t\t\t.map(tuple -> {\n\t\t\t\tPlanEntity planFromTuple = tuple.get(planEntity);\n\t\t\t\tString nickname = tuple.get(userEntity.nickname);\n\t\t\t\tList<String> tags = findAllTagsByPlanId(planFromTuple.getId());\n\n\t\t\t\treturn planMapper.toResponse(planFromTuple, nickname, tags);\n\t\t\t})\n\t\t\t.toList();\n\t}\n\n\tpublic List<PlanResponse.PlanInfo> findAllPlanByUserId(Long userId) {\n\t\treturn queryFactory.select(Projections.constructor(PlanResponse.PlanInfo.class,\n\t\t\t\tplanEntity.createdAt.year(),\n\t\t\t\tplanEntity.id,\n\t\t\t\tplanEntity.title,\n\t\t\t\tplanEntity.canRemind,\n\t\t\t\tfeedbackEntity.achieve.avg().intValue(),\n\t\t\t\tplanEntity.iconNumber\n\t\t\t))\n\t\t\t.from(planEntity)\n\t\t\t.leftJoin(feedbackEntity).on(feedbackEntity.planId.eq(planEntity.id))\n\t\t\t.groupBy(planEntity.createdAt.year(),\n\t\t\t\tplanEntity.id,\n\t\t\t\tplanEntity.title,\n\t\t\t\tplanEntity.canRemind,\n\t\t\t\tplanEntity.iconNumber)\n\t\t\t.where(planEntity.userId.eq(userId))\n\t\t\t.orderBy(planEntity.createdAt.year().desc())\n\t\t\t.fetch();\n\t}\n\n\tpublic List<RemindMessageInfo> findAllRemindablePlan(String remindTime, TimeValue time) {\n\t\treturn queryFactory.select(planEntity, userEntity.remindEmail)\n\t\t\t.from(planEntity)\n\t\t\t.join(userEntity).on(userEntity.id.eq(planEntity.userId))\n\t\t\t.where(planEntity.canRemind\n\t\t\t\t.and(planEntity.remindTime.eq(remindTime).and(isRemindable(time))))\n\t\t\t.fetch().stream()\n\t\t\t.map(t -> planMapper.toModel(t.get(planEntity), t.get(userEntity.remindEmail)))\n\t\t\t.toList();\n\t}\n\n\tprivate BooleanExpression isRemindable(TimeValue time) {\n\t\tRemindDate today = new RemindDate(time.getMonth(), time.getDate());\n\t\treturn planEntity.createdAt.year().eq(time.getYear())\n\t\t\t.andAnyOf(planEntity.messages.any().remindDate.eq(today));\n\t}\n}" }, { "identifier": "PlanMapper", "path": "src/main/java/com/newbarams/ajaja/module/plan/mapper/PlanMapper.java", "snippet": "@Mapper(componentModel = \"spring\")\npublic interface PlanMapper {\n\t@Mapping(source = \"content.title\", target = \"title\")\n\t@Mapping(source = \"content.description\", target = \"description\")\n\t@Mapping(source = \"info.remindTotalPeriod\", target = \"remindTotalPeriod\")\n\t@Mapping(source = \"info.remindTerm\", target = \"remindTerm\")\n\t@Mapping(source = \"info.remindDate\", target = \"remindDate\")\n\t@Mapping(target = \"remindTime\", expression = \"java(plan.getRemindTimeName())\")\n\t@Mapping(source = \"status.public\", target = \"isPublic\")\n\t@Mapping(source = \"status.canRemind\", target = \"canRemind\")\n\t@Mapping(source = \"status.canAjaja\", target = \"canAjaja\")\n\t@Mapping(source = \"status.deleted\", target = \"deleted\")\n\tPlanEntity toEntity(Plan plan);\n\n\t@Mapping(source = \"planEntity\", target = \"content\", qualifiedByName = \"toContent\")\n\t@Mapping(source = \"planEntity\", target = \"info\", qualifiedByName = \"toRemindInfo\")\n\t@Mapping(source = \"planEntity\", target = \"status\", qualifiedByName = \"toPlanStatus\")\n\t@Mapping(target = \"createdAt\", expression = \"java(parseTimeValue(planEntity.getCreatedAt()))\")\n\tPlan toDomain(PlanEntity planEntity);\n\n\tdefault TimeValue parseTimeValue(Instant createdAt) {\n\t\treturn createdAt == null ? null : new TimeValue(createdAt); // 계획 저장 후 조회 시 작성일 null로 인한 코드\n\t}\n\n\t@Named(\"toContent\")\n\tstatic Content toContent(PlanEntity planEntity) {\n\t\treturn new Content(planEntity.getTitle(), planEntity.getDescription());\n\t}\n\n\t@Named(\"toRemindInfo\")\n\tstatic RemindInfo toRemindInfo(PlanEntity planEntity) {\n\t\treturn new RemindInfo(planEntity.getRemindTotalPeriod(), planEntity.getRemindTerm(),\n\t\t\tplanEntity.getRemindDate(), planEntity.getRemindTime());\n\t}\n\n\t@Named(\"toPlanStatus\")\n\tstatic PlanStatus toPlanStatus(PlanEntity planEntity) {\n\t\treturn new PlanStatus(planEntity.isPublic(), planEntity.isCanRemind(), planEntity.isCanAjaja(),\n\t\t\tplanEntity.isDeleted());\n\t}\n\n\t@Mapping(source = \"request\", target = \"content\", qualifiedByName = \"toContent\")\n\t@Mapping(source = \"request\", target = \"info\", qualifiedByName = \"toRemindInfo\")\n\t@Mapping(source = \"request.messages\", target = \"messages\", qualifiedByName = \"toMessages\")\n\t@Mapping(source = \"request\", target = \"status\", qualifiedByName = \"toPlanStatus\")\n\tPlanParam.Create toParam(Long userId, PlanRequest.Create request, int month);\n\n\t@Named(\"toContent\")\n\tstatic Content toContent(PlanRequest.Create request) {\n\t\treturn new Content(request.getTitle(), request.getDescription());\n\t}\n\n\t@Named(\"toRemindInfo\")\n\tstatic RemindInfo toRemindInfo(PlanRequest.Create request) {\n\t\treturn new RemindInfo(request.getRemindTotalPeriod(), request.getRemindTerm(),\n\t\t\trequest.getRemindDate(), request.getRemindTime());\n\t}\n\n\t@Named(\"toPlanStatus\")\n\tstatic PlanStatus toPlanStatus(PlanRequest.Create request) {\n\t\treturn new PlanStatus(request.isPublic(), request.isCanAjaja());\n\t}\n\n\t@Mapping(source = \"plan.content.title\", target = \"title\")\n\t@Mapping(source = \"plan.content.description\", target = \"description\")\n\t@Mapping(source = \"plan.status.public\", target = \"isPublic\")\n\t@Mapping(source = \"plan.status.canRemind\", target = \"canRemind\")\n\t@Mapping(source = \"plan.status.canAjaja\", target = \"canAjaja\")\n\tPlanResponse.Create toResponse(Plan plan, List<String> tags);\n\n\t@Mapping(source = \"plan.ajajas\", target = \"ajajas\", qualifiedByName = \"toAjajaCount\")\n\tPlanResponse.GetAll toResponse(PlanEntity plan, String nickname, List<String> tags);\n\n\t@Named(\"toMessages\")\n\t@Mapping(source = \"dto.remindMonth\", target = \"remindMonth\")\n\t@Mapping(source = \"dto.remindDay\", target = \"remindDay\")\n\tList<Message> toMessages(List<PlanRequest.Message> dto);\n\n\t@Named(\"toAjajaCount\")\n\tstatic int toAjajaCount(List<AjajaEntity> ajajas) {\n\t\treturn ajajas.size();\n\t}\n\n\t@Mapping(source = \"request.public\", target = \"isPublic\")\n\t@Mapping(source = \"request\", target = \"content\", qualifiedByName = \"toContent\")\n\tPlanParam.Update toParam(Long userId, PlanRequest.Update request, int month);\n\n\t@Named(\"toContent\")\n\tstatic Content toContent(PlanRequest.Update request) {\n\t\treturn new Content(request.getTitle(), request.getDescription());\n\t}\n\n\t@Mapping(source = \"planYear\", target = \"year\")\n\t@Mapping(target = \"getPlanList\", expression = \"java(createPlanList(planInfos,planYear))\")\n\tPlanResponse.MainInfo toResponse(int planYear, int totalAchieveRate,\n\t\tList<PlanResponse.PlanInfo> planInfos);\n\n\tdefault List<PlanResponse.PlanInfo> createPlanList(List<PlanResponse.PlanInfo> planInfos, int planYear) {\n\t\treturn planInfos.stream()\n\t\t\t.filter(plan -> plan.getYear() == planYear)\n\t\t\t.toList();\n\t}\n\n\t@InheritConfiguration(name = \"toDomain\")\n\tRemindMessageInfo toModel(PlanEntity plan, String email);\n\n\t@Mapping(target = \"createdYear\", expression = \"java(plan.getCreatedAt().getYear())\")\n\t@Mapping(target = \"remindMonth\", expression = \"java(plan.getRemindMonth())\")\n\t@Mapping(target = \"periods\", expression = \"java(getFeedbackPeriods(plan.getMessages()))\")\n\t@Mapping(source = \"info.remindDate\", target = \"remindDate\")\n\t@Mapping(source = \"info.remindTotalPeriod\", target = \"totalPeriod\")\n\t@Mapping(source = \"info.remindTerm\", target = \"remindTerm\")\n\t@Mapping(source = \"info.remindTime\", target = \"remindTime\")\n\t@Mapping(source = \"content.title\", target = \"title\")\n\tPlanFeedbackInfo toModel(Plan plan);\n\n\tdefault List<FeedbackPeriod> getFeedbackPeriods(List<Message> messages) {\n\t\treturn messages.stream().map(Message::getRemindDate)\n\t\t\t.map(remindDate -> new FeedbackPeriod(remindDate.getRemindMonth(), remindDate.getRemindDay()))\n\t\t\t.toList();\n\t}\n}" }, { "identifier": "CreatePlanTagService", "path": "src/main/java/com/newbarams/ajaja/module/tag/application/CreatePlanTagService.java", "snippet": "@Service\n@Transactional\n@RequiredArgsConstructor\npublic class CreatePlanTagService {\n\tprivate final TagRepository tagRepository;\n\tprivate final PlanTagRepository planTagRepository;\n\n\tpublic List<String> create(Long planId, List<String> tagNames) {\n\t\tif (tagNames == null) {\n\t\t\treturn null;\n\t\t}\n\n\t\tSet<String> tagNameSet = new LinkedHashSet<>(tagNames);\n\n\t\treturn tagNameSet.stream()\n\t\t\t.map(tagName -> savePlanTag(planId, tagName))\n\t\t\t.toList();\n\t}\n\n\tprivate String savePlanTag(Long planId, String tagName) {\n\t\tTag tag = getOrCreateTagIfNotExists(tagName);\n\n\t\tPlanTag planTag = new PlanTag(planId, tag.getId());\n\t\tplanTagRepository.save(planTag);\n\n\t\treturn tag.getName();\n\t}\n\n\tprivate Tag getOrCreateTagIfNotExists(String name) {\n\t\treturn tagRepository.findByName(name)\n\t\t\t.orElseGet(() -> tagRepository.save(new Tag(name)));\n\t}\n}" } ]
import static com.newbarams.ajaja.global.exception.ErrorCode.*; import java.util.List; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.newbarams.ajaja.global.exception.AjajaException; import com.newbarams.ajaja.module.plan.domain.Plan; import com.newbarams.ajaja.module.plan.domain.PlanRepository; import com.newbarams.ajaja.module.plan.dto.PlanRequest; import com.newbarams.ajaja.module.plan.dto.PlanResponse; import com.newbarams.ajaja.module.plan.infra.PlanQueryRepository; import com.newbarams.ajaja.module.plan.mapper.PlanMapper; import com.newbarams.ajaja.module.tag.application.CreatePlanTagService; import lombok.RequiredArgsConstructor;
7,537
package com.newbarams.ajaja.module.plan.application; @Service @Transactional @RequiredArgsConstructor public class CreatePlanService { private static final int MAX_NUMBER_OF_PLANS = 4; private final PlanRepository planRepository; private final PlanQueryRepository planQueryRepository; private final CreatePlanTagService createPlanTagService; private final PlanMapper planMapper; public PlanResponse.Create create(Long userId, PlanRequest.Create request, int month) { checkNumberOfUserPlans(userId); Plan plan = Plan.create(planMapper.toParam(userId, request, month)); Plan savedPlan = planRepository.save(plan); List<String> tags = createPlanTagService.create(savedPlan.getId(), request.getTags()); return planMapper.toResponse(savedPlan, tags); } private void checkNumberOfUserPlans(Long userId) { long countOfPlans = planQueryRepository.countByUserId(userId); if (isMoreThanMaxNumberOfPlans(countOfPlans)) {
package com.newbarams.ajaja.module.plan.application; @Service @Transactional @RequiredArgsConstructor public class CreatePlanService { private static final int MAX_NUMBER_OF_PLANS = 4; private final PlanRepository planRepository; private final PlanQueryRepository planQueryRepository; private final CreatePlanTagService createPlanTagService; private final PlanMapper planMapper; public PlanResponse.Create create(Long userId, PlanRequest.Create request, int month) { checkNumberOfUserPlans(userId); Plan plan = Plan.create(planMapper.toParam(userId, request, month)); Plan savedPlan = planRepository.save(plan); List<String> tags = createPlanTagService.create(savedPlan.getId(), request.getTags()); return planMapper.toResponse(savedPlan, tags); } private void checkNumberOfUserPlans(Long userId) { long countOfPlans = planQueryRepository.countByUserId(userId); if (isMoreThanMaxNumberOfPlans(countOfPlans)) {
throw new AjajaException(EXCEED_MAX_NUMBER_OF_PLANS);
1
2023-10-23 07:24:17+00:00
12k
eclipse-jgit/jgit
org.eclipse.jgit/src/org/eclipse/jgit/notes/Note.java
[ { "identifier": "AnyObjectId", "path": "org.eclipse.jgit/src/org/eclipse/jgit/lib/AnyObjectId.java", "snippet": "public abstract class AnyObjectId implements Comparable<AnyObjectId> {\n\n\t/**\n\t * Compare two object identifier byte sequences for equality.\n\t *\n\t * @param firstObjectId\n\t * the first identifier to compare. Must not be null.\n\t * @param secondObjectId\n\t * the second identifier to compare. Must not be null.\n\t * @return true if the two identifiers are the same.\n\t * @deprecated use {@link #isEqual(AnyObjectId, AnyObjectId)} instead\n\t */\n\t@Deprecated\n\t@SuppressWarnings(\"AmbiguousMethodReference\")\n\tpublic static boolean equals(final AnyObjectId firstObjectId,\n\t\t\tfinal AnyObjectId secondObjectId) {\n\t\treturn isEqual(firstObjectId, secondObjectId);\n\t}\n\n\t/**\n\t * Compare two object identifier byte sequences for equality.\n\t *\n\t * @param firstObjectId\n\t * the first identifier to compare. Must not be null.\n\t * @param secondObjectId\n\t * the second identifier to compare. Must not be null.\n\t * @return true if the two identifiers are the same.\n\t * @since 5.4\n\t */\n\tpublic static boolean isEqual(final AnyObjectId firstObjectId,\n\t\t\tfinal AnyObjectId secondObjectId) {\n\t\tif (References.isSameObject(firstObjectId, secondObjectId)) {\n\t\t\treturn true;\n\t\t}\n\t\t// We test word 3 first since the git file-based ODB\n\t\t// uses the first byte of w1, and we use w2 as the\n\t\t// hash code, one of those probably came up with these\n\t\t// two instances which we are comparing for equality.\n\t\t// Therefore the first two words are very likely to be\n\t\t// identical. We want to break away from collisions as\n\t\t// quickly as possible.\n\t\treturn firstObjectId.w3 == secondObjectId.w3\n\t\t\t\t&& firstObjectId.w4 == secondObjectId.w4\n\t\t\t\t&& firstObjectId.w5 == secondObjectId.w5\n\t\t\t\t&& firstObjectId.w1 == secondObjectId.w1\n\t\t\t\t&& firstObjectId.w2 == secondObjectId.w2;\n\t}\n\n\tint w1;\n\n\tint w2;\n\n\tint w3;\n\n\tint w4;\n\n\tint w5;\n\n\t/**\n\t * Get the first 8 bits of the ObjectId.\n\t *\n\t * This is a faster version of {@code getByte(0)}.\n\t *\n\t * @return a discriminator usable for a fan-out style map. Returned values\n\t * are unsigned and thus are in the range [0,255] rather than the\n\t * signed byte range of [-128, 127].\n\t */\n\tpublic final int getFirstByte() {\n\t\treturn w1 >>> 24;\n\t}\n\n\t/**\n\t * Get any byte from the ObjectId.\n\t *\n\t * Callers hard-coding {@code getByte(0)} should instead use the much faster\n\t * special case variant {@link #getFirstByte()}.\n\t *\n\t * @param index\n\t * index of the byte to obtain from the raw form of the ObjectId.\n\t * Must be in range [0,\n\t * {@link org.eclipse.jgit.lib.Constants#OBJECT_ID_LENGTH}).\n\t * @return the value of the requested byte at {@code index}. Returned values\n\t * are unsigned and thus are in the range [0,255] rather than the\n\t * signed byte range of [-128, 127].\n\t * @throws java.lang.ArrayIndexOutOfBoundsException\n\t * {@code index} is less than 0, equal to\n\t * {@link org.eclipse.jgit.lib.Constants#OBJECT_ID_LENGTH}, or\n\t * greater than\n\t * {@link org.eclipse.jgit.lib.Constants#OBJECT_ID_LENGTH}.\n\t */\n\tpublic final int getByte(int index) {\n\t\tint w;\n\t\tswitch (index >> 2) {\n\t\tcase 0:\n\t\t\tw = w1;\n\t\t\tbreak;\n\t\tcase 1:\n\t\t\tw = w2;\n\t\t\tbreak;\n\t\tcase 2:\n\t\t\tw = w3;\n\t\t\tbreak;\n\t\tcase 3:\n\t\t\tw = w4;\n\t\t\tbreak;\n\t\tcase 4:\n\t\t\tw = w5;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tthrow new ArrayIndexOutOfBoundsException(index);\n\t\t}\n\n\t\treturn (w >>> (8 * (3 - (index & 3)))) & 0xff;\n\t}\n\n\t/**\n\t * {@inheritDoc}\n\t * <p>\n\t * Compare this ObjectId to another and obtain a sort ordering.\n\t */\n\t@Override\n\tpublic final int compareTo(AnyObjectId other) {\n\t\tif (this == other)\n\t\t\treturn 0;\n\n\t\tint cmp;\n\n\t\tcmp = NB.compareUInt32(w1, other.w1);\n\t\tif (cmp != 0)\n\t\t\treturn cmp;\n\n\t\tcmp = NB.compareUInt32(w2, other.w2);\n\t\tif (cmp != 0)\n\t\t\treturn cmp;\n\n\t\tcmp = NB.compareUInt32(w3, other.w3);\n\t\tif (cmp != 0)\n\t\t\treturn cmp;\n\n\t\tcmp = NB.compareUInt32(w4, other.w4);\n\t\tif (cmp != 0)\n\t\t\treturn cmp;\n\n\t\treturn NB.compareUInt32(w5, other.w5);\n\t}\n\n\t/**\n\t * Compare this ObjectId to a network-byte-order ObjectId.\n\t *\n\t * @param bs\n\t * array containing the other ObjectId in network byte order.\n\t * @param p\n\t * position within {@code bs} to start the compare at. At least\n\t * 20 bytes, starting at this position are required.\n\t * @return a negative integer, zero, or a positive integer as this object is\n\t * less than, equal to, or greater than the specified object.\n\t */\n\tpublic final int compareTo(byte[] bs, int p) {\n\t\tint cmp;\n\n\t\tcmp = NB.compareUInt32(w1, NB.decodeInt32(bs, p));\n\t\tif (cmp != 0)\n\t\t\treturn cmp;\n\n\t\tcmp = NB.compareUInt32(w2, NB.decodeInt32(bs, p + 4));\n\t\tif (cmp != 0)\n\t\t\treturn cmp;\n\n\t\tcmp = NB.compareUInt32(w3, NB.decodeInt32(bs, p + 8));\n\t\tif (cmp != 0)\n\t\t\treturn cmp;\n\n\t\tcmp = NB.compareUInt32(w4, NB.decodeInt32(bs, p + 12));\n\t\tif (cmp != 0)\n\t\t\treturn cmp;\n\n\t\treturn NB.compareUInt32(w5, NB.decodeInt32(bs, p + 16));\n\t}\n\n\t/**\n\t * Compare this ObjectId to a network-byte-order ObjectId.\n\t *\n\t * @param bs\n\t * array containing the other ObjectId in network byte order.\n\t * @param p\n\t * position within {@code bs} to start the compare at. At least 5\n\t * integers, starting at this position are required.\n\t * @return a negative integer, zero, or a positive integer as this object is\n\t * less than, equal to, or greater than the specified object.\n\t */\n\tpublic final int compareTo(int[] bs, int p) {\n\t\tint cmp;\n\n\t\tcmp = NB.compareUInt32(w1, bs[p]);\n\t\tif (cmp != 0)\n\t\t\treturn cmp;\n\n\t\tcmp = NB.compareUInt32(w2, bs[p + 1]);\n\t\tif (cmp != 0)\n\t\t\treturn cmp;\n\n\t\tcmp = NB.compareUInt32(w3, bs[p + 2]);\n\t\tif (cmp != 0)\n\t\t\treturn cmp;\n\n\t\tcmp = NB.compareUInt32(w4, bs[p + 3]);\n\t\tif (cmp != 0)\n\t\t\treturn cmp;\n\n\t\treturn NB.compareUInt32(w5, bs[p + 4]);\n\t}\n\n\t/**\n\t * Tests if this ObjectId starts with the given abbreviation.\n\t *\n\t * @param abbr\n\t * the abbreviation.\n\t * @return true if this ObjectId begins with the abbreviation; else false.\n\t */\n\tpublic boolean startsWith(AbbreviatedObjectId abbr) {\n\t\treturn abbr.prefixCompare(this) == 0;\n\t}\n\n\t@Override\n\tpublic final int hashCode() {\n\t\treturn w2;\n\t}\n\n\t/**\n\t * Determine if this ObjectId has exactly the same value as another.\n\t *\n\t * @param other\n\t * the other id to compare to. May be null.\n\t * @return true only if both ObjectIds have identical bits.\n\t */\n\t@SuppressWarnings({ \"NonOverridingEquals\", \"AmbiguousMethodReference\" })\n\tpublic final boolean equals(AnyObjectId other) {\n\t\treturn other != null ? isEqual(this, other) : false;\n\t}\n\n\t@Override\n\tpublic final boolean equals(Object o) {\n\t\tif (o instanceof AnyObjectId) {\n\t\t\treturn equals((AnyObjectId) o);\n\t\t}\n\t\treturn false;\n\t}\n\n\t/**\n\t * Copy this ObjectId to an output writer in raw binary.\n\t *\n\t * @param w\n\t * the buffer to copy to. Must be in big endian order.\n\t */\n\tpublic void copyRawTo(ByteBuffer w) {\n\t\tw.putInt(w1);\n\t\tw.putInt(w2);\n\t\tw.putInt(w3);\n\t\tw.putInt(w4);\n\t\tw.putInt(w5);\n\t}\n\n\t/**\n\t * Copy this ObjectId to a byte array.\n\t *\n\t * @param b\n\t * the buffer to copy to.\n\t * @param o\n\t * the offset within b to write at.\n\t */\n\tpublic void copyRawTo(byte[] b, int o) {\n\t\tNB.encodeInt32(b, o, w1);\n\t\tNB.encodeInt32(b, o + 4, w2);\n\t\tNB.encodeInt32(b, o + 8, w3);\n\t\tNB.encodeInt32(b, o + 12, w4);\n\t\tNB.encodeInt32(b, o + 16, w5);\n\t}\n\n\t/**\n\t * Copy this ObjectId to an int array.\n\t *\n\t * @param b\n\t * the buffer to copy to.\n\t * @param o\n\t * the offset within b to write at.\n\t */\n\tpublic void copyRawTo(int[] b, int o) {\n\t\tb[o] = w1;\n\t\tb[o + 1] = w2;\n\t\tb[o + 2] = w3;\n\t\tb[o + 3] = w4;\n\t\tb[o + 4] = w5;\n\t}\n\n\t/**\n\t * Copy this ObjectId to an output writer in raw binary.\n\t *\n\t * @param w\n\t * the stream to write to.\n\t * @throws java.io.IOException\n\t * the stream writing failed.\n\t */\n\tpublic void copyRawTo(OutputStream w) throws IOException {\n\t\twriteRawInt(w, w1);\n\t\twriteRawInt(w, w2);\n\t\twriteRawInt(w, w3);\n\t\twriteRawInt(w, w4);\n\t\twriteRawInt(w, w5);\n\t}\n\n\tprivate static void writeRawInt(OutputStream w, int v)\n\t\t\tthrows IOException {\n\t\tw.write(v >>> 24);\n\t\tw.write(v >>> 16);\n\t\tw.write(v >>> 8);\n\t\tw.write(v);\n\t}\n\n\t/**\n\t * Copy this ObjectId to an output writer in hex format.\n\t *\n\t * @param w\n\t * the stream to copy to.\n\t * @throws java.io.IOException\n\t * the stream writing failed.\n\t */\n\tpublic void copyTo(OutputStream w) throws IOException {\n\t\tw.write(toHexByteArray());\n\t}\n\n\t/**\n\t * Copy this ObjectId to a byte array in hex format.\n\t *\n\t * @param b\n\t * the buffer to copy to.\n\t * @param o\n\t * the offset within b to write at.\n\t */\n\tpublic void copyTo(byte[] b, int o) {\n\t\tformatHexByte(b, o + 0, w1);\n\t\tformatHexByte(b, o + 8, w2);\n\t\tformatHexByte(b, o + 16, w3);\n\t\tformatHexByte(b, o + 24, w4);\n\t\tformatHexByte(b, o + 32, w5);\n\t}\n\n\t/**\n\t * Copy this ObjectId to a ByteBuffer in hex format.\n\t *\n\t * @param b\n\t * the buffer to copy to.\n\t */\n\tpublic void copyTo(ByteBuffer b) {\n\t\tb.put(toHexByteArray());\n\t}\n\n\tprivate byte[] toHexByteArray() {\n\t\tfinal byte[] dst = new byte[Constants.OBJECT_ID_STRING_LENGTH];\n\t\tformatHexByte(dst, 0, w1);\n\t\tformatHexByte(dst, 8, w2);\n\t\tformatHexByte(dst, 16, w3);\n\t\tformatHexByte(dst, 24, w4);\n\t\tformatHexByte(dst, 32, w5);\n\t\treturn dst;\n\t}\n\n\tprivate static final byte[] hexbyte = { '0', '1', '2', '3', '4', '5', '6',\n\t\t\t'7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };\n\n\tprivate static void formatHexByte(byte[] dst, int p, int w) {\n\t\tint o = p + 7;\n\t\twhile (o >= p && w != 0) {\n\t\t\tdst[o--] = hexbyte[w & 0xf];\n\t\t\tw >>>= 4;\n\t\t}\n\t\twhile (o >= p)\n\t\t\tdst[o--] = '0';\n\t}\n\n\t/**\n\t * Copy this ObjectId to an output writer in hex format.\n\t *\n\t * @param w\n\t * the stream to copy to.\n\t * @throws java.io.IOException\n\t * the stream writing failed.\n\t */\n\tpublic void copyTo(Writer w) throws IOException {\n\t\tw.write(toHexCharArray());\n\t}\n\n\t/**\n\t * Copy this ObjectId to an output writer in hex format.\n\t *\n\t * @param tmp\n\t * temporary char array to buffer construct into before writing.\n\t * Must be at least large enough to hold 2 digits for each byte\n\t * of object id (40 characters or larger).\n\t * @param w\n\t * the stream to copy to.\n\t * @throws java.io.IOException\n\t * the stream writing failed.\n\t */\n\tpublic void copyTo(char[] tmp, Writer w) throws IOException {\n\t\ttoHexCharArray(tmp);\n\t\tw.write(tmp, 0, Constants.OBJECT_ID_STRING_LENGTH);\n\t}\n\n\t/**\n\t * Copy this ObjectId to a StringBuilder in hex format.\n\t *\n\t * @param tmp\n\t * temporary char array to buffer construct into before writing.\n\t * Must be at least large enough to hold 2 digits for each byte\n\t * of object id (40 characters or larger).\n\t * @param w\n\t * the string to append onto.\n\t */\n\tpublic void copyTo(char[] tmp, StringBuilder w) {\n\t\ttoHexCharArray(tmp);\n\t\tw.append(tmp, 0, Constants.OBJECT_ID_STRING_LENGTH);\n\t}\n\n\tprivate char[] toHexCharArray() {\n\t\tfinal char[] dst = new char[Constants.OBJECT_ID_STRING_LENGTH];\n\t\ttoHexCharArray(dst);\n\t\treturn dst;\n\t}\n\n\tprivate void toHexCharArray(char[] dst) {\n\t\tformatHexChar(dst, 0, w1);\n\t\tformatHexChar(dst, 8, w2);\n\t\tformatHexChar(dst, 16, w3);\n\t\tformatHexChar(dst, 24, w4);\n\t\tformatHexChar(dst, 32, w5);\n\t}\n\n\tprivate static final char[] hexchar = { '0', '1', '2', '3', '4', '5', '6',\n\t\t\t'7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };\n\n\tstatic void formatHexChar(char[] dst, int p, int w) {\n\t\tint o = p + 7;\n\t\twhile (o >= p && w != 0) {\n\t\t\tdst[o--] = hexchar[w & 0xf];\n\t\t\tw >>>= 4;\n\t\t}\n\t\twhile (o >= p)\n\t\t\tdst[o--] = '0';\n\t}\n\n\t@SuppressWarnings(\"nls\")\n\t@Override\n\tpublic String toString() {\n\t\treturn \"AnyObjectId[\" + name() + \"]\";\n\t}\n\n\t/**\n\t * <p>name.</p>\n\t *\n\t * @return string form of the SHA-1, in lower case hexadecimal.\n\t */\n\tpublic final String name() {\n\t\treturn new String(toHexCharArray());\n\t}\n\n\t/**\n\t * Get string form of the SHA-1, in lower case hexadecimal.\n\t *\n\t * @return string form of the SHA-1, in lower case hexadecimal.\n\t */\n\tpublic final String getName() {\n\t\treturn name();\n\t}\n\n\t/**\n\t * Return an abbreviation (prefix) of this object SHA-1.\n\t * <p>\n\t * This implementation does not guarantee uniqueness. Callers should instead\n\t * use\n\t * {@link org.eclipse.jgit.lib.ObjectReader#abbreviate(AnyObjectId, int)} to\n\t * obtain a unique abbreviation within the scope of a particular object\n\t * database.\n\t *\n\t * @param len\n\t * length of the abbreviated string.\n\t * @return SHA-1 abbreviation.\n\t */\n\tpublic AbbreviatedObjectId abbreviate(int len) {\n\t\tfinal int a = AbbreviatedObjectId.mask(len, 1, w1);\n\t\tfinal int b = AbbreviatedObjectId.mask(len, 2, w2);\n\t\tfinal int c = AbbreviatedObjectId.mask(len, 3, w3);\n\t\tfinal int d = AbbreviatedObjectId.mask(len, 4, w4);\n\t\tfinal int e = AbbreviatedObjectId.mask(len, 5, w5);\n\t\treturn new AbbreviatedObjectId(len, a, b, c, d, e);\n\t}\n\n\t/**\n\t * Obtain an immutable copy of this current object name value.\n\t * <p>\n\t * Only returns <code>this</code> if this instance is an unsubclassed\n\t * instance of {@link org.eclipse.jgit.lib.ObjectId}; otherwise a new\n\t * instance is returned holding the same value.\n\t * <p>\n\t * This method is useful to shed any additional memory that may be tied to\n\t * the subclass, yet retain the unique identity of the object id for future\n\t * lookups within maps and repositories.\n\t *\n\t * @return an immutable copy, using the smallest memory footprint possible.\n\t */\n\tpublic final ObjectId copy() {\n\t\tif (getClass() == ObjectId.class)\n\t\t\treturn (ObjectId) this;\n\t\treturn new ObjectId(this);\n\t}\n\n\t/**\n\t * Obtain an immutable copy of this current object name value.\n\t * <p>\n\t * See {@link #copy()} if <code>this</code> is a possibly subclassed (but\n\t * immutable) identity and the application needs a lightweight identity\n\t * <i>only</i> reference.\n\t *\n\t * @return an immutable copy. May be <code>this</code> if this is already\n\t * an immutable instance.\n\t */\n\tpublic abstract ObjectId toObjectId();\n}" }, { "identifier": "ObjectId", "path": "org.eclipse.jgit/src/org/eclipse/jgit/lib/ObjectId.java", "snippet": "public class ObjectId extends AnyObjectId implements Serializable {\n\tprivate static final long serialVersionUID = 1L;\n\n\tprivate static final ObjectId ZEROID;\n\n\tprivate static final String ZEROID_STR;\n\n\tstatic {\n\t\tZEROID = new ObjectId(0, 0, 0, 0, 0);\n\t\tZEROID_STR = ZEROID.name();\n\t}\n\n\t/**\n\t * Get the special all-null ObjectId.\n\t *\n\t * @return the all-null ObjectId, often used to stand-in for no object.\n\t */\n\tpublic static final ObjectId zeroId() {\n\t\treturn ZEROID;\n\t}\n\n\t/**\n\t * Test a string of characters to verify it is a hex format.\n\t * <p>\n\t * If true the string can be parsed with {@link #fromString(String)}.\n\t *\n\t * @param id\n\t * the string to test.\n\t * @return true if the string can converted into an ObjectId.\n\t */\n\tpublic static final boolean isId(@Nullable String id) {\n\t\tif (id == null) {\n\t\t\treturn false;\n\t\t}\n\t\tif (id.length() != Constants.OBJECT_ID_STRING_LENGTH)\n\t\t\treturn false;\n\t\ttry {\n\t\t\tfor (int i = 0; i < Constants.OBJECT_ID_STRING_LENGTH; i++) {\n\t\t\t\tRawParseUtils.parseHexInt4((byte) id.charAt(i));\n\t\t\t}\n\t\t\treturn true;\n\t\t} catch (ArrayIndexOutOfBoundsException e) {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t/**\n\t * Convert an ObjectId into a hex string representation.\n\t *\n\t * @param i\n\t * the id to convert. May be null.\n\t * @return the hex string conversion of this id's content.\n\t */\n\tpublic static final String toString(ObjectId i) {\n\t\treturn i != null ? i.name() : ZEROID_STR;\n\t}\n\n\t/**\n\t * Compare two object identifier byte sequences for equality.\n\t *\n\t * @param firstBuffer\n\t * the first buffer to compare against. Must have at least 20\n\t * bytes from position fi through the end of the buffer.\n\t * @param fi\n\t * first offset within firstBuffer to begin testing.\n\t * @param secondBuffer\n\t * the second buffer to compare against. Must have at least 20\n\t * bytes from position si through the end of the buffer.\n\t * @param si\n\t * first offset within secondBuffer to begin testing.\n\t * @return true if the two identifiers are the same.\n\t */\n\tpublic static boolean equals(final byte[] firstBuffer, final int fi,\n\t\t\tfinal byte[] secondBuffer, final int si) {\n\t\treturn firstBuffer[fi] == secondBuffer[si]\n\t\t\t\t&& firstBuffer[fi + 1] == secondBuffer[si + 1]\n\t\t\t\t&& firstBuffer[fi + 2] == secondBuffer[si + 2]\n\t\t\t\t&& firstBuffer[fi + 3] == secondBuffer[si + 3]\n\t\t\t\t&& firstBuffer[fi + 4] == secondBuffer[si + 4]\n\t\t\t\t&& firstBuffer[fi + 5] == secondBuffer[si + 5]\n\t\t\t\t&& firstBuffer[fi + 6] == secondBuffer[si + 6]\n\t\t\t\t&& firstBuffer[fi + 7] == secondBuffer[si + 7]\n\t\t\t\t&& firstBuffer[fi + 8] == secondBuffer[si + 8]\n\t\t\t\t&& firstBuffer[fi + 9] == secondBuffer[si + 9]\n\t\t\t\t&& firstBuffer[fi + 10] == secondBuffer[si + 10]\n\t\t\t\t&& firstBuffer[fi + 11] == secondBuffer[si + 11]\n\t\t\t\t&& firstBuffer[fi + 12] == secondBuffer[si + 12]\n\t\t\t\t&& firstBuffer[fi + 13] == secondBuffer[si + 13]\n\t\t\t\t&& firstBuffer[fi + 14] == secondBuffer[si + 14]\n\t\t\t\t&& firstBuffer[fi + 15] == secondBuffer[si + 15]\n\t\t\t\t&& firstBuffer[fi + 16] == secondBuffer[si + 16]\n\t\t\t\t&& firstBuffer[fi + 17] == secondBuffer[si + 17]\n\t\t\t\t&& firstBuffer[fi + 18] == secondBuffer[si + 18]\n\t\t\t\t&& firstBuffer[fi + 19] == secondBuffer[si + 19];\n\t}\n\n\t/**\n\t * Convert an ObjectId from raw binary representation.\n\t *\n\t * @param bs\n\t * the raw byte buffer to read from. At least 20 bytes must be\n\t * available within this byte array.\n\t * @return the converted object id.\n\t */\n\tpublic static final ObjectId fromRaw(byte[] bs) {\n\t\treturn fromRaw(bs, 0);\n\t}\n\n\t/**\n\t * Convert an ObjectId from raw binary representation.\n\t *\n\t * @param bs\n\t * the raw byte buffer to read from. At least 20 bytes after p\n\t * must be available within this byte array.\n\t * @param p\n\t * position to read the first byte of data from.\n\t * @return the converted object id.\n\t */\n\tpublic static final ObjectId fromRaw(byte[] bs, int p) {\n\t\tfinal int a = NB.decodeInt32(bs, p);\n\t\tfinal int b = NB.decodeInt32(bs, p + 4);\n\t\tfinal int c = NB.decodeInt32(bs, p + 8);\n\t\tfinal int d = NB.decodeInt32(bs, p + 12);\n\t\tfinal int e = NB.decodeInt32(bs, p + 16);\n\t\treturn new ObjectId(a, b, c, d, e);\n\t}\n\n\t/**\n\t * Convert an ObjectId from raw binary representation.\n\t *\n\t * @param is\n\t * the raw integers buffer to read from. At least 5 integers must\n\t * be available within this int array.\n\t * @return the converted object id.\n\t */\n\tpublic static final ObjectId fromRaw(int[] is) {\n\t\treturn fromRaw(is, 0);\n\t}\n\n\t/**\n\t * Convert an ObjectId from raw binary representation.\n\t *\n\t * @param is\n\t * the raw integers buffer to read from. At least 5 integers\n\t * after p must be available within this int array.\n\t * @param p\n\t * position to read the first integer of data from.\n\t * @return the converted object id.\n\t */\n\tpublic static final ObjectId fromRaw(int[] is, int p) {\n\t\treturn new ObjectId(is[p], is[p + 1], is[p + 2], is[p + 3], is[p + 4]);\n\t}\n\n\t/**\n\t * Convert an ObjectId from hex characters (US-ASCII).\n\t *\n\t * @param buf\n\t * the US-ASCII buffer to read from. At least 40 bytes after\n\t * offset must be available within this byte array.\n\t * @param offset\n\t * position to read the first character from.\n\t * @return the converted object id.\n\t */\n\tpublic static final ObjectId fromString(byte[] buf, int offset) {\n\t\treturn fromHexString(buf, offset);\n\t}\n\n\t/**\n\t * Convert an ObjectId from hex characters.\n\t *\n\t * @param str\n\t * the string to read from. Must be 40 characters long.\n\t * @return the converted object id.\n\t */\n\tpublic static ObjectId fromString(String str) {\n\t\tif (str.length() != Constants.OBJECT_ID_STRING_LENGTH) {\n\t\t\tthrow new InvalidObjectIdException(str);\n\t\t}\n\t\treturn fromHexString(Constants.encodeASCII(str), 0);\n\t}\n\n\tprivate static final ObjectId fromHexString(byte[] bs, int p) {\n\t\ttry {\n\t\t\tfinal int a = RawParseUtils.parseHexInt32(bs, p);\n\t\t\tfinal int b = RawParseUtils.parseHexInt32(bs, p + 8);\n\t\t\tfinal int c = RawParseUtils.parseHexInt32(bs, p + 16);\n\t\t\tfinal int d = RawParseUtils.parseHexInt32(bs, p + 24);\n\t\t\tfinal int e = RawParseUtils.parseHexInt32(bs, p + 32);\n\t\t\treturn new ObjectId(a, b, c, d, e);\n\t\t} catch (ArrayIndexOutOfBoundsException e) {\n\t\t\tInvalidObjectIdException e1 = new InvalidObjectIdException(bs, p,\n\t\t\t\t\tConstants.OBJECT_ID_STRING_LENGTH);\n\t\t\te1.initCause(e);\n\t\t\tthrow e1;\n\t\t}\n\t}\n\n\t/**\n\t * Construct an ObjectId from 160 bits provided in 5 words.\n\t *\n\t * @param new_1\n\t * an int\n\t * @param new_2\n\t * an int\n\t * @param new_3\n\t * an int\n\t * @param new_4\n\t * an int\n\t * @param new_5\n\t * an int\n\t * @since 4.7\n\t */\n\tpublic ObjectId(int new_1, int new_2, int new_3, int new_4, int new_5) {\n\t\tw1 = new_1;\n\t\tw2 = new_2;\n\t\tw3 = new_3;\n\t\tw4 = new_4;\n\t\tw5 = new_5;\n\t}\n\n\t/**\n\t * Initialize this instance by copying another existing ObjectId.\n\t * <p>\n\t * This constructor is mostly useful for subclasses who want to extend an\n\t * ObjectId with more properties, but initialize from an existing ObjectId\n\t * instance acquired by other means.\n\t *\n\t * @param src\n\t * another already parsed ObjectId to copy the value out of.\n\t */\n\tprotected ObjectId(AnyObjectId src) {\n\t\tw1 = src.w1;\n\t\tw2 = src.w2;\n\t\tw3 = src.w3;\n\t\tw4 = src.w4;\n\t\tw5 = src.w5;\n\t}\n\n\t@Override\n\tpublic ObjectId toObjectId() {\n\t\treturn this;\n\t}\n\n\tprivate void writeObject(ObjectOutputStream os) throws IOException {\n\t\tos.writeInt(w1);\n\t\tos.writeInt(w2);\n\t\tos.writeInt(w3);\n\t\tos.writeInt(w4);\n\t\tos.writeInt(w5);\n\t}\n\n\tprivate void readObject(ObjectInputStream ois) throws IOException {\n\t\tw1 = ois.readInt();\n\t\tw2 = ois.readInt();\n\t\tw3 = ois.readInt();\n\t\tw4 = ois.readInt();\n\t\tw5 = ois.readInt();\n\t}\n}" } ]
import org.eclipse.jgit.lib.AnyObjectId; import org.eclipse.jgit.lib.ObjectId;
7,476
/* * Copyright (C) 2010, Google Inc. and others * * This program and the accompanying materials are made available under the * terms of the Eclipse Distribution License v. 1.0 which is available at * https://www.eclipse.org/org/documents/edl-v10.php. * * SPDX-License-Identifier: BSD-3-Clause */ package org.eclipse.jgit.notes; /** * In-memory representation of a single note attached to one object. */ public class Note extends ObjectId { private ObjectId data; /** * A Git note about the object referenced by {@code noteOn}. * * @param noteOn * the object that has a note attached to it. * @param noteData * the actual note data contained in this note */
/* * Copyright (C) 2010, Google Inc. and others * * This program and the accompanying materials are made available under the * terms of the Eclipse Distribution License v. 1.0 which is available at * https://www.eclipse.org/org/documents/edl-v10.php. * * SPDX-License-Identifier: BSD-3-Clause */ package org.eclipse.jgit.notes; /** * In-memory representation of a single note attached to one object. */ public class Note extends ObjectId { private ObjectId data; /** * A Git note about the object referenced by {@code noteOn}. * * @param noteOn * the object that has a note attached to it. * @param noteData * the actual note data contained in this note */
public Note(AnyObjectId noteOn, ObjectId noteData) {
0
2023-10-20 15:09:17+00:00
12k
starfish-studios/Naturalist
common/src/main/java/com/starfish_studios/naturalist/common/entity/Elephant.java
[ { "identifier": "ElephantContainer", "path": "common/src/main/java/com/starfish_studios/naturalist/common/entity/core/ElephantContainer.java", "snippet": "public class ElephantContainer extends SimpleContainer {\n public ElephantContainer() {\n super(25);\n }\n}" }, { "identifier": "BabyHurtByTargetGoal", "path": "common/src/main/java/com/starfish_studios/naturalist/common/entity/core/ai/goal/BabyHurtByTargetGoal.java", "snippet": "public class BabyHurtByTargetGoal extends HurtByTargetGoal {\n public BabyHurtByTargetGoal(PathfinderMob pMob, Class<?>... pToIgnoreDamage) {\n super(pMob, pToIgnoreDamage);\n }\n\n @Override\n public void start() {\n super.start();\n if (this.mob.isBaby()) {\n this.alertOthers();\n this.stop();\n }\n }\n\n @Override\n protected void alertOther(Mob pMob, LivingEntity pTarget) {\n if (!pMob.isBaby()) {\n super.alertOther(pMob, pTarget);\n }\n }\n}" }, { "identifier": "BabyPanicGoal", "path": "common/src/main/java/com/starfish_studios/naturalist/common/entity/core/ai/goal/BabyPanicGoal.java", "snippet": "public class BabyPanicGoal extends PanicGoal {\n public BabyPanicGoal(PathfinderMob pMob, double pSpeedModifier) {\n super(pMob, pSpeedModifier);\n }\n\n @Override\n protected boolean shouldPanic() {\n return mob.getLastHurtByMob() != null && mob.isBaby() || mob.isOnFire();\n }\n}" }, { "identifier": "DistancedFollowParentGoal", "path": "common/src/main/java/com/starfish_studios/naturalist/common/entity/core/ai/goal/DistancedFollowParentGoal.java", "snippet": "public class DistancedFollowParentGoal extends Goal {\n protected final Animal animal;\n @Nullable\n protected Animal parent;\n private final double speedModifier;\n private int timeToRecalcPath;\n protected final double horizontalScanRange;\n protected final double verticalScanRange;\n protected final double followDistanceThreshold;\n\n public DistancedFollowParentGoal(Animal animal, double speedModifier, double horizontalScanRange, double verticalScanRange, double followDistanceThreshold) {\n this.animal = animal;\n this.speedModifier = speedModifier;\n this.horizontalScanRange = horizontalScanRange;\n this.verticalScanRange = verticalScanRange;\n this.followDistanceThreshold = followDistanceThreshold;\n }\n\n @Override\n public boolean canUse() {\n if (this.animal.getAge() >= 0) {\n return false;\n } else {\n List<? extends Animal> adults = this.animal.level.getEntitiesOfClass(this.animal.getClass(), this.animal.getBoundingBox().inflate(horizontalScanRange, verticalScanRange, horizontalScanRange));\n Animal parent = null;\n double distance = Double.MAX_VALUE;\n\n for(Animal adult : adults) {\n if (adult.getAge() >= 0) {\n double distanceToAdult = this.animal.distanceToSqr(adult);\n if (!(distanceToAdult > distance)) {\n distance = distanceToAdult;\n parent = adult;\n }\n }\n }\n\n if (parent == null) {\n return false;\n } else if (distance < Mth.square(followDistanceThreshold)) {\n return false;\n } else {\n this.parent = parent;\n return true;\n }\n }\n }\n\n @Override\n public boolean canContinueToUse() {\n if (this.animal.getAge() >= 0) {\n return false;\n } else if (!this.parent.isAlive()) {\n return false;\n } else {\n double distanceToParent = this.animal.distanceToSqr(this.parent);\n return !(distanceToParent < Mth.square(followDistanceThreshold)) && !(distanceToParent > 256.0D);\n }\n }\n\n @Override\n public void start() {\n this.timeToRecalcPath = 0;\n }\n\n @Override\n public void stop() {\n this.parent = null;\n }\n\n @Override\n public void tick() {\n if (--this.timeToRecalcPath <= 0) {\n this.timeToRecalcPath = this.adjustedTickDelay(10);\n this.animal.getNavigation().moveTo(this.parent, this.speedModifier);\n }\n }\n}" }, { "identifier": "NaturalistEntityTypes", "path": "common/src/main/java/com/starfish_studios/naturalist/core/registry/NaturalistEntityTypes.java", "snippet": "public class NaturalistEntityTypes {\n\n // PROJECTILES\n\n\n public static final Supplier<EntityType<ThrownDuckEgg>> DUCK_EGG = CommonPlatformHelper.registerEntityType(\"duck_egg\", ThrownDuckEgg::new, MobCategory.MISC, 0.25F, 0.25F, 16);\n\n // MOBS\n\n public static final Supplier<EntityType<Snail>> SNAIL = CommonPlatformHelper.registerEntityType(\"snail\", Snail::new, MobCategory.CREATURE, 0.7F, 0.7F, 10);\n public static final Supplier<EntityType<Bear>> BEAR = CommonPlatformHelper.registerEntityType(\"bear\", Bear::new, MobCategory.CREATURE, 1.4F, 1.7F, 10);\n public static final Supplier<EntityType<Butterfly>> BUTTERFLY = CommonPlatformHelper.registerEntityType(\"butterfly\", Butterfly::new, MobCategory.CREATURE, 0.7F, 0.6F, 8);\n public static final Supplier<EntityType<Moth>> MOTH = CommonPlatformHelper.registerEntityType(\"moth\", Moth::new, MobCategory.CREATURE, 0.7F, 0.6F, 8);\n public static final Supplier<EntityType<Firefly>> FIREFLY = CommonPlatformHelper.registerEntityType(\"firefly\", Firefly::new, MobCategory.AMBIENT, 0.7F, 0.6F, 8);\n public static final Supplier<EntityType<Snake>> SNAKE = CommonPlatformHelper.registerEntityType(\"snake\", Snake::new, MobCategory.CREATURE, 0.6F, 0.7F, 8);\n public static final Supplier<EntityType<Snake>> CORAL_SNAKE = CommonPlatformHelper.registerEntityType(\"coral_snake\", Snake::new, MobCategory.CREATURE, 0.6F, 0.7F, 8);\n public static final Supplier<EntityType<Snake>> RATTLESNAKE = CommonPlatformHelper.registerEntityType(\"rattlesnake\", Snake::new, MobCategory.CREATURE, 0.6F, 0.7F, 8);\n public static final Supplier<EntityType<Deer>> DEER = CommonPlatformHelper.registerEntityType(\"deer\", Deer::new, MobCategory.CREATURE, 1.3F, 1.6F, 10);\n public static final Supplier<EntityType<Bird>> BLUEJAY = CommonPlatformHelper.registerEntityType(\"bluejay\", Bird::new, MobCategory.CREATURE, 0.5F, 0.6F, 8);\n public static final Supplier<EntityType<Bird>> CANARY = CommonPlatformHelper.registerEntityType(\"canary\", Bird::new, MobCategory.CREATURE, 0.5F, 0.6F, 8);\n public static final Supplier<EntityType<Bird>> CARDINAL = CommonPlatformHelper.registerEntityType(\"cardinal\", Bird::new, MobCategory.CREATURE, 0.5F, 0.6F, 8);\n public static final Supplier<EntityType<Bird>> ROBIN = CommonPlatformHelper.registerEntityType(\"robin\", Bird::new, MobCategory.CREATURE, 0.5F, 0.6F, 8);\n public static final Supplier<EntityType<Caterpillar>> CATERPILLAR = CommonPlatformHelper.registerEntityType(\"caterpillar\", Caterpillar::new, MobCategory.CREATURE, 0.4F, 0.4F, 10);\n public static final Supplier<EntityType<Rhino>> RHINO = CommonPlatformHelper.registerEntityType(\"rhino\", Rhino::new, MobCategory.CREATURE, 2.5F, 3.0F, 10);\n public static final Supplier<EntityType<Lion>> LION = CommonPlatformHelper.registerEntityType(\"lion\", Lion::new, MobCategory.CREATURE, 1.5F, 1.8F, 10);\n public static final Supplier<EntityType<Elephant>> ELEPHANT = CommonPlatformHelper.registerEntityType(\"elephant\", Elephant::new, MobCategory.CREATURE, 2.5F, 3.5F, 10);\n public static final Supplier<EntityType<Zebra>> ZEBRA = CommonPlatformHelper.registerEntityType(\"zebra\", Zebra::new, MobCategory.CREATURE, 1.3964844f, 1.6f, 10);\n public static final Supplier<EntityType<Giraffe>> GIRAFFE = CommonPlatformHelper.registerEntityType(\"giraffe\", Giraffe::new, MobCategory.CREATURE, 1.9f, 5.4f, 10);\n public static final Supplier<EntityType<Hippo>> HIPPO = CommonPlatformHelper.registerEntityType(\"hippo\", Hippo::new, MobCategory.CREATURE, 1.8F, 1.8F, 10);\n public static final Supplier<EntityType<Vulture>> VULTURE = CommonPlatformHelper.registerEntityType(\"vulture\", Vulture::new, MobCategory.CREATURE, 0.9f, 0.5f, 10);\n public static final Supplier<EntityType<Boar>> BOAR = CommonPlatformHelper.registerEntityType(\"boar\", Boar::new, MobCategory.CREATURE, 0.9f, 0.9f, 10);\n\n public static final Supplier<EntityType<Dragonfly>> DRAGONFLY = CommonPlatformHelper.registerEntityType(\"dragonfly\", Dragonfly::new, MobCategory.AMBIENT, 0.9F, 0.7F, 8);\n public static final Supplier<EntityType<Catfish>> CATFISH = CommonPlatformHelper.registerEntityType(\"catfish\", Catfish::new, MobCategory.WATER_AMBIENT, 1.0F, 0.7F, 8);\n public static final Supplier<EntityType<Alligator>> ALLIGATOR = CommonPlatformHelper.registerEntityType(\"alligator\", Alligator::new, MobCategory.CREATURE, 1.8F, 0.8F, 10);\n public static final Supplier<EntityType<Bass>> BASS = CommonPlatformHelper.registerEntityType(\"bass\", Bass::new, MobCategory.WATER_AMBIENT, 0.7f, 0.4f, 4);\n public static final Supplier<EntityType<Lizard>> LIZARD = CommonPlatformHelper.registerEntityType(\"lizard\", Lizard::new, MobCategory.CREATURE, 0.8F, 0.5F, 10);\n public static final Supplier<EntityType<LizardTail>> LIZARD_TAIL = CommonPlatformHelper.registerEntityType(\"lizard_tail\", LizardTail::new, MobCategory.CREATURE, 0.7f, 0.5f, 10);\n public static final Supplier<EntityType<Tortoise>> TORTOISE = CommonPlatformHelper.registerEntityType(\"tortoise\", Tortoise::new, MobCategory.CREATURE, 1.2F, 0.875F, 10);\n public static final Supplier<EntityType<Duck>> DUCK = CommonPlatformHelper.registerEntityType(\"duck\", Duck::new, MobCategory.CREATURE, 0.6F, 1.0F, 10);\n public static final Supplier<EntityType<Hyena>> HYENA = CommonPlatformHelper.registerEntityType(\"hyena\", Hyena::new, MobCategory.CREATURE, 1.1F, 1.3F, 10);\n public static final Supplier<EntityType<Ostrich>> OSTRICH = CommonPlatformHelper.registerEntityType(\"ostrich\", Ostrich::new, MobCategory.CREATURE, 1.0F, 2.0F, 10);\n public static final Supplier<EntityType<Termite>> TERMITE = CommonPlatformHelper.registerEntityType(\"termite\", Termite::new, MobCategory.CREATURE, 1.0F, 0.7F, 10);\n\n\n public static void init() {}\n}" }, { "identifier": "NaturalistSoundEvents", "path": "common/src/main/java/com/starfish_studios/naturalist/core/registry/NaturalistSoundEvents.java", "snippet": "public class NaturalistSoundEvents {\n\n // MISC SOUNDS\n\n public static final Supplier<SoundEvent> SNAKE_HISS = CommonPlatformHelper.registerSoundEvent(\"snake_hiss\", () -> new SoundEvent(new ResourceLocation(Naturalist.MOD_ID, \"entity.snake.hiss\")));\n public static final Supplier<SoundEvent> SNAKE_HURT = CommonPlatformHelper.registerSoundEvent(\"snake_hurt\", () -> new SoundEvent(new ResourceLocation(Naturalist.MOD_ID, \"entity.snake.hurt\")));\n public static final Supplier<SoundEvent> SNAKE_RATTLE = CommonPlatformHelper.registerSoundEvent(\"snake_rattle\", () -> new SoundEvent(new ResourceLocation(Naturalist.MOD_ID, \"entity.snake.rattle\")));\n public static final Supplier<SoundEvent> SNAIL_CRUSH = CommonPlatformHelper.registerSoundEvent(\"snail_crush\", () -> new SoundEvent(new ResourceLocation(Naturalist.MOD_ID, \"entity.snail.crush\")));\n public static final Supplier<SoundEvent> SNAIL_FORWARD = CommonPlatformHelper.registerSoundEvent(\"snail_forward\", () -> new SoundEvent(new ResourceLocation(Naturalist.MOD_ID, \"entity.snail.forward\")));\n public static final Supplier<SoundEvent> SNAIL_BACK = CommonPlatformHelper.registerSoundEvent(\"snail_back\", () -> new SoundEvent(new ResourceLocation(Naturalist.MOD_ID, \"entity.snail.back\")));\n public static final Supplier<SoundEvent> BUCKET_FILL_SNAIL = CommonPlatformHelper.registerSoundEvent(\"bucket_fill_snail\", () -> new SoundEvent(new ResourceLocation(Naturalist.MOD_ID, \"item.bucket.fill_snail\")));\n public static final Supplier<SoundEvent> BUCKET_EMPTY_SNAIL = CommonPlatformHelper.registerSoundEvent(\"bucket_empty_snail\", () -> new SoundEvent(new ResourceLocation(Naturalist.MOD_ID, \"item.bucket.empty_snail\")));\n public static final Supplier<SoundEvent> BIRD_HURT = CommonPlatformHelper.registerSoundEvent(\"bird_hurt\", () -> new SoundEvent(new ResourceLocation(Naturalist.MOD_ID, \"entity.bird.hurt\")));\n public static final Supplier<SoundEvent> BIRD_DEATH = CommonPlatformHelper.registerSoundEvent(\"bird_death\", () -> new SoundEvent(new ResourceLocation(Naturalist.MOD_ID, \"entity.bird.death\")));\n public static final Supplier<SoundEvent> BIRD_EAT = CommonPlatformHelper.registerSoundEvent(\"bird_eat\", () -> new SoundEvent(new ResourceLocation(Naturalist.MOD_ID, \"entity.bird.eat\")));\n public static final Supplier<SoundEvent> BIRD_FLY = CommonPlatformHelper.registerSoundEvent(\"bird_fly\", () -> new SoundEvent(new ResourceLocation(Naturalist.MOD_ID, \"entity.bird.fly\")));\n public static final Supplier<SoundEvent> BIRD_AMBIENT_BLUEJAY = CommonPlatformHelper.registerSoundEvent(\"bird_ambient_bluejay\", () -> new SoundEvent(new ResourceLocation(Naturalist.MOD_ID, \"entity.bird.ambient_bluejay\")));\n public static final Supplier<SoundEvent> BIRD_AMBIENT_CANARY = CommonPlatformHelper.registerSoundEvent(\"bird_ambient_canary\", () -> new SoundEvent(new ResourceLocation(Naturalist.MOD_ID, \"entity.bird.ambient_canary\")));\n public static final Supplier<SoundEvent> BIRD_AMBIENT_ROBIN = CommonPlatformHelper.registerSoundEvent(\"bird_ambient_robin\", () -> new SoundEvent(new ResourceLocation(Naturalist.MOD_ID, \"entity.bird.ambient_robin\")));\n public static final Supplier<SoundEvent> BIRD_AMBIENT_CARDINAL = CommonPlatformHelper.registerSoundEvent(\"bird_ambient_cardinal\", () -> new SoundEvent(new ResourceLocation(Naturalist.MOD_ID, \"entity.bird.ambient_cardinal\")));\n public static final Supplier<SoundEvent> FIREFLY_HURT = CommonPlatformHelper.registerSoundEvent(\"firefly_hurt\", () -> new SoundEvent(new ResourceLocation(Naturalist.MOD_ID, \"entity.firefly.hurt\")));\n public static final Supplier<SoundEvent> FIREFLY_DEATH = CommonPlatformHelper.registerSoundEvent(\"firefly_death\", () -> new SoundEvent(new ResourceLocation(Naturalist.MOD_ID, \"entity.firefly.death\")));\n public static final Supplier<SoundEvent> FIREFLY_HIDE = CommonPlatformHelper.registerSoundEvent(\"firefly_hide\", () -> new SoundEvent(new ResourceLocation(Naturalist.MOD_ID, \"entity.firefly.hide\")));\n\n\n\n // FOREST SOUNDS\n\n public static final Supplier<SoundEvent> BEAR_HURT = CommonPlatformHelper.registerSoundEvent(\"bear_hurt\", () -> new SoundEvent(new ResourceLocation(Naturalist.MOD_ID, \"entity.bear.hurt\")));\n public static final Supplier<SoundEvent> BEAR_DEATH = CommonPlatformHelper.registerSoundEvent(\"bear_death\", () -> new SoundEvent(new ResourceLocation(Naturalist.MOD_ID, \"entity.bear.death\")));\n public static final Supplier<SoundEvent> BEAR_AMBIENT = CommonPlatformHelper.registerSoundEvent(\"bear_ambient\", () -> new SoundEvent(new ResourceLocation(Naturalist.MOD_ID, \"entity.bear.ambient\")));\n public static final Supplier<SoundEvent> BEAR_AMBIENT_BABY = CommonPlatformHelper.registerSoundEvent(\"bear_ambient_baby\", () -> new SoundEvent(new ResourceLocation(Naturalist.MOD_ID, \"entity.bear.ambient_baby\")));\n public static final Supplier<SoundEvent> BEAR_HURT_BABY = CommonPlatformHelper.registerSoundEvent(\"bear_hurt_baby\", () -> new SoundEvent(new ResourceLocation(Naturalist.MOD_ID, \"entity.bear.hurt_baby\")));\n public static final Supplier<SoundEvent> BEAR_SLEEP = CommonPlatformHelper.registerSoundEvent(\"bear_sleep\", () -> new SoundEvent(new ResourceLocation(Naturalist.MOD_ID, \"entity.bear.sleep\")));\n public static final Supplier<SoundEvent> BEAR_SNIFF = CommonPlatformHelper.registerSoundEvent(\"bear_sniff\", () -> new SoundEvent(new ResourceLocation(Naturalist.MOD_ID, \"entity.bear.sniff\")));\n public static final Supplier<SoundEvent> BEAR_SPIT = CommonPlatformHelper.registerSoundEvent(\"bear_spit\", () -> new SoundEvent(new ResourceLocation(Naturalist.MOD_ID, \"entity.bear.spit\")));\n public static final Supplier<SoundEvent> BEAR_EAT = CommonPlatformHelper.registerSoundEvent(\"bear_eat\", () -> new SoundEvent(new ResourceLocation(Naturalist.MOD_ID, \"entity.bear.eat\")));\n public static final Supplier<SoundEvent> DEER_AMBIENT = CommonPlatformHelper.registerSoundEvent(\"deer_ambient\", () -> new SoundEvent(new ResourceLocation(Naturalist.MOD_ID, \"entity.deer.ambient\")));\n public static final Supplier<SoundEvent> DEER_HURT = CommonPlatformHelper.registerSoundEvent(\"deer_hurt\", () -> new SoundEvent(new ResourceLocation(Naturalist.MOD_ID, \"entity.deer.hurt\")));\n public static final Supplier<SoundEvent> DEER_AMBIENT_BABY = CommonPlatformHelper.registerSoundEvent(\"deer_ambient_baby\", () -> new SoundEvent(new ResourceLocation(Naturalist.MOD_ID, \"entity.deer.ambient_baby\")));\n public static final Supplier<SoundEvent> DEER_HURT_BABY = CommonPlatformHelper.registerSoundEvent(\"deer_hurt_baby\", () -> new SoundEvent(new ResourceLocation(Naturalist.MOD_ID, \"entity.deer.hurt_baby\")));\n\n\n\n // SAVANNA SOUNDS\n\n public static final Supplier<SoundEvent> RHINO_SCRAPE = CommonPlatformHelper.registerSoundEvent(\"rhino_scrape\", () -> new SoundEvent(new ResourceLocation(Naturalist.MOD_ID, \"entity.rhino.scrape\")));\n public static final Supplier<SoundEvent> RHINO_AMBIENT = CommonPlatformHelper.registerSoundEvent(\"rhino_ambient\", () -> new SoundEvent(new ResourceLocation(Naturalist.MOD_ID, \"entity.rhino.ambient\")));\n public static final Supplier<SoundEvent> RHINO_AMBIENT_BABY = CommonPlatformHelper.registerSoundEvent(\"rhino_ambient_baby\", () -> new SoundEvent(new ResourceLocation(Naturalist.MOD_ID, \"entity.rhino.ambient_baby\")));\n public static final Supplier<SoundEvent> LION_HURT = CommonPlatformHelper.registerSoundEvent(\"lion_hurt\", () -> new SoundEvent(new ResourceLocation(Naturalist.MOD_ID, \"entity.lion.hurt\")));\n public static final Supplier<SoundEvent> LION_AMBIENT = CommonPlatformHelper.registerSoundEvent(\"lion_ambient\", () -> new SoundEvent(new ResourceLocation(Naturalist.MOD_ID, \"entity.lion.ambient\")));\n public static final Supplier<SoundEvent> LION_ROAR = CommonPlatformHelper.registerSoundEvent(\"lion_roar\", () -> new SoundEvent(new ResourceLocation(Naturalist.MOD_ID, \"entity.lion.roar\")));\n public static final Supplier<SoundEvent> ELEPHANT_HURT = CommonPlatformHelper.registerSoundEvent(\"elephant_hurt\", () -> new SoundEvent(new ResourceLocation(Naturalist.MOD_ID, \"entity.elephant.hurt\")));\n public static final Supplier<SoundEvent> ELEPHANT_AMBIENT = CommonPlatformHelper.registerSoundEvent(\"elephant_ambient\", () -> new SoundEvent(new ResourceLocation(Naturalist.MOD_ID, \"entity.elephant.ambient\")));\n public static final Supplier<SoundEvent> ZEBRA_AMBIENT = CommonPlatformHelper.registerSoundEvent(\"zebra_ambient\", () -> new SoundEvent(new ResourceLocation(Naturalist.MOD_ID, \"entity.zebra.ambient\")));\n public static final Supplier<SoundEvent> ZEBRA_HURT = CommonPlatformHelper.registerSoundEvent(\"zebra_hurt\", () -> new SoundEvent(new ResourceLocation(Naturalist.MOD_ID, \"entity.zebra.hurt\")));\n public static final Supplier<SoundEvent> ZEBRA_DEATH = CommonPlatformHelper.registerSoundEvent(\"zebra_death\", () -> new SoundEvent(new ResourceLocation(Naturalist.MOD_ID, \"entity.zebra.death\")));\n public static final Supplier<SoundEvent> ZEBRA_EAT = CommonPlatformHelper.registerSoundEvent(\"zebra_eat\", () -> new SoundEvent(new ResourceLocation(Naturalist.MOD_ID, \"entity.zebra.eat\")));\n public static final Supplier<SoundEvent> ZEBRA_BREATHE = CommonPlatformHelper.registerSoundEvent(\"zebra_breathe\", () -> new SoundEvent(new ResourceLocation(Naturalist.MOD_ID, \"entity.zebra.breathe\")));\n public static final Supplier<SoundEvent> ZEBRA_ANGRY = CommonPlatformHelper.registerSoundEvent(\"zebra_angry\", () -> new SoundEvent(new ResourceLocation(Naturalist.MOD_ID, \"entity.zebra.angry\")));\n public static final Supplier<SoundEvent> ZEBRA_JUMP = CommonPlatformHelper.registerSoundEvent(\"zebra_jump\", () -> new SoundEvent(new ResourceLocation(Naturalist.MOD_ID, \"entity.zebra.jump\")));\n public static final Supplier<SoundEvent> VULTURE_AMBIENT = CommonPlatformHelper.registerSoundEvent(\"vulture_ambient\", () -> new SoundEvent(new ResourceLocation(Naturalist.MOD_ID, \"entity.vulture.ambient\")));\n public static final Supplier<SoundEvent> VULTURE_HURT = CommonPlatformHelper.registerSoundEvent(\"vulture_hurt\", () -> new SoundEvent(new ResourceLocation(Naturalist.MOD_ID, \"entity.vulture.hurt\")));\n public static final Supplier<SoundEvent> VULTURE_DEATH = CommonPlatformHelper.registerSoundEvent(\"vulture_death\", () -> new SoundEvent(new ResourceLocation(Naturalist.MOD_ID, \"entity.vulture.death\")));\n public static final Supplier<SoundEvent> GIRAFFE_AMBIENT = CommonPlatformHelper.registerSoundEvent(\"giraffe_ambient\", () -> new SoundEvent(new ResourceLocation(Naturalist.MOD_ID, \"entity.giraffe.ambient\")));\n public static final Supplier<SoundEvent> HIPPO_AMBIENT = CommonPlatformHelper.registerSoundEvent(\"hippo_ambient\", () -> new SoundEvent(new ResourceLocation(Naturalist.MOD_ID, \"entity.hippo.ambient\")));\n public static final Supplier<SoundEvent> HIPPO_HURT = CommonPlatformHelper.registerSoundEvent(\"hippo_hurt\", () -> new SoundEvent(new ResourceLocation(Naturalist.MOD_ID, \"entity.hippo.hurt\")));\n public static final Supplier<SoundEvent> BOAR_AMBIENT = CommonPlatformHelper.registerSoundEvent(\"boar_ambient\", () -> new SoundEvent(new ResourceLocation(Naturalist.MOD_ID, \"entity.boar.ambient\")));\n public static final Supplier<SoundEvent> BOAR_HURT = CommonPlatformHelper.registerSoundEvent(\"boar_hurt\", () -> new SoundEvent(new ResourceLocation(Naturalist.MOD_ID, \"entity.boar.hurt\")));\n public static final Supplier<SoundEvent> BOAR_DEATH = CommonPlatformHelper.registerSoundEvent(\"boar_death\", () -> new SoundEvent(new ResourceLocation(Naturalist.MOD_ID, \"entity.boar.death\")));\n public static final Supplier<SoundEvent> HYENA_AMBIENT = CommonPlatformHelper.registerSoundEvent(\"hyena_ambient\", () -> new SoundEvent(new ResourceLocation(Naturalist.MOD_ID, \"entity.hyena.ambient\")));\n public static final Supplier<SoundEvent> HYENA_HURT = CommonPlatformHelper.registerSoundEvent(\"hyena_hurt\", () -> new SoundEvent(new ResourceLocation(Naturalist.MOD_ID, \"entity.hyena.hurt\")));\n\n public static final Supplier<SoundEvent> OSTRICH_AMBIENT = CommonPlatformHelper.registerSoundEvent(\"ostrich_ambient\", () -> new SoundEvent(new ResourceLocation(Naturalist.MOD_ID, \"entity.ostrich.ambient\")));\n public static final Supplier<SoundEvent> OSTRICH_HURT = CommonPlatformHelper.registerSoundEvent(\"ostrich_hurt\", () -> new SoundEvent(new ResourceLocation(Naturalist.MOD_ID, \"entity.ostrich.hurt\")));\n public static final Supplier<SoundEvent> OSTRICH_DEATH = CommonPlatformHelper.registerSoundEvent(\"ostrich_death\", () -> new SoundEvent(new ResourceLocation(Naturalist.MOD_ID, \"entity.ostrich.death\")));\n // Ostrich Eggs\n public static final Supplier<SoundEvent> OSTRICH_EGG_BREAK = CommonPlatformHelper.registerSoundEvent(\"ostrich_egg_break\", () -> new SoundEvent(new ResourceLocation(Naturalist.MOD_ID, \"entity.ostrich.egg_break\")));\n public static final Supplier<SoundEvent> OSTRICH_EGG_CRACK = CommonPlatformHelper.registerSoundEvent(\"ostrich_egg_crack\", () -> new SoundEvent(new ResourceLocation(Naturalist.MOD_ID, \"entity.ostrich.egg_crack\")));\n public static final Supplier<SoundEvent> OSTRICH_EGG_HATCH = CommonPlatformHelper.registerSoundEvent(\"ostrich_egg_hatch\", () -> new SoundEvent(new ResourceLocation(Naturalist.MOD_ID, \"entity.ostrich.egg_hatch\")));\n\n\n\n // SWAMP SOUNDS\n\n // Gator Eggs\n public static final Supplier<SoundEvent> GATOR_EGG_BREAK = CommonPlatformHelper.registerSoundEvent(\"alligator_egg_break\", () -> new SoundEvent(new ResourceLocation(Naturalist.MOD_ID, \"entity.alligator.egg_break\")));\n public static final Supplier<SoundEvent> GATOR_EGG_CRACK = CommonPlatformHelper.registerSoundEvent(\"alligator_egg_crack\", () -> new SoundEvent(new ResourceLocation(Naturalist.MOD_ID, \"entity.alligator.egg_crack\")));\n public static final Supplier<SoundEvent> GATOR_EGG_HATCH = CommonPlatformHelper.registerSoundEvent(\"alligator_egg_hatch\", () -> new SoundEvent(new ResourceLocation(Naturalist.MOD_ID, \"entity.alligator.egg_hatch\")));\n\n // Tortoise Eggs\n public static final Supplier<SoundEvent> TORTOISE_EGG_BREAK = CommonPlatformHelper.registerSoundEvent(\"tortoise_egg_break\", () -> new SoundEvent(new ResourceLocation(Naturalist.MOD_ID, \"entity.tortoise.egg_break\")));\n public static final Supplier<SoundEvent> TORTOISE_EGG_CRACK = CommonPlatformHelper.registerSoundEvent(\"tortoise_egg_crack\", () -> new SoundEvent(new ResourceLocation(Naturalist.MOD_ID, \"entity.tortoise.egg_crack\")));\n public static final Supplier<SoundEvent> TORTOISE_EGG_HATCH = CommonPlatformHelper.registerSoundEvent(\"tortoise_egg_hatch\", () -> new SoundEvent(new ResourceLocation(Naturalist.MOD_ID, \"entity.tortoise.egg_hatch\")));\n\n public static final Supplier<SoundEvent> GATOR_AMBIENT = CommonPlatformHelper.registerSoundEvent(\"alligator_ambient\", () -> new SoundEvent(new ResourceLocation(Naturalist.MOD_ID, \"entity.alligator.ambient\")));\n public static final Supplier<SoundEvent> GATOR_AMBIENT_BABY = CommonPlatformHelper.registerSoundEvent(\"alligator_ambient_baby\", () -> new SoundEvent(new ResourceLocation(Naturalist.MOD_ID, \"entity.alligator.ambient_baby\")));\n public static final Supplier<SoundEvent> GATOR_HURT = CommonPlatformHelper.registerSoundEvent(\"alligator_hurt\", () -> new SoundEvent(new ResourceLocation(Naturalist.MOD_ID, \"entity.alligator.hurt\")));\n public static final Supplier<SoundEvent> GATOR_DEATH = CommonPlatformHelper.registerSoundEvent(\"alligator_death\", () -> new SoundEvent(new ResourceLocation(Naturalist.MOD_ID, \"entity.alligator.death\")));\n public static final Supplier<SoundEvent> CATFISH_FLOP = CommonPlatformHelper.registerSoundEvent(\"catfish_flop\", () -> new SoundEvent(new ResourceLocation(Naturalist.MOD_ID, \"entity.catfish.flop\")));\n public static final Supplier<SoundEvent> BASS_FLOP = CommonPlatformHelper.registerSoundEvent(\"bass_flop\", () -> new SoundEvent(new ResourceLocation(Naturalist.MOD_ID, \"entity.bass.flop\")));\n public static final Supplier<SoundEvent> DRAGONFLY_LOOP = CommonPlatformHelper.registerSoundEvent(\"dragonfly_loop\", () -> new SoundEvent(new ResourceLocation(Naturalist.MOD_ID, \"entity.dragonfly.loop\")));\n // DUCK SOUNDS\n public static final Supplier<SoundEvent> DUCK_AMBIENT = CommonPlatformHelper.registerSoundEvent(\"duck_ambient\", () -> new SoundEvent(new ResourceLocation(Naturalist.MOD_ID, \"entity.duck.ambient\")));\n public static final Supplier<SoundEvent> DUCK_HURT = CommonPlatformHelper.registerSoundEvent(\"duck_hurt\", () -> new SoundEvent(new ResourceLocation(Naturalist.MOD_ID, \"entity.duck.hurt\")));\n public static final Supplier<SoundEvent> DUCK_DEATH = CommonPlatformHelper.registerSoundEvent(\"duck_death\", () -> new SoundEvent(new ResourceLocation(Naturalist.MOD_ID, \"entity.duck.death\")));\n public static final Supplier<SoundEvent> DUCK_STEP = CommonPlatformHelper.registerSoundEvent(\"duck_step\", () -> new SoundEvent(new ResourceLocation(Naturalist.MOD_ID, \"entity.duck.step\")));\n // RUBBER DUCKY SOUNDS\n public static final Supplier<SoundEvent> RUBBER_DUCKY_AMBIENT = CommonPlatformHelper.registerSoundEvent(\"rubber_ducky_ambient\", () -> new SoundEvent(new ResourceLocation(Naturalist.MOD_ID, \"entity.rubber_ducky.ambient\")));\n public static final Supplier<SoundEvent> RUBBER_DUCKY_HURT = CommonPlatformHelper.registerSoundEvent(\"rubber_ducky_hurt\", () -> new SoundEvent(new ResourceLocation(Naturalist.MOD_ID, \"entity.rubber_ducky.hurt\")));\n public static final Supplier<SoundEvent> RUBBER_DUCKY_DEATH = CommonPlatformHelper.registerSoundEvent(\"rubber_ducky_death\", () -> new SoundEvent(new ResourceLocation(Naturalist.MOD_ID, \"entity.rubber_ducky.death\")));\n\n\n public static void init() {}\n}" } ]
import com.starfish_studios.naturalist.common.entity.core.ElephantContainer; import com.starfish_studios.naturalist.common.entity.core.ai.goal.BabyHurtByTargetGoal; import com.starfish_studios.naturalist.common.entity.core.ai.goal.BabyPanicGoal; import com.starfish_studios.naturalist.common.entity.core.ai.goal.DistancedFollowParentGoal; import com.starfish_studios.naturalist.core.registry.NaturalistEntityTypes; import com.starfish_studios.naturalist.core.registry.NaturalistSoundEvents; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.nbt.CompoundTag; import net.minecraft.network.syncher.EntityDataAccessor; import net.minecraft.network.syncher.EntityDataSerializers; import net.minecraft.network.syncher.SynchedEntityData; import net.minecraft.server.level.ServerLevel; import net.minecraft.sounds.SoundEvent; import net.minecraft.sounds.SoundEvents; import net.minecraft.util.Mth; import net.minecraft.util.RandomSource; import net.minecraft.world.Container; import net.minecraft.world.DifficultyInstance; import net.minecraft.world.damagesource.DamageSource; import net.minecraft.world.entity.*; import net.minecraft.world.entity.ai.attributes.AttributeModifier; import net.minecraft.world.entity.ai.attributes.AttributeSupplier; import net.minecraft.world.entity.ai.attributes.Attributes; import net.minecraft.world.entity.ai.goal.*; import net.minecraft.world.entity.ai.navigation.GroundPathNavigation; import net.minecraft.world.entity.ai.navigation.PathNavigation; import net.minecraft.world.entity.animal.Bee; import net.minecraft.world.entity.animal.horse.AbstractChestedHorse; import net.minecraft.world.entity.player.Player; import net.minecraft.world.level.Level; import net.minecraft.world.level.LevelReader; import net.minecraft.world.level.ServerLevelAccessor; import net.minecraft.world.level.material.Fluids; import net.minecraft.world.phys.Vec3; import software.bernie.geckolib3.core.AnimationState; import software.bernie.geckolib3.core.IAnimatable; import software.bernie.geckolib3.core.PlayState; import software.bernie.geckolib3.core.builder.AnimationBuilder; import software.bernie.geckolib3.core.controller.AnimationController; import software.bernie.geckolib3.core.event.predicate.AnimationEvent; import software.bernie.geckolib3.core.manager.AnimationData; import software.bernie.geckolib3.core.manager.AnimationFactory; import software.bernie.geckolib3.util.GeckoLibUtil; import javax.annotation.Nullable; import java.util.EnumSet;
7,806
package com.starfish_studios.naturalist.common.entity; public class Elephant extends AbstractChestedHorse implements IAnimatable { private final AnimationFactory factory = GeckoLibUtil.createFactory(this); // private static final EntityDataAccessor<Integer> DIRTY_TICKS = SynchedEntityData.defineId(Elephant.class, EntityDataSerializers.INT); private static final EntityDataAccessor<Boolean> DRINKING = SynchedEntityData.defineId(Elephant.class, EntityDataSerializers.BOOLEAN);
package com.starfish_studios.naturalist.common.entity; public class Elephant extends AbstractChestedHorse implements IAnimatable { private final AnimationFactory factory = GeckoLibUtil.createFactory(this); // private static final EntityDataAccessor<Integer> DIRTY_TICKS = SynchedEntityData.defineId(Elephant.class, EntityDataSerializers.INT); private static final EntityDataAccessor<Boolean> DRINKING = SynchedEntityData.defineId(Elephant.class, EntityDataSerializers.BOOLEAN);
protected ElephantContainer inventory;
0
2023-10-16 21:54:32+00:00
12k
wangqi060934/MyAndroidToolsPro
app/src/main/java/cn/wq/myandroidtoolspro/recyclerview/fragment/ReceiverWithActionParentFragment.java
[ { "identifier": "MainActivity", "path": "app/src/free/java/cn/wq/myandroidtoolspro/MainActivity.java", "snippet": "public class MainActivity extends BaseActivity implements GridNavigationView.OnNavigationItemSelectedListener {\n private static final String TAG = \"MainActivity\";\n private static final String TAG_AD = \"MatAd\";\n private DrawerLayout mDrawerLayout;\n private GridNavigationView mNavigationView;\n private int mSavedMenuItemId;\n private static final String NAV_ITEM_ID = \"navItemId\";\n private static final int REQUEST_CODE_PERMISSION = 2;\n private boolean needKillSelf;\n// private BroadcastReceiver pkgAddReceiver;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n final int theme = PreferenceManager.getDefaultSharedPreferences(this).getInt(PREFERENCE_THEME, 0);\n if (theme == 2) {\n setTheme(R.style.AppThemeBlack);\n } else if (theme == 1) {\n setTheme(R.style.AppThemeDark);\n } else {\n setTheme(R.style.AppTheme);\n }\n\n super.onCreate(savedInstanceState);\n\n setContentView(R.layout.activity_main);\n\n mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);\n mNavigationView = (GridNavigationView) findViewById(R.id.navigationView);\n mNavigationView.setNavigationItemSelectedListener(this);\n\n if (savedInstanceState == null) {\n mSavedMenuItemId = R.id.about;\n\n //wq:bug on 2.3,https://code.google.com/p/android/issues/detail?id=81083\n// if(Build.VERSION.SDK_INT<11){\n// try {\n// Class.forName(\"android.os.AsyncTask\");\n// } catch (ClassNotFoundException e) {\n// e.printStackTrace();\n// }\n// }\n\n Intent intent = getIntent();\n if (intent == null || !intent.getBooleanExtra(\"restart\", false)) {\n mDrawerLayout.openDrawer(mNavigationView);\n }\n needKillSelf = intent != null && intent.getBooleanExtra(\"needKillSelf\", false);\n changeContainerFragment(R.id.about);\n } else {\n mSavedMenuItemId = savedInstanceState.getInt(NAV_ITEM_ID, R.id.about);\n }\n\n// if (Build.VERSION.SDK_INT < 11 && !checkAdbEnabled()) {\n// Toast.makeText(this, R.string.toast_adb, Toast.LENGTH_SHORT).show();\n// }\n\n boolean permGranted = checkPermission();\n\n if (theme == 2 && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {\n ActivityManager.TaskDescription description = new ActivityManager.TaskDescription(\n null,\n null,\n ContextCompat.getColor(this, R.color.dark_black));\n setTaskDescription(description);\n }\n\n initXlog();\n\n if (BuildConfig.DEBUG && Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {\n StrictMode.setThreadPolicy(\n new StrictMode.ThreadPolicy.Builder()\n .detectAll().penaltyLog().build());\n StrictMode.setVmPolicy(\n new StrictMode.VmPolicy.Builder().\n detectAll().penaltyLog().build());\n }\n\n// registerPkgAddReceiver();\n }\n\n// private void registerPkgAddReceiver() {\n// if (pkgAddReceiver == null) {\n// pkgAddReceiver = new BroadcastReceiver() {\n// @Override\n// public void onReceive(Context context, Intent intent) {\n// PackageAddReceiver.handleAppAdd(context, intent);\n// }\n// };\n// IntentFilter intentFilter = new IntentFilter(Intent.ACTION_PACKAGE_ADDED);\n// intentFilter.addDataScheme(\"package\");\n// registerReceiver(pkgAddReceiver, intentFilter);\n// }\n// }\n\n @Override\n public LinearLayout getAdContainer() {\n return findViewById(R.id.content_container);\n }\n\n /**\n * @return whethe the permissions has granted\n */\n private boolean checkPermission() {\n boolean sdPermFB = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)\n != PackageManager.PERMISSION_GRANTED;\n\n if (sdPermFB) {\n try {\n List<String> permList = new ArrayList<>(2);\n if (sdPermFB) {\n permList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);\n }\n ActivityCompat.requestPermissions(this, permList.toArray(new String[0])\n , REQUEST_CODE_PERMISSION);\n } catch (Exception e) {\n e.printStackTrace();\n }\n return false;\n }\n return true;\n }\n\n private void initXlog() {\n final String logPath = getExternalFilesDir(null) + \"/xlog\";\n\n // this is necessary, or may cash for SIGBUS\n final String cachePath = this.getFilesDir() + \"/xlog\";\n\n //init xlog\n if (BuildConfig.DEBUG) {\n Xlog.appenderOpen(Xlog.LEVEL_DEBUG, Xlog.AppednerModeAsync, cachePath, logPath, \"Mat\", null);\n Xlog.setConsoleLogOpen(true);\n } else {\n Xlog.appenderOpen(Xlog.LEVEL_INFO, Xlog.AppednerModeAsync, cachePath, logPath, \"Mat\", null);\n Xlog.setConsoleLogOpen(false);\n }\n\n com.tencent.mars.xlog.Log.setLogImp(new Xlog());\n }\n\n @Override\n public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {\n super.onRequestPermissionsResult(requestCode, permissions, grantResults);\n }\n\n @Override\n public boolean onNavigationItemSelected(MenuItem menuItem) {\n mDrawerLayout.closeDrawer(mNavigationView);\n\n final int id = menuItem.getItemId();\n// if(id==mSavedMenuItemId){\n// return true;\n// }\n menuItem.setChecked(true);\n\n changeContainerFragment(id);\n\n mSavedMenuItemId = id;\n return true;\n }\n\n @Override\n public boolean onKeyDown(int keyCode, KeyEvent event) {\n if (mSavedMenuItemId == R.id.logcat && keyCode == KeyEvent.KEYCODE_MENU) {\n if (mDrawerLayout.isDrawerOpen(mNavigationView)) {\n mDrawerLayout.closeDrawer(mNavigationView);\n } else {\n mDrawerLayout.openDrawer(mNavigationView);\n }\n return true;\n }\n return super.onKeyDown(keyCode, event);\n }\n\n @Override\n public void onSaveInstanceState(Bundle outState) {\n super.onSaveInstanceState(outState);\n outState.putInt(NAV_ITEM_ID, mSavedMenuItemId);\n }\n\n// @Override\n// public void onConfigurationChanged(Configuration newConfig) {\n// super.onConfigurationChanged(newConfig);\n// mDrawerToggle.onConfigurationChanged(newConfig);\n// }\n//\n// @Override\n// protected void onPostCreate(Bundle savedInstanceState) {\n// super.onPostCreate(savedInstanceState);\n// mDrawerToggle.syncState();\n// }\n\n @Override\n public boolean onOptionsItemSelected(MenuItem item) {\n switch (item.getItemId()) {\n case android.R.id.home:\n if (getSupportFragmentManager().getBackStackEntryCount() == 0) {\n if (mDrawerLayout.isDrawerOpen(mNavigationView)) {\n mDrawerLayout.closeDrawer(mNavigationView);\n } else\n mDrawerLayout.openDrawer(mNavigationView);\n } else {\n onBackPressed();\n }\n break;\n default:\n break;\n }\n return super.onOptionsItemSelected(item);\n }\n\n @Override\n public void onPause() {\n super.onPause();\n }\n\n @Override\n public void onResume() {\n super.onResume();\n\n }\n\n @Override\n protected void onStop() {\n super.onStop();\n if (needKillSelf) { //不然的话刚换主题后 马上从launcher icon永远启动会在new task中新建activity\n finish();\n// ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);\n// if (am != null) {\n// am.killBackgroundProcesses(getPackageName());\n// }\n }\n\n }\n\n @Override\n public void onDestroy() {\n super.onDestroy();\n\n com.tencent.mars.xlog.Log.appenderClose();\n\n File tempDB = new File(Utils.getTempDBPath(this));\n File tempDBwal = new File(Utils.getTempDBWalPath(this));\n File tempSPrefs = new File(Utils.getTempSPfrefsPath(this));\n\n if (tempDB.exists()) {\n tempDB.delete();\n }\n if (tempDBwal.exists()) {\n tempDBwal.delete();\n }\n if (tempSPrefs.exists()) {\n tempSPrefs.delete();\n }\n\n// if (pkgAddReceiver != null) {\n// try {\n// unregisterReceiver(pkgAddReceiver);\n// } catch (Exception e) {\n// Log.e(TAG, \"unregisterReceiver pkgAddReceiver\", e);\n// Utils.err(TAG, \"unregisterReceiver pkgAddReceiver\", e);\n// }\n// }\n }\n\n private void changeContainerFragment(int itemId) {\n Fragment f;\n switch (itemId) {\n case R.id.service:\n f = ComponentParentFragment.newInstance(0);\n break;\n case R.id.receiver:\n f = new ReceiverParentFragment();\n break;\n case R.id.activity:\n f = ComponentParentFragment.newInstance(2);\n break;\n case R.id.provider:\n f = ComponentParentFragment.newInstance(3);\n break;\n case R.id.preferece:\n f = AppListForDataFragment.newInstance(0);\n break;\n case R.id.database:\n f = AppListForDataFragment.newInstance(1);\n break;\n case R.id.process:\n f = new ProcessFragment();\n break;\n case R.id.logcat:\n f = new LogFragment();\n break;\n case R.id.uid:\n f = new UidFragment();\n break;\n case R.id.current:\n f = new CurrentFragment();\n break;\n case R.id.apps:\n f = new AppManageParentFragment();\n break;\n default:\n f = new AboutFragment();\n break;\n }\n\n if (getSupportFragmentManager() == null) {\n Log.e(TAG, \"getSupportFragmentManager is null when change to fragment:\" + f.toString());\n return;\n }\n getSupportFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);\n\n FragmentTransaction ft = getSupportFragmentManager().beginTransaction();\n ft.replace(R.id.content, f);\n// ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);\n ft.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out);\n ft.commit();\n }\n\n @Override\n public void onBackPressed() {\n if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) {\n mDrawerLayout.closeDrawer(GravityCompat.START);\n return;\n }\n\n if (onBackListener != null) {\n onBackListener.onBack();\n }\n\n super.onBackPressed();\n }\n\n public interface OnBackListener{\n void onBack();\n }\n private OnBackListener onBackListener;\n public void addOnBackListener(OnBackListener l) {\n onBackListener = l ;\n }\n public void removeOnBackListener() {\n onBackListener = null;\n }\n\n}" }, { "identifier": "MultiSelectionRecyclerListFragment", "path": "app/src/main/java/cn/wq/myandroidtoolspro/recyclerview/multi/MultiSelectionRecyclerListFragment.java", "snippet": "public abstract class MultiSelectionRecyclerListFragment<T extends ComponentEntry>\r\n extends RecyclerListFragment\r\n implements ActionMode.Callback, SearchView.OnQueryTextListener, RecyclerListView.OnRecyclerItemClickListener {\r\n private static final String TAG = \"MultiSelRecyclerLF\";\r\n private MultiSelectionUtils.Controller mController;\r\n private AbstractComponentAdapter<T> mAdapter;\r\n\r\n private SearchView searchView;\r\n private MenuItem searchMenuItem, toggleMenuItem;\r\n private Integer[] mSelectedItems;\r\n private List<ParallellDisableTask> mDisableTasks;\r\n private AtomicInteger parallelCount;\r\n// private CustomProgressDialogFragment dialog;\r\n private LoadDataTask mLoadDataTask;\r\n private ActionModeLefecycleCallback mActionModeCallBack;\r\n private Context mContext;\r\n// private final static String ADMOB_ACTIVITY_NAME = \"com.google.android.gms.ads.AdActivity\";\r\n\r\n private final static int PARAL_THRETHOLD = 8;//禁用数量较少时不用多任务同时处理\r\n protected IfwUtil.IfwEntry mIfwEntry;\r\n protected boolean hasLoadIfw, useParentIfw;\r\n\r\n public interface ActionModeLefecycleCallback {\r\n void onModeCreated();\r\n\r\n void onModeDestroyed();\r\n }\r\n\r\n public void addActionModeLefecycleCallback(ActionModeLefecycleCallback callback) {\r\n mActionModeCallBack = callback;\r\n }\r\n\r\n @Override\r\n public void onAttach(Context context) {\r\n super.onAttach(context);\r\n mContext = context;\r\n }\r\n\r\n @Override\r\n public void onActivityCreated(@Nullable Bundle savedInstanceState) {\r\n super.onActivityCreated(savedInstanceState);\r\n\r\n setHasOptionsMenu(true);\r\n mAdapter = generateAdapter();\r\n setAdapter(mAdapter);\r\n setEmptyText(getString(R.string.empty));\r\n\r\n Bundle data = getArguments();\r\n if (data != null) {\r\n useParentIfw = data.getBoolean(\"useParentIfw\", false);\r\n }\r\n //是否是子fragment,父fragment设置title就行了\r\n// if (data != null && !data.getBoolean(\"part\")) {\r\n// ((MainActivity) getActivity()).resetActionbar(true, data.getString(\"title\"));\r\n// }\r\n\r\n // 此前必须setAdapter\r\n mController = MultiSelectionUtils.attach(this);\r\n mController.restoreInstanceState(savedInstanceState);\r\n\r\n if (mLoadDataTask != null) {\r\n mLoadDataTask.cancel(true);\r\n }\r\n mLoadDataTask = new LoadDataTask();\r\n mLoadDataTask.execute();\r\n }\r\n\r\n public MultiSelectionUtils.Controller getMultiController() {\r\n return mController;\r\n }\r\n\r\n @Override\r\n public void onSaveInstanceState(Bundle outState) {\r\n super.onSaveInstanceState(outState);\r\n if (mController != null) {\r\n mController.saveInstanceState(outState);\r\n }\r\n }\r\n\r\n @Override\r\n public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {\r\n super.onCreateOptionsMenu(menu, inflater);\r\n inflater.inflate(R.menu.component, menu);\r\n\r\n searchMenuItem = menu.findItem(R.id.search_component);\r\n searchView = (SearchView) MenuItemCompat.getActionView(searchMenuItem);\r\n searchView.setQueryHint(getString(R.string.hint_app_search));\r\n searchView.setOnQueryTextListener(this);\r\n\r\n toggleMenuItem = menu.findItem(R.id.toggle_name);\r\n }\r\n\r\n @Override\r\n public boolean onOptionsItemSelected(MenuItem item) {\r\n switch (item.getItemId()) {\r\n case android.R.id.home:\r\n getActivity().onBackPressed();\r\n break;\r\n case R.id.toggle_name:\r\n boolean isFullMode = mAdapter.toggleName();\r\n toggleMenuItem.setIcon(isFullMode ? R.drawable.ic_short_name : R.drawable.ic_full_name_white);\r\n break;\r\n case R.id.start_multi_select:\r\n mController.startActionMode();\r\n break;\r\n default:\r\n break;\r\n }\r\n\r\n return super.onOptionsItemSelected(item);\r\n }\r\n\r\n @Override\r\n public void onPrepareOptionsMenu(Menu menu) {\r\n super.onPrepareOptionsMenu(menu);\r\n toggleMenuItem.setIcon(mAdapter.getIsFullName() ? R.drawable.ic_short_name : R.drawable.ic_full_name_white);\r\n }\r\n\r\n public void closeActionMode() {\r\n if (mController != null) {\r\n mController.finish();\r\n }\r\n }\r\n\r\n private class LoadDataTask extends AsyncTask<Void, Void, List<T>> {\r\n @Override\r\n protected List<T> doInBackground(Void... params) {\r\n return loadData();\r\n }\r\n\r\n @Override\r\n protected void onPostExecute(List<T> list) {\r\n super.onPostExecute(list);\r\n\r\n setListShown(true, true);\r\n mAdapter.setData(list);\r\n\r\n SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(mContext);\r\n //不加isAdded() 可能getChildFragmentManager() 会报错:Fragment has not been attached yet.\r\n if (!sharedPreferences.getBoolean(\"first_toast\", false) && isAdded()\r\n && getActivity() != null && !getActivity().isFinishing()) {\r\n\r\n FirstToastDialog dialog = new FirstToastDialog();\r\n try {\r\n dialog.show(getChildFragmentManager(), \"first\");\r\n } catch (Exception e) {\r\n }\r\n\r\n sharedPreferences.edit().putBoolean(\"first_toast\", true).apply();\r\n }\r\n\r\n if (Utils.isPmByIfw(mContext) && !hasLoadIfw && mIfwEntry != null && mIfwEntry.status < 0) {\r\n Toast.makeText(mContext, R.string.load_ifw_by_root_failed, Toast.LENGTH_LONG).show();\r\n }\r\n\r\n }\r\n\r\n @Override\r\n protected void onPreExecute() {\r\n super.onPreExecute();\r\n setListShown(false, true);\r\n }\r\n }\r\n\r\n /**\r\n * 在loadData之前加载ifw规则\r\n * @param packageName\r\n */\r\n protected void loadDataForIfw(String packageName) {\r\n if (useParentIfw) {\r\n mIfwEntry = AppInfoForManageFragment2.mIfwEntry;\r\n } else {\r\n try {\r\n mIfwEntry = IfwUtil.loadIfwFileForPkg(mContext, packageName, IfwUtil.COMPONENT_FLAG_ALL, hasLoadIfw);\r\n } catch (Exception e) {\r\n e.printStackTrace();\r\n Log.e(TAG, \"loadDataForIfw error\", e);\r\n }\r\n if (mIfwEntry != null && mIfwEntry != IfwUtil.IfwEntry.ROOT_ERROR) {\r\n hasLoadIfw = true;\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * 加载本app的所有ifw,后缀为{@link IfwUtil#BACKUP_SYSTEM_FILE_EXT_OF_MINE}\r\n */\r\n protected void loadAllMyIfw(File ifwTempDir) {\r\n //外层检测是否是ifw模式\r\n try {\r\n mIfwEntry = IfwUtil.loadAllIfwFile(mContext,IfwUtil.COMPONENT_FLAG_ALL, ifwTempDir,hasLoadIfw);\r\n } catch (Exception e) {\r\n e.printStackTrace();\r\n Log.e(TAG, \"loadAllMyIfw error\", e);\r\n }\r\n if (mIfwEntry != null && mIfwEntry != IfwUtil.IfwEntry.ROOT_ERROR) {\r\n hasLoadIfw = true;\r\n }\r\n }\r\n\r\n @Override\r\n public void onDestroy() {\r\n super.onDestroy();\r\n if (mIfwEntry != null) {\r\n mIfwEntry.clear();\r\n }\r\n }\r\n\r\n abstract protected List<T> loadData();\r\n\r\n abstract protected AbstractComponentAdapter<T> generateAdapter();\r\n\r\n /**\r\n * disable/enable后update下\r\n *\r\n * @param checkedItemPositions 选中的positions\r\n */\r\n abstract protected void reloadData(Integer... checkedItemPositions);\r\n\r\n /**\r\n * Service、Activity、Provider需要处理ifw模式下的禁用\r\n * @param positions\r\n */\r\n abstract protected boolean disableByIfw(Integer... positions);\r\n\r\n// private boolean canUseIfw() {\r\n// MultiSelectionRecyclerListFragment thisInst = MultiSelectionRecyclerListFragment.this;\r\n// return thisInst instanceof ServiceRecyclerListFragment\r\n// || thisInst instanceof ActivityRecyclerListFragment\r\n// || thisInst instanceof ReceiverRecyclerListFragment\r\n// //组件全局搜索\r\n// || thisInst instanceof SearchComponentInAllFragment;\r\n// }\r\n /**\r\n * 是否支持ifw禁用;provider不支持,另外组件全局模式下也要判断是否是provider\r\n */\r\n protected boolean isSupportIfw() {\r\n return false;\r\n }\r\n\r\n\r\n //--------------------------\r\n //---------ActionMode-------\r\n //--------------------------\r\n @Override\r\n public boolean onCreateActionMode(ActionMode mode, Menu menu) {\r\n mode.setTitle(R.string.multi_select);\r\n mode.getMenuInflater().inflate(R.menu.actionmode, menu);\r\n if (mActionModeCallBack != null) {\r\n mActionModeCallBack.onModeCreated();\r\n }\r\n return true;\r\n }\r\n\r\n @Override\r\n public void onDestroyActionMode(ActionMode mode) {\r\n if (mActionModeCallBack != null) {\r\n mActionModeCallBack.onModeDestroyed();\r\n }\r\n }\r\n\r\n @Override\r\n public boolean onPrepareActionMode(ActionMode mode, Menu menu) {\r\n return true;\r\n }\r\n\r\n @Override\r\n public boolean onActionItemClicked(ActionMode mode, MenuItem item) {\r\n switch (item.getItemId()) {\r\n case R.id.ok: {\r\n ArrayList<Integer> selectedPos = mController.getSelectedItemsPosition();\r\n int total = selectedPos.size();\r\n if (total == 0) {\r\n mode.finish();\r\n break;\r\n }\r\n\r\n mSelectedItems = new Integer[total];\r\n for (int i = 0; i < total; i++) {\r\n mSelectedItems[i] = selectedPos.get(i);\r\n }\r\n\r\n setProgressDialogVisibility(true);\r\n\r\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {\r\n final int CORE_POOL_SIZE;\r\n //ifw模式不需要并行处理\r\n if (total <= PARAL_THRETHOLD || Utils.isPmByIfw(mContext)) {\r\n CORE_POOL_SIZE = 1;\r\n } else {\r\n CORE_POOL_SIZE = Runtime.getRuntime().availableProcessors() + 1;\r\n }\r\n final int chunckSize = (int) Math.ceil(total / (float) CORE_POOL_SIZE);\r\n mDisableTasks = new ArrayList<>(CORE_POOL_SIZE);\r\n parallelCount = new AtomicInteger(CORE_POOL_SIZE);\r\n\r\n// mStartTime=System.currentTimeMillis();\r\n for (int i = 0; i < CORE_POOL_SIZE; i++) {\r\n if (i == CORE_POOL_SIZE - 1) {\r\n int length = total - i * chunckSize;\r\n if (length <= 0) {\r\n parallelCount.decrementAndGet();\r\n continue;\r\n }\r\n mDisableTasks.add(new ParallellDisableTask(mSelectedItems.length));\r\n Integer[] dest = new Integer[length];\r\n System.arraycopy(mSelectedItems, i * chunckSize, dest, 0, length);\r\n mDisableTasks.get(i).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, dest);\r\n } else {\r\n if (i * chunckSize > total) {\r\n parallelCount.decrementAndGet();\r\n continue;\r\n }\r\n int length = chunckSize;\r\n if (i * chunckSize + length > total) {\r\n length = total - i * chunckSize;\r\n }\r\n mDisableTasks.add(new ParallellDisableTask(mSelectedItems.length));\r\n Integer[] dest = new Integer[length];\r\n System.arraycopy(mSelectedItems, i * chunckSize, dest, 0, length);\r\n// mTasks[i].executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,dest);\r\n mDisableTasks.get(i).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, dest);\r\n }\r\n }\r\n } else {\r\n parallelCount = new AtomicInteger(1);\r\n mDisableTasks = new ArrayList<>(1);\r\n mDisableTasks.add(new ParallellDisableTask(mSelectedItems.length));\r\n mDisableTasks.get(0).execute(mSelectedItems);\r\n }\r\n mode.finish();\r\n }\r\n break;\r\n case R.id.copy: {\r\n ArrayList<Integer> selectedPos = mController.getSelectedItemsPosition();\r\n StringBuilder sb = new StringBuilder();\r\n for (int checkedItemId : selectedPos) {\r\n ComponentEntry entry = mAdapter.getItem(checkedItemId);\r\n if (mAdapter.getIsFullName()) {\r\n sb.append(entry.packageName).append(\"/\").append(entry.className);\r\n } else {\r\n sb.append(entry.className.substring(entry.className\r\n .lastIndexOf(\".\") + 1));\r\n }\r\n sb.append(\" \");\r\n }\r\n\r\n ClipboardManager clipboardManager = (ClipboardManager) mContext\r\n .getSystemService(Activity.CLIPBOARD_SERVICE);\r\n clipboardManager.setText(sb.toString());\r\n\r\n Toast.makeText(mContext, R.string.copy_toast,\r\n Toast.LENGTH_SHORT).show();\r\n }\r\n break;\r\n case R.id.selectAll: {\r\n ArrayList<Integer> selectedPos = mController.getSelectedItemsPosition();\r\n RecyclerView recyclerView = getRecyclerListView();\r\n if (selectedPos.size() == mAdapter.getItemCount()) {\r\n for (int i = 0; i < mAdapter.getItemCount(); i++) {\r\n MultiSelectableViewHolder holder = (MultiSelectableViewHolder) recyclerView.findViewHolderForLayoutPosition(i);\r\n mController.onStateChanged(i, false);\r\n if (holder != null) {\r\n holder.setSelected(false);\r\n }\r\n\r\n }\r\n mode.finish();\r\n } else {\r\n for (int i = 0; i < mAdapter.getItemCount(); i++) {\r\n MultiSelectableViewHolder holder = (MultiSelectableViewHolder) recyclerView.findViewHolderForLayoutPosition(i);\r\n mController.onStateChanged(i, true);\r\n if (holder != null) {\r\n holder.setSelected(true);\r\n }\r\n }\r\n }\r\n }\r\n break;\r\n default:\r\n break;\r\n }\r\n return true;\r\n }\r\n\r\n //--------------------------\r\n //--------------------------\r\n\r\n public static class FirstToastDialog extends DialogFragment {\r\n @NonNull\r\n @Override\r\n public Dialog onCreateDialog(Bundle savedInstanceState) {\r\n Dialog dialog = new AlertDialog.Builder(getContext())\r\n .setTitle(R.string.hint_first_time)\r\n .setView(R.layout.dialog_first_toast)\r\n .setNegativeButton(R.string.ok, null)\r\n .create();\r\n if (dialog.getWindow() != null) {\r\n dialog.getWindow().setWindowAnimations(R.style.DialogAnimation);\r\n }\r\n return dialog;\r\n }\r\n\r\n// @Override\r\n// public void onActivityCreated(Bundle savedInstanceState) {\r\n// super.onActivityCreated(savedInstanceState);\r\n// getDialog().getWindow().setWindowAnimations(R.style.DialogAnimation);\r\n// }\r\n }\r\n\r\n protected Comparator<T> comparator = new Comparator<T>() {\r\n @Override\r\n public int compare(T lhs, T rhs) {\r\n if (lhs instanceof ServiceEntry) {\r\n ServiceEntry le = (ServiceEntry) lhs;\r\n ServiceEntry re = (ServiceEntry) rhs;\r\n if (le.isRunning && !re.isRunning) {\r\n return -1;\r\n } else if (!le.isRunning && re.isRunning) {\r\n return 1;\r\n }\r\n }\r\n\r\n if (!lhs.enabled && rhs.enabled) {\r\n return -1;\r\n } else if (lhs.enabled && !rhs.enabled) {\r\n return 1;\r\n }\r\n\r\n String l = lhs.className\r\n .substring(lhs.className.lastIndexOf(\".\") + 1);\r\n String r = rhs.className\r\n .substring(rhs.className.lastIndexOf(\".\") + 1);\r\n return l.compareTo(r);\r\n }\r\n };\r\n\r\n // -----------------------------\r\n // ------------searchview-------\r\n // -----------------------------\r\n @Override\r\n public boolean onQueryTextChange(String query) {\r\n if (mAdapter != null) {\r\n mAdapter.getFilter().filter(query);\r\n }\r\n return true;\r\n }\r\n\r\n @Override\r\n public boolean onQueryTextSubmit(String query) {\r\n return true;\r\n }\r\n // -----------------------------\r\n\r\n /**\r\n * Android 8.0+获取running service需要用root命令,所以返回loadData(),其它返回boolean\r\n */\r\n private class ParallellDisableTask extends AsyncTask<Integer, Void, Object> {\r\n private boolean isGetServiceFor26up; //Android O(26)开始获取 service 特殊要处理\r\n private int errorType; //1.不允许禁用admob 2.组件实际不存在 3.shizuku失败 4.ifw失败\r\n private String errorMessage;\r\n\r\n private int total; //总数\r\n\r\n public ParallellDisableTask(int total) {\r\n this.total = total;\r\n }\r\n\r\n @Override\r\n protected void onPreExecute() {\r\n super.onPreExecute();\r\n Utils.debug(this + \"||onPreExecute\");\r\n }\r\n\r\n @Override\r\n protected void onPostExecute(Object result) {\r\n super.onPostExecute(result);\r\n int currentPendings = parallelCount.decrementAndGet();\r\n\r\n// System.out.println(result+\" : \"+parallelCount.get());\r\n Utils.debug(this + \"||onPostExecute,result=[\" + result + \"],currentPendings:[\" + currentPendings + \"],isGetServiceFor26up:\" + isGetServiceFor26up + \",errorType:\" + errorType);\r\n\r\n if (result instanceof Boolean) { //isGetServiceFor26up 可能返回 false\r\n boolean r = (boolean) result;\r\n if (r || errorType == 2) { //禁用了不存在的组件 可以认为成功了\r\n if (currentPendings <= 0) {\r\n reloadData(mSelectedItems);\r\n if (MenuItemCompat.isActionViewExpanded(searchMenuItem)) {\r\n mAdapter.getFilter().filter(searchView.getQuery());\r\n }\r\n setProgressDialogVisibility(false);\r\n }\r\n\r\n if (errorType == 2) {\r\n if (total == 1) {\r\n showToastInCenter(R.string.component_not_exist);\r\n } else {\r\n showToastInCenter(R.string.a_component_not_exist);\r\n }\r\n }\r\n } else {\r\n setProgressDialogVisibility(false);\r\n for (ParallellDisableTask mTask : mDisableTasks) {\r\n if (mTask != null) {\r\n mTask.cancel(true);\r\n }\r\n }\r\n\r\n if (errorType == 1) {\r\n showToastInCenter(R.string.disallow_disable_admob);\r\n } else if (errorType == 3) {\r\n showToastInCenter(getString(R.string.shizuku_run_command_failed, errorMessage));\r\n } else if (errorType == 4) {\r\n showToastInCenter(R.string.ifw_save_failed);\r\n } else {\r\n showToastInCenter(R.string.failed_to_gain_root);\r\n }\r\n\r\n }\r\n return;\r\n }\r\n\r\n if (isGetServiceFor26up) { //android o 8.0 的 service 特殊处理\r\n mAdapter.setData((List<T>) result);\r\n if (MenuItemCompat.isActionViewExpanded(searchMenuItem)) {\r\n mAdapter.getFilter().filter(searchView.getQuery());\r\n }\r\n setProgressDialogVisibility(false);\r\n }\r\n\r\n\r\n Utils.debug(this + \",3333\");\r\n }\r\n\r\n private void showToastInCenter(@StringRes int res) {\r\n Toast toast = Toast.makeText(mContext, res,\r\n Toast.LENGTH_SHORT);\r\n toast.setGravity(Gravity.CENTER, 0, 0);\r\n toast.show();\r\n }\r\n\r\n private void showToastInCenter(String res) {\r\n Toast toast = Toast.makeText(mContext, res,\r\n Toast.LENGTH_SHORT);\r\n toast.setGravity(Gravity.CENTER, 0, 0);\r\n toast.show();\r\n }\r\n\r\n @Override\r\n protected Object doInBackground(Integer... params) {\r\n if (isCancelled()) {\r\n return false;\r\n }\r\n isGetServiceFor26up = Build.VERSION.SDK_INT >= Build.VERSION_CODES.O\r\n && MultiSelectionRecyclerListFragment.this instanceof ServiceRecyclerListFragment;\r\n\r\n int pmChannel = PreferenceManager.getDefaultSharedPreferences(getContext())\r\n .getInt(BaseActivity.PREFERENCE_PM_CHANNER,BaseActivity.PM_CHANNEL_ROOT_COMMAND);\r\n boolean result;\r\n if (pmChannel == BaseActivity.PM_CHANNEL_SHIZUKU) {\r\n result = disableByShizuku(params);\r\n } else if(pmChannel == BaseActivity.PM_CHANNEL_IFW && isSupportIfw()){\r\n result = disableByIfw(params);\r\n if (!result) {\r\n errorType = 4;\r\n }\r\n }else {\r\n result = disableByPm(params);\r\n }\r\n\r\n if (result && isGetServiceFor26up) {\r\n Utils.debug(this + \",ffff\");\r\n // TODO: 2019/3/31 考虑不要重复加载ifw\r\n return loadData();\r\n }\r\n return result;\r\n\r\n }\r\n\r\n private boolean disableByShizuku(Integer... params) {\r\n PackageManager pm = mContext.getPackageManager();\r\n ComponentName cName;\r\n ComponentEntry entry;\r\n for (int i : params) {\r\n if (isCancelled()) {\r\n return false;\r\n }\r\n if (i >= mAdapter.getItemCount()) {\r\n continue;\r\n }\r\n entry = mAdapter.getItem(i);\r\n if (entry == null) {\r\n continue;\r\n }\r\n cName = new ComponentName(entry.packageName, entry.className);\r\n int newState;\r\n if (pm.getComponentEnabledSetting(cName) <= PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {\r\n //https://blog.csdn.net/linliang815/article/details/76179405\r\n //报错shell cannot change component state for */* to 2\r\n //api会识别成shell_uid\r\n newState = PackageManager.COMPONENT_ENABLED_STATE_DISABLED;\r\n } else {\r\n newState = PackageManager.COMPONENT_ENABLED_STATE_ENABLED;\r\n }\r\n try {\r\n Utils.debug(TAG,\"shizuku isAuthorized:\"+ ShizukuClient.getState().isAuthorized());\r\n ShizukuPackageManagerV26.setComponentEnabledSetting(\r\n cName,\r\n newState,\r\n// PackageManager.DONT_KILL_APP,\r\n 0,\r\n 0\r\n );\r\n } catch (Exception e) {\r\n Log.e(TAG, \"shizuku disable error\", e);\r\n Utils.err(TAG,\"shizuku disable error\", e);\r\n if (e.getMessage() != null) {\r\n errorMessage = e.getMessage();\r\n }\r\n errorType = 3;\r\n return false;\r\n }\r\n }\r\n return true;\r\n }\r\n\r\n private boolean disableByPm(Integer... params) {\r\n StringBuilder builder = new StringBuilder();\r\n PackageManager pm = mContext.getPackageManager();\r\n ComponentName cName;\r\n ComponentEntry entry;\r\n for (int i : params) {\r\n if (isCancelled()) {\r\n return false;\r\n }\r\n if (i >= mAdapter.getItemCount()) {\r\n continue;\r\n }\r\n entry = mAdapter.getItem(i);\r\n if (entry == null) {\r\n continue;\r\n }\r\n cName = new ComponentName(entry.packageName, entry.className);\r\n\r\n if (pm.getComponentEnabledSetting(cName) <= PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {\r\n //free版限制不允许禁止admob\r\n// if (BuildConfig.isFree && entry.className.equals(ADMOB_ACTIVITY_NAME)) {\r\n// errorType = 1;\r\n// return false;\r\n// }\r\n builder.append(\"pm disable \");\r\n } else {\r\n builder.append(\"pm enable \");\r\n }\r\n builder.append(entry.packageName);\r\n builder.append(\"/\");\r\n builder.append(Matcher.quoteReplacement(entry.className));\r\n builder.append(\"\\n\");\r\n }\r\n// return Utils.runRootCommand(builder.toString());\r\n// return Shell.SU.run(builder.toString()) != null;\r\n\r\n Utils.debug(this + \",4444\");\r\n\r\n boolean result;\r\n if (Shell.SU.available()) {\r\n// final List<String> ss = Shell.SU.runGetOnlyErr(builder.toString());\r\n// final Pattern pattern = Pattern.compile(\"[\\\\w\\\\W]+Component class [^ ]+ does not exist in [^ ]+\");\r\n// //禁用多个时 只有最后一个不存在时会影响process.exitValue()返回1\r\n// if (ss != null && ss.size() > 0 && pattern.matcher(ss.get(ss.size() - 1)).matches()) {\r\n// errorType = 2;\r\n// result = false;\r\n// } else {\r\n// result = ss != null;\r\n// }\r\n int r = Utils.runMultiPmDisableCommand(builder.toString());\r\n if (r == -2) {\r\n errorType = 2;\r\n }\r\n result = r > 0;\r\n } else {\r\n result = Shell.SU.run(builder.toString()) != null;\r\n }\r\n return result;\r\n }\r\n\r\n }\r\n\r\n private void setProgressDialogVisibility(boolean visible) {\r\n Utils.debug(\"setProgressDialogVisibility:\" + visible);\r\n CustomProgressDialogFragment dialog = (CustomProgressDialogFragment) getActivity().getSupportFragmentManager().findFragmentByTag(\"dialog\");\r\n if (visible) {\r\n if (dialog == null) {\r\n dialog = new CustomProgressDialogFragment();\r\n dialog.setStyle(DialogFragment.STYLE_NO_TITLE, 0);\r\n dialog.setCancelable(false);\r\n Utils.debug(\"setProgressDialogVisibility:\" + 5555);\r\n }\r\n\r\n //Can not perform this action after onSaveInstanceState\r\n if (!dialog.isVisible() && getActivity() != null && !getActivity().isFinishing()) {\r\n try {\r\n dialog.show(getActivity().getSupportFragmentManager(), \"dialog\");\r\n } catch (Exception e) {\r\n }\r\n Utils.debug(\"setProgressDialogVisibility:\" + 6666);\r\n }\r\n Utils.debug(\"setProgressDialogVisibility:\" + 7777);\r\n } else {\r\n //https://stackoverflow.com/a/19980877/1263423\r\n //或者判断 dialog.isResumed()\r\n // TODO: 2019/2/21 如果在后台可能dialog一直不会消失\r\n if (dialog != null && getFragmentManager()!=null) {\r\n dialog.dismissAllowingStateLoss();\r\n Utils.debug(\"setProgressDialogVisibility:\" + 8888);\r\n }\r\n Utils.debug(\"setProgressDialogVisibility:\" + 9999);\r\n }\r\n }\r\n\r\n @Override\r\n public void onItemClick(int position, View v) {\r\n setProgressDialogVisibility(true);\r\n parallelCount = new AtomicInteger(1);\r\n\r\n mSelectedItems = new Integer[]{position};\r\n mDisableTasks = new ArrayList<>(1);\r\n mDisableTasks.add(new ParallellDisableTask(1));\r\n mDisableTasks.get(0).execute(position);\r\n }\r\n\r\n}\r" }, { "identifier": "BaseFragment", "path": "app/src/main/java/cn/wq/myandroidtoolspro/recyclerview/toolbar/BaseFragment.java", "snippet": "public class BaseFragment extends Fragment{\r\n private ActionBar mActionBar;\r\n\r\n @Override\r\n public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {\r\n super.onViewCreated(view, savedInstanceState);\r\n\r\n Toolbar toolbar=(Toolbar) view.findViewById(R.id.toolbar);\r\n AppCompatActivity activity = (AppCompatActivity) getActivity();\r\n activity.setSupportActionBar(toolbar);\r\n mActionBar=activity.getSupportActionBar();\r\n if (mActionBar != null) {\r\n mActionBar.setDisplayHomeAsUpEnabled(true);\r\n }\r\n\r\n final boolean isDark = PreferenceManager.getDefaultSharedPreferences(getContext()).getInt(BaseActivity.PREFERENCE_THEME, 0) > 0;\r\n if (isDark) {\r\n toolbar.setPopupTheme(R.style.ThemeOverlay_AppCompat_Dark);\r\n }\r\n }\r\n\r\n /**\r\n * @param iconType 0:normal 1:back 2:close\r\n */\r\n protected void initActionbar(int iconType,String title){\r\n if(title==null){\r\n mActionBar.setTitle(R.string.app_name);\r\n }else{\r\n mActionBar.setTitle(title);\r\n }\r\n\r\n switch (iconType) {\r\n case 1:\r\n mActionBar.setHomeAsUpIndicator(R.drawable.ic_arrow_back_white_24dp);\r\n break;\r\n case 2:\r\n mActionBar.setHomeAsUpIndicator(R.drawable.ic_close_white_24dp);\r\n break;\r\n default:\r\n mActionBar.setHomeAsUpIndicator(R.drawable.ic_menu_white);\r\n break;\r\n }\r\n }\r\n\r\n protected void setToolbarLogo(String packageName) {\r\n if (mActionBar == null || TextUtils.isEmpty(packageName)) {\r\n return;\r\n }\r\n try {\r\n int length = (int) (getResources().getDisplayMetrics().density * 24);\r\n Drawable icon=getContext().getPackageManager().getApplicationIcon(packageName);\r\n View view=getView();\r\n if (view != null) {\r\n Toolbar toolbar= (Toolbar) view.findViewById(R.id.toolbar);\r\n toolbar.setLogo(icon);\r\n for (int i = 0; i < toolbar.getChildCount(); i++) {\r\n View child = toolbar.getChildAt(i);\r\n if (child instanceof ImageView){\r\n ImageView iv = (ImageView) child;\r\n if ( iv.getDrawable() == icon ) {\r\n ViewGroup.LayoutParams params=iv.getLayoutParams();\r\n params.width=params.height=length;\r\n }\r\n }\r\n }\r\n }\r\n\r\n } catch (PackageManager.NameNotFoundException e) {\r\n e.printStackTrace();\r\n }\r\n }\r\n\r\n}\r" } ]
import android.os.Bundle; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.content.ContextCompat; import android.support.v4.view.ViewPager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import cn.wq.myandroidtoolspro.MainActivity; import cn.wq.myandroidtoolspro.R; import cn.wq.myandroidtoolspro.recyclerview.multi.MultiSelectionRecyclerListFragment; import cn.wq.myandroidtoolspro.recyclerview.toolbar.BaseFragment;
9,949
package cn.wq.myandroidtoolspro.recyclerview.fragment; public class ReceiverWithActionParentFragment extends BaseFragment { private String action; private ViewPager mViewPager; private TabLayout mTabLayout; public static ReceiverWithActionParentFragment newInstance(String action){ ReceiverWithActionParentFragment f=new ReceiverWithActionParentFragment(); Bundle data=new Bundle(); data.putString("action", action); f.setArguments(data); return f; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); initActionbar(1,action); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { action=getArguments().getString("action"); View rootView=inflater.inflate(R.layout.fragment_component_parent, container, false); mViewPager = (ViewPager) rootView.findViewById(R.id.view_pager); mViewPager.setAdapter(new MyPagerAdapter(this, action)); mTabLayout = (TabLayout) rootView.findViewById(R.id.tab_layout); mTabLayout.setupWithViewPager(mViewPager); mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { private int pre_pos; @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { if (pre_pos == position) { return; }
package cn.wq.myandroidtoolspro.recyclerview.fragment; public class ReceiverWithActionParentFragment extends BaseFragment { private String action; private ViewPager mViewPager; private TabLayout mTabLayout; public static ReceiverWithActionParentFragment newInstance(String action){ ReceiverWithActionParentFragment f=new ReceiverWithActionParentFragment(); Bundle data=new Bundle(); data.putString("action", action); f.setArguments(data); return f; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); initActionbar(1,action); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { action=getArguments().getString("action"); View rootView=inflater.inflate(R.layout.fragment_component_parent, container, false); mViewPager = (ViewPager) rootView.findViewById(R.id.view_pager); mViewPager.setAdapter(new MyPagerAdapter(this, action)); mTabLayout = (TabLayout) rootView.findViewById(R.id.tab_layout); mTabLayout.setupWithViewPager(mViewPager); mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { private int pre_pos; @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { if (pre_pos == position) { return; }
MultiSelectionRecyclerListFragment fragment = getFragment(pre_pos);
1
2023-10-18 14:32:49+00:00
12k
instana/otel-dc
rdb/src/main/java/com/instana/dc/rdb/AbstractDbDc.java
[ { "identifier": "AbstractDc", "path": "internal/otel-dc/src/main/java/com/instana/dc/AbstractDc.java", "snippet": "public abstract class AbstractDc implements IDc {\n private final Map<String, Meter> meters = new ConcurrentHashMap<>();\n private final Map<String, RawMetric> rawMetricsMap;\n\n\n public AbstractDc(Map<String, RawMetric> rawMetricsMap) {\n this.rawMetricsMap = rawMetricsMap;\n }\n\n @Override\n public void initOnce() throws Exception {\n }\n\n @Override\n public Map<String, Meter> getMeters() {\n return meters;\n }\n\n @Override\n public void initMeters(OpenTelemetry openTelemetry) {\n Meter defaultMeter = openTelemetry.meterBuilder(\"instana.otel.sensor.sdk\").setInstrumentationVersion(\"1.0.0\").build();\n meters.put(RawMetric.DEFAULT, defaultMeter);\n }\n\n @Override\n public void registerMetrics() {\n for (RawMetric rawMetric : rawMetricsMap.values()) {\n DcUtil.registerMetric(meters, rawMetric);\n }\n }\n\n @Override\n public RawMetric getRawMetric(String name) {\n return rawMetricsMap.get(name);\n }\n\n @Override\n public Map<String, RawMetric> getRawMetricsMap() {\n return rawMetricsMap;\n }\n\n @Override\n public SdkMeterProvider getDefaultSdkMeterProvider(Resource resource, String otelBackendUrl, long callbackInterval, boolean usingHTTP, long timeout) {\n if (!usingHTTP)\n return SdkMeterProvider.builder().setResource(resource)\n .registerMetricReader(PeriodicMetricReader.builder(OtlpGrpcMetricExporter.builder().setEndpoint(otelBackendUrl).setTimeout(timeout, TimeUnit.SECONDS).build()).setInterval(Duration.ofSeconds(callbackInterval)).build())\n .build();\n return SdkMeterProvider.builder().setResource(resource)\n .registerMetricReader(PeriodicMetricReader.builder(OtlpHttpMetricExporter.builder().setEndpoint(otelBackendUrl).setTimeout(timeout, TimeUnit.SECONDS).build()).setInterval(Duration.ofSeconds(callbackInterval)).build())\n .build();\n }\n\n}" }, { "identifier": "DcUtil", "path": "internal/otel-dc/src/main/java/com/instana/dc/DcUtil.java", "snippet": "public class DcUtil {\n private static final Logger logger = Logger.getLogger(DcUtil.class.getName());\n\n /* Configurations for the Data Collector:\n */\n public final static String POLLING_INTERVAL = \"poll.interval\";\n public static final int DEFAULT_POLL_INTERVAL = 30; //unit is second, read database\n public final static String CALLBACK_INTERVAL = \"callback.interval\";\n public static final int DEFAULT_CALLBACK_INTERVAL = 60; //unit is second, send to backend\n public final static String OTEL_BACKEND_URL = \"otel.backend.url\";\n public final static String OTEL_BACKEND_USING_HTTP = \"otel.backend.using.http\";\n public final static String DEFAULT_OTEL_BACKEND_URL = \"http://127.0.0.1:4317\";\n public final static String OTEL_SERVICE_NAME = \"otel.service.name\";\n public final static String DEFAULT_OTEL_SERVICE_NAME = \"odcd.default.service\";\n public final static String OTEL_SERVICE_INSTANCE_ID = \"otel.service.instance.id\";\n public final static String DEFAULT_OTEL_SERVICE_INSTANCE_ID = \"odcd.default.id\";\n\n //Standard environment variables;\n public static final String OTEL_RESOURCE_ATTRIBUTES = \"OTEL_RESOURCE_ATTRIBUTES\";\n\n //Configuration files;\n public static final String LOGGING_PROP = \"config/logging.properties\";\n public static final String CONFIG_YAML = \"config/config.yaml\";\n public static final String CONFIG_ENV = \"DC_CONFIG\";\n public static final String INSTANA_PLUGIN = \"INSTANA_PLUGIN\";\n\n\n /* Data Collector Utilities:\n */\n public static Resource mergeResourceAttributesFromEnv(Resource resource) {\n String resAttrs = System.getenv(OTEL_RESOURCE_ATTRIBUTES);\n if (resAttrs != null) {\n for (String resAttr : resAttrs.split(\",\")) {\n String[] kv = resAttr.split(\"=\");\n if (kv.length != 2)\n continue;\n String key = kv[0].trim();\n String value = kv[1].trim();\n resource = resource.merge(Resource.create(Attributes.of(AttributeKey.stringKey(key), value)));\n }\n }\n return resource;\n }\n\n public static void _registerMeterWithLongMetric(Meter meter, InstrumentType instrumentType, String metricName, String unit, String desc, AtomicLong data) {\n switch (instrumentType) {\n case GAUGE:\n meter.gaugeBuilder(metricName).setUnit(unit).setDescription(desc).buildWithCallback(measurement -> measurement.record(data.get()));\n break;\n case COUNTER:\n meter.counterBuilder(metricName).setUnit(unit).setDescription(desc).buildWithCallback(measurement -> measurement.record(data.get()));\n break;\n case UPDOWN_COUNTER:\n meter.upDownCounterBuilder(metricName).setUnit(unit).setDescription(desc).buildWithCallback(measurement -> measurement.record(data.get()));\n break;\n default:\n logger.log(Level.WARNING, \"Currently only following instrument types are supported, Gauge, Counter, UpDownCounter, while your type is {0}\", instrumentType);\n }\n }\n\n public static void _registerMeterWithDoubleMetric(Meter meter, InstrumentType instrumentType, String metricName, String unit, String desc, AtomicDouble data) {\n switch (instrumentType) {\n case GAUGE:\n meter.gaugeBuilder(metricName).setUnit(unit).setDescription(desc).buildWithCallback(measurement -> measurement.record(data.get()));\n break;\n case COUNTER:\n meter.counterBuilder(metricName).setUnit(unit).setDescription(desc).buildWithCallback(measurement -> measurement.record((long) data.get()));\n break;\n case UPDOWN_COUNTER:\n meter.upDownCounterBuilder(metricName).setUnit(unit).setDescription(desc).buildWithCallback(measurement -> measurement.record((long) data.get()));\n break;\n default:\n logger.log(Level.WARNING, \"Currently only following instrument types are supported, Gauge, Counter, UpDownCounter, while your type is {0}\", instrumentType);\n }\n }\n\n public static Attributes convertMapToAttributes(Map<String, Object> map) {\n AttributesBuilder builder = Attributes.builder();\n for (Map.Entry<String, Object> entry : map.entrySet()) {\n String key = entry.getKey();\n Object value = entry.getValue();\n if (value instanceof Long) {\n builder.put(key, (Long) value);\n } else if (value instanceof Double) {\n builder.put(key, (Double) value);\n } else if (value instanceof Boolean) {\n builder.put(key, (Boolean) value);\n } else {\n builder.put(key, value.toString());\n }\n }\n return builder.build();\n }\n\n public static void registerMetric(Map<String, Meter> meters, RawMetric rawMetric) {\n Consumer<ObservableLongMeasurement> recordLongMetric = measurement -> {\n rawMetric.purgeOutdatedDps();\n boolean clearDps = rawMetric.isClearDps();\n Iterator<Map.Entry<String, RawMetric.DataPoint>> iterator = rawMetric.getDataPoints().entrySet().iterator();\n while (iterator.hasNext()) {\n RawMetric.DataPoint dp = iterator.next().getValue();\n Long value = dp.getLongValue();\n if (value == null)\n continue;\n measurement.record(value, convertMapToAttributes(dp.getAttributes()));\n if (clearDps) {\n iterator.remove();\n }\n }\n };\n Consumer<ObservableDoubleMeasurement> recordDoubleMetric = measurement -> {\n rawMetric.purgeOutdatedDps();\n boolean clearDps = rawMetric.isClearDps();\n Iterator<Map.Entry<String, RawMetric.DataPoint>> iterator = rawMetric.getDataPoints().entrySet().iterator();\n while (iterator.hasNext()) {\n RawMetric.DataPoint dp = iterator.next().getValue();\n Double value = dp.getDoubleValue();\n if (value == null)\n continue;\n measurement.record(value, convertMapToAttributes(dp.getAttributes()));\n if (clearDps) {\n iterator.remove();\n }\n }\n };\n\n Meter meter = meters.get(rawMetric.getMeterName());\n switch (rawMetric.getInstrumentType()) {\n case GAUGE:\n if (rawMetric.isInteger())\n meter.gaugeBuilder(rawMetric.getName()).ofLongs().setUnit(rawMetric.getUnit()).setDescription(rawMetric.getDescription())\n .buildWithCallback(recordLongMetric);\n else\n meter.gaugeBuilder(rawMetric.getName()).setUnit(rawMetric.getUnit()).setDescription(rawMetric.getDescription())\n .buildWithCallback(recordDoubleMetric);\n break;\n case COUNTER:\n if (rawMetric.isInteger())\n meter.counterBuilder(rawMetric.getName()).setUnit(rawMetric.getUnit()).setDescription(rawMetric.getDescription())\n .buildWithCallback(recordLongMetric);\n else\n meter.counterBuilder(rawMetric.getName()).ofDoubles().setUnit(rawMetric.getUnit()).setDescription(rawMetric.getDescription())\n .buildWithCallback(recordDoubleMetric);\n break;\n case UPDOWN_COUNTER:\n if (rawMetric.isInteger())\n meter.upDownCounterBuilder(rawMetric.getName()).setUnit(rawMetric.getUnit()).setDescription(rawMetric.getDescription())\n .buildWithCallback(recordLongMetric);\n else\n meter.upDownCounterBuilder(rawMetric.getName()).ofDoubles().setUnit(rawMetric.getUnit()).setDescription(rawMetric.getDescription())\n .buildWithCallback(recordDoubleMetric);\n break;\n default:\n logger.log(Level.WARNING, \"Currently only following instrument types are supported, Gauge, Counter, UpDownCounter, while your type is {0}\", rawMetric.getInstrumentType());\n }\n }\n\n public static long getPid() {\n // While this is not strictly defined, almost all commonly used JVMs format this as\n // pid@hostname.\n String runtimeName = ManagementFactory.getRuntimeMXBean().getName();\n int atIndex = runtimeName.indexOf('@');\n if (atIndex >= 0) {\n String pidString = runtimeName.substring(0, atIndex);\n try {\n return Long.parseLong(pidString);\n } catch (NumberFormatException ignored) {\n // Ignore parse failure.\n }\n }\n return -1;\n }\n\n public static String base64Decode(String encodedStr) {\n return new String(Base64.getDecoder().decode(encodedStr));\n }\n}" }, { "identifier": "IDc", "path": "internal/otel-dc/src/main/java/com/instana/dc/IDc.java", "snippet": "public interface IDc {\n void initOnce() throws Exception;\n Resource getResourceAttributes();\n void initDC() throws Exception;\n SdkMeterProvider getDefaultSdkMeterProvider(Resource resource, String otelBackendUrl, long callbackInterval, boolean usingHTTP, long timeout);\n\n void initMeters(OpenTelemetry openTelemetry);\n void registerMetrics();\n\n void collectData();\n void start();\n\n RawMetric getRawMetric(String name);\n Map<String, RawMetric> getRawMetricsMap();\n Map<String, Meter> getMeters();\n}" }, { "identifier": "ContainerResource", "path": "internal/otel-dc/src/main/java/com/instana/dc/resources/ContainerResource.java", "snippet": "public final class ContainerResource {\n\n static final Filesystem FILESYSTEM_INSTANCE = new Filesystem();\n private static final Resource INSTANCE = buildSingleton();\n\n private static Resource buildSingleton() {\n // can't initialize this statically without running afoul of animalSniffer on paths\n return new ContainerResource().buildResource();\n }\n\n private final CgroupV1ContainerIdExtractor v1Extractor;\n private final CgroupV2ContainerIdExtractor v2Extractor;\n\n private ContainerResource() {\n this(new CgroupV1ContainerIdExtractor(), new CgroupV2ContainerIdExtractor());\n }\n\n // Visible for testing\n ContainerResource(\n CgroupV1ContainerIdExtractor v1Extractor, CgroupV2ContainerIdExtractor v2Extractor) {\n this.v1Extractor = v1Extractor;\n this.v2Extractor = v2Extractor;\n }\n\n // Visible for testing\n Resource buildResource() {\n return getContainerId()\n .map(id -> Resource.create(Attributes.of(CONTAINER_ID, id)))\n .orElseGet(Resource::empty);\n }\n\n private Optional<String> getContainerId() {\n Optional<String> v1Result = v1Extractor.extractContainerId();\n if (v1Result.isPresent()) {\n return v1Result;\n }\n return v2Extractor.extractContainerId();\n }\n\n /** Returns resource with container information. */\n public static Resource get() {\n return INSTANCE;\n }\n\n // Exists for testing\n static class Filesystem {\n\n boolean isReadable(Path path) {\n return Files.isReadable(path);\n }\n\n @MustBeClosed\n Stream<String> lines(Path path) throws IOException {\n return Files.lines(path);\n }\n }\n}" }, { "identifier": "DcUtil", "path": "internal/otel-dc/src/main/java/com/instana/dc/DcUtil.java", "snippet": "public class DcUtil {\n private static final Logger logger = Logger.getLogger(DcUtil.class.getName());\n\n /* Configurations for the Data Collector:\n */\n public final static String POLLING_INTERVAL = \"poll.interval\";\n public static final int DEFAULT_POLL_INTERVAL = 30; //unit is second, read database\n public final static String CALLBACK_INTERVAL = \"callback.interval\";\n public static final int DEFAULT_CALLBACK_INTERVAL = 60; //unit is second, send to backend\n public final static String OTEL_BACKEND_URL = \"otel.backend.url\";\n public final static String OTEL_BACKEND_USING_HTTP = \"otel.backend.using.http\";\n public final static String DEFAULT_OTEL_BACKEND_URL = \"http://127.0.0.1:4317\";\n public final static String OTEL_SERVICE_NAME = \"otel.service.name\";\n public final static String DEFAULT_OTEL_SERVICE_NAME = \"odcd.default.service\";\n public final static String OTEL_SERVICE_INSTANCE_ID = \"otel.service.instance.id\";\n public final static String DEFAULT_OTEL_SERVICE_INSTANCE_ID = \"odcd.default.id\";\n\n //Standard environment variables;\n public static final String OTEL_RESOURCE_ATTRIBUTES = \"OTEL_RESOURCE_ATTRIBUTES\";\n\n //Configuration files;\n public static final String LOGGING_PROP = \"config/logging.properties\";\n public static final String CONFIG_YAML = \"config/config.yaml\";\n public static final String CONFIG_ENV = \"DC_CONFIG\";\n public static final String INSTANA_PLUGIN = \"INSTANA_PLUGIN\";\n\n\n /* Data Collector Utilities:\n */\n public static Resource mergeResourceAttributesFromEnv(Resource resource) {\n String resAttrs = System.getenv(OTEL_RESOURCE_ATTRIBUTES);\n if (resAttrs != null) {\n for (String resAttr : resAttrs.split(\",\")) {\n String[] kv = resAttr.split(\"=\");\n if (kv.length != 2)\n continue;\n String key = kv[0].trim();\n String value = kv[1].trim();\n resource = resource.merge(Resource.create(Attributes.of(AttributeKey.stringKey(key), value)));\n }\n }\n return resource;\n }\n\n public static void _registerMeterWithLongMetric(Meter meter, InstrumentType instrumentType, String metricName, String unit, String desc, AtomicLong data) {\n switch (instrumentType) {\n case GAUGE:\n meter.gaugeBuilder(metricName).setUnit(unit).setDescription(desc).buildWithCallback(measurement -> measurement.record(data.get()));\n break;\n case COUNTER:\n meter.counterBuilder(metricName).setUnit(unit).setDescription(desc).buildWithCallback(measurement -> measurement.record(data.get()));\n break;\n case UPDOWN_COUNTER:\n meter.upDownCounterBuilder(metricName).setUnit(unit).setDescription(desc).buildWithCallback(measurement -> measurement.record(data.get()));\n break;\n default:\n logger.log(Level.WARNING, \"Currently only following instrument types are supported, Gauge, Counter, UpDownCounter, while your type is {0}\", instrumentType);\n }\n }\n\n public static void _registerMeterWithDoubleMetric(Meter meter, InstrumentType instrumentType, String metricName, String unit, String desc, AtomicDouble data) {\n switch (instrumentType) {\n case GAUGE:\n meter.gaugeBuilder(metricName).setUnit(unit).setDescription(desc).buildWithCallback(measurement -> measurement.record(data.get()));\n break;\n case COUNTER:\n meter.counterBuilder(metricName).setUnit(unit).setDescription(desc).buildWithCallback(measurement -> measurement.record((long) data.get()));\n break;\n case UPDOWN_COUNTER:\n meter.upDownCounterBuilder(metricName).setUnit(unit).setDescription(desc).buildWithCallback(measurement -> measurement.record((long) data.get()));\n break;\n default:\n logger.log(Level.WARNING, \"Currently only following instrument types are supported, Gauge, Counter, UpDownCounter, while your type is {0}\", instrumentType);\n }\n }\n\n public static Attributes convertMapToAttributes(Map<String, Object> map) {\n AttributesBuilder builder = Attributes.builder();\n for (Map.Entry<String, Object> entry : map.entrySet()) {\n String key = entry.getKey();\n Object value = entry.getValue();\n if (value instanceof Long) {\n builder.put(key, (Long) value);\n } else if (value instanceof Double) {\n builder.put(key, (Double) value);\n } else if (value instanceof Boolean) {\n builder.put(key, (Boolean) value);\n } else {\n builder.put(key, value.toString());\n }\n }\n return builder.build();\n }\n\n public static void registerMetric(Map<String, Meter> meters, RawMetric rawMetric) {\n Consumer<ObservableLongMeasurement> recordLongMetric = measurement -> {\n rawMetric.purgeOutdatedDps();\n boolean clearDps = rawMetric.isClearDps();\n Iterator<Map.Entry<String, RawMetric.DataPoint>> iterator = rawMetric.getDataPoints().entrySet().iterator();\n while (iterator.hasNext()) {\n RawMetric.DataPoint dp = iterator.next().getValue();\n Long value = dp.getLongValue();\n if (value == null)\n continue;\n measurement.record(value, convertMapToAttributes(dp.getAttributes()));\n if (clearDps) {\n iterator.remove();\n }\n }\n };\n Consumer<ObservableDoubleMeasurement> recordDoubleMetric = measurement -> {\n rawMetric.purgeOutdatedDps();\n boolean clearDps = rawMetric.isClearDps();\n Iterator<Map.Entry<String, RawMetric.DataPoint>> iterator = rawMetric.getDataPoints().entrySet().iterator();\n while (iterator.hasNext()) {\n RawMetric.DataPoint dp = iterator.next().getValue();\n Double value = dp.getDoubleValue();\n if (value == null)\n continue;\n measurement.record(value, convertMapToAttributes(dp.getAttributes()));\n if (clearDps) {\n iterator.remove();\n }\n }\n };\n\n Meter meter = meters.get(rawMetric.getMeterName());\n switch (rawMetric.getInstrumentType()) {\n case GAUGE:\n if (rawMetric.isInteger())\n meter.gaugeBuilder(rawMetric.getName()).ofLongs().setUnit(rawMetric.getUnit()).setDescription(rawMetric.getDescription())\n .buildWithCallback(recordLongMetric);\n else\n meter.gaugeBuilder(rawMetric.getName()).setUnit(rawMetric.getUnit()).setDescription(rawMetric.getDescription())\n .buildWithCallback(recordDoubleMetric);\n break;\n case COUNTER:\n if (rawMetric.isInteger())\n meter.counterBuilder(rawMetric.getName()).setUnit(rawMetric.getUnit()).setDescription(rawMetric.getDescription())\n .buildWithCallback(recordLongMetric);\n else\n meter.counterBuilder(rawMetric.getName()).ofDoubles().setUnit(rawMetric.getUnit()).setDescription(rawMetric.getDescription())\n .buildWithCallback(recordDoubleMetric);\n break;\n case UPDOWN_COUNTER:\n if (rawMetric.isInteger())\n meter.upDownCounterBuilder(rawMetric.getName()).setUnit(rawMetric.getUnit()).setDescription(rawMetric.getDescription())\n .buildWithCallback(recordLongMetric);\n else\n meter.upDownCounterBuilder(rawMetric.getName()).ofDoubles().setUnit(rawMetric.getUnit()).setDescription(rawMetric.getDescription())\n .buildWithCallback(recordDoubleMetric);\n break;\n default:\n logger.log(Level.WARNING, \"Currently only following instrument types are supported, Gauge, Counter, UpDownCounter, while your type is {0}\", rawMetric.getInstrumentType());\n }\n }\n\n public static long getPid() {\n // While this is not strictly defined, almost all commonly used JVMs format this as\n // pid@hostname.\n String runtimeName = ManagementFactory.getRuntimeMXBean().getName();\n int atIndex = runtimeName.indexOf('@');\n if (atIndex >= 0) {\n String pidString = runtimeName.substring(0, atIndex);\n try {\n return Long.parseLong(pidString);\n } catch (NumberFormatException ignored) {\n // Ignore parse failure.\n }\n }\n return -1;\n }\n\n public static String base64Decode(String encodedStr) {\n return new String(Base64.getDecoder().decode(encodedStr));\n }\n}" }, { "identifier": "DbDcUtil", "path": "rdb/src/main/java/com/instana/dc/rdb/DbDcUtil.java", "snippet": "public class DbDcUtil {\n private static final Logger logger = Logger.getLogger(DbDcUtil.class.getName());\n\n /* Configurations for the Data Collector:\n */\n public static final String DB_SYSTEM = \"db.system\";\n public static final String DB_DRIVER = \"db.driver\";\n public static final String DB_ADDRESS = \"db.address\";\n public static final String DB_PORT = \"db.port\";\n public static final String DB_USERNAME = \"db.username\";\n public static final String DB_PASSWORD = \"db.password\";\n public static final String DB_CONN_URL = \"db.connection.url\";\n public static final String DB_ENTITY_TYPE = \"db.entity.type\";\n public static final String DEFAULT_DB_ENTITY_TYPE = \"DATABASE\";\n public static final String DB_NAME = \"db.name\";\n public static final String DB_VERSION = \"db.version\";\n public static final String DB_TENANT_ID = \"db.tenant.id\";\n public static final String DB_TENANT_NAME = \"db.tenant.name\";\n public static final String DB_ENTITY_PARENT_ID = \"db.entity.parent.id\";\n public static final String DEFAULT_INSTRUMENTATION_SCOPE = \"instana.sensor-sdk.dc.db\";\n public static final String DEFAULT_INSTRUMENTATION_SCOPE_VER = \"1.0.0\";\n\n /* Configurations for Metrics:\n */\n public static final String UNIT_S = \"s\";\n public static final String UNIT_BY = \"By\";\n public static final String UNIT_1 = \"1\";\n\n public static final String DB_STATUS_NAME = DB_STATUS.getKey();\n public static final String DB_STATUS_DESC = \"The status of the database\";\n public static final String DB_STATUS_UNIT = \"{status}\";\n\n public static final String DB_INSTANCE_COUNT_NAME = DB_INSTANCE_COUNT.getKey();\n public static final String DB_INSTANCE_COUNT_DESC = \"The total number of db instances\";\n public static final String DB_INSTANCE_COUNT_UNIT = \"{instance}\";\n\n public static final String DB_INSTANCE_ACTIVE_COUNT_NAME = DB_INSTANCE_ACTIVE_COUNT.getKey();\n public static final String DB_INSTANCE_ACTIVE_COUNT_DESC = \"The total number of active db instances\";\n public static final String DB_INSTANCE_ACTIVE_COUNT_UNIT = \"{instance}\";\n\n public static final String DB_SESSION_COUNT_NAME = DB_SESSION_COUNT.getKey();\n public static final String DB_SESSION_COUNT_DESC = \"Number of sessions\";\n public static final String DB_SESSION_COUNT_UNIT = \"{session}\";\n\n public static final String DB_SESSION_ACTIVE_COUNT_NAME = DB_SESSION_ACTIVE_COUNT.getKey();\n public static final String DB_SESSION_ACTIVE_COUNT_DESC = \"The number of active database sessions\";\n public static final String DB_SESSION_ACTIVE_COUNT_UNIT = \"{session}\";\n\n public static final String DB_TRANSACTION_COUNT_NAME = DB_TRANSACTION_COUNT.getKey();\n public static final String DB_TRANSACTIONS_COUNT_DESC = \"The number of completed transactions\";\n public static final String DB_TRANSACTION_COUNT_UNIT = \"{transaction}\";\n\n public static final String DB_TRANSACTION_RATE_NAME = DB_TRANSACTION_RATE.getKey();\n public static final String DB_TRANSACTION_RATE_DESC = \"The number of transactions per second\";\n public static final String DB_TRANSACTION_RATE_UNIT = \"{transaction}\";\n\n public static final String DB_TRANSACTION_LATENCY_NAME = DB_TRANSACTION_LATENCY.getKey();\n public static final String DB_TRANSACTION_LATENCY_DESC = \"The average transaction latency\";\n\n public static final String DB_SQL_COUNT_NAME = DB_SQL_COUNT.getKey();\n public static final String DB_SQL_COUNT_DESC = \"The number of SQLs\";\n public static final String DB_SQL_COUNT_UNIT = \"{sql}\";\n\n public static final String DB_SQL_RATE_NAME = DB_SQL_RATE.getKey();\n public static final String DB_SQL_RATE_DESC = \"The number of SQL per second\";\n public static final String DB_SQL_RATE_UNIT = \"{sql}\";\n\n public static final String DB_SQL_LATENCY_NAME = DB_SQL_LATENCY.getKey();\n public static final String DB_SQL_LATENCY_DESC = \"The average SQL latency\";\n\n public static final String DB_IO_READ_RATE_NAME = DB_IO_READ_RATE.getKey();\n public static final String DB_IO_READ_RATE_DESC = \"The physical read per second\";\n\n public static final String DB_IO_WRITE_RATE_NAME = DB_IO_WRITE_RATE.getKey();\n public static final String DB_IO_WRITE_RATE_DESC = \"The physical write per second\";\n\n public static final String DB_TASK_WAIT_COUNT_NAME = DB_TASK_WAIT_COUNT.getKey();\n public static final String DB_TASK_WAIT_COUNT_DESC = \"The number of waiting task\";\n public static final String DB_TASK_WAIT_COUNT_UNIT = \"{tasks}\";\n\n public static final String DB_TASK_AVG_WAIT_TIME_NAME = DB_TASK_AVG_WAIT_TIME.getKey();\n public static final String DB_TASK_AVG_WAIT_TIME_DESC = \"Average task wait time\";\n\n public static final String DB_CACHE_HIT_NAME = DB_CACHE_HIT.getKey();\n public static final String DB_CACHE_HIT_DESC = \"The cache hit ratio/percentage\";\n public static final String DB_CACHE_HIT_KEY = TYPE.getKey();\n\n public static final String DB_SQL_ELAPSED_TIME_NAME = DB_SQL_ELAPSED_TIME.getKey();\n public static final String DB_SQL_ELAPSED_TIME_DESC = \"The elapsed time in second of the query\";\n public static final String DB_SQL_ELAPSED_TIME_KEY = SQL_ID.getKey();\n\n public static final String DB_LOCK_TIME_NAME = DB_LOCK_TIME.getKey();\n public static final String DB_LOCK_TIME_DESC = \"The lock elapsed time\";\n public static final String DB_LOCK_TIME_KEY = LOCK_ID.getKey();\n\n public static final String DB_LOCK_COUNT_NAME = DB_LOCK_COUNT.getKey();\n public static final String DB_LOCK_COUNT_DESC = \"The number of database locks\";\n public static final String DB_LOCK_COUNT_UNIT = \"{lock}\";\n public static final String DB_LOCK_COUNT_KEY = TYPE.getKey();\n\n public static final String DB_TABLESPACE_SIZE_NAME = DB_TABLESPACE_SIZE.getKey();\n public static final String DB_TABLESPACE_SIZE_DESC = \"The size (in bytes) of the tablespace\";\n public static final String DB_TABLESPACE_SIZE_KEY = TABLESPACE_NAME.getKey();\n\n public static final String DB_TABLESPACE_USED_NAME = DB_TABLESPACE_USED.getKey();\n public static final String DB_TABLESPACE_USED_DESC = \"The used size (in bytes) of the tablespace\";\n public static final String DB_TABLESPACE_USED_KEY = TABLESPACE_NAME.getKey();\n\n public static final String DB_TABLESPACE_UTILIZATION_NAME = DB_TABLESPACE_UTILIZATION.getKey();\n public static final String DB_TABLESPACE_UTILIZATION_DESC = \"The used percentage of the tablespace\";\n public static final String DB_TABLESPACE_UTILIZATION_KEY = TABLESPACE_NAME.getKey();\n\n public static final String DB_TABLESPACE_MAX_NAME = DB_TABLESPACE_MAX.getKey();\n public static final String DB_TABLESPACE_MAX_DESC = \"The max size (in bytes) of the tablespace\";\n public static final String DB_TABLESPACE_MAX_KEY = TABLESPACE_NAME.getKey();\n\n public static final String DB_CPU_UTILIZATION_NAME = DB_CPU_UTILIZATION.getKey();\n public static final String DB_CPU_UTILIZATION_DESC = \"The percentage of used CPU\";\n\n public static final String DB_MEM_UTILIZATION_NAME = DB_MEM_UTILIZATION.getKey();\n public static final String DB_MEM_UTILIZATION_DESC = \"The percentage of used memory on the file system\";\n\n public static final String DB_DISK_UTILIZATION_NAME = DB_DISK_UTILIZATION.getKey();\n public static final String DB_DISK_UTILIZATION_DESC = \"The percentage of used disk space on the file system\";\n public static final String DB_DISK_UTILIZATION_KEY = PATH.getKey();\n\n public static final String DB_DISK_USAGE_NAME = DB_DISK_USAGE.getKey();\n public static final String DB_DISK_USAGE_DESC = \"The size (in bytes) of the used disk space on the file system\";\n public static final String DB_DISK_USAGE_KEY = PATH.getKey();\n\n public static final String DB_BACKUP_CYCLE_NAME = DB_BACKUP_CYCLE.getKey();\n public static final String DB_BACKUP_CYCLE_DESC = \"Backup cycle\";\n\n\n /* Utilities:\n **/\n public static ResultSet executeQuery(Connection connection, String query) throws SQLException {\n Statement statement = connection.createStatement();\n return statement.executeQuery(query);\n }\n\n public static Number getSimpleMetricWithSql(Connection connection, String queryStr) {\n try {\n ResultSet rs = executeQuery(connection, queryStr);\n if (rs.isClosed()) {\n logger.severe(\"getSimpleMetricWithSql: ResultSet is closed\");\n return null;\n }\n if (rs.next()) {\n return (Number) rs.getObject(1);\n } else {\n logger.log(Level.WARNING, \"getSimpleMetricWithSql: No result\");\n return null;\n }\n } catch (Exception e) {\n logger.log(Level.SEVERE, \"getSimpleMetricWithSql: Error occurred\", e);\n return null;\n }\n }\n\n public static String getSimpleStringWithSql(Connection connection, String queryStr) {\n try {\n ResultSet rs = executeQuery(connection, queryStr);\n if (rs.isClosed()) {\n logger.severe(\"getSimpleStringWithSql: ResultSet is closed\");\n return null;\n }\n if (rs.next()) {\n return rs.getString(1);\n } else {\n logger.log(Level.WARNING, \"getSimpleStringWithSql: No result\");\n return null;\n }\n } catch (Exception e) {\n logger.log(Level.SEVERE, \"getSimpleStringWithSql: Error occurred\", e);\n return null;\n }\n }\n\n @SuppressWarnings(\"unchecked\")\n public static <T> List<T> getSimpleListWithSql(Connection connection, String queryStr) {\n try {\n ResultSet rs = executeQuery(connection, queryStr);\n if (rs.isClosed()) {\n logger.severe(\"getSimpleObjectWithSql: ResultSet is closed\");\n return null;\n }\n List<T> list = new ArrayList<>();\n int nColumn = rs.getMetaData().getColumnCount();\n if (rs.next()) {\n for (int i = 1; i <= nColumn; i++) {\n list.add((T) rs.getObject(i));\n }\n return list;\n } else {\n logger.log(Level.WARNING, \"getSimpleObjectWithSql: No result\");\n return null;\n }\n } catch (Exception e) {\n logger.log(Level.SEVERE, \"getSimpleObjectWithSql: Error occurred\", e);\n return null;\n }\n }\n\n public static List<SimpleQueryResult> getMetricWithSql(Connection connection, String queryStr, String... attrs) {\n List<SimpleQueryResult> results = new ArrayList<>();\n try {\n ResultSet rs = executeQuery(connection, queryStr);\n if (rs.isClosed()) {\n logger.severe(\"getMetricWithSql: ResultSet is closed\");\n return null;\n }\n while (rs.next()) {\n int n = 1;\n SimpleQueryResult result = new SimpleQueryResult((Number) rs.getObject(n));\n for (String attr : attrs) {\n n++;\n Object obj = rs.getObject(n);\n if (obj == null) {\n obj = \"null\";\n }\n result.setAttribute(attr, obj);\n if (n == 2) {\n result.setKey(obj.toString());\n }\n }\n results.add(result);\n }\n return results;\n } catch (Exception e) {\n logger.log(Level.SEVERE, \"getMetricWithSql: Error occurred\", e);\n return null;\n }\n }\n\n}" } ]
import com.instana.dc.AbstractDc; import com.instana.dc.DcUtil; import com.instana.dc.IDc; import com.instana.dc.resources.ContainerResource; import io.opentelemetry.api.OpenTelemetry; import io.opentelemetry.api.common.Attributes; import io.opentelemetry.sdk.OpenTelemetrySdk; import io.opentelemetry.sdk.metrics.SdkMeterProvider; import io.opentelemetry.sdk.resources.Resource; import io.opentelemetry.semconv.ResourceAttributes; import io.opentelemetry.semconv.SemanticAttributes; import java.net.InetAddress; import java.net.UnknownHostException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.Map; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.logging.Logger; import static com.instana.dc.DcUtil.*; import static com.instana.dc.rdb.DbDcUtil.*; import static io.opentelemetry.api.common.AttributeKey.stringKey;
8,365
/* * (c) Copyright IBM Corp. 2023 * (c) Copyright Instana Inc. */ package com.instana.dc.rdb; public abstract class AbstractDbDc extends AbstractDc implements IDc { private static final Logger logger = Logger.getLogger(AbstractDbDc.class.getName()); private final String dbSystem; private final String dbDriver; private String dbAddress; private long dbPort; private String dbConnUrl; private String dbUserName; private String dbPassword; private String dbName; private String dbVersion; private String dbEntityType; private String dbTenantId; private String dbTenantName; private final String otelBackendUrl; private final boolean otelUsingHttp; private final int pollInterval; private final int callbackInterval; private final String serviceName; private String serviceInstanceId; private String dbEntityParentId; private final ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor(); public AbstractDbDc(Map<String, String> properties, String dbSystem, String dbDriver) { super(new DbRawMetricRegistry().getMap()); this.dbSystem = dbSystem; this.dbDriver = dbDriver; String pollInt = properties.get(POLLING_INTERVAL); pollInterval = pollInt == null ? DEFAULT_POLL_INTERVAL : Integer.parseInt(pollInt); String callbackInt = properties.get(CALLBACK_INTERVAL); callbackInterval = callbackInt == null ? DEFAULT_CALLBACK_INTERVAL : Integer.parseInt(callbackInt); otelBackendUrl = properties.get(OTEL_BACKEND_URL); otelUsingHttp = "true".equalsIgnoreCase(properties.get(OTEL_BACKEND_USING_HTTP)); serviceName = properties.get(OTEL_SERVICE_NAME); serviceInstanceId = properties.get(OTEL_SERVICE_INSTANCE_ID); dbEntityParentId = properties.get(DB_ENTITY_PARENT_ID); dbAddress = properties.get(DB_ADDRESS); dbPort = Long.parseLong(properties.get(DB_PORT)); dbConnUrl = properties.get(DB_CONN_URL); dbUserName = properties.get(DB_USERNAME); dbPassword = properties.get(DB_PASSWORD); dbEntityType = properties.get(DB_ENTITY_TYPE); if (dbEntityType == null) { dbEntityType = DEFAULT_DB_ENTITY_TYPE; } dbEntityType = dbEntityType.toUpperCase(); dbTenantId = properties.get(DB_TENANT_ID); dbTenantName = properties.get(DB_TENANT_NAME); dbName = properties.get(DB_NAME); dbVersion = properties.get(DB_VERSION); } @Override public Resource getResourceAttributes() { Resource resource = Resource.getDefault() .merge(Resource.create(Attributes.of(ResourceAttributes.SERVICE_NAME, serviceName, SemanticAttributes.DB_SYSTEM, dbSystem, com.instana.agent.sensorsdk.semconv.ResourceAttributes.SERVER_ADDRESS, dbAddress, com.instana.agent.sensorsdk.semconv.ResourceAttributes.SERVER_PORT, dbPort, SemanticAttributes.DB_NAME, dbName, com.instana.agent.sensorsdk.semconv.ResourceAttributes.DB_VERSION, dbVersion ))) .merge(Resource.create(Attributes.of(ResourceAttributes.SERVICE_INSTANCE_ID, serviceInstanceId, com.instana.agent.sensorsdk.semconv.ResourceAttributes.DB_ENTITY_TYPE, dbEntityType,
/* * (c) Copyright IBM Corp. 2023 * (c) Copyright Instana Inc. */ package com.instana.dc.rdb; public abstract class AbstractDbDc extends AbstractDc implements IDc { private static final Logger logger = Logger.getLogger(AbstractDbDc.class.getName()); private final String dbSystem; private final String dbDriver; private String dbAddress; private long dbPort; private String dbConnUrl; private String dbUserName; private String dbPassword; private String dbName; private String dbVersion; private String dbEntityType; private String dbTenantId; private String dbTenantName; private final String otelBackendUrl; private final boolean otelUsingHttp; private final int pollInterval; private final int callbackInterval; private final String serviceName; private String serviceInstanceId; private String dbEntityParentId; private final ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor(); public AbstractDbDc(Map<String, String> properties, String dbSystem, String dbDriver) { super(new DbRawMetricRegistry().getMap()); this.dbSystem = dbSystem; this.dbDriver = dbDriver; String pollInt = properties.get(POLLING_INTERVAL); pollInterval = pollInt == null ? DEFAULT_POLL_INTERVAL : Integer.parseInt(pollInt); String callbackInt = properties.get(CALLBACK_INTERVAL); callbackInterval = callbackInt == null ? DEFAULT_CALLBACK_INTERVAL : Integer.parseInt(callbackInt); otelBackendUrl = properties.get(OTEL_BACKEND_URL); otelUsingHttp = "true".equalsIgnoreCase(properties.get(OTEL_BACKEND_USING_HTTP)); serviceName = properties.get(OTEL_SERVICE_NAME); serviceInstanceId = properties.get(OTEL_SERVICE_INSTANCE_ID); dbEntityParentId = properties.get(DB_ENTITY_PARENT_ID); dbAddress = properties.get(DB_ADDRESS); dbPort = Long.parseLong(properties.get(DB_PORT)); dbConnUrl = properties.get(DB_CONN_URL); dbUserName = properties.get(DB_USERNAME); dbPassword = properties.get(DB_PASSWORD); dbEntityType = properties.get(DB_ENTITY_TYPE); if (dbEntityType == null) { dbEntityType = DEFAULT_DB_ENTITY_TYPE; } dbEntityType = dbEntityType.toUpperCase(); dbTenantId = properties.get(DB_TENANT_ID); dbTenantName = properties.get(DB_TENANT_NAME); dbName = properties.get(DB_NAME); dbVersion = properties.get(DB_VERSION); } @Override public Resource getResourceAttributes() { Resource resource = Resource.getDefault() .merge(Resource.create(Attributes.of(ResourceAttributes.SERVICE_NAME, serviceName, SemanticAttributes.DB_SYSTEM, dbSystem, com.instana.agent.sensorsdk.semconv.ResourceAttributes.SERVER_ADDRESS, dbAddress, com.instana.agent.sensorsdk.semconv.ResourceAttributes.SERVER_PORT, dbPort, SemanticAttributes.DB_NAME, dbName, com.instana.agent.sensorsdk.semconv.ResourceAttributes.DB_VERSION, dbVersion ))) .merge(Resource.create(Attributes.of(ResourceAttributes.SERVICE_INSTANCE_ID, serviceInstanceId, com.instana.agent.sensorsdk.semconv.ResourceAttributes.DB_ENTITY_TYPE, dbEntityType,
stringKey(DcUtil.INSTANA_PLUGIN),
4
2023-10-23 01:16:38+00:00
12k
A1anSong/jd_unidbg
unidbg-ios/src/main/java/com/github/unidbg/file/ios/BaseDarwinFileIO.java
[ { "identifier": "Emulator", "path": "unidbg-api/src/main/java/com/github/unidbg/Emulator.java", "snippet": "public interface Emulator<T extends NewFileIO> extends Closeable, ArmDisassembler, Serializable {\n\n int getPointerSize();\n\n boolean is64Bit();\n boolean is32Bit();\n\n int getPageAlign();\n\n /**\n * trace memory read\n */\n TraceHook traceRead();\n TraceHook traceRead(long begin, long end);\n TraceHook traceRead(long begin, long end, TraceReadListener listener);\n\n /**\n * trace memory write\n */\n TraceHook traceWrite();\n TraceHook traceWrite(long begin, long end);\n TraceHook traceWrite(long begin, long end, TraceWriteListener listener);\n\n void setTraceSystemMemoryWrite(long begin, long end, TraceSystemMemoryWriteListener listener);\n\n /**\n * trace instruction\n * note: low performance\n */\n TraceHook traceCode();\n TraceHook traceCode(long begin, long end);\n TraceHook traceCode(long begin, long end, TraceCodeListener listener);\n\n Number eFunc(long begin, Number... arguments);\n\n Number eEntry(long begin, long sp);\n\n /**\n * emulate signal handler\n * @param sig signal number\n * @return <code>true</code> means called handler function.\n */\n boolean emulateSignal(int sig);\n\n /**\n * 是否正在运行\n */\n boolean isRunning();\n\n /**\n * show all registers\n */\n void showRegs();\n\n /**\n * show registers\n */\n void showRegs(int... regs);\n\n Module loadLibrary(File libraryFile);\n Module loadLibrary(File libraryFile, boolean forceCallInit);\n\n Memory getMemory();\n\n Backend getBackend();\n\n int getPid();\n\n String getProcessName();\n\n Debugger attach();\n\n Debugger attach(DebuggerType type);\n\n FileSystem<T> getFileSystem();\n\n SvcMemory getSvcMemory();\n\n SyscallHandler<T> getSyscallHandler();\n\n Family getFamily();\n LibraryFile createURLibraryFile(URL url, String libName);\n\n Dlfcn getDlfcn();\n\n /**\n * @param timeout Duration to emulate the code (in microseconds). When this value is 0, we will emulate the code in infinite time, until the code is finished.\n */\n void setTimeout(long timeout);\n\n <V extends RegisterContext> V getContext();\n\n Unwinder getUnwinder();\n\n void pushContext(int off);\n int popContext();\n\n ThreadDispatcher getThreadDispatcher();\n\n long getReturnAddress();\n\n void set(String key, Object value);\n <V> V get(String key);\n\n}" }, { "identifier": "BaseFileIO", "path": "unidbg-api/src/main/java/com/github/unidbg/file/BaseFileIO.java", "snippet": "public abstract class BaseFileIO extends AbstractFileIO implements NewFileIO {\n\n public BaseFileIO(int oflags) {\n super(oflags);\n }\n\n}" }, { "identifier": "UnidbgFileFilter", "path": "unidbg-api/src/main/java/com/github/unidbg/file/UnidbgFileFilter.java", "snippet": "public class UnidbgFileFilter implements FileFilter {\n\n public static final String UNIDBG_PREFIX = \"__ignore.unidbg\";\n\n @Override\n public boolean accept(File pathname) {\n return !pathname.getName().startsWith(UNIDBG_PREFIX);\n }\n\n}" }, { "identifier": "DirectoryFileIO", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/file/DirectoryFileIO.java", "snippet": "public class DirectoryFileIO extends BaseDarwinFileIO {\n\n public static class DirectoryEntry {\n private final boolean isFile;\n private final String name;\n public DirectoryEntry(boolean isFile, String name) {\n this.isFile = isFile;\n this.name = name;\n }\n }\n\n private static DirectoryEntry[] createEntries(File dir) {\n List<DirectoryEntry> list = new ArrayList<>();\n File[] files = dir.listFiles(new UnidbgFileFilter());\n if (files != null) {\n Arrays.sort(files);\n for (File file : files) {\n list.add(new DirectoryEntry(file.isFile(), file.getName()));\n }\n }\n return list.toArray(new DirectoryEntry[0]);\n }\n\n private final String path;\n\n private final List<DirectoryEntry> entries;\n\n private final File dir;\n\n public DirectoryFileIO(int oflags, String path, File dir) {\n this(oflags, path, dir, createEntries(dir));\n }\n\n public DirectoryFileIO(int oflags, String path, DirectoryEntry... entries) {\n this(oflags, path, null, entries);\n }\n\n public DirectoryFileIO(int oflags, String path, File dir, DirectoryEntry... entries) {\n super(oflags);\n\n this.path = path;\n this.dir = dir;\n\n this.entries = new ArrayList<>();\n this.entries.add(new DirectoryEntry(false, \".\"));\n this.entries.add(new DirectoryEntry(false, \"..\"));\n if (entries != null) {\n Collections.addAll(this.entries, entries);\n }\n }\n\n @Override\n public int fstatfs(StatFS statFS) {\n return 0;\n }\n\n @Override\n public int fstat(Emulator<?> emulator, StatStructure stat) {\n stat.st_dev = 1;\n stat.st_mode = IO.S_IFDIR | 0x777;\n stat.setSize(0);\n stat.st_blksize = 0;\n stat.st_ino = 7;\n stat.pack();\n return 0;\n }\n\n @Override\n public void close() {\n }\n\n @Override\n public String toString() {\n return path;\n }\n\n @Override\n public int fcntl(Emulator<?> emulator, int cmd, long arg) {\n if (cmd == F_GETPATH) {\n UnidbgPointer pointer = UnidbgPointer.pointer(emulator, arg);\n if (pointer != null) {\n pointer.setString(0, getPath());\n }\n return 0;\n }\n\n return super.fcntl(emulator, cmd, arg);\n }\n\n @Override\n public String getPath() {\n return path;\n }\n\n @Override\n public int getdirentries64(Pointer buf, int bufSize) {\n int offset = 0;\n for (Iterator<DirectoryFileIO.DirectoryEntry> iterator = this.entries.iterator(); iterator.hasNext(); ) {\n DirectoryFileIO.DirectoryEntry entry = iterator.next();\n byte[] data = entry.name.getBytes(StandardCharsets.UTF_8);\n long d_reclen = ARM.alignSize(data.length + 24, 8);\n\n if (offset + d_reclen >= bufSize) {\n break;\n }\n\n Dirent dirent = new Dirent(buf.share(offset));\n dirent.d_fileno = 1;\n dirent.d_reclen = (short) d_reclen;\n dirent.d_type = entry.isFile ? Dirent.DT_REG : Dirent.DT_DIR;\n dirent.d_namlen = (short) (data.length);\n dirent.d_name = Arrays.copyOf(data, data.length + 1);\n dirent.pack();\n offset += d_reclen;\n\n iterator.remove();\n }\n\n return offset;\n }\n\n @Override\n public int listxattr(Pointer namebuf, int size, int options) {\n if (dir == null) {\n throw new UnsupportedOperationException(\"path=\" + path + \", options=0x\" + Integer.toHexString(options));\n }\n return listxattr(dir, namebuf, size);\n }\n\n @Override\n public int removexattr(String name) {\n if (dir == null) {\n throw new UnsupportedOperationException(\"path=\" + path + \", name=\" + name);\n }\n return removexattr(dir, name);\n }\n\n @Override\n public int setxattr(String name, byte[] data) {\n if (dir == null) {\n throw new UnsupportedOperationException(\"path=\" + path + \", name=\" + name);\n }\n return setxattr(dir, name, data);\n }\n\n @Override\n public int getxattr(Emulator<?> emulator, String name, Pointer value, int size) {\n if (dir == null) {\n throw new UnsupportedOperationException(\"path=\" + path + \", name=\" + name);\n }\n return getxattr(emulator, dir, name, value, size);\n }\n\n @Override\n public int chmod(int mode) {\n if (dir == null) {\n throw new UnsupportedOperationException(\"path=\" + path + \", mode=0x\" + Integer.toHexString(mode));\n }\n return chmod(dir, mode);\n }\n\n @Override\n public int chown(int uid, int gid) {\n if (dir == null) {\n throw new UnsupportedOperationException(\"path=\" + path + \", uid=\" + uid + \", gid=\" + gid);\n }\n return chown(dir, uid, gid);\n }\n\n @Override\n public int chflags(int flags) {\n if (dir == null) {\n throw new UnsupportedOperationException(\"path=\" + path + \", flags=0x\" + Integer.toHexString(flags));\n }\n return chflags(dir, flags);\n }\n}" }, { "identifier": "AttrList", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/struct/attr/AttrList.java", "snippet": "public class AttrList extends UnidbgStructure {\n\n public AttrList(Pointer p) {\n super(p);\n unpack();\n }\n\n public short bitmapcount; /* number of attr. bit sets in list (should be 5) */\n public short reserved; /* (to maintain 4-byte alignment) */\n\n public AttributeSet attributeSet;\n\n @Override\n protected List<String> getFieldOrder() {\n return Arrays.asList(\"bitmapcount\", \"reserved\", \"attributeSet\");\n }\n\n}" }, { "identifier": "AttrReference", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/struct/attr/AttrReference.java", "snippet": "public class AttrReference extends UnidbgStructure {\n\n private final byte[] bytes;\n\n public AttrReference(Pointer p, byte[] bytes) {\n super(p);\n this.bytes = bytes;\n attr_length = (int) ARM.alignSize(bytes.length + 1, 8);\n }\n\n public int attr_dataoffset;\n public int attr_length;\n\n @Override\n protected List<String> getFieldOrder() {\n return Arrays.asList(\"attr_dataoffset\", \"attr_length\");\n }\n\n private boolean started;\n\n public void check(UnidbgStructure structure, int size) {\n if (structure == this) {\n started = true;\n }\n\n if (started) {\n attr_dataoffset += size;\n }\n }\n\n public void writeAttr(Pointer pointer) {\n pointer.write(0, Arrays.copyOf(bytes, attr_length), 0, attr_length);\n pack();\n }\n}" }, { "identifier": "AttributeSet", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/struct/attr/AttributeSet.java", "snippet": "public class AttributeSet extends UnidbgStructure {\n\n public AttributeSet(Pointer p) {\n super(p);\n }\n\n public int commonattr; /* common attribute group */\n public int volattr; /* Volume attribute group */\n public int dirattr; /* directory attribute group */\n public int fileattr; /* file attribute group */\n public int forkattr; /* fork attribute group */\n\n @Override\n protected List<String> getFieldOrder() {\n return Arrays.asList(\"commonattr\", \"volattr\", \"dirattr\", \"fileattr\", \"forkattr\");\n }\n\n}" }, { "identifier": "Dev", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/struct/attr/Dev.java", "snippet": "public class Dev extends UnidbgStructure {\n\n public Dev(Pointer p) {\n super(p);\n }\n\n public int dev;\n\n @Override\n protected List<String> getFieldOrder() {\n return Collections.singletonList(\"dev\");\n }\n\n}" }, { "identifier": "FinderInfo", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/struct/attr/FinderInfo.java", "snippet": "public class FinderInfo extends UnidbgStructure {\n\n public FinderInfo(Pointer p) {\n super(p);\n }\n\n public byte[] finderInfo = new byte[32];\n\n @Override\n protected List<String> getFieldOrder() {\n return Collections.singletonList(\"finderInfo\");\n }\n\n}" }, { "identifier": "Fsid", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/struct/attr/Fsid.java", "snippet": "public class Fsid extends UnidbgStructure {\n\n public Fsid(Pointer p) {\n super(p);\n }\n\n public int[] val = new int[2];\t/* file system id type */\n\n @Override\n protected List<String> getFieldOrder() {\n return Collections.singletonList(\"val\");\n }\n\n}" }, { "identifier": "ObjId", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/struct/attr/ObjId.java", "snippet": "public class ObjId extends UnidbgStructure {\n\n public ObjId(Pointer p) {\n super(p);\n }\n\n public int fid_objno;\n public int fid_generation;\n\n @Override\n protected List<String> getFieldOrder() {\n return Arrays.asList(\"fid_objno\", \"fid_generation\");\n }\n}" }, { "identifier": "ObjType", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/struct/attr/ObjType.java", "snippet": "public class ObjType extends UnidbgStructure {\n\n public ObjType(Pointer p) {\n super(p);\n }\n\n public int type;\n\n @Override\n protected List<String> getFieldOrder() {\n return Collections.singletonList(\"type\");\n }\n\n}" }, { "identifier": "UserAccess", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/struct/attr/UserAccess.java", "snippet": "public class UserAccess extends UnidbgStructure {\n\n public UserAccess(Pointer p) {\n super(p);\n }\n\n public int mode;\n\n @Override\n protected List<String> getFieldOrder() {\n return Collections.singletonList(\"mode\");\n }\n\n}" }, { "identifier": "StatFS", "path": "unidbg-ios/src/main/java/com/github/unidbg/ios/struct/kernel/StatFS.java", "snippet": "public class StatFS extends UnidbgStructure {\n\n private static final int MFSTYPENAMELEN = 16; /* length of fs type name including null */\n private static final int MAXPATHLEN = 1024; /* max bytes in pathname */\n\n public StatFS(byte[] data) {\n super(data);\n }\n\n public StatFS(Pointer p) {\n super(p);\n }\n\n public int f_bsize; /* fundamental file system block size */\n public int f_iosize; /* optimal transfer block size */\n public long f_blocks; /* total data blocks in file system */\n public long f_bfree; /* free blocks in fs */\n public long f_bavail; /* free blocks avail to non-superuser */\n public long f_files; /* total file nodes in file system */\n public long f_ffree; /* free file nodes in fs */\n\n public long f_fsid; /* file system id */\n public int f_owner; /* user that mounted the filesystem */\n public int f_type; /* type of filesystem */\n public int f_flags; /* copy of mount exported flags */\n public int f_fssubtype; /* fs sub-type (flavor) */\n\n public byte[] f_fstypename = new byte[MFSTYPENAMELEN]; /* fs type name */\n public byte[] f_mntonname = new byte[MAXPATHLEN]; /* directory on which mounted */\n public byte[] f_mntfromname = new byte[MAXPATHLEN]; /* mounted filesystem */\n public int[] f_reserved = new int[8]; /* For future use */\n\n public void setFsTypeName(String fsTypeName) {\n if (fsTypeName == null) {\n throw new NullPointerException();\n }\n byte[] data = fsTypeName.getBytes(StandardCharsets.UTF_8);\n if (data.length + 1 >= MFSTYPENAMELEN) {\n throw new IllegalStateException(\"Invalid MFSTYPENAMELEN: \" + MFSTYPENAMELEN);\n }\n f_fstypename = Arrays.copyOf(data, MFSTYPENAMELEN);\n }\n\n public void setMntOnName(String mntOnName) {\n if (mntOnName == null) {\n throw new NullPointerException();\n }\n byte[] data = mntOnName.getBytes(StandardCharsets.UTF_8);\n if (data.length + 1 >= MAXPATHLEN) {\n throw new IllegalStateException(\"Invalid MAXPATHLEN: \" + MAXPATHLEN);\n }\n f_mntonname = Arrays.copyOf(data, MAXPATHLEN);\n }\n\n public void setMntFromName(String mntFromName) {\n if (mntFromName == null) {\n throw new NullPointerException();\n }\n byte[] data = mntFromName.getBytes(StandardCharsets.UTF_8);\n if (data.length + 1 >= MAXPATHLEN) {\n throw new IllegalStateException(\"Invalid MAXPATHLEN: \" + MAXPATHLEN);\n }\n f_mntfromname = Arrays.copyOf(data, MAXPATHLEN);\n }\n\n @Override\n protected List<String> getFieldOrder() {\n return Arrays.asList(\"f_bsize\", \"f_iosize\", \"f_blocks\", \"f_bfree\", \"f_bavail\", \"f_files\", \"f_ffree\", \"f_fsid\", \"f_owner\",\n \"f_type\", \"f_flags\", \"f_fssubtype\", \"f_fstypename\", \"f_mntonname\", \"f_mntfromname\", \"f_reserved\");\n }\n\n}" }, { "identifier": "UnidbgStructure", "path": "unidbg-api/src/main/java/com/github/unidbg/pointer/UnidbgStructure.java", "snippet": "public abstract class UnidbgStructure extends Structure implements PointerArg {\n\n /** Placeholder pointer to help avoid auto-allocation of memory where a\n * Structure needs a valid pointer but want to avoid actually reading from it.\n */\n private static final Pointer PLACEHOLDER_MEMORY = new UnidbgPointer(null, null) {\n @Override\n public UnidbgPointer share(long offset, long sz) { return this; }\n };\n\n public static int calculateSize(Class<? extends UnidbgStructure> type) {\n try {\n Constructor<? extends UnidbgStructure> constructor = type.getConstructor(Pointer.class);\n return constructor.newInstance(PLACEHOLDER_MEMORY).calculateSize(false);\n } catch (NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) {\n throw new IllegalStateException(e);\n }\n }\n\n private static class ByteArrayPointer extends UnidbgPointer {\n private final Emulator<?> emulator;\n private final byte[] data;\n public ByteArrayPointer(Emulator<?> emulator, byte[] data) {\n super(emulator, data);\n this.emulator = emulator;\n this.data = data;\n }\n @Override\n public UnidbgPointer share(long offset, long sz) {\n if (offset == 0) {\n return this;\n }\n if (offset > 0 && offset + sz < data.length) {\n if (sz == 0) {\n sz = data.length - offset;\n }\n byte[] tmp = new byte[(int) sz];\n System.arraycopy(data, (int) offset, tmp, 0, (int) sz);\n return new ByteArrayPointer(emulator, tmp);\n }\n throw new UnsupportedOperationException(\"offset=0x\" + Long.toHexString(offset) + \", sz=\" + sz);\n }\n }\n\n protected UnidbgStructure(Emulator<?> emulator, byte[] data) {\n this(new ByteArrayPointer(emulator, data));\n }\n\n protected UnidbgStructure(byte[] data) {\n this(null, data);\n }\n\n protected UnidbgStructure(Pointer p) {\n super(p);\n\n checkPointer(p);\n }\n\n private void checkPointer(Pointer p) {\n if (p == null) {\n throw new NullPointerException(\"p is null\");\n }\n if (!(p instanceof UnidbgPointer) && !isPlaceholderMemory(p)) {\n throw new IllegalArgumentException(\"p is NOT UnidbgPointer\");\n }\n }\n\n @Override\n protected int getNativeSize(Class<?> nativeType, Object value) {\n if (Pointer.class.isAssignableFrom(nativeType)) {\n throw new UnsupportedOperationException();\n }\n\n return super.getNativeSize(nativeType, value);\n }\n\n @Override\n protected int getNativeAlignment(Class<?> type, Object value, boolean isFirstElement) {\n if (Pointer.class.isAssignableFrom(type)) {\n throw new UnsupportedOperationException();\n }\n\n return super.getNativeAlignment(type, value, isFirstElement);\n }\n\n private boolean isPlaceholderMemory(Pointer p) {\n return \"native@0x0\".equals(p.toString());\n }\n\n public void pack() {\n super.write();\n }\n\n public void unpack() {\n super.read();\n }\n\n /**\n * @param debug If true, will include a native memory dump of the\n * Structure's backing memory.\n * @return String representation of this object.\n */\n public String toString(boolean debug) {\n return toString(0, true, debug);\n }\n\n private String format(Class<?> type) {\n String s = type.getName();\n int dot = s.lastIndexOf(\".\");\n return s.substring(dot + 1);\n }\n\n private String toString(int indent, boolean showContents, boolean dumpMemory) {\n ensureAllocated();\n String LS = System.getProperty(\"line.separator\");\n String name = format(getClass()) + \"(\" + getPointer() + \")\";\n if (!(getPointer() instanceof Memory)) {\n name += \" (\" + size() + \" bytes)\";\n }\n StringBuilder prefix = new StringBuilder();\n for (int idx=0;idx < indent;idx++) {\n prefix.append(\" \");\n }\n StringBuilder contents = new StringBuilder(LS);\n if (!showContents) {\n contents = new StringBuilder(\"...}\");\n }\n else for (Iterator<StructField> i = fields().values().iterator(); i.hasNext();) {\n StructField sf = i.next();\n Object value = getFieldValue(sf.field);\n String type = format(sf.type);\n String index = \"\";\n contents.append(prefix);\n if (sf.type.isArray() && value != null) {\n type = format(sf.type.getComponentType());\n index = \"[\" + Array.getLength(value) + \"]\";\n }\n contents.append(String.format(\" %s %s%s@0x%X\", type, sf.name, index, sf.offset));\n if (value instanceof UnidbgStructure) {\n value = ((UnidbgStructure)value).toString(indent + 1, !(value instanceof Structure.ByReference), dumpMemory);\n }\n contents.append(\"=\");\n if (value instanceof Long) {\n contents.append(String.format(\"0x%08X\", value));\n }\n else if (value instanceof Integer) {\n contents.append(String.format(\"0x%04X\", value));\n }\n else if (value instanceof Short) {\n contents.append(String.format(\"0x%02X\", value));\n }\n else if (value instanceof Byte) {\n contents.append(String.format(\"0x%01X\", value));\n }\n else if (value instanceof byte[]) {\n contents.append(Hex.encodeHexString((byte[]) value));\n }\n else {\n contents.append(String.valueOf(value).trim());\n }\n contents.append(LS);\n if (!i.hasNext())\n contents.append(prefix).append(\"}\");\n }\n if (indent == 0 && dumpMemory) {\n final int BYTES_PER_ROW = 4;\n contents.append(LS).append(\"memory dump\").append(LS);\n byte[] buf = getPointer().getByteArray(0, size());\n for (int i=0;i < buf.length;i++) {\n if ((i % BYTES_PER_ROW) == 0) contents.append(\"[\");\n if (buf[i] >=0 && buf[i] < 16)\n contents.append(\"0\");\n contents.append(Integer.toHexString(buf[i] & 0xff));\n if ((i % BYTES_PER_ROW) == BYTES_PER_ROW-1 && i < buf.length-1)\n contents.append(\"]\").append(LS);\n }\n contents.append(\"]\");\n }\n return name + \" {\" + contents;\n }\n\n /** Obtain the value currently in the Java field. Does not read from\n * native memory.\n * @param field field to look up\n * @return current field value (Java-side only)\n */\n private Object getFieldValue(Field field) {\n try {\n return field.get(this);\n }\n catch (Exception e) {\n throw new Error(\"Exception reading field '\" + field.getName() + \"' in \" + getClass(), e);\n }\n }\n\n private static final Field FIELD_STRUCT_FIELDS;\n\n static {\n try {\n FIELD_STRUCT_FIELDS = Structure.class.getDeclaredField(\"structFields\");\n FIELD_STRUCT_FIELDS.setAccessible(true);\n } catch (NoSuchFieldException e) {\n throw new IllegalStateException(e);\n }\n }\n\n /** Return all fields in this structure (ordered). This represents the\n * layout of the structure, and will be shared among Structures of the\n * same class except when the Structure can have a variable size.\n * NOTE: {@link #ensureAllocated()} <em>must</em> be called prior to\n * calling this method.\n * @return {@link Map} of field names to field representations.\n */\n @SuppressWarnings(\"unchecked\")\n private Map<String, StructField> fields() {\n try {\n return (Map<String, StructField>) FIELD_STRUCT_FIELDS.get(this);\n } catch (IllegalAccessException e) {\n throw new IllegalStateException(e);\n }\n }\n}" }, { "identifier": "UnixEmulator", "path": "unidbg-api/src/main/java/com/github/unidbg/unix/UnixEmulator.java", "snippet": "public interface UnixEmulator {\n\n int EPERM = 1; /* Operation not permitted */\n int ENOENT = 2; /* No such file or directory */\n int ESRCH = 3; /* No such process */\n int EINTR = 4; /* Interrupted system call */\n int EBADF = 9; /* Bad file descriptor */\n int EAGAIN = 11; /* Resource temporarily unavailable */\n int ENOMEM = 12; /* Cannot allocate memory */\n int EACCES = 13; /* Permission denied */\n int EFAULT = 14; /* Bad address */\n int EEXIST = 17; /* File exists */\n int ENOTDIR = 20; /* Not a directory */\n int EINVAL = 22; /* Invalid argument */\n int ENOTTY = 25; /* Inappropriate ioctl for device */\n int ENOSYS = 38; /* Function not implemented */\n int ENOATTR = 93; /* Attribute not found */\n int EOPNOTSUPP = 95; /* Operation not supported on transport endpoint */\n int EAFNOSUPPORT = 97; /* Address family not supported by protocol family */\n int EADDRINUSE = 98; /* Address already in use */\n int ECONNREFUSED = 111; /* Connection refused */\n\n}" }, { "identifier": "TimeSpec32", "path": "unidbg-api/src/main/java/com/github/unidbg/unix/struct/TimeSpec32.java", "snippet": "public class TimeSpec32 extends TimeSpec {\n\n public TimeSpec32(Pointer p) {\n super(p);\n }\n\n public int tv_sec; // unsigned long\n public int tv_nsec; // long\n\n @Override\n public long getTvSec() {\n return tv_sec;\n }\n\n @Override\n public long getTvNsec() {\n return tv_nsec;\n }\n\n @Override\n protected void setTv(long tvSec, long tvNsec) {\n this.tv_sec = (int) tvSec;\n this.tv_nsec = (int) tvNsec;\n }\n\n @Override\n protected List<String> getFieldOrder() {\n return Arrays.asList(\"tv_sec\", \"tv_nsec\");\n }\n\n}" } ]
import com.alibaba.fastjson.JSON; import com.github.unidbg.Emulator; import com.github.unidbg.file.BaseFileIO; import com.github.unidbg.file.UnidbgFileFilter; import com.github.unidbg.ios.file.DirectoryFileIO; import com.github.unidbg.ios.struct.attr.AttrList; import com.github.unidbg.ios.struct.attr.AttrReference; import com.github.unidbg.ios.struct.attr.AttributeSet; import com.github.unidbg.ios.struct.attr.Dev; import com.github.unidbg.ios.struct.attr.FinderInfo; import com.github.unidbg.ios.struct.attr.Fsid; import com.github.unidbg.ios.struct.attr.ObjId; import com.github.unidbg.ios.struct.attr.ObjType; import com.github.unidbg.ios.struct.attr.UserAccess; import com.github.unidbg.ios.struct.kernel.StatFS; import com.github.unidbg.pointer.UnidbgStructure; import com.github.unidbg.unix.UnixEmulator; import com.github.unidbg.unix.struct.TimeSpec32; import com.sun.jna.Pointer; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List;
9,526
} @Override public int listxattr(Pointer namebuf, int size, int options) { throw new UnsupportedOperationException(getClass().getName()); } @Override public int removexattr(String name) { throw new UnsupportedOperationException(getClass().getName()); } @Override public int setxattr(String name, byte[] data) { throw new UnsupportedOperationException(getClass().getName()); } @Override public int getxattr(Emulator<?> emulator, String name, Pointer value, int size) { throw new UnsupportedOperationException(getClass().getName()); } @Override public int chown(int uid, int gid) { throw new UnsupportedOperationException(getClass().getName()); } @Override public int chmod(int mode) { throw new UnsupportedOperationException(getClass().getName()); } @Override public int chflags(int flags) { throw new UnsupportedOperationException(getClass().getName()); } protected final int chflags(File dest, int flags) { try { DarwinFileAttr attr = loadAttr(dest); if (attr == null) { attr = new DarwinFileAttr(); } attr.flags = flags; File file = createAttrFile(dest); FileUtils.writeStringToFile(file, JSON.toJSONString(attr), StandardCharsets.UTF_8); return 0; } catch (IOException e) { throw new IllegalStateException(e); } } protected final int chmod(File dest, int mode) { try { DarwinFileAttr attr = loadAttr(dest); if (attr == null) { attr = new DarwinFileAttr(); } attr.mode = mode; File file = createAttrFile(dest); FileUtils.writeStringToFile(file, JSON.toJSONString(attr), StandardCharsets.UTF_8); return 0; } catch (IOException e) { throw new IllegalStateException(e); } } protected final int chown(File dest, int uid, int gid) { try { DarwinFileAttr attr = loadAttr(dest); if (attr == null) { attr = new DarwinFileAttr(); } attr.uid = uid; attr.gid = gid; File file = createAttrFile(dest); FileUtils.writeStringToFile(file, JSON.toJSONString(attr), StandardCharsets.UTF_8); return 0; } catch (IOException e) { throw new IllegalStateException(e); } } protected final DarwinFileAttr loadAttr(File dest) throws IOException { File file = createAttrFile(dest); if (file.exists()) { return JSON.parseObject(FileUtils.readFileToString(file, StandardCharsets.UTF_8), DarwinFileAttr.class); } else { return null; } } protected final int listxattr(File dest, Pointer namebuf, int size) { try { DarwinFileAttr attr = loadAttr(dest); if (attr == null || attr.xattr == null) { return 0; } int ret = 0; Pointer buffer = namebuf; for (String name : attr.xattr.keySet()) { byte[] data = name.getBytes(StandardCharsets.UTF_8); ret += (data.length + 1); if (buffer != null && ret <= size) { buffer.write(0, Arrays.copyOf(data, data.length + 1), 0, data.length + 1); buffer = buffer.share(data.length + 1); } } return ret; } catch (IOException e) { throw new IllegalStateException(e); } } protected final int getxattr(Emulator<?> emulator, File dest, String name, Pointer value, int size) { try { DarwinFileAttr attr = loadAttr(dest); byte[] data = attr == null || attr.xattr == null ? null : attr.xattr.get(name); if (data == null) {
package com.github.unidbg.file.ios; public abstract class BaseDarwinFileIO extends BaseFileIO implements DarwinFileIO { private static final Log log = LogFactory.getLog(BaseDarwinFileIO.class); public static File createAttrFile(File dest) { if (!dest.exists()) { throw new IllegalStateException("dest=" + dest); } File file; if (dest.isDirectory()) { file = new File(dest, UnidbgFileFilter.UNIDBG_PREFIX + ".json"); } else { file = new File(dest.getParentFile(), UnidbgFileFilter.UNIDBG_PREFIX + "_" + dest.getName() + ".json"); } return file; } public BaseDarwinFileIO(int oflags) { super(oflags); } public int fstat(Emulator<?> emulator, StatStructure stat) { throw new UnsupportedOperationException(getClass().getName()); } private int protectionClass; @Override public int fcntl(Emulator<?> emulator, int cmd, long arg) { if (cmd == F_NOCACHE) { return 0; } if (cmd == F_SETLK) { return 0; } if (cmd == F_SETLKW) { return 0; } if (cmd == F_SETPROTECTIONCLASS) { protectionClass = (int) arg; return 0; } if (cmd == F_GETPROTECTIONCLASS) { return protectionClass; } if(cmd == F_SINGLE_WRITER) { return 0; } if (cmd == F_PREALLOCATE) { return 0; } return super.fcntl(emulator, cmd, arg); } public int fstatfs(StatFS statFS) { throw new UnsupportedOperationException(getClass().getName() + " path=" + getPath()); } @Override public int getattrlist(AttrList attrList, Pointer attrBuf, int attrBufSize) { if (attrList.bitmapcount != ATTR_BIT_MAP_COUNT) { throw new UnsupportedOperationException("bitmapcount=" + attrList.bitmapcount); } AttributeSet attributeSet = attrList.attributeSet; Pointer pointer = attrBuf.share(4); List<UnidbgStructure> list = new ArrayList<>(); List<AttrReference> attrReferenceList = new ArrayList<>(); AttributeSet returnedAttributeSet = null; if ((attributeSet.commonattr & ATTR_CMN_RETURNED_ATTRS) != 0) { returnedAttributeSet = new AttributeSet(pointer); pointer = pointer.share(returnedAttributeSet.size()); list.add(returnedAttributeSet); attributeSet.commonattr &= ~ATTR_CMN_RETURNED_ATTRS; } if((attributeSet.commonattr & ATTR_CMN_NAME) != 0) { String name = FilenameUtils.getName(getPath()); byte[] bytes = name.getBytes(StandardCharsets.UTF_8); AttrReference attrReference = new AttrReference(pointer, bytes); attrReferenceList.add(attrReference); pointer = pointer.share(attrReference.size()); list.add(attrReference); attributeSet.commonattr &= ~ATTR_CMN_NAME; if (returnedAttributeSet != null) { returnedAttributeSet.commonattr |= ATTR_CMN_NAME; } } if((attributeSet.commonattr & ATTR_CMN_DEVID) != 0) { Dev dev = new Dev(pointer); dev.dev = 1; pointer = pointer.share(dev.size()); list.add(dev); attributeSet.commonattr &= ~ATTR_CMN_DEVID; if (returnedAttributeSet != null) { returnedAttributeSet.commonattr |= ATTR_CMN_DEVID; } } if((attributeSet.commonattr & ATTR_CMN_FSID) != 0) { Fsid fsid = new Fsid(pointer); fsid.val[0] = 0; fsid.val[1] = 0; pointer = pointer.share(fsid.size()); list.add(fsid); attributeSet.commonattr &= ~ATTR_CMN_FSID; if (returnedAttributeSet != null) { returnedAttributeSet.commonattr |= ATTR_CMN_FSID; } } if((attributeSet.commonattr & ATTR_CMN_OBJTYPE) != 0) { ObjType objType = new ObjType(pointer); objType.type = this instanceof DirectoryFileIO ? vtype.VDIR.ordinal() : vtype.VREG.ordinal(); pointer = pointer.share(objType.size()); list.add(objType); attributeSet.commonattr &= ~ATTR_CMN_OBJTYPE; if (returnedAttributeSet != null) { returnedAttributeSet.commonattr |= ATTR_CMN_OBJTYPE; } } if((attributeSet.commonattr & ATTR_CMN_OBJID) != 0) { ObjId objId = new ObjId(pointer); objId.fid_objno = 0; objId.fid_generation = 0; pointer = pointer.share(objId.size()); list.add(objId); attributeSet.commonattr &= ~ATTR_CMN_OBJID; if (returnedAttributeSet != null) { returnedAttributeSet.commonattr |= ATTR_CMN_OBJID; } } if((attributeSet.commonattr & ATTR_CMN_CRTIME) != 0) { TimeSpec32 timeSpec = new TimeSpec32(pointer); pointer = pointer.share(timeSpec.size()); list.add(timeSpec); attributeSet.commonattr &= ~ATTR_CMN_CRTIME; if (returnedAttributeSet != null) { returnedAttributeSet.commonattr |= ATTR_CMN_CRTIME; } } if ((attributeSet.commonattr & ATTR_CMN_FNDRINFO) != 0) { FinderInfo finderInfo = new FinderInfo(pointer); pointer = pointer.share(finderInfo.size()); list.add(finderInfo); attributeSet.commonattr &= ~ATTR_CMN_FNDRINFO; if (returnedAttributeSet != null) { returnedAttributeSet.commonattr |= ATTR_CMN_FNDRINFO; } } if ((attributeSet.commonattr & ATTR_CMN_USERACCESS) != 0) { UserAccess userAccess = new UserAccess(pointer); userAccess.mode = X_OK | W_OK | R_OK; // pointer = pointer.share(userAccess.size()); list.add(userAccess); attributeSet.commonattr &= ~ATTR_CMN_USERACCESS; if (returnedAttributeSet != null) { returnedAttributeSet.commonattr |= ATTR_CMN_USERACCESS; } } if (attributeSet.commonattr != 0 || attributeSet.volattr != 0 || attributeSet.dirattr != 0 || attributeSet.fileattr != 0 || attributeSet.forkattr != 0) { if (returnedAttributeSet == null) { return -1; } } int len = 0; for (UnidbgStructure structure : list) { int size = structure.size(); len += size; structure.pack(); for (AttrReference attrReference : attrReferenceList) { attrReference.check(structure, size); } } attrBuf.setInt(0, len + 4); for (AttrReference attrReference : attrReferenceList) { pointer = attrBuf.share(attrReference.attr_dataoffset + 4); attrReference.writeAttr(pointer); } return 0; } @Override public int setattrlist(AttrList attrList, Pointer attrBuf, int attrBufSize) { if (attrList.bitmapcount != ATTR_BIT_MAP_COUNT) { throw new UnsupportedOperationException("bitmapcount=" + attrList.bitmapcount); } AttributeSet attributeSet = attrList.attributeSet; Pointer pointer = attrBuf.share(4); if((attributeSet.commonattr & ATTR_CMN_CRTIME) != 0) { TimeSpec32 timeSpec = new TimeSpec32(pointer); pointer = pointer.share(timeSpec.size()); if (log.isDebugEnabled()) { log.debug("setattrlist timeSpec=" + timeSpec + ", pointer=" + pointer); } attributeSet.commonattr &= ~ATTR_CMN_CRTIME; } if((attributeSet.commonattr & ATTR_CMN_MODTIME) != 0) { TimeSpec32 timeSpec = new TimeSpec32(pointer); pointer = pointer.share(timeSpec.size()); if (log.isDebugEnabled()) { log.debug("setattrlist timeSpec=" + timeSpec + ", pointer=" + pointer); } attributeSet.commonattr &= ~ATTR_CMN_MODTIME; } if ((attributeSet.commonattr & ATTR_CMN_FNDRINFO) != 0) { FinderInfo finderInfo = new FinderInfo(pointer); pointer = pointer.share(finderInfo.size()); if (log.isDebugEnabled()) { log.debug("setattrlist finderInfo=" + finderInfo + ", pointer=" + pointer); } attributeSet.commonattr &= ~ATTR_CMN_FNDRINFO; } if (attributeSet.commonattr != 0 || attributeSet.volattr != 0 || attributeSet.dirattr != 0 || attributeSet.fileattr != 0 || attributeSet.forkattr != 0) { return -1; } return 0; } @Override public int getdirentries64(Pointer buf, int bufSize) { throw new UnsupportedOperationException(getClass().getName()); } @Override public int listxattr(Pointer namebuf, int size, int options) { throw new UnsupportedOperationException(getClass().getName()); } @Override public int removexattr(String name) { throw new UnsupportedOperationException(getClass().getName()); } @Override public int setxattr(String name, byte[] data) { throw new UnsupportedOperationException(getClass().getName()); } @Override public int getxattr(Emulator<?> emulator, String name, Pointer value, int size) { throw new UnsupportedOperationException(getClass().getName()); } @Override public int chown(int uid, int gid) { throw new UnsupportedOperationException(getClass().getName()); } @Override public int chmod(int mode) { throw new UnsupportedOperationException(getClass().getName()); } @Override public int chflags(int flags) { throw new UnsupportedOperationException(getClass().getName()); } protected final int chflags(File dest, int flags) { try { DarwinFileAttr attr = loadAttr(dest); if (attr == null) { attr = new DarwinFileAttr(); } attr.flags = flags; File file = createAttrFile(dest); FileUtils.writeStringToFile(file, JSON.toJSONString(attr), StandardCharsets.UTF_8); return 0; } catch (IOException e) { throw new IllegalStateException(e); } } protected final int chmod(File dest, int mode) { try { DarwinFileAttr attr = loadAttr(dest); if (attr == null) { attr = new DarwinFileAttr(); } attr.mode = mode; File file = createAttrFile(dest); FileUtils.writeStringToFile(file, JSON.toJSONString(attr), StandardCharsets.UTF_8); return 0; } catch (IOException e) { throw new IllegalStateException(e); } } protected final int chown(File dest, int uid, int gid) { try { DarwinFileAttr attr = loadAttr(dest); if (attr == null) { attr = new DarwinFileAttr(); } attr.uid = uid; attr.gid = gid; File file = createAttrFile(dest); FileUtils.writeStringToFile(file, JSON.toJSONString(attr), StandardCharsets.UTF_8); return 0; } catch (IOException e) { throw new IllegalStateException(e); } } protected final DarwinFileAttr loadAttr(File dest) throws IOException { File file = createAttrFile(dest); if (file.exists()) { return JSON.parseObject(FileUtils.readFileToString(file, StandardCharsets.UTF_8), DarwinFileAttr.class); } else { return null; } } protected final int listxattr(File dest, Pointer namebuf, int size) { try { DarwinFileAttr attr = loadAttr(dest); if (attr == null || attr.xattr == null) { return 0; } int ret = 0; Pointer buffer = namebuf; for (String name : attr.xattr.keySet()) { byte[] data = name.getBytes(StandardCharsets.UTF_8); ret += (data.length + 1); if (buffer != null && ret <= size) { buffer.write(0, Arrays.copyOf(data, data.length + 1), 0, data.length + 1); buffer = buffer.share(data.length + 1); } } return ret; } catch (IOException e) { throw new IllegalStateException(e); } } protected final int getxattr(Emulator<?> emulator, File dest, String name, Pointer value, int size) { try { DarwinFileAttr attr = loadAttr(dest); byte[] data = attr == null || attr.xattr == null ? null : attr.xattr.get(name); if (data == null) {
emulator.getMemory().setErrno(UnixEmulator.ENOATTR);
15
2023-10-17 06:13:28+00:00
12k
aabssmc/Skuishy
src/main/java/lol/aabss/skuishy/Skuishy.java
[ { "identifier": "CustomEvents", "path": "src/main/java/lol/aabss/skuishy/events/CustomEvents.java", "snippet": "public class CustomEvents implements Listener {\n\n @EventHandler\n public void onShieldBreak(PlayerItemCooldownEvent e) {\n if (e.getType() == Material.SHIELD) {\n if (e.getCooldown() > 0){\n new ShieldBreakEvent(e.getPlayer()).callEvent();\n }\n }\n }\n\n @EventHandler\n public void onHeadRotate(PlayerMoveEvent e) {\n if (e.getFrom().getX() == e.getTo().getX() && e.getFrom().getY() == e.getTo().getY() && e.getFrom().getZ() == e.getTo().getZ()){\n if (e.getFrom().getYaw() != e.getTo().getYaw() || e.getFrom().getPitch() != e.getTo().getPitch()){\n Bukkit.getServer().getPluginManager().callEvent(new HeadRotationEvent(e.getPlayer(), e.getFrom(), e.getTo()));\n }\n }\n\n }\n}" }, { "identifier": "Metrics", "path": "src/main/java/lol/aabss/skuishy/hooks/Metrics.java", "snippet": "@SuppressWarnings(\"unused\")\npublic class Metrics {\n\n private final Plugin plugin;\n\n private final MetricsBase metricsBase;\n\n /**\n * Creates a new Metrics instance.\n *\n * @param plugin Your plugin instance.\n * @param serviceId The id of the service. It can be found at <a\n * href=\"https://bstats.org/what-is-my-plugin-id\">What is my plugin id?</a>\n */\n public Metrics(JavaPlugin plugin, int serviceId) {\n this.plugin = plugin;\n // Get the config file\n File bStatsFolder = new File(plugin.getDataFolder().getParentFile(), \"bStats\");\n File configFile = new File(bStatsFolder, \"config.yml\");\n FileConfiguration config = YamlConfiguration.loadConfiguration(configFile);\n if (!config.isSet(\"serverUuid\")) {\n config.addDefault(\"enabled\", true);\n config.addDefault(\"serverUuid\", UUID.randomUUID().toString());\n config.addDefault(\"logFailedRequests\", false);\n config.addDefault(\"logSentData\", false);\n config.addDefault(\"logResponseStatusText\", false);\n // Inform the server owners about bStats\n List<String> header = new ArrayList<>();\n header.add(\"\"\"\n bStats (https://bStats.org) collects some basic information for plugin authors, like how\n many people use their plugin and their total player count. It's recommended to keep bStats\n enabled, but if you're not comfortable with this, you can turn this setting off. There is no\n performance penalty associated with having metrics enabled, and data sent to bStats is fully\n anonymous.\"\"\");\n config\n .options()\n .setHeader(header)\n .copyDefaults(true);\n try {\n config.save(configFile);\n } catch (IOException ignored) {\n }\n }\n // Load the data\n boolean enabled = config.getBoolean(\"enabled\", true);\n String serverUUID = config.getString(\"serverUuid\");\n boolean logErrors = config.getBoolean(\"logFailedRequests\", false);\n boolean logSentData = config.getBoolean(\"logSentData\", false);\n boolean logResponseStatusText = config.getBoolean(\"logResponseStatusText\", false);\n metricsBase =\n new MetricsBase(\n \"bukkit\",\n serverUUID,\n serviceId,\n enabled,\n this::appendPlatformData,\n this::appendServiceData,\n submitDataTask -> Bukkit.getScheduler().runTask(plugin, submitDataTask),\n plugin::isEnabled,\n (message, error) -> this.plugin.getLogger().log(Level.WARNING, message, error),\n (message) -> this.plugin.getLogger().log(Level.INFO, message),\n logErrors,\n logSentData,\n logResponseStatusText);\n }\n\n /** Shuts down the underlying scheduler service. */\n public void shutdown() {\n metricsBase.shutdown();\n }\n\n /**\n * Adds a custom chart.\n *\n * @param chart The chart to add.\n */\n public void addCustomChart(CustomChart chart) {\n metricsBase.addCustomChart(chart);\n }\n\n private void appendPlatformData(JsonObjectBuilder builder) {\n builder.appendField(\"playerAmount\", getPlayerAmount());\n builder.appendField(\"onlineMode\", Bukkit.getOnlineMode() ? 1 : 0);\n builder.appendField(\"bukkitVersion\", Bukkit.getVersion());\n builder.appendField(\"bukkitName\", Bukkit.getName());\n builder.appendField(\"javaVersion\", System.getProperty(\"java.version\"));\n builder.appendField(\"osName\", System.getProperty(\"os.name\"));\n builder.appendField(\"osArch\", System.getProperty(\"os.arch\"));\n builder.appendField(\"osVersion\", System.getProperty(\"os.version\"));\n builder.appendField(\"coreCount\", Runtime.getRuntime().availableProcessors());\n }\n\n private void appendServiceData(JsonObjectBuilder builder) {\n builder.appendField(\"pluginVersion\", plugin.getPluginMeta().getVersion());\n }\n\n private int getPlayerAmount() {\n try {\n // Around MC 1.8 the return type was changed from an array to a collection,\n // This fixes java.lang.NoSuchMethodError:\n // org.bukkit.Bukkit.getOnlinePlayers()Ljava/util/Collection;\n Method onlinePlayersMethod = Class.forName(\"org.bukkit.Server\").getMethod(\"getOnlinePlayers\");\n return onlinePlayersMethod.getReturnType().equals(Collection.class)\n ? ((Collection<?>) onlinePlayersMethod.invoke(Bukkit.getServer())).size()\n : ((Player[]) onlinePlayersMethod.invoke(Bukkit.getServer())).length;\n } catch (Exception e) {\n // Just use the new method if the reflection failed\n return Bukkit.getOnlinePlayers().size();\n }\n }\n\n public static class MetricsBase {\n\n /** The version of the Metrics class. */\n public static final String METRICS_VERSION = \"3.0.2\";\n\n private static final String REPORT_URL = \"https://bStats.org/api/v2/data/%s\";\n\n private final ScheduledExecutorService scheduler;\n\n private final String platform;\n\n private final String serverUuid;\n\n private final int serviceId;\n\n private final Consumer<JsonObjectBuilder> appendPlatformDataConsumer;\n\n private final Consumer<JsonObjectBuilder> appendServiceDataConsumer;\n\n private final Consumer<Runnable> submitTaskConsumer;\n\n private final Supplier<Boolean> checkServiceEnabledSupplier;\n\n private final BiConsumer<String, Throwable> errorLogger;\n\n private final Consumer<String> infoLogger;\n\n private final boolean logErrors;\n\n private final boolean logSentData;\n\n private final boolean logResponseStatusText;\n\n private final Set<CustomChart> customCharts = new HashSet<>();\n\n private final boolean enabled;\n\n /**\n * Creates a new MetricsBase class instance.\n *\n * @param platform The platform of the service.\n * @param serviceId The id of the service.\n * @param serverUuid The server uuid.\n * @param enabled Whether or not data sending is enabled.\n * @param appendPlatformDataConsumer A consumer that receives a {@code JsonObjectBuilder} and\n * appends all platform-specific data.\n * @param appendServiceDataConsumer A consumer that receives a {@code JsonObjectBuilder} and\n * appends all service-specific data.\n * @param submitTaskConsumer A consumer that takes a runnable with the submit task. This can be\n * used to delegate the data collection to a another thread to prevent errors caused by\n * concurrency. Can be {@code null}.\n * @param checkServiceEnabledSupplier A supplier to check if the service is still enabled.\n * @param errorLogger A consumer that accepts log message and an error.\n * @param infoLogger A consumer that accepts info log messages.\n * @param logErrors Whether or not errors should be logged.\n * @param logSentData Whether or not the sent data should be logged.\n * @param logResponseStatusText Whether or not the response status text should be logged.\n */\n public MetricsBase(\n String platform,\n String serverUuid,\n int serviceId,\n boolean enabled,\n Consumer<JsonObjectBuilder> appendPlatformDataConsumer,\n Consumer<JsonObjectBuilder> appendServiceDataConsumer,\n Consumer<Runnable> submitTaskConsumer,\n Supplier<Boolean> checkServiceEnabledSupplier,\n BiConsumer<String, Throwable> errorLogger,\n Consumer<String> infoLogger,\n boolean logErrors,\n boolean logSentData,\n boolean logResponseStatusText) {\n ScheduledThreadPoolExecutor scheduler =\n new ScheduledThreadPoolExecutor(1, task -> new Thread(task, \"bStats-Metrics\"));\n // We want delayed tasks (non-periodic) that will execute in the future to be\n // cancelled when the scheduler is shutdown.\n // Otherwise, we risk preventing the server from shutting down even when\n // MetricsBase#shutdown() is called\n scheduler.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);\n this.scheduler = scheduler;\n this.platform = platform;\n this.serverUuid = serverUuid;\n this.serviceId = serviceId;\n this.enabled = enabled;\n this.appendPlatformDataConsumer = appendPlatformDataConsumer;\n this.appendServiceDataConsumer = appendServiceDataConsumer;\n this.submitTaskConsumer = submitTaskConsumer;\n this.checkServiceEnabledSupplier = checkServiceEnabledSupplier;\n this.errorLogger = errorLogger;\n this.infoLogger = infoLogger;\n this.logErrors = logErrors;\n this.logSentData = logSentData;\n this.logResponseStatusText = logResponseStatusText;\n checkRelocation();\n if (enabled) {\n // WARNING: Removing the option to opt-out will get your plugin banned from\n // bStats\n startSubmitting();\n }\n }\n\n public void addCustomChart(CustomChart chart) {\n this.customCharts.add(chart);\n }\n\n public void shutdown() {\n scheduler.shutdown();\n }\n\n private void startSubmitting() {\n final Runnable submitTask =\n () -> {\n if (!enabled || !checkServiceEnabledSupplier.get()) {\n // Submitting data or service is disabled\n scheduler.shutdown();\n return;\n }\n if (submitTaskConsumer != null) {\n submitTaskConsumer.accept(this::submitData);\n } else {\n this.submitData();\n }\n };\n // Many servers tend to restart at a fixed time at xx:00 which causes an uneven\n // distribution of requests on the\n // bStats backend. To circumvent this problem, we introduce some randomness into\n // the initial and second delay.\n // WARNING: You must not modify and part of this Metrics class, including the\n // submit delay or frequency!\n // WARNING: Modifying this code will get your plugin banned on bStats. Just\n // don't do it!\n long initialDelay = (long) (1000 * 60 * (3 + Math.random() * 3));\n long secondDelay = (long) (1000 * 60 * (Math.random() * 30));\n scheduler.schedule(submitTask, initialDelay, TimeUnit.MILLISECONDS);\n scheduler.scheduleAtFixedRate(\n submitTask, initialDelay + secondDelay, 1000 * 60 * 30, TimeUnit.MILLISECONDS);\n }\n\n private void submitData() {\n final JsonObjectBuilder baseJsonBuilder = new JsonObjectBuilder();\n appendPlatformDataConsumer.accept(baseJsonBuilder);\n final JsonObjectBuilder serviceJsonBuilder = new JsonObjectBuilder();\n appendServiceDataConsumer.accept(serviceJsonBuilder);\n JsonObjectBuilder.JsonObject[] chartData =\n customCharts.stream()\n .map(customChart -> customChart.getRequestJsonObject(errorLogger, logErrors))\n .filter(Objects::nonNull)\n .toArray(JsonObjectBuilder.JsonObject[]::new);\n serviceJsonBuilder.appendField(\"id\", serviceId);\n serviceJsonBuilder.appendField(\"customCharts\", chartData);\n baseJsonBuilder.appendField(\"service\", serviceJsonBuilder.build());\n baseJsonBuilder.appendField(\"serverUUID\", serverUuid);\n baseJsonBuilder.appendField(\"metricsVersion\", METRICS_VERSION);\n JsonObjectBuilder.JsonObject data = baseJsonBuilder.build();\n scheduler.execute(\n () -> {\n try {\n // Send the data\n sendData(data);\n } catch (Exception e) {\n // Something went wrong! :(\n if (logErrors) {\n errorLogger.accept(\"Could not submit bStats metrics data\", e);\n }\n }\n });\n }\n\n private void sendData(JsonObjectBuilder.JsonObject data) throws Exception {\n if (logSentData) {\n infoLogger.accept(\"Sent bStats metrics data: \" + data.toString());\n }\n String url = String.format(REPORT_URL, platform);\n HttpsURLConnection connection = (HttpsURLConnection) new URL(url).openConnection();\n // Compress the data to save bandwidth\n byte[] compressedData = compress(data.toString());\n connection.setRequestMethod(\"POST\");\n connection.addRequestProperty(\"Accept\", \"application/json\");\n connection.addRequestProperty(\"Connection\", \"close\");\n connection.addRequestProperty(\"Content-Encoding\", \"gzip\");\n connection.addRequestProperty(\"Content-Length\", String.valueOf(compressedData.length));\n connection.setRequestProperty(\"Content-Type\", \"application/json\");\n connection.setRequestProperty(\"User-Agent\", \"Metrics-Service/1\");\n connection.setDoOutput(true);\n try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) {\n outputStream.write(compressedData);\n }\n StringBuilder builder = new StringBuilder();\n try (BufferedReader bufferedReader =\n new BufferedReader(new InputStreamReader(connection.getInputStream()))) {\n String line;\n while ((line = bufferedReader.readLine()) != null) {\n builder.append(line);\n }\n }\n if (logResponseStatusText) {\n infoLogger.accept(\"Sent data to bStats and received response: \" + builder);\n }\n }\n\n /** Checks that the class was properly relocated. */\n private void checkRelocation() {\n // You can use the property to disable the check in your test environment\n if (System.getProperty(\"bstats.relocatecheck\") == null\n || !System.getProperty(\"bstats.relocatecheck\").equals(\"false\")) {\n // Maven's Relocate is clever and changes strings, too. So we have to use this\n // little \"trick\" ... :D\n final String defaultPackage =\n new String(new byte[] {'o', 'r', 'g', '.', 'b', 's', 't', 'a', 't', 's'});\n final String examplePackage =\n new String(new byte[] {'y', 'o', 'u', 'r', '.', 'p', 'a', 'c', 'k', 'a', 'g', 'e'});\n // We want to make sure no one just copy & pastes the example and uses the wrong\n // package names\n if (MetricsBase.class.getPackage().getName().startsWith(defaultPackage)\n || MetricsBase.class.getPackage().getName().startsWith(examplePackage)) {\n throw new IllegalStateException(\"bStats Metrics class has not been relocated correctly!\");\n }\n }\n }\n\n /**\n * Gzips the given string.\n *\n * @param str The string to gzip.\n * @return The gzipped string.\n */\n private static byte[] compress(final String str) throws IOException {\n if (str == null) {\n return null;\n }\n ByteArrayOutputStream outputStream = new ByteArrayOutputStream();\n try (GZIPOutputStream gzip = new GZIPOutputStream(outputStream)) {\n gzip.write(str.getBytes(StandardCharsets.UTF_8));\n }\n return outputStream.toByteArray();\n }\n }\n\n public static class SimplePie extends CustomChart {\n\n private final Callable<String> callable;\n\n /**\n * Class constructor.\n *\n * @param chartId The id of the chart.\n * @param callable The callable which is used to request the chart data.\n */\n public SimplePie(String chartId, Callable<String> callable) {\n super(chartId);\n this.callable = callable;\n }\n\n @Override\n protected JsonObjectBuilder.JsonObject getChartData() throws Exception {\n String value = callable.call();\n if (value == null || value.isEmpty()) {\n // Null = skip the chart\n return null;\n }\n return new JsonObjectBuilder().appendField(\"value\", value).build();\n }\n }\n\n public static class MultiLineChart extends CustomChart {\n\n private final Callable<Map<String, Integer>> callable;\n\n /**\n * Class constructor.\n *\n * @param chartId The id of the chart.\n * @param callable The callable which is used to request the chart data.\n */\n public MultiLineChart(String chartId, Callable<Map<String, Integer>> callable) {\n super(chartId);\n this.callable = callable;\n }\n\n @Override\n protected JsonObjectBuilder.JsonObject getChartData() throws Exception {\n JsonObjectBuilder valuesBuilder = new JsonObjectBuilder();\n Map<String, Integer> map = callable.call();\n if (map == null || map.isEmpty()) {\n // Null = skip the chart\n return null;\n }\n boolean allSkipped = true;\n for (Map.Entry<String, Integer> entry : map.entrySet()) {\n if (entry.getValue() == 0) {\n // Skip this invalid\n continue;\n }\n allSkipped = false;\n valuesBuilder.appendField(entry.getKey(), entry.getValue());\n }\n if (allSkipped) {\n // Null = skip the chart\n return null;\n }\n return new JsonObjectBuilder().appendField(\"values\", valuesBuilder.build()).build();\n }\n }\n\n public static class AdvancedPie extends CustomChart {\n\n private final Callable<Map<String, Integer>> callable;\n\n /**\n * Class constructor.\n *\n * @param chartId The id of the chart.\n * @param callable The callable which is used to request the chart data.\n */\n public AdvancedPie(String chartId, Callable<Map<String, Integer>> callable) {\n super(chartId);\n this.callable = callable;\n }\n\n @Override\n protected JsonObjectBuilder.JsonObject getChartData() throws Exception {\n JsonObjectBuilder valuesBuilder = new JsonObjectBuilder();\n Map<String, Integer> map = callable.call();\n if (map == null || map.isEmpty()) {\n // Null = skip the chart\n return null;\n }\n boolean allSkipped = true;\n for (Map.Entry<String, Integer> entry : map.entrySet()) {\n if (entry.getValue() == 0) {\n // Skip this invalid\n continue;\n }\n allSkipped = false;\n valuesBuilder.appendField(entry.getKey(), entry.getValue());\n }\n if (allSkipped) {\n // Null = skip the chart\n return null;\n }\n return new JsonObjectBuilder().appendField(\"values\", valuesBuilder.build()).build();\n }\n }\n\n public static class SimpleBarChart extends CustomChart {\n\n private final Callable<Map<String, Integer>> callable;\n\n /**\n * Class constructor.\n *\n * @param chartId The id of the chart.\n * @param callable The callable which is used to request the chart data.\n */\n public SimpleBarChart(String chartId, Callable<Map<String, Integer>> callable) {\n super(chartId);\n this.callable = callable;\n }\n\n @Override\n protected JsonObjectBuilder.JsonObject getChartData() throws Exception {\n JsonObjectBuilder valuesBuilder = new JsonObjectBuilder();\n Map<String, Integer> map = callable.call();\n if (map == null || map.isEmpty()) {\n // Null = skip the chart\n return null;\n }\n for (Map.Entry<String, Integer> entry : map.entrySet()) {\n valuesBuilder.appendField(entry.getKey(), new int[] {entry.getValue()});\n }\n return new JsonObjectBuilder().appendField(\"values\", valuesBuilder.build()).build();\n }\n }\n\n public static class AdvancedBarChart extends CustomChart {\n\n private final Callable<Map<String, int[]>> callable;\n\n /**\n * Class constructor.\n *\n * @param chartId The id of the chart.\n * @param callable The callable which is used to request the chart data.\n */\n public AdvancedBarChart(String chartId, Callable<Map<String, int[]>> callable) {\n super(chartId);\n this.callable = callable;\n }\n\n @Override\n protected JsonObjectBuilder.JsonObject getChartData() throws Exception {\n JsonObjectBuilder valuesBuilder = new JsonObjectBuilder();\n Map<String, int[]> map = callable.call();\n if (map == null || map.isEmpty()) {\n // Null = skip the chart\n return null;\n }\n boolean allSkipped = true;\n for (Map.Entry<String, int[]> entry : map.entrySet()) {\n if (entry.getValue().length == 0) {\n // Skip this invalid\n continue;\n }\n allSkipped = false;\n valuesBuilder.appendField(entry.getKey(), entry.getValue());\n }\n if (allSkipped) {\n // Null = skip the chart\n return null;\n }\n return new JsonObjectBuilder().appendField(\"values\", valuesBuilder.build()).build();\n }\n }\n\n public static class DrilldownPie extends CustomChart {\n\n private final Callable<Map<String, Map<String, Integer>>> callable;\n\n /**\n * Class constructor.\n *\n * @param chartId The id of the chart.\n * @param callable The callable which is used to request the chart data.\n */\n public DrilldownPie(String chartId, Callable<Map<String, Map<String, Integer>>> callable) {\n super(chartId);\n this.callable = callable;\n }\n\n @Override\n public JsonObjectBuilder.JsonObject getChartData() throws Exception {\n JsonObjectBuilder valuesBuilder = new JsonObjectBuilder();\n Map<String, Map<String, Integer>> map = callable.call();\n if (map == null || map.isEmpty()) {\n // Null = skip the chart\n return null;\n }\n boolean reallyAllSkipped = true;\n for (Map.Entry<String, Map<String, Integer>> entryValues : map.entrySet()) {\n JsonObjectBuilder valueBuilder = new JsonObjectBuilder();\n boolean allSkipped = true;\n for (Map.Entry<String, Integer> valueEntry : map.get(entryValues.getKey()).entrySet()) {\n valueBuilder.appendField(valueEntry.getKey(), valueEntry.getValue());\n allSkipped = false;\n }\n if (!allSkipped) {\n reallyAllSkipped = false;\n valuesBuilder.appendField(entryValues.getKey(), valueBuilder.build());\n }\n }\n if (reallyAllSkipped) {\n // Null = skip the chart\n return null;\n }\n return new JsonObjectBuilder().appendField(\"values\", valuesBuilder.build()).build();\n }\n }\n\n public abstract static class CustomChart {\n\n private final String chartId;\n\n protected CustomChart(String chartId) {\n if (chartId == null) {\n throw new IllegalArgumentException(\"chartId must not be null\");\n }\n this.chartId = chartId;\n }\n\n public JsonObjectBuilder.JsonObject getRequestJsonObject(\n BiConsumer<String, Throwable> errorLogger, boolean logErrors) {\n JsonObjectBuilder builder = new JsonObjectBuilder();\n builder.appendField(\"chartId\", chartId);\n try {\n JsonObjectBuilder.JsonObject data = getChartData();\n if (data == null) {\n // If the data is null we don't send the chart.\n return null;\n }\n builder.appendField(\"data\", data);\n } catch (Throwable t) {\n if (logErrors) {\n errorLogger.accept(\"Failed to get data for custom chart with id \" + chartId, t);\n }\n return null;\n }\n return builder.build();\n }\n\n protected abstract JsonObjectBuilder.JsonObject getChartData() throws Exception;\n }\n\n public static class SingleLineChart extends CustomChart {\n\n private final Callable<Integer> callable;\n\n /**\n * Class constructor.\n *\n * @param chartId The id of the chart.\n * @param callable The callable which is used to request the chart data.\n */\n public SingleLineChart(String chartId, Callable<Integer> callable) {\n super(chartId);\n this.callable = callable;\n }\n\n @Override\n protected JsonObjectBuilder.JsonObject getChartData() throws Exception {\n int value = callable.call();\n if (value == 0) {\n // Null = skip the chart\n return null;\n }\n return new JsonObjectBuilder().appendField(\"value\", value).build();\n }\n }\n\n /**\n * An extremely simple JSON builder.\n *\n * <p>While this class is neither feature-rich nor the most performant one, it's sufficient enough\n * for its use-case.\n */\n public static class JsonObjectBuilder {\n\n private StringBuilder builder = new StringBuilder();\n\n private boolean hasAtLeastOneField = false;\n\n public JsonObjectBuilder() {\n builder.append(\"{\");\n }\n\n /**\n * Appends a null field to the JSON.\n *\n * @param key The key of the field.\n * @return A reference to this object.\n */\n public JsonObjectBuilder appendNull(String key) {\n appendFieldUnescaped(key, \"null\");\n return this;\n }\n\n /**\n * Appends a string field to the JSON.\n *\n * @param key The key of the field.\n * @param value The value of the field.\n * @return A reference to this object.\n */\n public JsonObjectBuilder appendField(String key, String value) {\n if (value == null) {\n throw new IllegalArgumentException(\"JSON value must not be null\");\n }\n appendFieldUnescaped(key, \"\\\"\" + escape(value) + \"\\\"\");\n return this;\n }\n\n /**\n * Appends an integer field to the JSON.\n *\n * @param key The key of the field.\n * @param value The value of the field.\n * @return A reference to this object.\n */\n public JsonObjectBuilder appendField(String key, int value) {\n appendFieldUnescaped(key, String.valueOf(value));\n return this;\n }\n\n /**\n * Appends an object to the JSON.\n *\n * @param key The key of the field.\n * @param object The object.\n * @return A reference to this object.\n */\n public JsonObjectBuilder appendField(String key, JsonObject object) {\n if (object == null) {\n throw new IllegalArgumentException(\"JSON object must not be null\");\n }\n appendFieldUnescaped(key, object.toString());\n return this;\n }\n\n /**\n * Appends a string array to the JSON.\n *\n * @param key The key of the field.\n * @param values The string array.\n * @return A reference to this object.\n */\n public JsonObjectBuilder appendField(String key, String[] values) {\n if (values == null) {\n throw new IllegalArgumentException(\"JSON values must not be null\");\n }\n String escapedValues =\n Arrays.stream(values)\n .map(value -> \"\\\"\" + escape(value) + \"\\\"\")\n .collect(Collectors.joining(\",\"));\n appendFieldUnescaped(key, \"[\" + escapedValues + \"]\");\n return this;\n }\n\n /**\n * Appends an integer array to the JSON.\n *\n * @param key The key of the field.\n * @param values The integer array.\n * @return A reference to this object.\n */\n public JsonObjectBuilder appendField(String key, int[] values) {\n if (values == null) {\n throw new IllegalArgumentException(\"JSON values must not be null\");\n }\n String escapedValues =\n Arrays.stream(values).mapToObj(String::valueOf).collect(Collectors.joining(\",\"));\n appendFieldUnescaped(key, \"[\" + escapedValues + \"]\");\n return this;\n }\n\n /**\n * Appends an object array to the JSON.\n *\n * @param key The key of the field.\n * @param values The integer array.\n * @return A reference to this object.\n */\n public JsonObjectBuilder appendField(String key, JsonObject[] values) {\n if (values == null) {\n throw new IllegalArgumentException(\"JSON values must not be null\");\n }\n String escapedValues =\n Arrays.stream(values).map(JsonObject::toString).collect(Collectors.joining(\",\"));\n appendFieldUnescaped(key, \"[\" + escapedValues + \"]\");\n return this;\n }\n\n /**\n * Appends a field to the object.\n *\n * @param key The key of the field.\n * @param escapedValue The escaped value of the field.\n */\n private void appendFieldUnescaped(String key, String escapedValue) {\n if (builder == null) {\n throw new IllegalStateException(\"JSON has already been built\");\n }\n if (key == null) {\n throw new IllegalArgumentException(\"JSON key must not be null\");\n }\n if (hasAtLeastOneField) {\n builder.append(\",\");\n }\n builder.append(\"\\\"\").append(escape(key)).append(\"\\\":\").append(escapedValue);\n hasAtLeastOneField = true;\n }\n\n /**\n * Builds the JSON string and invalidates this builder.\n *\n * @return The built JSON string.\n */\n public JsonObject build() {\n if (builder == null) {\n throw new IllegalStateException(\"JSON has already been built\");\n }\n JsonObject object = new JsonObject(builder.append(\"}\").toString());\n builder = null;\n return object;\n }\n\n /**\n * Escapes the given string like stated in https://www.ietf.org/rfc/rfc4627.txt.\n *\n * <p>This method escapes only the necessary characters '\"', '\\'. and '\\u0000' - '\\u001F'.\n * Compact escapes are not used (e.g., '\\n' is escaped as \"\\u000a\" and not as \"\\n\").\n *\n * @param value The value to escape.\n * @return The escaped value.\n */\n private static String escape(String value) {\n final StringBuilder builder = new StringBuilder();\n for (int i = 0; i < value.length(); i++) {\n char c = value.charAt(i);\n if (c == '\"') {\n builder.append(\"\\\\\\\"\");\n } else if (c == '\\\\') {\n builder.append(\"\\\\\\\\\");\n } else if (c <= '\\u000F') {\n builder.append(\"\\\\u000\").append(Integer.toHexString(c));\n } else if (c <= '\\u001F') {\n builder.append(\"\\\\u00\").append(Integer.toHexString(c));\n } else {\n builder.append(c);\n }\n }\n return builder.toString();\n }\n\n /**\n * A super simple representation of a JSON object.\n *\n * <p>This class only exists to make methods of the {@link JsonObjectBuilder} type-safe and not\n * allow a raw string inputs for methods like {@link JsonObjectBuilder#appendField(String,\n * JsonObject)}.\n */\n public static class JsonObject {\n\n private final String value;\n\n private JsonObject(String value) {\n this.value = value;\n }\n\n @Override\n public String toString() {\n return value;\n }\n }\n }\n}" } ]
import ch.njol.skript.Skript; import ch.njol.skript.SkriptAddon; import lol.aabss.skuishy.events.CustomEvents; import lol.aabss.skuishy.hooks.Metrics; import org.bukkit.Bukkit; import org.bukkit.plugin.java.JavaPlugin; import java.io.IOException;
7,552
package lol.aabss.skuishy; public class Skuishy extends JavaPlugin{ public static Skuishy instance; private SkriptAddon addon; public static long start = System.currentTimeMillis()/50; public void onEnable() {
package lol.aabss.skuishy; public class Skuishy extends JavaPlugin{ public static Skuishy instance; private SkriptAddon addon; public static long start = System.currentTimeMillis()/50; public void onEnable() {
getServer().getPluginManager().registerEvents(new CustomEvents(), this);
0
2023-10-24 23:48:14+00:00
12k
histevehu/12306
business/src/main/java/com/steve/train/business/mq/ConfirmOrderConsumer.java
[ { "identifier": "ConfirmOrderMQDTO", "path": "business/src/main/java/com/steve/train/business/dto/ConfirmOrderMQDTO.java", "snippet": "public class ConfirmOrderMQDTO {\n /**\n * 日志流程号,用于同转异时,用同一个流水号\n */\n private String logId;\n\n /**\n * 日期\n */\n private Date date;\n\n /**\n * 车次编号\n */\n private String trainCode;\n\n public String getLogId() {\n return logId;\n }\n\n public void setLogId(String logId) {\n this.logId = logId;\n }\n\n public Date getDate() {\n return date;\n }\n\n public void setDate(Date date) {\n this.date = date;\n }\n\n public String getTrainCode() {\n return trainCode;\n }\n\n public void setTrainCode(String trainCode) {\n this.trainCode = trainCode;\n }\n\n @Override\n public String toString() {\n final StringBuilder sb = new StringBuilder(\"ConfirmOrderMQDto{\");\n sb.append(\"logId=\").append(logId);\n sb.append(\", date=\").append(date);\n sb.append(\", trainCode='\").append(trainCode).append('\\'');\n sb.append('}');\n return sb.toString();\n }\n}" }, { "identifier": "ConfirmOrderService", "path": "business/src/main/java/com/steve/train/business/service/ConfirmOrderService.java", "snippet": "@Service\npublic class ConfirmOrderService {\n\n private static final Logger LOG = LoggerFactory.getLogger(ConfirmOrderService.class);\n\n @Resource\n private ConfirmOrderMapper confirmOrderMapper;\n @Resource\n private DailyTrainTicketService dailyTrainTicketService;\n @Resource\n private DailyTrainCarriageService dailyTrainCarriageService;\n @Resource\n private DailyTrainSeatService dailyTrainSeatService;\n @Resource\n private AfterConfirmOrderService afterConfirmOrderService;\n\n @Resource\n private SkTokenService skTokenService;\n\n /**\n * 注意:@AutoWired按byType自动注入,⽽@Resource默认按byName自动注入,即直接根据bean的ID进⾏注⼊。<br><br>\n * 使用JDK的@Resource:会根据变量名去查找原始类。比如,在 {@link RedisController}中我们声明了变量{@link RedisController#redisTemplate},JDK会根据变量名查找{@link RedisTemplate}类并注入。而在这里如果我们将{@link StringRedisTemplate}类型的变量命名为{@link ConfirmOrderService#redisTemplate}则JDK会找到{@link RedisTemplate}类,这与声明的{@link StringRedisTemplate}不符,则会报错:Bean named 'redisTemplate' is expected to be of type 'org.springframework.data.redis.core.StringRedisTemplate' but was actually of type 'org.springframework.data.redis.core.RedisTemplate'。<br><br>\n * 使用Spring的@AutoWired:会根据变量类型去常量池找该类型的变量。\n */\n // @Resource\n @Autowired\n private StringRedisTemplate redisTemplate;\n\n @Autowired\n private RedissonClient redissonClient;\n\n\n public void save(ConfirmOrderDoReq req) {\n DateTime now = DateTime.now();\n ConfirmOrder confirmOrder = BeanUtil.copyProperties(req, ConfirmOrder.class);\n if (ObjectUtil.isNull(confirmOrder.getId())) {\n confirmOrder.setId(SnowFlakeUtil.getSnowFlakeNextId());\n confirmOrder.setCreateTime(now);\n confirmOrder.setUpdateTime(now);\n confirmOrderMapper.insert(confirmOrder);\n } else {\n confirmOrder.setUpdateTime(now);\n confirmOrderMapper.updateByPrimaryKey(confirmOrder);\n }\n }\n\n public PageResp<ConfirmOrderQueryResp> queryList(ConfirmOrderQueryReq req) {\n ConfirmOrderExample confirmOrderExample = new ConfirmOrderExample();\n confirmOrderExample.setOrderByClause(\"id asc\");\n ConfirmOrderExample.Criteria criteria = confirmOrderExample.createCriteria();\n\n LOG.info(\"查询页码:{}\", req.getPage());\n LOG.info(\"每页条数:{}\", req.getSize());\n PageHelper.startPage(req.getPage(), req.getSize());\n List<ConfirmOrder> confirmOrderList = confirmOrderMapper.selectByExample(confirmOrderExample);\n\n PageInfo<ConfirmOrder> pageInfo = new PageInfo<>(confirmOrderList);\n LOG.info(\"总行数:{}\", pageInfo.getTotal());\n LOG.info(\"总页数:{}\", pageInfo.getPages());\n\n List<ConfirmOrderQueryResp> list = BeanUtil.copyToList(confirmOrderList, ConfirmOrderQueryResp.class);\n\n PageResp<ConfirmOrderQueryResp> pageResp = new PageResp<>();\n pageResp.setTotal(pageInfo.getTotal());\n pageResp.setList(list);\n return pageResp;\n }\n\n public void delete(Long id) {\n confirmOrderMapper.deleteByPrimaryKey(id);\n }\n\n /**\n * 出票业务流程。\n * 注意:当一个消费者拿到了某个车次锁,则该车次下所有的票都由他来出,一张一张出,直到所有的订单都出完\n *\n * @param dto\n */\n @SentinelResource(value = \"doConfirm\", blockHandler = \"doConfirmBlock\")\n // 单机学习也使用Spring自带异步线程以替代MQ\n // 注意:和@Transactional一样,必须是外部类调用本方法才可生效,因为@Async注解会生成一个代理类,而只有当外部类调用才会生成,内部类调用本方法无效\n // @Async\n public void doConfirm(ConfirmOrderMQDTO dto) {\n // 若使用@Async或MQ异步处理启用了新的线程,原服务中的事件流水号不会自动传递过来,需要通过req对象传递\n // 同理,若使用Spring自带的@Async,也需要手动传递事件流水号\n MDC.put(\"LOG_ID\", dto.getLogId());\n LOG.info(\"异步出票开始:{}\", dto);\n // 为该日期该车次生成Redis分布式锁key\n String dlConfirmKey = RedisKeyTypeEnum.DL_CONFIRM_ORDER.getCode() + \"-\" + DateUtil.formatDate(dto.getDate()) + \"-\" + dto.getTrainCode();\n // 获取基本的Redis分布锁\n /* Boolean redisDL = redisTemplate.opsForValue().setIfAbsent(dlKey, dlKey, 60, TimeUnit.SECONDS);\n if (Boolean.TRUE.equals(redisDL)) {\n LOG.info(\"获得分布式锁,lockKey:{}\", dlKey);\n } else {\n // 只是没抢到锁,并不知道票抢完了没,所以提示稍候再试\n // LOG.info(\"很遗憾,没抢到锁!lockKey:{}\", lockKey);\n LOG.warn(\"获得分布式锁失败,lockKey:{}\", dlKey);\n throw new BusinessException(BusinessExceptionEnum.CONFIRM_ORDER_LOCK_FAIL);\n }*/\n\n // 问题1:线程执行时间超过锁时间,会导致锁失效,从而出现超卖\n // 解决方案1:引入看门狗(守护线程)(项目主流使用此方案):定时查询锁剩余时间,当小于一定值时自动延时。使用守护线程的好处是会随主线程的结束而结束,所以不会出现一直重置而永不过期的问题\n // 使用看门狗守护进程方案:\n RLock dlConfirm = null;\n boolean watchDogLock = false;\n try {\n dlConfirm = redissonClient.getLock(dlConfirmKey);\n watchDogLock = dlConfirm.tryLock(0, TimeUnit.SECONDS);\n } catch (InterruptedException e) {\n LOG.warn(\"看门狗尝试获得购票分布锁发生错误,{}\", e.getMessage());\n throw new RuntimeException(e);\n }\n if (watchDogLock) {\n LOG.info(\"看门狗获得购票分布锁成功\");\n } else {\n LOG.warn(\"看门狗获得购票分布锁失败,有其它消费线程正在出票,不做任何处理\");\n // 不必抛出异常,因为MQ消费者抛出异常没有对应处理方法,没有意义\n return;\n }\n\n // 问题2:Redis集群宕机,不同的请求在新老结点中都获取到了锁\n // 解决方案2:Redis红锁,一个分布式锁由多个节点共同维护,每个节点通过竞争获得锁。算法要求至少半数以上的节点成功获取锁才算锁获取成功。由于开销大,项目一般很少使用。\n // 使用Redis红锁方案:(假设有3个节点,则至少要获得⌊3/2⌋+1=2个节点的锁)\n /*RLock lock1 = redissonClient1.getLock(dlKey);\n RLock lock2 = redissonClient2.getLock(dlKey);\n RLock lock3 = redissonClient3.getLock(dlKey);\n RedissonRedLock redissonRedLock=new RedissonRedLock(lock1,lock2,lock3);\n boolean tryRedLock=redissonRedLock.tryLock(0, TimeUnit.SECONDS);\n if (tryRedLock) {\n ...后续代码同看门狗方案\n */\n\n // 本消费者获得了该车次的购票分布锁,代表其拥有了售卖该日期车次的权限。无论有多少订单,都由本消费者来处理\n try {\n // 循环处理订单。该车次下所有的票都由本消费者来出,一张一张出,直到所有的订单都出完\n while (true) {\n // 查询确认订单表中指定日期&指定车次&处于初始状态的订单记录,\n ConfirmOrderExample confirmOrderExample = new ConfirmOrderExample();\n confirmOrderExample.setOrderByClause(\"id asc\");\n ConfirmOrderExample.Criteria criteria = confirmOrderExample.createCriteria();\n criteria.andDateEqualTo(dto.getDate())\n .andTrainCodeEqualTo(dto.getTrainCode())\n .andStatusEqualTo(ConfirmOrderStatusEnum.INIT.getCode());\n // 分页处理,每次取N条。后端处理大批量数据的常用做法,使用分页处理,而不是一次性查到内存里。\n PageHelper.startPage(1, 5);\n List<ConfirmOrder> list = confirmOrderMapper.selectByExampleWithBLOBs(confirmOrderExample);\n if (CollUtil.isEmpty(list)) {\n LOG.info(\"没有需要处理的订单,结束循环\");\n break;\n } else {\n LOG.info(\"本次处理{}条订单\", list.size());\n }\n // 逐条地卖\n list.forEach(confirmOrder -> {\n // 即使该订单出票出现异常,也不能影响处理下一个订单\n try {\n sell(confirmOrder);\n } catch (BusinessException e) {\n if (e.getE().equals(BusinessExceptionEnum.CONFIRM_ORDER_TICKET_COUNT_ERROR)) {\n LOG.info(\"本订单余票不足,继续售卖下一个订单\");\n confirmOrder.setStatus(ConfirmOrderStatusEnum.EMPTY.getCode());\n updateStatus(confirmOrder);\n } else {\n throw e;\n }\n }\n });\n }\n } finally {\n // 当分布锁非空且为当前线程所持有时,释放锁\n // 释放购票分布锁\n if (null != dlConfirm && dlConfirm.isHeldByCurrentThread()) {\n LOG.info(\"购票流程结束,释放购票分布锁。key:{}\", dlConfirmKey);\n dlConfirm.unlock();\n }\n }\n\n }\n\n /**\n * 降级方法,需包含限流原方法的所有参数+BlockException参数\n */\n public void doConfirmBlock(ConfirmOrderDoReq req, BlockException e) {\n LOG.info(\"购票请求被限流:{}\", req);\n throw new BusinessException(BusinessExceptionEnum.CONFIRM_ORDER_FLOW_EXCEPTION);\n }\n\n /**\n * 售票\n */\n // TODO:省略业务数据校验,如:车次是否存在、余票是否存在、车次是否在有效期内、tickets条数>0\n // TODO:省略同乘客同车次是否已经买过\n private void sell(ConfirmOrder confirmOrder) {\n // 构造ConfirmOrderDoReq\n ConfirmOrderDoReq req = new ConfirmOrderDoReq();\n req.setMemberId(confirmOrder.getMemberId());\n req.setDate(confirmOrder.getDate());\n req.setTrainCode(confirmOrder.getTrainCode());\n req.setStart(confirmOrder.getStart());\n req.setEnd(confirmOrder.getEnd());\n req.setDailyTrainTicketId(confirmOrder.getDailyTrainTicketId());\n req.setTickets(JSON.parseArray(confirmOrder.getTickets(), ConfirmOrderTicketReq.class));\n req.setImageCode(\"\");\n req.setImageCodeToken(\"\");\n req.setLogId(\"\");\n // 将确认订单的状态更新为处理中,避免重复处理\n confirmOrder.setStatus(ConfirmOrderStatusEnum.PENDING.getCode());\n updateStatus(confirmOrder);\n LOG.info(\"confirm_order[{}]状态更新为处理中\", confirmOrder.getId());\n\n Date date = req.getDate();\n String trainCode = req.getTrainCode();\n String start = req.getStart();\n String end = req.getEnd();\n // 查出余票记录,需要得到真实的库存\n DailyTrainTicket dailyTrainTicket = dailyTrainTicketService.selectByUnique(date, trainCode, start, end);\n LOG.info(\"查出余票记录:{}\", dailyTrainTicket);\n\n // 扣减余票数量,并判断余票是否足够\n reduceTickets(req, dailyTrainTicket);\n\n // 计算相对于第一个座位的偏移值\n // 比如选择的是c1,d2,则偏移值是:[0,5]\n // 比如选择的是a1,b1,c1,则偏移值是:[0,1,2]\n List<ConfirmOrderTicketReq> tickets = req.getTickets();\n List<DailyTrainSeat> finalSeatList = new ArrayList<>();\n ConfirmOrderTicketReq ticketReq0 = tickets.get(0);\n // 因为如果选座则该订单所有购票都为选座,所以通过第一张票的选座字段是否为空可以判断该订单的所有车票是否为选座票\n if (StrUtil.isNotBlank(ticketReq0.getSeat())) {\n LOG.info(\"本次购票有选座\");\n // 查出本次选座的座位类型都有哪些列,用于计算所选座位与第一个座位的偏离值\n List<SeatColEnum> colEnumList = SeatColEnum.getColsByType(ticketReq0.getSeatTypeCode());\n LOG.info(\"本次选座的座位类型包含的列:{}\", colEnumList);\n // 组成和前端两排选座一样的列表,用于作参照的座位列表,例:referSeatList = {A1, C1, D1, F1, A2, C2, D2, F2}\n List<String> referSeatList = new ArrayList<>();\n for (int i = 1; i <= 2; i++) {\n for (SeatColEnum seatColEnum : colEnumList) {\n referSeatList.add(seatColEnum.getCode() + i);\n }\n }\n LOG.info(\"用于作参照的两排座位:{}\", referSeatList);\n\n List<Integer> offsetList = new ArrayList<>();\n // 绝对偏移值,即:在参照座位列表中的位置\n List<Integer> aboluteOffsetList = new ArrayList<>();\n for (ConfirmOrderTicketReq ticketReq : tickets) {\n int index = referSeatList.indexOf(ticketReq.getSeat());\n aboluteOffsetList.add(index);\n }\n LOG.info(\"计算得到所有座位的绝对偏移值:{}\", aboluteOffsetList);\n for (Integer index : aboluteOffsetList) {\n int offset = index - aboluteOffsetList.get(0);\n offsetList.add(offset);\n }\n LOG.info(\"计算得到所有座位的相对第一个座位的偏移值:{}\", offsetList);\n // 选座\n // 一个车箱一个车箱的获取座位数据\n // 挑选符合条件的座位,如果这个车箱不满足,则进入下个车箱(多个选座应该在同一个车厢内)\n getSeat(finalSeatList, date, trainCode, ticketReq0.getSeatTypeCode(), ticketReq0.getSeat().split(\"\")[0], // 第一个座位的列名,如从A1得到A\n offsetList, dailyTrainTicket.getStartIndex(), dailyTrainTicket.getEndIndex());\n\n } else {\n LOG.info(\"本次购票没有选座\");\n for (ConfirmOrderTicketReq ticketReq : tickets) {\n getSeat(finalSeatList, date, trainCode, ticketReq.getSeatTypeCode(), null, null, dailyTrainTicket.getStartIndex(), dailyTrainTicket.getEndIndex());\n }\n }\n LOG.info(\"最终选座:{}\", finalSeatList);\n\n // 选中座位后事务处理:\n // 座位表修改售卖情况sell;\n // 余票详情表修改余票;\n // 为会员增加购票记录\n // 更新确认订单为成功\n try {\n afterConfirmOrderService.afterDoConfirm(dailyTrainTicket, finalSeatList, tickets, confirmOrder);\n } catch (Exception e) {\n LOG.error(\"保存购票信息失败\", e);\n throw new BusinessException(BusinessExceptionEnum.CONFIRM_ORDER_EXCEPTION);\n }\n }\n\n /**\n * 更新订单状态\n */\n public void updateStatus(ConfirmOrder confirmOrder) {\n ConfirmOrder confirmOrderForUpdate = new ConfirmOrder();\n confirmOrderForUpdate.setId(confirmOrder.getId());\n confirmOrderForUpdate.setUpdateTime(new Date());\n confirmOrderForUpdate.setStatus(confirmOrder.getStatus());\n confirmOrderMapper.updateByPrimaryKeySelective(confirmOrderForUpdate);\n }\n\n /**\n * 扣减余票\n */\n private static void reduceTickets(ConfirmOrderDoReq req, DailyTrainTicket dailyTrainTicket) {\n for (ConfirmOrderTicketReq ticketReq : req.getTickets()) {\n String seatTypeCode = ticketReq.getSeatTypeCode();\n // 循环SeatTypeEnum的枚举类的getCode方法,直到值等于目标值seatTypeCode,返回该枚举类\n SeatTypeEnum seatTypeEnum = EnumUtil.getBy(SeatTypeEnum::getCode, seatTypeCode);\n switch (seatTypeEnum) {\n case YDZ -> {\n int countLeft = dailyTrainTicket.getYdz() - 1;\n if (countLeft < 0) {\n throw new BusinessException(BusinessExceptionEnum.CONFIRM_ORDER_TICKET_COUNT_ERROR);\n }\n dailyTrainTicket.setYdz(countLeft);\n }\n case EDZ -> {\n int countLeft = dailyTrainTicket.getEdz() - 1;\n if (countLeft < 0) {\n throw new BusinessException(BusinessExceptionEnum.CONFIRM_ORDER_TICKET_COUNT_ERROR);\n }\n dailyTrainTicket.setEdz(countLeft);\n }\n case RW -> {\n int countLeft = dailyTrainTicket.getRw() - 1;\n if (countLeft < 0) {\n throw new BusinessException(BusinessExceptionEnum.CONFIRM_ORDER_TICKET_COUNT_ERROR);\n }\n dailyTrainTicket.setRw(countLeft);\n }\n case YW -> {\n int countLeft = dailyTrainTicket.getYw() - 1;\n if (countLeft < 0) {\n throw new BusinessException(BusinessExceptionEnum.CONFIRM_ORDER_TICKET_COUNT_ERROR);\n }\n dailyTrainTicket.setYw(countLeft);\n }\n }\n }\n }\n\n /**\n * 挑座位,如果有选座,则一次性挑完,如果无选座,则一个一个挑\n *\n * @param date\n * @param trainCode\n * @param seatType\n * @param column\n * @param offsetList\n */\n private void getSeat(List<DailyTrainSeat> finalSeatList, Date date, String trainCode, String seatType, String column, List<Integer> offsetList, Integer startIndex, Integer endIndex) {\n List<DailyTrainSeat> getSeatList;\n List<DailyTrainCarriage> carriageList = dailyTrainCarriageService.selectBySeatType(date, trainCode, seatType);\n LOG.info(\"共查出{}个符合条件的车厢\", carriageList.size());\n\n // 遍历每个车厢\n for (DailyTrainCarriage dailyTrainCarriage : carriageList) {\n LOG.info(\"开始从车厢{}选座\", dailyTrainCarriage.getIndex());\n getSeatList = new ArrayList<>();\n List<DailyTrainSeat> seatList = dailyTrainSeatService.selectByCarriage(date, trainCode, dailyTrainCarriage.getIndex());\n LOG.info(\"车厢{}的座位数:{}\", dailyTrainCarriage.getIndex(), seatList.size());\n // 遍历当前车厢的每个座位\n for (int i = 0; i < seatList.size(); i++) {\n DailyTrainSeat dailyTrainSeat = seatList.get(i);\n // 该座位在当前车厢的绝对位置编号\n Integer seatIndex = dailyTrainSeat.getCarriageSeatIndex();\n // 该座位的列名\n String col = dailyTrainSeat.getCol();\n // 判断当前座位不能被选中过\n boolean alreadyChooseFlag = false;\n // 通过遍历已经决定的座位列表,看看当前座位是否已经被选中\n for (DailyTrainSeat finalSeat : finalSeatList) {\n // 根据id是否存在来判断,不能判断对象,因为选中后,sell信息会被更新,对象信息变了\n if (finalSeat.getId().equals(dailyTrainSeat.getId())) {\n alreadyChooseFlag = true;\n break;\n }\n }\n if (alreadyChooseFlag) {\n LOG.info(\"座位{}被选中过,不能重复选中,继续判断下一个座位\", seatIndex);\n continue;\n }\n\n // 判断column,有值的话要比对列号\n if (StrUtil.isBlank(column)) {\n LOG.info(\"无选座\");\n } else {\n if (!column.equals(col)) {\n LOG.info(\"座位{}列值不对,继续判断下一个座位,当前列值:{},目标列值:{}\", seatIndex, col, column);\n continue;\n }\n }\n\n boolean isChoose = calSell(dailyTrainSeat, startIndex, endIndex);\n if (isChoose) {\n LOG.info(\"选中座位\");\n getSeatList.add(dailyTrainSeat);\n } else {\n continue;\n }\n\n // 根据offset选剩下的座位\n boolean isGetAllOffsetSeat = true;\n if (CollUtil.isNotEmpty(offsetList)) {\n LOG.info(\"有偏移值:{},校验偏移的座位是否可选\", offsetList);\n // 从索引1开始,索引0就是当前已选中的票\n for (int j = 1; j < offsetList.size(); j++) {\n Integer offset = offsetList.get(j);\n // 座位在库的索引是从1开始\n // int nextIndex = seatIndex + offset - 1;\n int nextIndex = i + offset;\n // 有选座时,一定要是在同一个车箱\n if (nextIndex >= seatList.size()) {\n LOG.info(\"座位{}不可选,偏移后的索引超出了这个车箱的座位数\", nextIndex);\n isGetAllOffsetSeat = false;\n break;\n }\n\n DailyTrainSeat nextDailyTrainSeat = seatList.get(nextIndex);\n boolean isChooseNext = calSell(nextDailyTrainSeat, startIndex, endIndex);\n if (isChooseNext) {\n LOG.info(\"座位{}被选中\", nextDailyTrainSeat.getCarriageSeatIndex());\n getSeatList.add(nextDailyTrainSeat);\n } else {\n LOG.info(\"座位{}不可选\", nextDailyTrainSeat.getCarriageSeatIndex());\n isGetAllOffsetSeat = false;\n break;\n }\n }\n }\n if (!isGetAllOffsetSeat) {\n getSeatList = new ArrayList<>();\n continue;\n }\n\n // 保存选好的座位\n finalSeatList.addAll(getSeatList);\n return;\n }\n }\n }\n\n /**\n * 计算某座位在区间内是否可卖\n * 例:sell=10001,本次购买区间站1~4,则区间已售000\n * 全部是0,表示这个区间可买;只要有1,就表示区间内已售过票\n * 选中后,要计算购票后的sell,比如原来是10001,本次购买区间站1~4\n * 方案:构造本次购票造成的售卖信息01110,和原sell 10001按位或,最终得到11111\n */\n private boolean calSell(DailyTrainSeat dailyTrainSeat, Integer startIndex, Integer endIndex) {\n // 00001, 00000\n String sell = dailyTrainSeat.getSell();\n // 000, 000\n String sellPart = sell.substring(startIndex, endIndex);\n if (Integer.parseInt(sellPart) > 0) {\n LOG.info(\"座位{}在本次车站区间{}~{}已售过票,不可选中该座位\", dailyTrainSeat.getCarriageSeatIndex(), startIndex, endIndex);\n return false;\n } else {\n LOG.info(\"座位{}在本次车站区间{}~{}未售过票,可选中该座位\", dailyTrainSeat.getCarriageSeatIndex(), startIndex, endIndex);\n // 111, 111\n String curSell = sellPart.replace('0', '1');\n // 0111, 0111\n curSell = StrUtil.fillBefore(curSell, '0', endIndex);\n // 01110, 01110\n curSell = StrUtil.fillAfter(curSell, '0', sell.length());\n\n // 当前区间售票信息curSell 01110与库里的已售信息sell 00001按位或,即可得到该座位卖出此票后的售票详情\n // 15(01111), 14(01110 = 01110|00000)\n // .binaryToInt将二进制字符串转为int整数,再做与运算\n int newSellInt = NumberUtil.binaryToInt(curSell) | NumberUtil.binaryToInt(sell);\n // 1111, 1110\n // 再将整数转为二进制字符串\n String newSell = NumberUtil.getBinaryStr(newSellInt);\n // 01111, 01110\n newSell = StrUtil.fillBefore(newSell, '0', sell.length());\n LOG.info(\"座位{}被选中,原售票信息:{},车站区间:{}~{},即:{},最终售票信息:{}\", dailyTrainSeat.getCarriageSeatIndex(), sell, startIndex, endIndex, curSell, newSell);\n dailyTrainSeat.setSell(newSell);\n return true;\n\n }\n }\n\n\n /**\n * 查询订单处理状态\n *\n * @param id 订单ID\n * @return 返回状态码或者实际排队数量\n */\n public Integer queryLineCount(Long id) {\n ConfirmOrder confirmOrder = confirmOrderMapper.selectByPrimaryKey(id);\n ConfirmOrderStatusEnum statusEnum = EnumUtil.getBy(ConfirmOrderStatusEnum::getCode, confirmOrder.getStatus());\n return switch (statusEnum) {\n case PENDING -> 0; // 排队0\n case SUCCESS -> -1; // 成功\n case FAILURE -> -2; // 失败\n case EMPTY -> -3; // 无票\n case CANCEL -> -4; // 取消\n case INIT -> {\n // 需要查表得到实际排队数量\n // 排在第几位,下面的写法:where a=1 and (b=1 or c=1)不支持,但等价于Mybatis支持的 where (a=1 and b=1) or (a=1 and c=1)\n ConfirmOrderExample confirmOrderExample = new ConfirmOrderExample();\n // 获取该日期车次中创建时间在本订单之前的处于初始化或排队状态的订单数量\n confirmOrderExample.or().andDateEqualTo(confirmOrder.getDate())\n .andTrainCodeEqualTo(confirmOrder.getTrainCode())\n .andCreateTimeLessThan(confirmOrder.getCreateTime())\n .andStatusEqualTo(ConfirmOrderStatusEnum.INIT.getCode());\n confirmOrderExample.or().andDateEqualTo(confirmOrder.getDate())\n .andTrainCodeEqualTo(confirmOrder.getTrainCode())\n .andCreateTimeLessThan(confirmOrder.getCreateTime())\n .andStatusEqualTo(ConfirmOrderStatusEnum.PENDING.getCode());\n yield Math.toIntExact(confirmOrderMapper.countByExample(confirmOrderExample));\n }\n };\n }\n\n /**\n * 取消排队,只有I(初始)状态才能取消排队,所以按状态更新\n *\n * @param id 订单ID\n * @return 返回影响的数据条数\n */\n public Integer cancel(Long id) {\n ConfirmOrderExample confirmOrderExample = new ConfirmOrderExample();\n ConfirmOrderExample.Criteria criteria = confirmOrderExample.createCriteria();\n criteria.andIdEqualTo(id).andStatusEqualTo(ConfirmOrderStatusEnum.INIT.getCode());\n ConfirmOrder confirmOrder = new ConfirmOrder();\n confirmOrder.setStatus(ConfirmOrderStatusEnum.CANCEL.getCode());\n return confirmOrderMapper.updateByExampleSelective(confirmOrder, confirmOrderExample);\n }\n\n}" } ]
import com.alibaba.fastjson.JSON; import com.steve.train.business.dto.ConfirmOrderMQDTO; import com.steve.train.business.service.ConfirmOrderService; import jakarta.annotation.Resource; import org.apache.rocketmq.common.message.MessageExt; import org.apache.rocketmq.spring.annotation.RocketMQMessageListener; import org.apache.rocketmq.spring.core.RocketMQListener; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.MDC; import org.springframework.stereotype.Service;
7,747
package com.steve.train.business.mq; @Service @RocketMQMessageListener(consumerGroup = "default", topic = "CONFIRM_ORDER") public class ConfirmOrderConsumer implements RocketMQListener<MessageExt> { private final static Logger LOG = LoggerFactory.getLogger(ConfirmOrderConsumer.class); @Resource private ConfirmOrderService confirmOrderService; @Override public void onMessage(MessageExt messageExt) { byte[] body = messageExt.getBody();
package com.steve.train.business.mq; @Service @RocketMQMessageListener(consumerGroup = "default", topic = "CONFIRM_ORDER") public class ConfirmOrderConsumer implements RocketMQListener<MessageExt> { private final static Logger LOG = LoggerFactory.getLogger(ConfirmOrderConsumer.class); @Resource private ConfirmOrderService confirmOrderService; @Override public void onMessage(MessageExt messageExt) { byte[] body = messageExt.getBody();
ConfirmOrderMQDTO dto = JSON.parseObject(new String(body), ConfirmOrderMQDTO.class);
0
2023-10-23 01:20:56+00:00
12k
team-moabam/moabam-BE
src/test/java/com/moabam/api/application/room/RoomServiceTest.java
[ { "identifier": "RoomType", "path": "src/main/java/com/moabam/api/domain/room/RoomType.java", "snippet": "public enum RoomType {\n\n\tMORNING,\n\tNIGHT\n}" }, { "identifier": "MemberService", "path": "src/main/java/com/moabam/api/application/member/MemberService.java", "snippet": "@Service\n@Transactional(readOnly = true)\n@RequiredArgsConstructor\npublic class MemberService {\n\n\tprivate final RankingService rankingService;\n\tprivate final FcmService fcmService;\n\tprivate final MemberRepository memberRepository;\n\tprivate final InventoryRepository inventoryRepository;\n\tprivate final ItemRepository itemRepository;\n\tprivate final MemberSearchRepository memberSearchRepository;\n\tprivate final ParticipantSearchRepository participantSearchRepository;\n\tprivate final ParticipantRepository participantRepository;\n\tprivate final ClockHolder clockHolder;\n\n\tpublic Member findMember(Long memberId) {\n\t\treturn memberSearchRepository.findMember(memberId)\n\t\t\t.orElseThrow(() -> new NotFoundException(MEMBER_NOT_FOUND));\n\t}\n\n\t@Transactional\n\tpublic LoginResponse login(AuthorizationTokenInfoResponse authorizationTokenInfoResponse) {\n\t\tOptional<Member> member = memberRepository.findBySocialId(String.valueOf(authorizationTokenInfoResponse.id()));\n\t\tMember loginMember = member.orElseGet(() -> signUp(authorizationTokenInfoResponse.id()));\n\n\t\treturn AuthMapper.toLoginResponse(loginMember, member.isEmpty());\n\t}\n\n\tpublic List<Member> getRoomMembers(List<Long> memberIds) {\n\t\treturn memberRepository.findAllById(memberIds);\n\t}\n\n\tpublic void validateMemberToDelete(Long memberId) {\n\t\tList<Participant> participants = memberSearchRepository.findParticipantByMemberId(memberId);\n\n\t\tif (!participants.isEmpty()) {\n\t\t\tthrow new NotFoundException(MEMBER_NOT_FOUND);\n\t\t}\n\t}\n\n\t@Transactional\n\tpublic void delete(Member member) {\n\t\tList<Participant> participants = participantSearchRepository.findAllByMemberIdParticipant(member.getId());\n\n\t\tif (!participants.isEmpty()) {\n\t\t\tthrow new BadRequestException(NEED_TO_EXIT_ALL_ROOMS);\n\t\t}\n\n\t\tmember.delete(clockHolder.dateTime());\n\t\tmemberRepository.flush();\n\t\tmemberRepository.delete(member);\n\t\trankingService.removeRanking(MemberMapper.toRankingInfo(member));\n\t\tfcmService.deleteTokenByMemberId(member.getId());\n\t}\n\n\tpublic MemberInfoResponse searchInfo(AuthMember authMember, Long memberId) {\n\t\tLong searchId = authMember.id();\n\t\tboolean isMe = confirmMe(searchId, memberId);\n\n\t\tif (!isMe) {\n\t\t\tsearchId = memberId;\n\t\t}\n\t\tMemberInfoSearchResponse memberInfoSearchResponse = findMemberInfo(searchId, isMe);\n\n\t\treturn MemberMapper.toMemberInfoResponse(memberInfoSearchResponse);\n\t}\n\n\t@Transactional\n\tpublic void modifyInfo(AuthMember authMember, ModifyMemberRequest modifyMemberRequest, String newProfileUri) {\n\t\tvalidateNickname(modifyMemberRequest.nickname());\n\t\tMember member = memberSearchRepository.findMember(authMember.id())\n\t\t\t.orElseThrow(() -> new NotFoundException(MEMBER_NOT_FOUND));\n\n\t\tRankingInfo beforeInfo = MemberMapper.toRankingInfo(member);\n\t\tmember.changeNickName(modifyMemberRequest.nickname());\n\n\t\tboolean nickNameChanged = member.changeNickName(modifyMemberRequest.nickname());\n\t\tmember.changeIntro(modifyMemberRequest.intro());\n\t\tmember.changeProfileUri(newProfileUri);\n\t\tmemberRepository.save(member);\n\n\t\tRankingInfo afterInfo = MemberMapper.toRankingInfo(member);\n\t\trankingService.changeInfos(beforeInfo, afterInfo);\n\n\t\tif (nickNameChanged) {\n\t\t\tchangeNickname(authMember.id(), modifyMemberRequest.nickname());\n\t\t}\n\t}\n\n\tpublic UpdateRanking getRankingInfo(AuthMember authMember) {\n\t\tMember member = findMember(authMember.id());\n\n\t\treturn MemberMapper.toUpdateRanking(member);\n\t}\n\n\t@Scheduled(cron = \"0 11 * * * *\")\n\tpublic void updateAllRanking() {\n\t\tList<Member> members = memberSearchRepository.findAllMembers();\n\t\tList<UpdateRanking> updateRankings = members.stream()\n\t\t\t.map(MemberMapper::toUpdateRanking)\n\t\t\t.toList();\n\n\t\trankingService.updateScores(updateRankings);\n\t}\n\n\tprivate void changeNickname(Long memberId, String changedName) {\n\t\tList<Participant> participants = participantSearchRepository.findAllRoomMangerByMemberId(memberId);\n\n\t\tfor (Participant participant : participants) {\n\t\t\tparticipant.getRoom().changeManagerNickname(changedName);\n\t\t}\n\t}\n\n\tprivate void validateNickname(String nickname) {\n\t\tif (Objects.isNull(nickname)) {\n\t\t\treturn;\n\t\t}\n\t\tif (StringUtils.isEmpty(nickname) && memberRepository.existsByNickname(nickname)) {\n\t\t\tthrow new ConflictException(NICKNAME_CONFLICT);\n\t\t}\n\t}\n\n\tprivate Member signUp(Long socialId) {\n\t\tMember member = MemberMapper.toMember(socialId);\n\t\tMember savedMember = memberRepository.save(member);\n\t\tsaveMyEgg(savedMember);\n\t\trankingService.addRanking(MemberMapper.toRankingInfo(member), member.getTotalCertifyCount());\n\n\t\treturn savedMember;\n\t}\n\n\tprivate void saveMyEgg(Member member) {\n\t\tList<Item> items = getBasicEggs();\n\t\tList<Inventory> inventories = items.stream()\n\t\t\t.map(item -> MemberMapper.toInventory(member.getId(), item))\n\t\t\t.toList();\n\t\tinventoryRepository.saveAll(inventories);\n\t}\n\n\tprivate List<Item> getBasicEggs() {\n\t\tList<Item> items = itemRepository.findAllById(List.of(BaseDataCode.MORNING_EGG, BaseDataCode.NIGHT_EGG));\n\n\t\tif (items.isEmpty()) {\n\t\t\tthrow new BadRequestException(BASIC_SKIN_NOT_FOUND);\n\t\t}\n\n\t\treturn items;\n\t}\n\n\tprivate MemberInfoSearchResponse findMemberInfo(Long searchId, boolean isMe) {\n\t\tList<MemberInfo> memberInfos = memberSearchRepository.findMemberAndBadges(searchId, isMe);\n\n\t\tif (memberInfos.isEmpty()) {\n\t\t\tthrow new BadRequestException(MEMBER_NOT_FOUND);\n\t\t}\n\n\t\treturn MemberMapper.toMemberInfoSearchResponse(memberInfos);\n\t}\n\n\tprivate boolean confirmMe(Long myId, Long memberId) {\n\t\treturn Objects.isNull(memberId) || myId.equals(memberId);\n\t}\n}" }, { "identifier": "RoomMapper", "path": "src/main/java/com/moabam/api/application/room/mapper/RoomMapper.java", "snippet": "@NoArgsConstructor(access = AccessLevel.PRIVATE)\npublic final class RoomMapper {\n\n\tpublic static Room toRoomEntity(CreateRoomRequest createRoomRequest) {\n\t\treturn Room.builder()\n\t\t\t.title(createRoomRequest.title())\n\t\t\t.password(createRoomRequest.password())\n\t\t\t.roomType(createRoomRequest.roomType())\n\t\t\t.certifyTime(createRoomRequest.certifyTime())\n\t\t\t.maxUserCount(createRoomRequest.maxUserCount())\n\t\t\t.build();\n\t}\n\n\tpublic static RoomDetailsResponse toRoomDetailsResponse(Long memberId, Room room, String managerNickname,\n\t\tList<RoutineResponse> routineResponses, List<LocalDate> certifiedDates,\n\t\tList<TodayCertificateRankResponse> todayCertificateRankResponses, double completePercentage) {\n\t\treturn RoomDetailsResponse.builder()\n\t\t\t.roomId(room.getId())\n\t\t\t.roomCreatedAt(room.getCreatedAt())\n\t\t\t.myMemberId(memberId)\n\t\t\t.title(room.getTitle())\n\t\t\t.managerNickName(managerNickname)\n\t\t\t.roomImage(room.getRoomImage())\n\t\t\t.level(room.getLevel())\n\t\t\t.currentExp(room.getExp())\n\t\t\t.totalExp(RoomExp.of(room.getLevel()).getTotalExp())\n\t\t\t.roomType(room.getRoomType())\n\t\t\t.certifyTime(room.getCertifyTime())\n\t\t\t.currentUserCount(room.getCurrentUserCount())\n\t\t\t.maxUserCount(room.getMaxUserCount())\n\t\t\t.announcement(room.getAnnouncement())\n\t\t\t.completePercentage(completePercentage)\n\t\t\t.certifiedDates(certifiedDates)\n\t\t\t.routines(routineResponses)\n\t\t\t.todayCertificateRank(todayCertificateRankResponses)\n\t\t\t.build();\n\t}\n\n\tpublic static MyRoomResponse toMyRoomResponse(Room room, boolean isMemberCertifiedToday,\n\t\tboolean isRoomCertifiedToday) {\n\t\treturn MyRoomResponse.builder()\n\t\t\t.roomId(room.getId())\n\t\t\t.title(room.getTitle())\n\t\t\t.roomType(room.getRoomType())\n\t\t\t.certifyTime(room.getCertifyTime())\n\t\t\t.currentUserCount(room.getCurrentUserCount())\n\t\t\t.maxUserCount(room.getMaxUserCount())\n\t\t\t.obtainedBugs(room.getLevel())\n\t\t\t.isMemberCertifiedToday(isMemberCertifiedToday)\n\t\t\t.isRoomCertifiedToday(isRoomCertifiedToday)\n\t\t\t.build();\n\t}\n\n\tpublic static MyRoomsResponse toMyRoomsResponse(List<MyRoomResponse> myRoomResponses) {\n\t\treturn MyRoomsResponse.builder()\n\t\t\t.participatingRooms(myRoomResponses)\n\t\t\t.build();\n\t}\n\n\tpublic static RoomHistoryResponse toRoomHistoryResponse(Long roomId, String title, Participant participant) {\n\t\treturn RoomHistoryResponse.builder()\n\t\t\t.roomId(roomId)\n\t\t\t.title(title)\n\t\t\t.createdAt(participant.getCreatedAt())\n\t\t\t.deletedAt(participant.getDeletedAt())\n\t\t\t.build();\n\t}\n\n\tpublic static RoomsHistoryResponse toRoomsHistoryResponse(List<RoomHistoryResponse> roomHistoryResponses) {\n\t\treturn RoomsHistoryResponse.builder()\n\t\t\t.roomHistory(roomHistoryResponses)\n\t\t\t.build();\n\t}\n\n\tpublic static ManageRoomResponse toManageRoomResponse(Room room, Long managerId, List<RoutineResponse> routines,\n\t\tList<ParticipantResponse> participantResponses) {\n\t\treturn ManageRoomResponse.builder()\n\t\t\t.roomId(room.getId())\n\t\t\t.title(room.getTitle())\n\t\t\t.managerId(managerId)\n\t\t\t.announcement(room.getAnnouncement())\n\t\t\t.roomType(room.getRoomType())\n\t\t\t.certifyTime(room.getCertifyTime())\n\t\t\t.maxUserCount(room.getMaxUserCount())\n\t\t\t.password(room.getPassword())\n\t\t\t.routines(routines)\n\t\t\t.participants(participantResponses)\n\t\t\t.build();\n\t}\n\n\tpublic static GetAllRoomResponse toSearchAllRoomResponse(Room room, List<RoutineResponse> routineResponses,\n\t\tboolean isPassword) {\n\t\treturn GetAllRoomResponse.builder()\n\t\t\t.id(room.getId())\n\t\t\t.title(room.getTitle())\n\t\t\t.image(room.getRoomImage())\n\t\t\t.isPassword(isPassword)\n\t\t\t.managerNickname(room.getManagerNickname())\n\t\t\t.level(room.getLevel())\n\t\t\t.roomType(room.getRoomType())\n\t\t\t.certifyTime(room.getCertifyTime())\n\t\t\t.currentUserCount(room.getCurrentUserCount())\n\t\t\t.maxUserCount(room.getMaxUserCount())\n\t\t\t.routines(routineResponses)\n\t\t\t.build();\n\t}\n\n\tpublic static GetAllRoomsResponse toSearchAllRoomsResponse(boolean hasNext,\n\t\tList<GetAllRoomResponse> getAllRoomResponse) {\n\t\treturn GetAllRoomsResponse.builder()\n\t\t\t.hasNext(hasNext)\n\t\t\t.rooms(getAllRoomResponse)\n\t\t\t.build();\n\t}\n\n\tpublic static UnJoinedRoomDetailsResponse toUnJoinedRoomDetails(Room room, List<RoutineResponse> routines,\n\t\tList<UnJoinedRoomCertificateRankResponse> responses) {\n\t\treturn UnJoinedRoomDetailsResponse.builder()\n\t\t\t.roomId(room.getId())\n\t\t\t.isPassword(!isEmpty(room.getPassword()))\n\t\t\t.title(room.getTitle())\n\t\t\t.roomImage(room.getRoomImage())\n\t\t\t.level(room.getLevel())\n\t\t\t.currentExp(room.getExp())\n\t\t\t.totalExp(RoomExp.of(room.getLevel()).getTotalExp())\n\t\t\t.roomType(room.getRoomType())\n\t\t\t.certifyTime(room.getCertifyTime())\n\t\t\t.currentUserCount(room.getCurrentUserCount())\n\t\t\t.maxUserCount(room.getMaxUserCount())\n\t\t\t.announcement(room.getAnnouncement())\n\t\t\t.routines(routines)\n\t\t\t.certifiedRanks(responses)\n\t\t\t.build();\n\t}\n\n\tpublic static UnJoinedRoomCertificateRankResponse toUnJoinedRoomCertificateRankResponse(Member member, int rank,\n\t\tInventory inventory) {\n\t\treturn UnJoinedRoomCertificateRankResponse.builder()\n\t\t\t.rank(rank)\n\t\t\t.memberId(member.getId())\n\t\t\t.nickname(member.getNickname())\n\t\t\t.awakeImage(inventory.getItem().getAwakeImage())\n\t\t\t.sleepImage(inventory.getItem().getSleepImage())\n\t\t\t.build();\n\t}\n}" }, { "identifier": "Member", "path": "src/main/java/com/moabam/api/domain/member/Member.java", "snippet": "@Entity\n@Getter\n@Table(name = \"member\")\n@SQLDelete(sql = \"UPDATE member SET deleted_at = CURRENT_TIMESTAMP where id = ?\")\n@NoArgsConstructor(access = AccessLevel.PROTECTED)\npublic class Member extends BaseTimeEntity {\n\n\t@Id\n\t@GeneratedValue(strategy = GenerationType.IDENTITY)\n\t@Column(name = \"id\")\n\tprivate Long id;\n\n\t@Column(name = \"social_id\", nullable = false, unique = true)\n\tprivate String socialId;\n\n\t@Column(name = \"nickname\", unique = true)\n\tprivate String nickname;\n\n\t@Column(name = \"intro\", length = 30)\n\tprivate String intro;\n\n\t@Column(name = \"profile_image\", nullable = false)\n\tprivate String profileImage;\n\n\t@Column(name = \"morning_image\", nullable = false)\n\tprivate String morningImage;\n\n\t@Column(name = \"night_image\", nullable = false)\n\tprivate String nightImage;\n\n\t@Column(name = \"total_certify_count\", nullable = false)\n\t@ColumnDefault(\"0\")\n\tprivate long totalCertifyCount;\n\n\t@Column(name = \"report_count\", nullable = false)\n\t@ColumnDefault(\"0\")\n\tprivate int reportCount;\n\n\t@Column(name = \"current_night_count\", nullable = false)\n\t@ColumnDefault(\"0\")\n\tprivate int currentNightCount;\n\n\t@Column(name = \"current_morning_count\", nullable = false)\n\t@ColumnDefault(\"0\")\n\tprivate int currentMorningCount;\n\n\t@Embedded\n\tprivate Bug bug;\n\n\t@Enumerated(EnumType.STRING)\n\t@Column(name = \"role\", nullable = false)\n\t@ColumnDefault(\"'USER'\")\n\tprivate Role role;\n\n\t@Column(name = \"deleted_at\")\n\tprivate LocalDateTime deletedAt;\n\n\t@Builder\n\tprivate Member(Long id, String socialId, Bug bug) {\n\t\tthis.id = id;\n\t\tthis.socialId = requireNonNull(socialId);\n\t\tthis.nickname = createNickName();\n\t\tthis.intro = \"\";\n\t\tthis.profileImage = IMAGE_DOMAIN + MEMBER_PROFILE_URL;\n\t\tthis.morningImage = IMAGE_DOMAIN + DEFAULT_MORNING_EGG_URL;\n\t\tthis.nightImage = IMAGE_DOMAIN + DEFAULT_NIGHT_EGG_URL;\n\t\tthis.bug = requireNonNull(bug);\n\t\tthis.role = Role.USER;\n\t}\n\n\tpublic void enterRoom(RoomType roomType) {\n\t\tif (roomType.equals(RoomType.MORNING)) {\n\t\t\tthis.currentMorningCount++;\n\t\t\treturn;\n\t\t}\n\n\t\tif (roomType.equals(RoomType.NIGHT)) {\n\t\t\tthis.currentNightCount++;\n\t\t}\n\t}\n\n\tpublic void exitRoom(RoomType roomType) {\n\t\tif (roomType.equals(RoomType.MORNING) && currentMorningCount > 0) {\n\t\t\tthis.currentMorningCount--;\n\t\t\treturn;\n\t\t}\n\n\t\tif (roomType.equals(RoomType.NIGHT) && currentNightCount > 0) {\n\t\t\tthis.currentNightCount--;\n\t\t}\n\t}\n\n\tpublic int getLevel() {\n\t\treturn (int)(totalCertifyCount / LEVEL_DIVISOR) + 1;\n\t}\n\n\tpublic void increaseTotalCertifyCount() {\n\t\tthis.totalCertifyCount++;\n\t}\n\n\tpublic void delete(LocalDateTime now) {\n\t\tsocialId = deleteSocialId(now);\n\t\tnickname = null;\n\t}\n\n\tpublic boolean changeNickName(String nickname) {\n\t\tif (Objects.isNull(nickname)) {\n\t\t\treturn false;\n\t\t}\n\t\tthis.nickname = nickname;\n\t\treturn true;\n\t}\n\n\tpublic void changeIntro(String intro) {\n\t\tthis.intro = requireNonNullElse(intro, this.intro);\n\t}\n\n\tpublic void changeProfileUri(String newProfileUri) {\n\t\tthis.profileImage = requireNonNullElse(newProfileUri, profileImage);\n\t}\n\n\tpublic void changeDefaultSkintUrl(Item item) throws NotFoundException {\n\t\tif (ItemType.MORNING.equals(item.getType())) {\n\t\t\tthis.morningImage = item.getAwakeImage();\n\t\t\treturn;\n\t\t}\n\n\t\tif (ItemType.NIGHT.equals(item.getType())) {\n\t\t\tthis.nightImage = item.getAwakeImage();\n\t\t\treturn;\n\t\t}\n\n\t\tthrow new NotFoundException(SKIN_TYPE_NOT_FOUND);\n\t}\n\n\tprivate String createNickName() {\n\t\treturn \"오목눈이#\" + randomStringValues();\n\t}\n\n\tprivate String deleteSocialId(LocalDateTime now) {\n\t\treturn \"delete_\" + now.toString() + randomNumberValues();\n\t}\n}" }, { "identifier": "Participant", "path": "src/main/java/com/moabam/api/domain/room/Participant.java", "snippet": "@Entity\n@Getter\n@Table(name = \"participant\")\n@SQLDelete(sql = \"UPDATE participant SET deleted_at = CURRENT_TIMESTAMP where id = ?\")\n@NoArgsConstructor(access = AccessLevel.PROTECTED)\npublic class Participant extends BaseTimeEntity {\n\n\t@Id\n\t@GeneratedValue(strategy = GenerationType.IDENTITY)\n\t@Column(name = \"id\")\n\tprivate Long id;\n\n\t@ManyToOne(fetch = FetchType.LAZY)\n\t@JoinColumn(name = \"room_id\")\n\tprivate Room room;\n\n\t@Column(name = \"member_id\", updatable = false, nullable = false)\n\tprivate Long memberId;\n\n\t@Column(name = \"is_manager\")\n\tprivate boolean isManager;\n\n\t@Column(name = \"certify_count\")\n\tprivate int certifyCount;\n\n\t@Column(name = \"deleted_at\")\n\tprivate LocalDateTime deletedAt;\n\n\t@Column(name = \"deleted_room_title\", length = 30)\n\tprivate String deletedRoomTitle;\n\n\t@Builder\n\tprivate Participant(Long id, Room room, Long memberId) {\n\t\tthis.id = id;\n\t\tthis.room = requireNonNull(room);\n\t\tthis.memberId = requireNonNull(memberId);\n\t\tthis.isManager = false;\n\t\tthis.certifyCount = 0;\n\t}\n\n\tpublic void disableManager() {\n\t\tthis.isManager = false;\n\t}\n\n\tpublic void enableManager() {\n\t\tthis.isManager = true;\n\t}\n\n\tpublic void updateCertifyCount() {\n\t\tthis.certifyCount += 1;\n\t}\n\n\tpublic void removeRoom() {\n\t\tthis.deletedRoomTitle = this.room.getTitle();\n\t}\n}" }, { "identifier": "Room", "path": "src/main/java/com/moabam/api/domain/room/Room.java", "snippet": "@Entity\n@Getter\n@Table(name = \"room\")\n@NoArgsConstructor(access = AccessLevel.PROTECTED)\n@SQLDelete(sql = \"UPDATE room SET deleted_at = CURRENT_TIMESTAMP where id = ?\")\npublic class Room extends BaseTimeEntity {\n\n\tprivate static final int LEVEL_0 = 0;\n\tprivate static final int LEVEL_1 = 1;\n\tprivate static final int LEVEL_2 = 2;\n\tprivate static final int LEVEL_3 = 3;\n\tprivate static final int LEVEL_4 = 4;\n\tprivate static final int LEVEL_5 = 5;\n\tprivate static final String ROOM_LEVEL_0_IMAGE = \"https://image.moabam.com/moabam/default/room-level-00.png\";\n\tprivate static final String ROOM_LEVEL_1_IMAGE = \"https://image.moabam.com/moabam/default/room-level-01.png\";\n\tprivate static final String ROOM_LEVEL_2_IMAGE = \"https://image.moabam.com/moabam/default/room-level-02.png\";\n\tprivate static final String ROOM_LEVEL_3_IMAGE = \"https://image.moabam.com/moabam/default/room-level-03.png\";\n\tprivate static final String ROOM_LEVEL_4_IMAGE = \"https://image.moabam.com/moabam/default/room-level-04.png\";\n\tprivate static final String ROOM_LEVEL_5_IMAGE = \"https://image.moabam.com/moabam/default/room-level-05.png\";\n\tprivate static final int MORNING_START_TIME = 4;\n\tprivate static final int MORNING_END_TIME = 10;\n\tprivate static final int NIGHT_START_TIME = 20;\n\tprivate static final int NIGHT_END_TIME = 2;\n\tprivate static final int CLOCK_ZERO = 0;\n\n\t@Id\n\t@GeneratedValue(strategy = GenerationType.IDENTITY)\n\t@Column(name = \"id\")\n\tprivate Long id;\n\n\t@Column(name = \"title\",\n\t\tcolumnDefinition = \"VARCHAR(20) NOT NULL, FULLTEXT INDEX full_title (title) WITH PARSER ngram\")\n\tprivate String title;\n\n\t@Column(name = \"password\", length = 8)\n\tprivate String password;\n\n\t@ColumnDefault(\"0\")\n\t@Column(name = \"level\", nullable = false)\n\tprivate int level;\n\n\t@ColumnDefault(\"0\")\n\t@Column(name = \"exp\", nullable = false)\n\tprivate int exp;\n\n\t@Enumerated(value = EnumType.STRING)\n\t@Column(name = \"room_type\")\n\tprivate RoomType roomType;\n\n\t@Column(name = \"certify_time\", nullable = false)\n\tprivate int certifyTime;\n\n\t@Column(name = \"current_user_count\", nullable = false)\n\tprivate int currentUserCount;\n\n\t@Column(name = \"max_user_count\", nullable = false)\n\tprivate int maxUserCount;\n\n\t@Column(name = \"announcement\", length = 100)\n\tprivate String announcement;\n\n\t@ColumnDefault(\"'\" + ROOM_LEVEL_0_IMAGE + \"'\")\n\t@Column(name = \"room_image\", length = 500)\n\tprivate String roomImage;\n\n\t@Column(name = \"manager_nickname\",\n\t\tcolumnDefinition = \"VARCHAR(30), FULLTEXT INDEX full_nickname (manager_nickname) WITH PARSER ngram\")\n\tprivate String managerNickname;\n\n\t@Column(name = \"deleted_at\")\n\tprivate LocalDateTime deletedAt;\n\n\t@Builder\n\tprivate Room(Long id, String title, String password, RoomType roomType, int certifyTime, int maxUserCount) {\n\t\tthis.id = id;\n\t\tthis.title = requireNonNull(title);\n\t\tthis.password = password;\n\t\tthis.level = 0;\n\t\tthis.exp = 0;\n\t\tthis.roomType = requireNonNull(roomType);\n\t\tthis.certifyTime = validateCertifyTime(roomType, certifyTime);\n\t\tthis.currentUserCount = 1;\n\t\tthis.maxUserCount = maxUserCount;\n\t\tthis.roomImage = ROOM_LEVEL_0_IMAGE;\n\t}\n\n\tpublic void levelUp() {\n\t\tthis.level += 1;\n\t\tthis.exp = 0;\n\t\tupgradeRoomImage(this.level);\n\t}\n\n\tpublic void upgradeRoomImage(int level) {\n\t\tif (level == LEVEL_1) {\n\t\t\tthis.roomImage = ROOM_LEVEL_1_IMAGE;\n\t\t\treturn;\n\t\t}\n\n\t\tif (level == LEVEL_2) {\n\t\t\tthis.roomImage = ROOM_LEVEL_2_IMAGE;\n\t\t\treturn;\n\t\t}\n\n\t\tif (level == LEVEL_3) {\n\t\t\tthis.roomImage = ROOM_LEVEL_3_IMAGE;\n\t\t\treturn;\n\t\t}\n\n\t\tif (level == LEVEL_4) {\n\t\t\tthis.roomImage = ROOM_LEVEL_4_IMAGE;\n\t\t\treturn;\n\t\t}\n\n\t\tif (level == LEVEL_5) {\n\t\t\tthis.roomImage = ROOM_LEVEL_5_IMAGE;\n\t\t}\n\t}\n\n\tpublic void gainExp() {\n\t\tthis.exp += 1;\n\t}\n\n\tpublic void changeAnnouncement(String announcement) {\n\t\tthis.announcement = announcement;\n\t}\n\n\tpublic void changeTitle(String title) {\n\t\tthis.title = title;\n\t}\n\n\tpublic void changePassword(String password) {\n\t\tthis.password = password;\n\t}\n\n\tpublic void changeManagerNickname(String managerNickname) {\n\t\tthis.managerNickname = managerNickname;\n\t}\n\n\tpublic void changeMaxCount(int maxUserCount) {\n\t\tif (maxUserCount < this.currentUserCount) {\n\t\t\tthrow new BadRequestException(ROOM_MAX_USER_COUNT_MODIFY_FAIL);\n\t\t}\n\n\t\tthis.maxUserCount = maxUserCount;\n\t}\n\n\tpublic void increaseCurrentUserCount() {\n\t\tthis.currentUserCount += 1;\n\t}\n\n\tpublic void decreaseCurrentUserCount() {\n\t\tthis.currentUserCount -= 1;\n\t}\n\n\tpublic void changeCertifyTime(int certifyTime) {\n\t\tthis.certifyTime = validateCertifyTime(this.roomType, certifyTime);\n\t}\n\n\tprivate int validateCertifyTime(RoomType roomType, int certifyTime) {\n\t\tif (roomType.equals(MORNING) && (certifyTime < MORNING_START_TIME || certifyTime > MORNING_END_TIME)) {\n\t\t\tthrow new BadRequestException(INVALID_REQUEST_FIELD);\n\t\t}\n\n\t\tif (roomType.equals(NIGHT)\n\t\t\t&& ((certifyTime < NIGHT_START_TIME && certifyTime > NIGHT_END_TIME) || certifyTime < CLOCK_ZERO)) {\n\t\t\tthrow new BadRequestException(INVALID_REQUEST_FIELD);\n\t\t}\n\n\t\treturn certifyTime;\n\t}\n}" }, { "identifier": "Routine", "path": "src/main/java/com/moabam/api/domain/room/Routine.java", "snippet": "@Entity\n@Getter\n@Table(name = \"routine\")\n@NoArgsConstructor(access = AccessLevel.PROTECTED)\npublic class Routine extends BaseTimeEntity {\n\n\t@Id\n\t@GeneratedValue(strategy = GenerationType.IDENTITY)\n\t@Column(name = \"id\")\n\tprivate Long id;\n\n\t@ManyToOne(fetch = FetchType.LAZY)\n\t@JoinColumn(name = \"room_id\", updatable = false)\n\tprivate Room room;\n\n\t@Column(name = \"content\",\n\t\tcolumnDefinition = \"VARCHAR(20) NOT NULL, FULLTEXT INDEX full_content (content) WITH PARSER ngram\")\n\tprivate String content;\n\n\t@Builder\n\tprivate Routine(Long id, Room room, String content) {\n\t\tthis.id = id;\n\t\tthis.room = requireNonNull(room);\n\t\tthis.content = validateContent(content);\n\t}\n\n\tpublic void changeContent(String content) {\n\t\tthis.content = content;\n\t}\n\n\tprivate String validateContent(String content) {\n\t\tif (StringUtils.isBlank(content) || content.length() > 20) {\n\t\t\tthrow new BadRequestException(ROUTINE_LENGTH_ERROR);\n\t\t}\n\n\t\treturn content;\n\t}\n}" }, { "identifier": "ParticipantRepository", "path": "src/main/java/com/moabam/api/domain/room/repository/ParticipantRepository.java", "snippet": "public interface ParticipantRepository extends JpaRepository<Participant, Long> {\n\n\tList<Participant> findAllByMemberId(Long id);\n}" }, { "identifier": "ParticipantSearchRepository", "path": "src/main/java/com/moabam/api/domain/room/repository/ParticipantSearchRepository.java", "snippet": "@Repository\n@RequiredArgsConstructor\npublic class ParticipantSearchRepository {\n\n\tprivate final JPAQueryFactory jpaQueryFactory;\n\n\tpublic Optional<Participant> findOne(Long memberId, Long roomId) {\n\t\treturn Optional.ofNullable(\n\t\t\tjpaQueryFactory\n\t\t\t\t.selectFrom(participant)\n\t\t\t\t.join(participant.room, room).fetchJoin()\n\t\t\t\t.where(\n\t\t\t\t\tDynamicQuery.generateEq(roomId, participant.room.id::eq),\n\t\t\t\t\tDynamicQuery.generateEq(memberId, participant.memberId::eq),\n\t\t\t\t\tparticipant.deletedAt.isNull()\n\t\t\t\t)\n\t\t\t\t.fetchOne()\n\t\t);\n\t}\n\n\tpublic List<Participant> findAllByRoomId(Long roomId) {\n\t\treturn jpaQueryFactory\n\t\t\t.selectFrom(participant)\n\t\t\t.where(\n\t\t\t\tparticipant.room.id.eq(roomId),\n\t\t\t\tparticipant.deletedAt.isNull()\n\t\t\t)\n\t\t\t.fetch();\n\t}\n\n\tpublic List<Participant> findAllByMemberIdParticipant(Long memberId) {\n\t\treturn jpaQueryFactory\n\t\t\t.selectFrom(participant)\n\t\t\t.where(\n\t\t\t\tparticipant.memberId.eq(memberId),\n\t\t\t\tparticipant.deletedAt.isNull()\n\t\t\t)\n\t\t\t.fetch();\n\t}\n\n\tpublic List<Participant> findAllWithDeletedByRoomId(Long roomId) {\n\t\treturn jpaQueryFactory\n\t\t\t.selectFrom(participant)\n\t\t\t.where(\n\t\t\t\tparticipant.room.id.eq(roomId)\n\t\t\t)\n\t\t\t.fetch();\n\t}\n\n\tpublic List<Participant> findAllByRoomIdBeforeDate(Long roomId, LocalDateTime date) {\n\t\treturn jpaQueryFactory\n\t\t\t.selectFrom(participant)\n\t\t\t.where(\n\t\t\t\tparticipant.room.id.eq(roomId),\n\t\t\t\tparticipant.createdAt.before(date),\n\t\t\t\tparticipant.deletedAt.isNull()\n\t\t\t)\n\t\t\t.fetch();\n\t}\n\n\tpublic List<Participant> findNotDeletedAllByMemberId(Long memberId) {\n\t\treturn jpaQueryFactory\n\t\t\t.selectFrom(participant)\n\t\t\t.join(participant.room, room).fetchJoin()\n\t\t\t.where(\n\t\t\t\tparticipant.memberId.eq(memberId),\n\t\t\t\tparticipant.deletedAt.isNull()\n\t\t\t)\n\t\t\t.fetch();\n\t}\n\n\tpublic List<Participant> findAllByMemberId(Long memberId) {\n\t\treturn jpaQueryFactory\n\t\t\t.selectFrom(participant)\n\t\t\t.leftJoin(participant.room, room).fetchJoin()\n\t\t\t.where(\n\t\t\t\tparticipant.memberId.eq(memberId)\n\t\t\t)\n\t\t\t.orderBy(participant.createdAt.desc())\n\t\t\t.fetch();\n\t}\n\n\tpublic List<Participant> findAllByRoomCertifyTime(int certifyTime) {\n\t\treturn jpaQueryFactory\n\t\t\t.selectFrom(participant)\n\t\t\t.join(participant.room, room).fetchJoin()\n\t\t\t.where(\n\t\t\t\tparticipant.room.certifyTime.eq(certifyTime),\n\t\t\t\tparticipant.deletedAt.isNull()\n\t\t\t)\n\t\t\t.fetch();\n\t}\n\n\tpublic List<Participant> findAllRoomMangerByMemberId(Long memberId) {\n\t\treturn jpaQueryFactory\n\t\t\t.selectFrom(participant)\n\t\t\t.join(participant.room, room).fetchJoin()\n\t\t\t.where(\n\t\t\t\tparticipant.memberId.eq(memberId),\n\t\t\t\tparticipant.isManager.isTrue()\n\t\t\t)\n\t\t\t.fetch();\n\t}\n}" }, { "identifier": "RoomRepository", "path": "src/main/java/com/moabam/api/domain/room/repository/RoomRepository.java", "snippet": "public interface RoomRepository extends JpaRepository<Room, Long> {\n\n\t@Lock(LockModeType.PESSIMISTIC_WRITE)\n\tOptional<Room> findWithPessimisticLockByIdAndDeletedAtIsNull(Long id);\n\n\t@Query(value = \"select distinct rm.* from room rm left join routine rt on rm.id = rt.room_id \"\n\t\t+ \"where (rm.title like %:keyword% \"\n\t\t+ \"or rm.manager_nickname like %:keyword% \"\n\t\t+ \"or rt.content like %:keyword%) \"\n\t\t+ \"and rm.deleted_at is null \"\n\t\t+ \"order by rm.id desc limit 11\", nativeQuery = true)\n\tList<Room> searchByKeyword(@Param(value = \"keyword\") String keyword);\n\n\t@Query(value = \"select distinct rm.* from room rm left join routine rt on rm.id = rt.room_id \"\n\t\t+ \"where (rm.title like %:keyword% \"\n\t\t+ \"or rm.manager_nickname like %:keyword% \"\n\t\t+ \"or rt.content like %:keyword%) \"\n\t\t+ \"and rm.room_type = :roomType \"\n\t\t+ \"and rm.deleted_at is null \"\n\t\t+ \"order by rm.id desc limit 11\", nativeQuery = true)\n\tList<Room> searchByKeywordAndRoomType(@Param(value = \"keyword\") String keyword,\n\t\t@Param(value = \"roomType\") String roomType);\n\n\t@Query(value = \"select distinct rm.* from room rm left join routine rt on rm.id = rt.room_id \"\n\t\t+ \"where (rm.title like %:keyword% \"\n\t\t+ \"or rm.manager_nickname like %:keyword% \"\n\t\t+ \"or rt.content like %:keyword%) \"\n\t\t+ \"and rm.id < :roomId \"\n\t\t+ \"and rm.deleted_at is null \"\n\t\t+ \"order by rm.id desc limit 11\", nativeQuery = true)\n\tList<Room> searchByKeywordAndRoomId(@Param(value = \"keyword\") String keyword, @Param(value = \"roomId\") Long roomId);\n\n\t@Query(value = \"select distinct rm.* from room rm left join routine rt on rm.id = rt.room_id \"\n\t\t+ \"where (rm.title like %:keyword% \"\n\t\t+ \"or rm.manager_nickname like %:keyword% \"\n\t\t+ \"or rt.content like %:keyword%) \"\n\t\t+ \"and rm.room_type = :roomType \"\n\t\t+ \"and rm.id < :roomId \"\n\t\t+ \"and rm.deleted_at is null \"\n\t\t+ \"order by rm.id desc limit 11\", nativeQuery = true)\n\tList<Room> searchByKeywordAndRoomIdAndRoomType(@Param(value = \"keyword\") String keyword,\n\t\t@Param(value = \"roomType\") String roomType, @Param(value = \"roomId\") Long roomId);\n}" }, { "identifier": "RoutineRepository", "path": "src/main/java/com/moabam/api/domain/room/repository/RoutineRepository.java", "snippet": "public interface RoutineRepository extends JpaRepository<Routine, Long> {\n\n\tList<Routine> findAllByRoomId(Long roomId);\n\n\tList<Routine> findAllByRoomIdIn(List<Long> roomIds);\n}" }, { "identifier": "ForbiddenException", "path": "src/main/java/com/moabam/global/error/exception/ForbiddenException.java", "snippet": "public class ForbiddenException extends MoabamException {\n\n\tpublic ForbiddenException(ErrorMessage errorMessage) {\n\t\tsuper(errorMessage);\n\t}\n}" }, { "identifier": "MemberFixture", "path": "src/test/java/com/moabam/support/fixture/MemberFixture.java", "snippet": "public final class MemberFixture {\n\n\tpublic static final String SOCIAL_ID = \"1\";\n\tpublic static final String NICKNAME = \"모아밤\";\n\n\tpublic static Member member() {\n\t\treturn Member.builder()\n\t\t\t.socialId(SOCIAL_ID)\n\t\t\t.bug(BugFixture.bug())\n\t\t\t.build();\n\t}\n\n\tpublic static Member member(Long id) {\n\t\treturn Member.builder()\n\t\t\t.id(id)\n\t\t\t.socialId(SOCIAL_ID)\n\t\t\t.bug(BugFixture.bug())\n\t\t\t.build();\n\t}\n\n\tpublic static Member member(Bug bug) {\n\t\treturn Member.builder()\n\t\t\t.socialId(SOCIAL_ID)\n\t\t\t.bug(bug)\n\t\t\t.build();\n\t}\n\n\tpublic static Member member(String socialId) {\n\t\treturn Member.builder()\n\t\t\t.socialId(socialId)\n\t\t\t.bug(BugFixture.bug())\n\t\t\t.build();\n\t}\n}" }, { "identifier": "RoomFixture", "path": "src/test/java/com/moabam/support/fixture/RoomFixture.java", "snippet": "public class RoomFixture {\n\n\tpublic static Room room() {\n\t\treturn Room.builder()\n\t\t\t.title(\"testTitle\")\n\t\t\t.roomType(RoomType.MORNING)\n\t\t\t.certifyTime(10)\n\t\t\t.maxUserCount(8)\n\t\t\t.build();\n\t}\n\n\tpublic static Room room(int certifyTime) {\n\t\treturn Room.builder()\n\t\t\t.id(1L)\n\t\t\t.title(\"testTitle\")\n\t\t\t.roomType(RoomType.MORNING)\n\t\t\t.certifyTime(certifyTime)\n\t\t\t.maxUserCount(8)\n\t\t\t.build();\n\t}\n\n\tpublic static Room room(String title, RoomType roomType, int certifyTime) {\n\t\treturn Room.builder()\n\t\t\t.title(title)\n\t\t\t.roomType(roomType)\n\t\t\t.certifyTime(certifyTime)\n\t\t\t.maxUserCount(8)\n\t\t\t.build();\n\t}\n\n\tpublic static Room room(String title, RoomType roomType, int certifyTime, String password) {\n\t\treturn Room.builder()\n\t\t\t.title(title)\n\t\t\t.password(password)\n\t\t\t.roomType(roomType)\n\t\t\t.certifyTime(certifyTime)\n\t\t\t.maxUserCount(8)\n\t\t\t.build();\n\t}\n\n\tpublic static Participant participant(Room room, Long memberId) {\n\t\treturn Participant.builder()\n\t\t\t.room(room)\n\t\t\t.memberId(memberId)\n\t\t\t.build();\n\t}\n\n\tpublic static Routine routine(Room room, String content) {\n\t\treturn Routine.builder()\n\t\t\t.room(room)\n\t\t\t.content(content)\n\t\t\t.build();\n\t}\n\n\tpublic static List<Routine> routines(Room room) {\n\t\tList<Routine> routines = new ArrayList<>();\n\n\t\tRoutine routine1 = Routine.builder()\n\t\t\t.room(room)\n\t\t\t.content(\"첫 루틴\")\n\t\t\t.build();\n\t\tRoutine routine2 = Routine.builder()\n\t\t\t.room(room)\n\t\t\t.content(\"두번째 루틴\")\n\t\t\t.build();\n\n\t\troutines.add(routine1);\n\t\troutines.add(routine2);\n\n\t\treturn routines;\n\t}\n\n\tpublic static Certification certification(Routine routine) {\n\t\treturn Certification.builder()\n\t\t\t.routine(routine)\n\t\t\t.memberId(1L)\n\t\t\t.image(\"test1\")\n\t\t\t.build();\n\t}\n\n\tpublic static DailyMemberCertification dailyMemberCertification(Long memberId, Long roomId,\n\t\tParticipant participant) {\n\t\treturn DailyMemberCertification.builder()\n\t\t\t.memberId(memberId)\n\t\t\t.roomId(roomId)\n\t\t\t.participant(participant)\n\t\t\t.build();\n\t}\n\n\tpublic static List<DailyMemberCertification> dailyMemberCertifications(Long roomId, Participant participant) {\n\n\t\tList<DailyMemberCertification> dailyMemberCertifications = new ArrayList<>();\n\t\tdailyMemberCertifications.add(DailyMemberCertification.builder()\n\t\t\t.roomId(roomId)\n\t\t\t.memberId(1L)\n\t\t\t.participant(participant)\n\t\t\t.build());\n\t\tdailyMemberCertifications.add(DailyMemberCertification.builder()\n\t\t\t.roomId(roomId)\n\t\t\t.memberId(2L)\n\t\t\t.participant(participant)\n\t\t\t.build());\n\t\tdailyMemberCertifications.add(DailyMemberCertification.builder()\n\t\t\t.roomId(roomId)\n\t\t\t.memberId(3L)\n\t\t\t.participant(participant)\n\t\t\t.build());\n\n\t\treturn dailyMemberCertifications;\n\t}\n\n\tpublic static DailyRoomCertification dailyRoomCertification(Long roomId, LocalDate today) {\n\t\treturn DailyRoomCertification.builder()\n\t\t\t.roomId(roomId)\n\t\t\t.certifiedAt(today)\n\t\t\t.build();\n\t}\n\n\tpublic static MockMultipartFile makeMultipartFile1() {\n\t\ttry {\n\t\t\tFile file = new File(\"src/test/resources/image.png\");\n\t\t\tFileInputStream fileInputStream = new FileInputStream(file);\n\n\t\t\treturn new MockMultipartFile(\"1\", \"image.png\", \"image/png\", fileInputStream);\n\t\t} catch (final IOException e) {\n\t\t\tthrow new RuntimeException(e);\n\t\t}\n\t}\n\n\tpublic static MockMultipartFile makeMultipartFile2() {\n\t\ttry {\n\t\t\tFile file = new File(\"src/test/resources/image.png\");\n\t\t\tFileInputStream fileInputStream = new FileInputStream(file);\n\n\t\t\treturn new MockMultipartFile(\"2\", \"image.png\", \"image/png\", fileInputStream);\n\t\t} catch (final IOException e) {\n\t\t\tthrow new RuntimeException(e);\n\t\t}\n\t}\n\n\tpublic static MockMultipartFile makeMultipartFile3() {\n\t\ttry {\n\t\t\tFile file = new File(\"src/test/resources/image.png\");\n\t\t\tFileInputStream fileInputStream = new FileInputStream(file);\n\n\t\t\treturn new MockMultipartFile(\"3\", \"image.png\", \"image/png\", fileInputStream);\n\t\t} catch (final IOException e) {\n\t\t\tthrow new RuntimeException(e);\n\t\t}\n\t}\n}" } ]
import static com.moabam.api.domain.room.RoomType.*; import static org.assertj.core.api.Assertions.*; import static org.mockito.BDDMockito.*; import java.util.ArrayList; import java.util.List; import java.util.Optional; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentMatchers; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import com.moabam.api.application.member.MemberService; import com.moabam.api.application.room.mapper.RoomMapper; import com.moabam.api.domain.member.Member; import com.moabam.api.domain.room.Participant; import com.moabam.api.domain.room.Room; import com.moabam.api.domain.room.Routine; import com.moabam.api.domain.room.repository.ParticipantRepository; import com.moabam.api.domain.room.repository.ParticipantSearchRepository; import com.moabam.api.domain.room.repository.RoomRepository; import com.moabam.api.domain.room.repository.RoutineRepository; import com.moabam.api.dto.room.CreateRoomRequest; import com.moabam.global.error.exception.ForbiddenException; import com.moabam.support.fixture.MemberFixture; import com.moabam.support.fixture.RoomFixture;
9,610
package com.moabam.api.application.room; @ExtendWith(MockitoExtension.class) class RoomServiceTest { @InjectMocks private RoomService roomService; @Mock
package com.moabam.api.application.room; @ExtendWith(MockitoExtension.class) class RoomServiceTest { @InjectMocks private RoomService roomService; @Mock
private MemberService memberService;
1
2023-10-20 06:15:43+00:00
12k
liukanshan1/PrivateTrace-Core
src/main/java/Priloc/protocol/Main2.java
[ { "identifier": "Circle", "path": "src/main/java/Priloc/area/basic/Circle.java", "snippet": "public class Circle implements Serializable {\n private Point center;\n private double radius;\n public static final circleFilter DISTANCE_FILTER = new distantFilter();\n public static final circleFilter AREA_FILTER = new areaFilter();\n\n public Circle(Point center, double radius) {\n this.center = center;\n this.radius = radius;\n }\n\n public double getRadius() {\n return radius;\n }\n\n public Point getCenter() {\n return center;\n }\n\n @Override\n public String toString() {\n return \"Circle{\" +\n \"center=\" + center +\n \", radius=\" + radius +\n '}';\n }\n\n public boolean isInside(Circle c) {\n return center.distance(c.center) <= Math.abs(radius - c.radius);\n }\n\n public boolean isInside(Point p) {\n return center.distance(p) <= radius;\n }\n\n public static boolean isInside(Point p, Circle[] circles) {\n for (Circle c : circles) {\n if (c.isInside(p)) return true;\n }\n return false;\n }\n\n public EncryptedCircle encrypt(){\n return new EncryptedCircle(this);\n }\n\n public EncryptedCircle enc(){\n return encrypt();\n }\n\n public static EncryptedCircle[] encrypt(Circle[] circles,PaillierKey pk){\n EncryptedCircle[] encryptedCircles = new EncryptedCircle[circles.length];\n for(int i = 0; i < circles.length; i++){\n encryptedCircles[i] = circles[i].encrypt();\n }\n return encryptedCircles;\n }\n\n public double area() {\n return Math.PI * radius * radius;\n }\n\n public boolean isIntersect(Circle c) {\n return center.distance(c.center) <= radius + c.radius;\n }\n\n public boolean isIntersect(List<Circle> circles) {\n for (Circle c : circles) {\n if (isIntersect(c)) {\n return true;\n }\n }\n return false;\n }\n\n /* AI生成代码,未验证逻辑! */\n public double intersectArea(Circle c) {\n if (!isIntersect(c)) {\n return 0;\n }\n double d = center.distance(c.center);\n double r1 = radius;\n double r2 = c.radius;\n double a = Math.acos((r1 * r1 + d * d - r2 * r2) / (2 * r1 * d));\n double b = Math.acos((r2 * r2 + d * d - r1 * r1) / (2 * r2 * d));\n return r1 * r1 * a + r2 * r2 * b - d * r1 * Math.sin(a);\n }\n\n /* 新增的圆c的有用面积占圆c的面积的百分比 */\n public double utility(Circle c) {\n return 1 - intersectArea(c) / c.area();\n }\n\n public static abstract class circleFilter {\n public abstract boolean reject(Circle c, Circle newCircle, double strict);\n public abstract boolean reject(Circle c, Circle newCircle);\n }\n\n public static class distantFilter extends circleFilter {\n @Override\n public boolean reject(Circle c, Circle newCircle, double strict) {\n if (newCircle.radius > Constant.RADIUS) {\n return true;\n }\n if (Constant.REJECT_R_LESS_P5) {\n if (newCircle.radius < 0.5) {\n return true;\n }\n }\n double distance = c.center.distance(newCircle.center);\n return distance < (c.radius + newCircle.radius) * strict + Math.abs(c.radius - newCircle.radius) * (1-strict);\n }\n\n @Override\n public String toString() {\n return \"距离过滤器\";\n }\n\n @Override\n public boolean reject(Circle c, Circle newCircle) {\n return reject(c, newCircle, 0.2);\n }\n }\n\n public static class areaFilter extends circleFilter {\n @Override\n public boolean reject(Circle c, Circle newCircle, double strict) {\n if (newCircle.radius > Constant.RADIUS) {\n return true;\n }\n if (Constant.REJECT_R_LESS_P5) {\n if (newCircle.radius < 0.5) {\n return true;\n }\n }\n return c.utility(newCircle) < strict;\n }\n\n @Override\n public String toString() {\n return \"面积过滤器\";\n }\n\n @Override\n public boolean reject(Circle c, Circle newCircle) {\n return reject(c, newCircle, 0.5);\n }\n }\n}" }, { "identifier": "EncryptedCircle", "path": "src/main/java/Priloc/area/basic/EncryptedCircle.java", "snippet": "public class EncryptedCircle implements Serializable {\n private EncryptedPoint encryptedPoint;\n private double radius;\n\n public EncryptedCircle(Circle circle) {\n this.encryptedPoint = new EncryptedPoint(circle.getCenter());\n this.radius = circle.getRadius();\n }\n\n public EncryptedCircle(EncryptedPoint encryptedPoint, double radius) {\n this.encryptedPoint = encryptedPoint;\n this.radius = radius;\n }\n\n public double getRadius() {\n return radius;\n }\n\n public BigInteger squareDistance(EncryptedCircle other) {\n return encryptedPoint.squareDistance(other.encryptedPoint);\n }\n\n public EncSquareDistance encSquareDistance(EncryptedCircle other) {\n return new EncSquareDistance(squareDistance(other));\n }\n\n public int isIntersect(double maxSquareDistance, BigInteger squareDistance) {\n BigInteger maxSquareDistanceEnc = Utils.encryptDouble(maxSquareDistance);\n return SecCmp.secCmp(squareDistance, maxSquareDistanceEnc, User.pai, User.cp, User.csp);\n }\n\n /**\n * -1 相交\n * 0 不允许 prune\n * n 允许 prune 2n+1 个节点\n */\n public Pair<Integer, BigInteger> howFarAway(EncryptedCircle other) {\n double maxSquareDistance = (radius + other.radius) * (radius + other.radius);\n BigInteger squareDistance = squareDistance(other);\n int result = isIntersect(maxSquareDistance, squareDistance);\n if (result == 0) {\n for (int i = 0; i < Constant.COMPARE_DISTANCE.length; i++) {\n result = isIntersect(Constant.COMPARE_DISTANCE[i], squareDistance);\n if (result != 0) {\n // System.out.println((\"修剪\" + Constant.PRUNE_NUM[i]));\n return new Pair<>(Constant.PRUNE_NUM[i], squareDistance);\n }\n }\n // System.out.println((\"修剪\" + Constant.PRUNE_NUM[Constant.PRUNE_NUM.length - 1]));\n return new Pair<>(Constant.PRUNE_NUM[Constant.PRUNE_NUM.length - 1], squareDistance);\n } else {\n return new Pair<>(-1, squareDistance);\n }\n }\n\n public Pair<Integer, BigInteger> noHowFarAway(EncryptedCircle other) {\n double maxSquareDistance = (radius + other.radius) * (radius + other.radius);\n BigInteger squareDistance = squareDistance(other);\n int result = isIntersect(maxSquareDistance, squareDistance);\n if (result == 0) {\n return new Pair<>(0, squareDistance);\n } else {\n return new Pair<>(-1, squareDistance);\n }\n }\n\n public boolean isIntersect(EncryptedCircle other) {\n double maxSquareDistance = (radius + other.radius) * (radius + other.radius);\n BigInteger squareDistance = squareDistance(other);\n BigInteger maxSquareDistanceEnc = Utils.encryptDouble(maxSquareDistance);\n int result = SecCmp.secCmp(squareDistance, maxSquareDistanceEnc, User.pai, User.cp, User.csp);\n if (result == 0) {\n return false;\n } else {\n return true;\n }\n }\n\n public Circle decrypt() {\n return new Circle(this.encryptedPoint.decrypt(), this.radius);\n }\n}" }, { "identifier": "Polygon", "path": "src/main/java/Priloc/area/shape/Polygon.java", "snippet": "public class Polygon implements Shape {\n private Triangle[] triangles;\n\n public Polygon(Location... locations) {\n triangles = new Triangle[locations.length - 2];\n for(int i = 0; i < locations.length - 2; i++) {\n triangles[i] = new Triangle(locations[0], locations[i + 1], locations[i + 2]);\n }\n }\n\n @Override\n public void init() {\n for(Triangle triangle : triangles) {\n triangle.init();\n }\n }\n\n @Override\n public Circle[] fitByCircle(int num, Circle.circleFilter filter, double strict) {\n Circle[] circles = new Circle[num * triangles.length];\n for (int i = 0; i < triangles.length; i++) {\n Circle[] cs = triangles[i].fitByCircle(num, filter, strict);\n System.arraycopy(cs, 0, circles, i * num, num);\n }\n return circles;\n }\n\n @Override\n public Circle[] fitByCircle(int num, Circle.circleFilter filter) {\n Circle[] circles = new Circle[num * triangles.length];\n for (int i = 0; i < triangles.length; i++) {\n Circle[] cs = triangles[i].fitByCircle(num, filter);\n System.arraycopy(cs, 0, circles, i * num, num);\n }\n return circles;\n }\n\n @Override\n public double checkCoverage(int num, Circle[] circles) {\n double res = 0;\n int len = circles.length / triangles.length;\n Circle[] cs = new Circle[len];\n for (int i = 0; i < triangles.length; i++) {\n System.arraycopy(circles, i * len, cs, 0, len);\n res += triangles[i].checkCoverage(num, cs);\n }\n return res / triangles.length;\n }\n}" }, { "identifier": "Shape", "path": "src/main/java/Priloc/area/shape/Shape.java", "snippet": "public interface Shape {\n void init();\n Circle[] fitByCircle(int num, Circle.circleFilter filter, double strict);\n Circle[] fitByCircle(int num, Circle.circleFilter filter);\n default EncryptedCircle[] encrypt(PaillierKey pk, Circle[] circles) {\n return Circle.encrypt(circles, pk);\n }\n default Circle[] fit() {\n return fitByCircle(Constant.TRIANGLE_NUM, Constant.FILTER);\n }\n double checkCoverage(int num, Circle[] circles);\n}" }, { "identifier": "Triangle", "path": "src/main/java/Priloc/area/shape/Triangle.java", "snippet": "public class Triangle implements Shape {\n\n private Point point1, point2, point3;\n private double maxX, maxY, maxZ, minX, minY, minZ;\n private Plane plane;\n private double side12, side13, side23;\n private double area = 0;\n private boolean initialized = false;\n\n public Triangle(Point point1, Point point2, Point point3, boolean lazyInit) {\n this.point1 = point1;\n this.point2 = point2;\n this.point3 = point3;\n }\n\n public Triangle(Point point1, Point point2, Point point3) {\n this.point1 = point1;\n this.point2 = point2;\n this.point3 = point3;\n init();\n }\n\n public Triangle(Location loc1, Location loc2, Location loc3) {\n this(new Point(loc1), new Point(loc2), new Point(loc3));\n }\n\n @Override\n public void init() {\n if(initialized) return;\n this.maxX = Math.max(point1.getX(), Math.max(point2.getX(), point3.getX()));\n this.maxY = Math.max(point1.getY(), Math.max(point2.getY(), point3.getY()));\n this.maxZ = Math.max(point1.getZ(), Math.max(point2.getZ(), point3.getZ()));\n this.minX = Math.min(point1.getX(), Math.min(point2.getX(), point3.getX()));\n this.minY = Math.min(point1.getY(), Math.min(point2.getY(), point3.getY()));\n this.minZ = Math.min(point1.getZ(), Math.min(point2.getZ(), point3.getZ()));\n this.plane = new Plane(point1, point2, point3);\n this.side12 = point1.distance(point2);\n this.side13 = point1.distance(point3);\n this.side23 = point2.distance(point3);\n double s = (side12 + side13 + side23) / 2;\n this.area = Math.sqrt(s * (s - side12) * (s - side13) * (s - side23));\n initialized = true;\n }\n\n /* 未检查是否init! */\n public double getArea() {\n return area;\n }\n\n public boolean isInside(Point p, double error) {\n if (!initialized) {\n init();\n }\n if (p.getX() > maxX || p.getX() < minX || p.getY() > maxY || p.getY() < minY || p.getZ() > maxZ || p.getZ() < minZ) {\n return false;\n }\n if (plane.isInside(p)) {\n double a = new Triangle(point1, point2, p).getArea();\n double b = new Triangle(point1, point3, p).getArea();\n double c = new Triangle(point2, point3, p).getArea();\n // 允许一些误差值\n return Math.abs(a + b + c - area) < error;\n }\n return false;\n }\n\n public boolean isInside(Point p) {\n return isInside(p, 0.01);\n }\n\n private Point samplingPoint() {\n if (!initialized) {\n init();\n }\n while (true) {\n // 没有实现一定概率上关注三个角(FREED仓库里面的shapes.py)\n double x = Math.random() * (maxX - minX) + minX;\n double y = Math.random() * (maxY - minY) + minY;\n Point p = plane.getPointFromXY(x, y);\n if (isInside(p)) {\n return p;\n }\n }\n }\n\n private Point[] samplingPoints(int num) {\n Point[] points = new Point[num];\n for (int i = 0; i < num; i++) {\n points[i] = samplingPoint();\n }\n return points;\n }\n\n private Circle getInscribedCircle(Point point) {\n if (!initialized) {\n init();\n }\n Triangle t12 = new Triangle(point1, point2, point);\n Triangle t13 = new Triangle(point1, point3, point);\n Triangle t23 = new Triangle(point2, point3, point);\n double h12 = 2 * t12.getArea() / side12;\n double h13 = 2 * t13.getArea() / side13;\n double h23 = 2 * t23.getArea() / side23;\n double r = Math.min(h12, Math.min(h13, h23));\n return new Circle(point, r);\n }\n\n @Override\n public Circle[] fitByCircle(int num, Circle.circleFilter filter, double strict) {\n Circle[] circles = new Circle[num];\n for (int i = 0; i < num; i++) {\n Circle c;\n while (true) {\n c = getInscribedCircle(samplingPoint());\n if (filter(circles, i, c, filter, strict)) {\n break;\n }\n }\n circles[i] = c;\n }\n return circles;\n }\n\n private boolean filter(Circle[] circles, int end, Circle c, Circle.circleFilter filter, double strict) {\n for (int j = 0; j < end; j++) {\n if (filter.reject(circles[j], c, strict)) {\n return false;\n }\n }\n return true;\n }\n\n @Override\n public Circle[] fitByCircle(int num, Circle.circleFilter filter) {\n Circle[] circles = new Circle[num];\n for (int i = 0; i < num; i++) {\n Circle c;\n while (true) {\n c = getInscribedCircle(samplingPoint());\n if (filter(circles, i, c, filter)) {\n break;\n }\n }\n circles[i] = c;\n }\n return circles;\n }\n\n private boolean filter(Circle[] circles, int end, Circle c, Circle.circleFilter filter) {\n for (int j = 0; j < end; j++) {\n if (filter.reject(circles[j], c)) {\n return false;\n }\n }\n return true;\n }\n\n @Override\n public double checkCoverage(int num, Circle[] circles) {\n Point[] points = samplingPoints(num);\n List<Circle> circleList = new ArrayList<>();\n for (Point p : points) {\n circleList.add(new Circle(p, Constant.RADIUS));\n }\n double count = 0.0;\n for (Circle c : circleList) {\n if (c.isIntersect(List.of(circles))) {\n count++;\n }\n }\n return count / num;\n }\n}" }, { "identifier": "EncTrajectory", "path": "src/main/java/Priloc/data/EncTrajectory.java", "snippet": "public class EncTrajectory implements Serializable {\n private List<EncTmLocData> eTLDs;\n private String name;\n\n public EncTrajectory(Trajectory trajectory) {\n this.name = trajectory.getName();\n List<TimeLocationData> tlds = trajectory.getTLDs();\n this.eTLDs = new ArrayList<>();\n EncTmLocData pETLD = null;\n for (int i = 0; i < tlds.size(); i++) {\n TimeLocationData tld = tlds.get(i);\n EncTmLocData cETLD = tld.encrypt();\n if (pETLD != null) {\n pETLD.setNext(cETLD);\n }\n cETLD.setPrevious(pETLD);\n eTLDs.add(cETLD);\n pETLD = cETLD;\n }\n }\n\n public EncTrajectory(EncryptedCircle encryptedCircle) {\n this.name = \"范围轨迹\";\n eTLDs = new ArrayList<>();\n EncTmLocData pETLD = null;\n for (int i = 0; i < 24; i++) {\n for (int j = 0; j < 60; j += Constant.INTERVAL) {\n Date date = new Date(2008, Calendar.JUNE, 24, i, j);\n EncTmLocData cETLD = new EncTmLocData(encryptedCircle, date);\n if (pETLD != null) {\n pETLD.setNext(cETLD);\n }\n cETLD.setPrevious(pETLD);\n eTLDs.add(cETLD);\n pETLD = cETLD;\n }\n }\n }\n\n @Override\n public String toString() {\n return \"EncTrajectory{\" +\n \"name=\" + name +\n '}';\n }\n\n public List<EncTmLocData> geteTLDs() {\n return eTLDs;\n }\n\n public Date getStartDate() {\n return this.eTLDs.get(0).getDate();\n }\n\n public Date getEndDate() {\n return this.eTLDs.get(eTLDs.size() - 1).getDate();\n }\n\n// private void writeObject(ObjectOutputStream out) throws IOException {\n// //只序列化以下3个成员变量\n// out.writeObject(this.eTLDs);\n// out.writeObject(this.name);\n// }\n//\n// private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {\n// //注意:read()的顺序要和write()的顺序一致。\n// this.eTLDs = (List<EncTmLocData>) in.readObject();\n// this.name = (String) in.readObject();\n// EncTmLocData prev = null;\n// for (EncTmLocData curr : eTLDs) {\n// curr.setPrevious(prev);\n// if (prev != null) {\n// prev.setNext(curr);\n// }\n// prev = curr;\n// }\n// }\n}" }, { "identifier": "TimeLocationData", "path": "src/main/java/Priloc/data/TimeLocationData.java", "snippet": "public class TimeLocationData implements Serializable {\n private Location loc;\n private Date date;\n private double accuracy = Constant.RADIUS;\n private TimeLocationData nTLD = null;\n private TimeLocationData pTLD = null;\n\n public TimeLocationData(Location loc, Date date) {\n this.loc = loc;\n this.date = date;\n }\n\n public TimeLocationData(Location loc, Date date, TimeLocationData nTLD) {\n this.loc = loc;\n this.date = date;\n this.nTLD = nTLD;\n }\n\n public void setDate(Date date) {\n this.date = date;\n }\n\n public void setNext(TimeLocationData nTLD) {\n this.nTLD = nTLD;\n }\n\n public void setPrevious(TimeLocationData pTLD) {\n this.pTLD = pTLD;\n }\n\n @Override\n public String toString() {\n return \"TrajectoryData{\" +\n \"loc=\" + loc +\n \", date=\" + date +\n '}';\n }\n\n public Location getLoc() {\n return loc;\n }\n\n public Date getDate() {\n return date;\n }\n\n public double getAccuracy() {\n return accuracy;\n }\n\n public boolean hasNext() {\n return nTLD != null;\n }\n\n public TimeLocationData next() {\n return nTLD;\n }\n\n public boolean hasPrevious() {\n return pTLD != null;\n }\n\n public TimeLocationData previous() {\n return pTLD;\n }\n\n public EncTmLocData encrypt(){\n return new EncTmLocData(this);\n }\n\n public Circle getCircle() {\n return new Circle(new Point(loc), accuracy);\n }\n}" }, { "identifier": "Trajectory", "path": "src/main/java/Priloc/data/Trajectory.java", "snippet": "public class Trajectory implements Callable<EncTrajectory>, Serializable {\n private List<TimeLocationData> TLDs;\n private String name;\n\n public Trajectory(List<TimeLocationData> tlds, String name) {\n this.TLDs = tlds;\n this.name = name;\n }\n\n public String getName() {\n return name;\n }\n\n @Override\n public String toString() {\n return \"Trajectory{\" +\n \"name='\" + name + '\\'' +\n \"size='\" + TLDs.size() + '\\'' +\n '}';\n }\n\n public List<TimeLocationData> getTLDs() {\n return TLDs;\n }\n\n public Date getStartDate() {\n return this.TLDs.get(0).getDate();\n }\n\n public Date getEndDate() {\n return this.TLDs.get(TLDs.size() - 1).getDate();\n }\n\n public EncTrajectory encrypt() {\n return new EncTrajectory(this);\n }\n\n public static boolean isIntersect(Trajectory t1, Trajectory t2) {\n // 判断时间重合\n Map<Date, List<Circle>> positiveCircles = new HashMap<>();\n for (TimeLocationData tld : t1.TLDs) {\n Date startDate = tld.getDate();\n List<Circle> circles = positiveCircles.get(startDate);\n if (circles == null) {\n circles = new ArrayList<>();\n }\n circles.add(tld.getCircle());\n positiveCircles.put(startDate, circles);\n }\n for (TimeLocationData tld : t2.TLDs) {\n Date startDate = tld.getDate();\n List<Circle> circles = positiveCircles.get(startDate);\n if (circles == null) {\n continue;\n }\n if (tld.getCircle().isIntersect(circles)) {\n return true;\n }\n }\n return false;\n }\n\n @Override\n public EncTrajectory call() {\n return encrypt();\n }\n\n// /**\n// * 自定义序列化 搭配transist使用\n// */\n// private void writeObject(ObjectOutputStream out) throws IOException {\n// //只序列化以下3个成员变量\n// out.writeObject(this.TLDs);\n// out.writeObject(this.name);\n// }\n//\n// private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {\n// //注意:read()的顺序要和write()的顺序一致。\n// this.TLDs = (List<TimeLocationData>) in.readObject();\n// this.name = (String) in.readObject();\n// TimeLocationData prev = null;\n// for (TimeLocationData curr : TLDs) {\n// curr.setPrevious(prev);\n// if (prev != null) {\n// prev.setNext(curr);\n// }\n// prev = curr;\n// }\n// }\n}" }, { "identifier": "Location", "path": "src/main/java/Priloc/geo/Location.java", "snippet": "public class Location implements Serializable {\n private double latitude;\n private double longitude;\n private double altitude = 0.0;\n\n public Location(double latitude, double longitude, double altitude) {\n this(latitude, longitude);\n this.altitude = altitude;\n }\n\n public Location(double latitude, double longitude) {\n this.latitude = latitude;\n this.longitude = longitude;\n }\n\n public double getLatitude() {\n return latitude;\n }\n\n public double getLongitude() {\n return longitude;\n }\n\n @Override\n public String toString() {\n return \"PlainLocation{\" +\n \"latitude=\" + latitude +\n \", longitude=\" + longitude +\n \", altitude=\" + altitude +\n //\", XYZ=\" + toXYZ() +\n '}';\n }\n\n public Turple<Double, Double, Double> toXYZ() {\n return Utils.gcj02ToXYZ(longitude, latitude, altitude);\n }\n\n public EncryptedPoint encrypt() {\n Turple<Double, Double, Double> xyz = toXYZ();\n return new EncryptedPoint(xyz.first, xyz.second, xyz.third);\n }\n\n public double squareDistance(Location other) {\n// Turple<Double, Double, Double> xyz1 = toXYZ();\n// Turple<Double, Double, Double> xyz2 = other.toXYZ();\n// return Math.pow(xyz1.first - xyz2.first, 2) + Math.pow(xyz1.second - xyz2.second, 2) + Math.pow(xyz1.third - xyz2.third, 2);\n return Math.pow(distance(other), 2);\n }\n\n public double distance(Location other) {\n// return Math.sqrt(squareDistance(other));\n GlobalCoordinates source = new GlobalCoordinates(latitude, longitude);\n GlobalCoordinates target = new GlobalCoordinates(other.latitude, other.longitude);\n return new GeodeticCalculator().calculateGeodeticCurve(Ellipsoid.WGS84, source, target).getEllipsoidalDistance();\n }\n\n public double encodeDistance(Location other) {\n Turple<Double, Double, Double> xyz1 = toXYZ();\n Turple<Double, Double, Double> xyz2 = other.toXYZ();\n double squareDist = Math.pow(xyz1.first - xyz2.first, 2) + Math.pow(xyz1.second - xyz2.second, 2) + Math.pow(xyz1.third - xyz2.third, 2);\n return Math.sqrt(squareDist);\n }\n}" }, { "identifier": "Constant", "path": "src/main/java/Priloc/utils/Constant.java", "snippet": "public class Constant {\n public static final int FIXED_POINT = 8;\n public static final int THREAD = 12;\n public static final int KEY_LEN = 512;\n public static final int[] REDUCE = new int[]{2160000, 1820000, -5690000};\n\n public static final boolean IGNORE_DATE = true;\n public static final boolean REJECT_R_LESS_P5 = true;\n\n // 时间段大小\n public final static int INTERVAL = 10;\n // 每个时间段的移动最大距离\n public static final double RADIUS = 200.0;\n // TODO 优化 不同时间段的活跃距离\n public static final double[] COMPARE_DISTANCE = new double[]{1200 * 1200.0};\n public static final int[] PRUNE_NUM = new int[]{0, 2};\n // 控制形状拟合效果\n public static final int TRIANGLE_NUM = 100;\n public static final Circle.circleFilter FILTER = new Circle.distantFilter(); //new Circle.areaFilter();\n\n public static String toStr() {\n return \"Constant{\" +\n \"INTERVAL=\" + INTERVAL +\n \", RADIUS=\" + RADIUS +\n \", IGNORE_DATE=\" + IGNORE_DATE +\n \", REJECT_R_LESS_P5=\" + REJECT_R_LESS_P5 +\n \", COMPARE_DISTANCE=\" + Arrays.toString(COMPARE_DISTANCE) +\n \", PRUNE_NUM=\" + Arrays.toString(PRUNE_NUM) +\n \", TRIANGLE_NUM=\" + TRIANGLE_NUM +\n \", FILTER=\" + FILTER +\n '}';\n }\n}" }, { "identifier": "Pair", "path": "src/main/java/Priloc/utils/Pair.java", "snippet": "public class Pair<T1, T2> {\n\t\n public final T1 first;\n public final T2 second;\n\n public Pair(T1 first, T2 second) {\n this.first = first;\n this.second = second;\n }\n\n @Override\n public String toString() {\n return \"Pair{\" +\n \"first=\" + first +\n \", second=\" + second +\n '}';\n }\n}" }, { "identifier": "User", "path": "src/main/java/Priloc/utils/User.java", "snippet": "public class User {\n\n\tpublic static PaillierPrivateKey prikey = null;\n\tpublic static Paillier pai = null;\n\tprivate static PaillierThdPrivateKey[] ThdKey = null;\n\tpublic static PaillierThdDec cp = null;\n\tpublic static PaillierThdDec csp = null;\n\n\tstatic {\n\t\tKeys key;\n\t\ttry {\n\t\t\tkey = (Keys) Utils.readObject(\"./keys\");\n\t\t} catch (Exception e) {\n\t\t\tkey = new Keys(Constant.KEY_LEN);\n\t\t\ttry {\n\t\t\t\tUtils.writeObject(key, \"./keys\");\n\t\t\t} catch (IOException ex) {\n\t\t\t\tthrow new RuntimeException(ex);\n\t\t\t}\n\t\t}\n\t\tprikey = key.prikey;\n\t\tpai = key.pai;\n\t\tThdKey = key.ThdKey;\n\t\tcp = key.cp;\n\t\tcsp = key.csp;\n\t}\n}" }, { "identifier": "getEncTrajectories", "path": "src/main/java/Priloc/protocol/Main.java", "snippet": " public static Pair<EncTrajectory[], Trajectory[]> getEncTrajectories(ExecutorService pool, StopWatch stopWatch) throws Exception{\n stopWatch.start(\"读取待比较的轨迹\");\n String pathname = \"./GeoLife Trajectories 1.3/Data/002/Trajectory/\";\n File dir = new File(pathname);\n String[] negativePath = dir.list();\n TrajectoryReader[] negativeReaders = new TrajectoryReader[negativePath.length];\n for (int i = 0; i < negativePath.length; i++) {\n negativeReaders[i] = new TrajectoryReader(pathname + negativePath[i]);\n }\n Trajectory[] negativeTrajectories = new Trajectory[negativePath.length];\n for (int i = 0; i < negativePath.length; i++) {\n negativeTrajectories[i] = negativeReaders[i].load();\n }\n stopWatch.stop();\n System.out.println(\"数据读取完成\" + stopWatch.shortSummary());\n // 加密待比较轨迹\n EncTrajectory[] eNegativeTrajectories = new EncTrajectory[negativePath.length];\n Future<EncTrajectory>[] future1 = new Future[negativePath.length];\n// stopWatch.start(\"加密待比较轨迹\");\n// for (int i = 0; i < negativePath.length; i++) {\n// future1[i] = pool.submit(negativeTrajectories[i]);\n// }\n// for (int i = 0; i < negativePath.length; i++) {\n// eNegativeTrajectories[i] = future1[i].get();\n// }\n// stopWatch.stop();\n System.out.println(\"加密完成\" + stopWatch.shortSummary());\n return new Pair<>(eNegativeTrajectories, negativeTrajectories);\n }" } ]
import Priloc.area.basic.Circle; import Priloc.area.basic.EncryptedCircle; import Priloc.area.shape.Polygon; import Priloc.area.shape.Shape; import Priloc.area.shape.Triangle; import Priloc.data.EncTrajectory; import Priloc.data.TimeLocationData; import Priloc.data.Trajectory; import Priloc.geo.Location; import Priloc.utils.Constant; import Priloc.utils.Pair; import Priloc.utils.User; import org.springframework.util.StopWatch; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import static Priloc.protocol.Main.getEncTrajectories;
8,447
package Priloc.protocol; public class Main2 { public static void main(String[] args) throws Exception { System.out.println(Constant.toStr()); User.pai.setDecryption(User.prikey); ExecutorService pool = Executors.newFixedThreadPool(Constant.THREAD); StopWatch stopWatch = new StopWatch(); // Part-1 范围比较 // 生成范围 stopWatch.start("创建范围"); Location l1 = new Location(39.913385, 116.415884); Location l2 = new Location(39.915744, 116.417761); Location l3 = new Location(39.91306, 116.419576); Triangle triangle = new Triangle(l1, l2, l3); // 王府井 市中心三角 l1 = new Location(40.004086, 116.393274); l2 = new Location(39.994413, 116.393884); l3 = new Location(39.994911, 116.407646); Location l4 = new Location(40.004721, 116.407036); Polygon p1 = new Polygon(l1, l2, l3, l4); // 国家体育中心鸟巢 Shape[] shapes = new Shape[2]; shapes[0] = triangle; shapes[1] = p1; stopWatch.stop(); System.out.println(stopWatch.getTotalTimeSeconds()); // 拟合
package Priloc.protocol; public class Main2 { public static void main(String[] args) throws Exception { System.out.println(Constant.toStr()); User.pai.setDecryption(User.prikey); ExecutorService pool = Executors.newFixedThreadPool(Constant.THREAD); StopWatch stopWatch = new StopWatch(); // Part-1 范围比较 // 生成范围 stopWatch.start("创建范围"); Location l1 = new Location(39.913385, 116.415884); Location l2 = new Location(39.915744, 116.417761); Location l3 = new Location(39.91306, 116.419576); Triangle triangle = new Triangle(l1, l2, l3); // 王府井 市中心三角 l1 = new Location(40.004086, 116.393274); l2 = new Location(39.994413, 116.393884); l3 = new Location(39.994911, 116.407646); Location l4 = new Location(40.004721, 116.407036); Polygon p1 = new Polygon(l1, l2, l3, l4); // 国家体育中心鸟巢 Shape[] shapes = new Shape[2]; shapes[0] = triangle; shapes[1] = p1; stopWatch.stop(); System.out.println(stopWatch.getTotalTimeSeconds()); // 拟合
Future<Circle[]>[] futures = new Future[shapes.length];
0
2023-10-22 06:28:51+00:00
12k
tuxming/xmfx
BaseUI/src/main/java/com/xm2013/jfx/control/listview/XmListCell.java
[ { "identifier": "FxKit", "path": "BaseUI/src/main/java/com/xm2013/jfx/common/FxKit.java", "snippet": "public class FxKit {\n\n /** The Constant DOUBLE_ARROW_RIGHT. */\n public static final String DOUBLE_ARROW_RIGHT = \"<svg version=\\\"1.1\\\" xmlns=\\\"http://www.w3.org/2000/svg\\\" p-id=\\\"1050\\\">\" +\n \"<path d=\\\"M759.466667 533.333333L469.333333 243.2l29.866667-29.866667 320 320-320 320-29.866667-29.866666 \" +\n \"290.133334-290.133334z m-298.666667 0L170.666667 243.2l29.866666-29.866667 320 320L200.533333 853.333333l\" +\n \"-29.866666-29.866666 290.133333-290.133334z\\\" fill=\\\"#444444\\\" p-id=\\\"1051\\\"></path></svg>\";\n\n /** The Constant DOUBLE_ARROW_LEFT. */\n public static final String DOUBLE_ARROW_LEFT = \"<svg version=\\\"1.1\\\" xmlns=\\\"http://www.w3.org/2000/svg\\\" p-id=\\\"1197\\\">\" +\n \"<path d=\\\"M170.666667 533.333333L490.666667 213.333333l29.866666 29.866667-290.133333 290.133333 290.133333 \" +\n \"290.133334-29.866666 29.866666L170.666667 533.333333z m298.666666 0L789.333333 213.333333l29.866667 29.866667\" +\n \"-290.133333 290.133333 290.133333 290.133334-29.866667 29.866666-320-320z\\\" fill=\\\"#444444\\\" p-id=\\\"1198\\\"></path></svg>\";\n\n /** The Constant ARROW_RIGHT. */\n public static final String ARROW_RIGHT = \"M674.133333 533.333333L341.333333 200.533333l29.866667-29.866666 \" +\n \"362.666667 362.666666L371.2 896l-29.866667-29.866667 332.8-332.8z\";\n\n /** The Constant ARROW_LEFT. */\n public static final String ARROW_LEFT = \"M396.8 494.933333l332.8-332.8-29.866667-29.866666-362.666666 362.666666 \" +\n \"362.666666 362.666667 29.866667-29.866667-332.8-332.8z\";\n\n /** The Constant CLEAN_PATH. */\n public static final String CLEAN_PATH = \"M512 64c-247.00852 0-448 200.960516-448 448S264.960516 960 512 \" +\n \"960c247.00852 0 448-200.960516 448-448S759.039484 64 512 64zM694.752211 \" +\n \"649.984034c12.480043 12.54369 12.447359 32.768069-0.063647 45.248112-6.239161 \" +\n \"6.208198-14.399785 9.34412-22.591372 9.34412-8.224271 0-16.415858-3.135923-22.65674\" +\n \"-9.407768l-137.60043-138.016718-138.047682 136.576912c-6.239161 6.14455-14.368821\" +\n \" 9.247789-22.496761 9.247789-8.255235 0-16.479505-3.168606-22.751351-9.504099-12.416396\" +\n \"-12.576374-12.320065-32.800753 0.25631-45.248112l137.887703-136.384249-137.376804-137.824056c\" +\n \"-12.480043-12.512727-12.447359-32.768069 0.063647-45.248112 12.512727-12.512727 \" +\n \"32.735385-12.447359 45.248112 0.063647l137.567746 137.984034 138.047682-136.575192c12.54369\" +\n \"-12.447359 32.831716-12.320065 45.248112 0.25631 12.447359 12.576374 12.320065 \" +\n \"32.831716-0.25631 45.248112L557.344443 512.127295 694.752211 649.984034z\";\n\n /** The Constant DATE_PATH. */\n public static final String DATE_PATH = \"M929.493333 73.130667l-187.413333 0L742.08 24.874667c0-11.776-9.536-\" +\n \"21.333333-21.333333-21.333333s-21.333333 9.557333-21.333333 21.333333l0 48.256L324.565333 73.130667 \" +\n \"324.565333 24.874667c0-11.776-9.557333-21.333333-21.333333-21.333333s-21.333333 9.557333-21.333333 \" +\n \"21.333333l0 48.256L129.28 73.130667c-55.210667 0-125.717333 70.485333-125.717333 125.717333l0 695.914667c0 \" +\n \"55.210667 70.506667 125.717333 125.717333 125.717333L929.493333 1020.48c59.349333 0 90.965333-73.002667 \" +\n \"90.965333-125.717333L1020.458667 198.826667C1020.458667 146.133333 988.864 73.130667 929.493333 \" +\n \"73.130667zM129.28 115.797333l152.64 0 0 152.64c0 11.776 9.557333 21.333333 21.333333 21.333333s21.333333-\" +\n \"9.557333 21.333333-21.333333L324.586667 115.797333l374.848 0 0 152.64c0 11.776 9.536 21.333333 21.333333 \" +\n \"21.333333s21.333333-9.557333 21.333333-21.333333L742.101333 115.797333l187.413333 0c26.752 0 48.298667 \" +\n \"45.418667 48.298667 83.050667l0 187.434667L46.229333 386.282667 46.229333 198.826667C46.229333 166.229333 \" +\n \"96.661333 115.797333 129.28 115.797333zM929.493333 977.792 129.28 977.792c-31.829333 0-83.050667-51.221333\" +\n \"-83.050667-83.050667L46.229333 428.928l931.562667 0 0 465.813333C977.792 932.352 956.245333 \" +\n \"977.792 929.493333 977.792z\";\n\n /** The user agent stylesheet. */\n public static String USER_AGENT_STYLESHEET = getResourceURL(\"/css/control.css\");\n\n /** The Constant INPUT_STYLE_CLASS. */\n public final static String INPUT_STYLE_CLASS = \"xm-input-field\";\n\n /**\n * Gets the resource URL.\n *\n * @param path the path\n * @return the resource URL\n */\n public static String getResourceURL(String path) {\n return FxKit.class.getResource(path).toExternalForm();\n }\n\n /** The time pattern. */\n public static String TIME_PATTERN = \"HH:mm:ss\";\n \n /** The year pattern. */\n public static String YEAR_PATTERN = \"yyyy\";\n \n /** The month pattern. */\n public static String MONTH_PATTERN = \"yyyy-MM\";\n \n /** The date pattern. */\n public static String DATE_PATTERN = \"yyyy-MM-dd\";\n \n /** The datetime pattern. */\n public static String DATETIME_PATTERN = \"yyyy-MM-dd HH:mm:ss\";\n\n /**\n * New property.\n *\n * @param <T> the generic type\n * @param initValue the init value\n * @param cssMetaData the css meta data\n * @param bean the bean\n * @param name the name\n * @return the object property\n */\n public static <T> ObjectProperty<T> newProperty(T initValue, CssMetaData cssMetaData, Object bean, String name) {\n\n ObjectProperty<T> value = new StyleableObjectProperty<T>(initValue) {\n @Override\n public Object getBean() {\n return bean;\n }\n\n @Override\n public String getName() {\n return name;\n }\n\n @Override\n public CssMetaData<? extends Styleable, T> getCssMetaData() {\n return cssMetaData;\n }\n };\n return value;\n }\n\n /**\n * New double property.\n *\n * @param initValue the init value\n * @param cssMetaData the css meta data\n * @param bean the bean\n * @param name the name\n * @return the double property\n */\n public static DoubleProperty newDoubleProperty(Double initValue, CssMetaData cssMetaData, Object bean, String name) {\n return new StyleableDoubleProperty(initValue) {\n\n @Override\n public void invalidated() {\n }\n\n @Override\n public CssMetaData getCssMetaData() {\n return cssMetaData;\n }\n\n @Override\n public Object getBean() {\n return bean;\n }\n\n @Override\n public String getName() {\n return name;\n }\n };\n }\n\n /**\n * New integer property.\n *\n * @param initValue the init value\n * @param cssMetaData the css meta data\n * @param bean the bean\n * @param name the name\n * @return the integer property\n */\n public static IntegerProperty newIntegerProperty(Integer initValue, CssMetaData cssMetaData, Object bean, String name) {\n return new StyleableIntegerProperty(initValue) {\n\n @Override\n public void invalidated() {\n }\n\n @Override\n public CssMetaData getCssMetaData() {\n return cssMetaData;\n }\n\n @Override\n public Object getBean() {\n return bean;\n }\n\n @Override\n public String getName() {\n return name;\n }\n };\n }\n\n /**\n * New boolean property.\n *\n * @param initValue the init value\n * @param cssMetaData the css meta data\n * @param bean the bean\n * @param name the name\n * @return the boolean property\n */\n public static BooleanProperty newBooleanProperty(Boolean initValue, CssMetaData cssMetaData, Object bean, String name) {\n return new StyleableBooleanProperty(initValue) {\n\n @Override\n public void invalidated() {\n }\n\n @Override\n public CssMetaData getCssMetaData() {\n return cssMetaData;\n }\n\n @Override\n public Object getBean() {\n return bean;\n }\n\n @Override\n public String getName() {\n return name;\n }\n };\n }\n\n /**\n * New string property.\n *\n * @param initValue the init value\n * @param cssMetaData the css meta data\n * @param bean the bean\n * @param name the name\n * @return the styleable string property\n */\n public static StyleableStringProperty newStringProperty(String initValue, CssMetaData cssMetaData, Object bean, String name) {\n return new StyleableStringProperty(initValue) {\n\n @Override\n public void invalidated() {\n }\n\n @Override\n public CssMetaData getCssMetaData() {\n return cssMetaData;\n }\n\n @Override\n public Object getBean() {\n return bean;\n }\n\n @Override\n public String getName() {\n return name;\n }\n };\n }\n\n /**\n * 颜色转16进制格式的颜色.\n *\n * @param c the c\n * @return the string\n */\n public static String formatHexString(Color c) {\n if (c != null) {\n\n return String.format((Locale) null, \"#%02x%02x%02x%02x\", Math.round(c.getRed() * 255), Math.round(c.getGreen() * 255), Math.round(c.getBlue() * 255), Math.round(c.getOpacity() * 255));\n } else {\n return null;\n }\n }\n\n /**\n * Derive paint.\n *\n * @param paint the paint\n * @param brightneee the brightneee\n * @return the paint\n */\n public static Paint derivePaint(Paint paint, double brightneee){\n Paint color = null;\n if(paint instanceof Color){\n color = deriveColor((Color) paint, brightneee);\n }else if(paint instanceof LinearGradient){\n\n LinearGradient lgColor = (LinearGradient) paint;\n List<Stop> stops = lgColor.getStops();\n List<Stop> newStops = new ArrayList<Stop>();\n for(Stop stop : stops){\n Color c1 = deriveColor( stop.getColor(), brightneee);\n newStops.add(new Stop(stop.getOffset(), c1));\n }\n\n color = new LinearGradient(\n lgColor.getStartX(),\n lgColor.getStartY(),\n lgColor.getEndX(),\n lgColor.getEndX(),\n lgColor.isProportional(),\n lgColor.getCycleMethod(),\n newStops\n );\n }else if(paint instanceof RadialGradient){\n\n RadialGradient lgColor = (RadialGradient) paint;\n List<Stop> stops = lgColor.getStops();\n List<Stop> nstops = new ArrayList<Stop>();\n for(Stop stop : stops){\n Color c1 = deriveColor( stop.getColor(), brightneee);\n nstops.add(new Stop(stop.getOffset(), c1));\n }\n\n color = new RadialGradient(\n lgColor.getFocusAngle(),\n lgColor.getFocusDistance(),\n lgColor.getCenterX(),\n lgColor.getCenterY(),\n lgColor.getRadius(),\n lgColor.isProportional(),\n lgColor.getCycleMethod(),\n nstops\n );\n }\n\n return color;\n }\n\n /**\n * Derives a lighter or darker of a given color.\n *\n * @param c The color to derive from\n * @param brightness The brightness difference for the new color -1.0 being 100% dark which is always black, 0.0 being\n * no change and 1.0 being 100% lighter which is always white\n * @return the color\n */\n public static Color deriveColor(Color c, double brightness) {\n double baseBrightness = calculateBrightness(c);\n double calcBrightness = brightness;\n // Fine adjustments to colors in ranges of brightness to adjust the contrast for them\n if (brightness > 0) {\n if (baseBrightness > 0.85) {\n calcBrightness = calcBrightness * 1.6;\n } else if (baseBrightness > 0.6) {\n // no change\n } else if (baseBrightness > 0.5) {\n calcBrightness = calcBrightness * 0.9;\n } else if (baseBrightness > 0.4) {\n calcBrightness = calcBrightness * 0.8;\n } else if (baseBrightness > 0.3) {\n calcBrightness = calcBrightness * 0.7;\n } else {\n calcBrightness = calcBrightness * 0.6;\n }\n } else {\n if (baseBrightness < 0.2) {\n calcBrightness = calcBrightness * 0.6;\n }\n }\n // clamp brightness\n if (calcBrightness < -1) {\n calcBrightness = -1;\n } else if (calcBrightness > 1) {\n calcBrightness = 1;\n }\n // window two take the calculated brightness multiplyer and derive color based on source color\n double[] hsb = RGBtoHSB(c.getRed(), c.getGreen(), c.getBlue());\n // change brightness\n if (calcBrightness > 0) { // brighter\n hsb[1] *= 1 - calcBrightness;\n hsb[2] += (1 - hsb[2]) * calcBrightness;\n } else { // darker\n hsb[2] *= calcBrightness + 1;\n }\n // clip saturation and brightness\n if (hsb[1] < 0) {\n hsb[1] = 0;\n } else if (hsb[1] > 1) {\n hsb[1] = 1;\n }\n if (hsb[2] < 0) {\n hsb[2] = 0;\n } else if (hsb[2] > 1) {\n hsb[2] = 1;\n }\n // convert back to color\n // Color c2 = Color.hsb((int)hsb[0], hsb[1], hsb[2],c.getOpacity());\n return Color.hsb((int) hsb[0], hsb[1], hsb[2], c.getOpacity());\n\n\t\t/* var hsb:Number[] = RGBtoHSB(c.red,c.green,c.blue);\n // change brightness\n if (brightness > 0) {\n //var bright:Number = brightness * (1-calculateBrightness(c));\n var bright:Number = if (calculateBrightness(c)<0.65 and brightness > 0.5) {\n if (calculateBrightness(c)<0.2) then brightness * 0.55 else brightness * 0.7\n } else brightness;\n // brighter\n hsb[1] *= 1 - bright;\n hsb[2] += (1 - hsb[2]) * bright;\n } else {\n // darker\n hsb[2] *= brightness+1;\n }\n // clip saturation and brightness\n if (hsb[1] < 0) { hsb[1] = 0;} else if (hsb[1] > 1) {hsb[1] = 1}\n if (hsb[2] < 0) { hsb[2] = 0;} else if (hsb[2] > 1) {hsb[2] = 1}\n // convert back to color\n return Color.hsb(hsb[0],hsb[1],hsb[2]) */\n }\n\n /**\n * Calculates a perceptual brightness for a color between 0.0 black and 1.0 while\n *\n * @param color the color\n * @return the double\n */\n public static double calculateBrightness(Color color) {\n return (0.3 * color.getRed()) + (0.59 * color.getGreen()) + (0.11 * color.getBlue());\n }\n\n /**\n * RG bto HSB.\n *\n * @param r the r\n * @param g the g\n * @param b the b\n * @return the double[]\n */\n public static double[] RGBtoHSB(double r, double g, double b) {\n double hue, saturation, brightness;\n double[] hsbvals = new double[3];\n double cmax = (r > g) ? r : g;\n if (b > cmax) cmax = b;\n double cmin = (r < g) ? r : g;\n if (b < cmin) cmin = b;\n\n brightness = cmax;\n if (cmax != 0) saturation = (double) (cmax - cmin) / cmax;\n else saturation = 0;\n\n if (saturation == 0) {\n hue = 0;\n } else {\n double redc = (cmax - r) / (cmax - cmin);\n double greenc = (cmax - g) / (cmax - cmin);\n double bluec = (cmax - b) / (cmax - cmin);\n if (r == cmax) hue = bluec - greenc;\n else if (g == cmax) hue = 2.0 + redc - bluec;\n else hue = 4.0 + greenc - redc;\n hue = hue / 6.0;\n if (hue < 0) hue = hue + 1.0;\n }\n hsbvals[0] = hue * 360;\n hsbvals[1] = saturation;\n hsbvals[2] = brightness;\n return hsbvals;\n }\n\n /**\n * Gets the gray.\n *\n * @param color the color\n * @return the gray\n */\n public static int getGray(Color color) {\n String grayColor = color.grayscale().toString();\n int gray = Integer.parseInt(grayColor.substring(2,4), 16);\n return gray;\n }\n\n /**\n * 获取指定灰度的颜色,亮色\n * 1白色,0黑色.\n *\n * @param color the color\n * @param light the light\n * @return the light color\n */\n public static Color getLightColor(Color color, double light){\n\n if(light < color.grayscale().getRed()){\n return color;\n }\n\n while(light>color.grayscale().getRed()){\n color = deriveColor(color, 0.1);\n }\n return color;\n }\n\n /**\n * 获取指定灰度的颜色,亮色\n * 1白色,0黑色.\n *\n * @param paint the paint\n * @param light the light\n * @return the light paint\n */\n public static Paint getLightPaint(Paint paint, double light){\n\n if(paint instanceof Color){\n return getLightColor((Color) paint, light);\n }else if(paint instanceof LinearGradient){\n\n LinearGradient lgColor = (LinearGradient) paint;\n List<Stop> stops = lgColor.getStops();\n List<Stop> newStops = new ArrayList<Stop>();\n for(Stop stop : stops){\n Color c1 = stop.getColor().deriveColor(0, 1, 0.1, 1);\n c1 = getLightColor(c1, light);\n newStops.add(new Stop(stop.getOffset(), c1));\n }\n\n return new LinearGradient(\n lgColor.getStartX(),\n lgColor.getStartY(),\n lgColor.getEndX(),\n lgColor.getEndX(),\n lgColor.isProportional(),\n lgColor.getCycleMethod(),\n newStops\n );\n\n }else if(paint instanceof RadialGradient){\n\n RadialGradient lgColor = (RadialGradient) paint;\n List<Stop> stops = lgColor.getStops();\n List<Stop> newStops = new ArrayList<Stop>();\n for(Stop stop : stops){\n Color c1 = stop.getColor().deriveColor(0, 1, 0.1, 1);\n c1 = getLightColor(c1, light);\n newStops.add(new Stop(stop.getOffset(), c1));\n }\n\n return new RadialGradient(\n lgColor.getFocusAngle(),\n lgColor.getFocusDistance(),\n lgColor.getCenterX(),\n lgColor.getCenterY(),\n lgColor.getRadius(),\n lgColor.isProportional(),\n lgColor.getCycleMethod(),\n newStops\n );\n\n }\n return paint;\n }\n\n /**\n * 获取指定灰度的颜色,亮色\n * 1白色,0黑色.\n *\n * @param paint the paint\n * @param dark the dark\n * @return the dark paint\n */\n public static Paint getDarkPaint(Paint paint, double dark){\n if(paint instanceof Color){\n return getDarkColor((Color) paint, dark);\n }else if(paint instanceof LinearGradient){\n\n LinearGradient lgColor = (LinearGradient) paint;\n List<Stop> stops = lgColor.getStops();\n List<Stop> newStops = new ArrayList<Stop>();\n for(Stop stop : stops){\n Color c1 = getDarkColor( stop.getColor(), dark);\n newStops.add(new Stop(stop.getOffset(), c1));\n }\n\n return new LinearGradient(\n lgColor.getStartX(),\n lgColor.getStartY(),\n lgColor.getEndX(),\n lgColor.getEndX(),\n lgColor.isProportional(),\n lgColor.getCycleMethod(),\n newStops\n );\n\n }else if(paint instanceof RadialGradient){\n\n RadialGradient lgColor = (RadialGradient) paint;\n List<Stop> stops = lgColor.getStops();\n List<Stop> newStops = new ArrayList<Stop>();\n for(Stop stop : stops){\n Color c1 = getDarkColor( stop.getColor(), dark);\n newStops.add(new Stop(stop.getOffset(), c1));\n }\n\n return new RadialGradient(\n lgColor.getFocusAngle(),\n lgColor.getFocusDistance(),\n lgColor.getCenterX(),\n lgColor.getCenterY(),\n lgColor.getRadius(),\n lgColor.isProportional(),\n lgColor.getCycleMethod(),\n newStops\n );\n\n }\n return paint;\n }\n\n /**\n * 获取指定灰度的颜色,暗色\n * 1白色,0黑色.\n *\n * @param color the color\n * @param light the light\n * @return the dark color\n */\n public static Color getDarkColor(Color color, double light){\n\n double curr = color.grayscale().getBlue();\n if(curr<light){\n return color;\n }\n\n while(light<curr){\n color = deriveColor(color, -0.1);\n curr = color.grayscale().getBlue();\n }\n return color;\n }\n\n /**\n * 解析svg的xml文档.\n *\n * @param content the content\n * @return the array list\n */\n public static ArrayList<PathInfo> parseSvg(String content){\n ArrayList<PathInfo> list=new ArrayList<>();\n\n DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();\n\n DocumentBuilder db=null;\n Document dom=null;\n\n try {\n StringReader sr=new StringReader(content);\n InputSource is=new InputSource(sr);\n //设置不验证\n dbf.setValidating(false);\n db=dbf.newDocumentBuilder();\n //忽略DTD文档类型定义验证\n db.setEntityResolver(new EntityResolver() {\n @Override\n public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {\n return new InputSource(new ByteArrayInputStream(\"<?xml version='1.0' encoding='UTF-8'?>\".getBytes()));\n }\n });\n\n dom=db.parse(is);\n Element item = dom.getDocumentElement();\n NodeList paths = dom.getElementsByTagName(\"path\");\n for (int i = 0; i < paths.getLength(); i++) {\n Node node= paths.item(i);\n Element element = (Element) node;\n PathInfo info=new PathInfo();\n String pathD=element.getAttribute(\"d\");\n //info.setPathD(ratePath(pathD,rate));\n info.setPathD(pathD);\n String pathFill = element.getAttribute(\"fill\");\n info.setPathFill(pathFill==\"\"?\"#000000\":pathFill);\n String pathID = element.getAttribute(\"p-id\");\n //如果不存在p-id,就设置p-id\n pathID=pathID.trim().isEmpty()?String.valueOf(i):pathID;\n info.setPathId(\"p-id\"+pathID);\n list.add(info);\n }\n } catch (ParserConfigurationException e) {\n e.printStackTrace();\n } catch (SAXException e) {\n e.printStackTrace();\n } catch (IOException e) {\n e.printStackTrace();\n }\n\n return list;\n }\n\n /**\n * 获取指定颜色的透明度\n * 1白色,0黑色.\n *\n * @param paint the paint\n * @param opacity the opacity\n * @return the opacity paint\n */\n public static Paint getOpacityPaint(Paint paint, double opacity){\n\n if(paint instanceof Color){\n return getOpacityColor((Color) paint, opacity);\n }else if(paint instanceof LinearGradient){\n\n LinearGradient lgColor = (LinearGradient) paint;\n List<Stop> stops = lgColor.getStops();\n List<Stop> newStops = new ArrayList<Stop>();\n for(Stop stop : stops){\n Color c1 = stop.getColor();\n newStops.add(new Stop(stop.getOffset(), getOpacityColor(c1, opacity)));\n }\n\n return new LinearGradient(\n lgColor.getStartX(),\n lgColor.getStartY(),\n lgColor.getEndX(),\n lgColor.getEndX(),\n lgColor.isProportional(),\n lgColor.getCycleMethod(),\n newStops\n );\n\n }else if(paint instanceof RadialGradient){\n\n RadialGradient lgColor = (RadialGradient) paint;\n List<Stop> stops = lgColor.getStops();\n List<Stop> newStops = new ArrayList<Stop>();\n for(Stop stop : stops){\n newStops.add(new Stop(stop.getOffset(), getOpacityColor(stop.getColor(), opacity)));\n }\n\n return new RadialGradient(\n lgColor.getFocusAngle(),\n lgColor.getFocusDistance(),\n lgColor.getCenterX(),\n lgColor.getCenterY(),\n lgColor.getRadius(),\n lgColor.isProportional(),\n lgColor.getCycleMethod(),\n newStops\n );\n\n }\n return paint;\n }\n\n\n /**\n * Gets the opacity color.\n *\n * @param color the color\n * @param opacity the opacity\n * @return the opacity color\n */\n public static Color getOpacityColor(Color color, double opacity){\n return new Color(color.getRed(), color.getGreen(), color.getBlue(), opacity);\n }\n\n}" }, { "identifier": "ClickAnimate", "path": "BaseUI/src/main/java/com/xm2013/jfx/control/animate/ClickAnimate.java", "snippet": "public interface ClickAnimate {\n /**\n * 设置动画的起始位置\n * @param x double\n * @param y double\n * @return ClickAnimate\n */\n ClickAnimate setPoint(double x, double y);\n\n /**\n * 设置节点位置,\n * 因为是不同的调用方式,所以实现方法可能不一样,所以改用回调的方式,交给组件自己实现\n * @param callback ResetNodePositionCallback\n */\n void setNodePosition(ResetNodePositionCallback callback);\n\n /**\n * 添加节点到control\n * 因为是不同的调用方式,所以实现方法可能不一样,所以改用回调的方式,交给组件自己实现\n * @param callback CallBack\n */\n void setAddNode(CallBack<Node> callback);\n\n /**\n * 移除节点control\n * 因为是不同的调用方式,所以实现方法可能不一样,所以改用回调的方式,交给组件自己实现\n * @param callback CallBack\n */\n void setRemoveNode(CallBack<Node> callback);\n\n /**\n * 播放动画\n */\n void play();\n\n /**\n * 销毁\n */\n void dispose();\n}" }, { "identifier": "HueType", "path": "BaseUI/src/main/java/com/xm2013/jfx/control/base/HueType.java", "snippet": "public enum HueType {\n /**\n * 暗色调, 在背景色是暗色的情况下,组件应该有的表现\n */\n DARK,\n /**\n * 亮色调, 在北京是亮色的情况下,组件应该有的表现\n */\n LIGHT,\n\n /**\n * 无色,就是没有背景色,没有边框色,只有文本或者图标颜色\n */\n NONE\n}" }, { "identifier": "SizeType", "path": "BaseUI/src/main/java/com/xm2013/jfx/control/base/SizeType.java", "snippet": "public enum SizeType {\n\n /**\n * 小尺寸\n */\n SMALL,\n /**\n * 中等尺寸\n */\n MEDIUM,\n /**\n * 大尺寸\n */\n LARGE;\n}" } ]
import com.xm2013.jfx.common.FxKit; import com.xm2013.jfx.control.animate.ClickAnimate; import com.xm2013.jfx.control.base.HueType; import com.xm2013.jfx.control.base.SizeType; import javafx.animation.AnimationTimer; import javafx.collections.ObservableSet; import javafx.collections.SetChangeListener; import javafx.css.PseudoClass; import javafx.geometry.Insets; import javafx.scene.control.ListCell; import javafx.scene.control.ListView; import javafx.scene.layout.Background; import javafx.scene.layout.BackgroundFill; import javafx.scene.layout.CornerRadii; import javafx.scene.paint.*; import javafx.scene.text.Font; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map;
9,523
/* * MIT License * * Copyright (c) 2023 [email protected] / wechat: t5x5m5 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ package com.xm2013.jfx.control.listview; /** * 自定义ListCell,实现了根据主题色的变换 */ public class XmListCell<T> extends ListCell<T> { private static final String DEFAULT_STYLE_CLASS = "xm-list-cell"; class ListCellSkinInfo { public Paint fontColor; public Background background; public ListCellSkinInfo(Paint fontColor, Background background){ this.fontColor = fontColor; this.background = background; } } private Map<Integer, ListCellSkinInfo> infos = new LinkedHashMap<>(); private static PseudoClass odd = PseudoClass.getPseudoClass("odd"); private static PseudoClass selected = PseudoClass.getPseudoClass("selected"); private static PseudoClass filled = PseudoClass.getPseudoClass("filled"); private static PseudoClass hover = PseudoClass.getPseudoClass("hover"); private ClickAnimate clickAnimate = null; private double startRadius = 0.01; private double endRadius = 10; private boolean prevSelected = false; public XmListCell() { getStyleClass().addAll(DEFAULT_STYLE_CLASS); listViewProperty().addListener((ob, ov, nv)->{ updateSkin(0); }); ObservableSet<PseudoClass> pseudoClassStates = getPseudoClassStates(); pseudoClassStates.addListener((SetChangeListener<PseudoClass>) change -> { // System.out.println(getText()+": "+pseudoClassStates); boolean isOdd = pseudoClassStates.contains(odd); boolean isSelected = pseudoClassStates.contains(selected); // boolean isFilled = pseudoClassStates.contains(filled); boolean isHover = pseudoClassStates.contains(hover); if(isOdd){ if(!isSelected && !isHover){ updateSkin(1); prevSelected = false; return; } } if(isSelected){ if(!prevSelected){ updateSelectedStatus(); // updateSkin(2); } prevSelected = true; return; } prevSelected = false; if(isHover){ updateSkin(3); return; } updateSkin(0); }); } private void updateSelectedStatus(){ setTextFill(Color.WHITE); List<Stop> stops = new ArrayList<>(); Color color = ((XmListView)getListView()).getColorType().getFxColor(); stops.add(new Stop(0, color)); stops.add(new Stop(1, Color.TRANSPARENT)); startRadius = 0.01; AnimationTimer timer = new AnimationTimer() { final double frameDuration = 1_000_000_000.0 / 60; long lastUpdate = 0; @Override public void handle(long now) { double elapsedNanos = now - lastUpdate; if (elapsedNanos >= frameDuration) { startRadius += 0.25; if(startRadius<endRadius){ RadialGradient radialGradient = new RadialGradient(0, 0, 0, 0.5, startRadius,true, CycleMethod.NO_CYCLE, stops); setBackground(new Background(new BackgroundFill(radialGradient, CornerRadii.EMPTY, Insets.EMPTY))); if(!getPseudoClassStates().contains(selected)){ if(getPseudoClassStates().contains(odd)){ updateSkin(1); }else{ updateSkin(0); } stop(); } }else{ stop(); if(!getPseudoClassStates().contains(selected)){ if(getPseudoClassStates().contains(odd)){ updateSkin(1); }else{ updateSkin(0); } } } lastUpdate = now; } } }; timer.start(); } /** * 0-默认 * 1-odd * 2-selected * 3-hover * @param status int */ private void updateSkin(int status){ // setBackground(new Background(new BackgroundFill(Color.TRANSPARENT, CornerRadii.EMPTY, Insets.EMPTY))); ListCellSkinInfo info = getInfo(status); if(info == null){ return; } ListView<T> tv = listViewProperty().get(); if(tv instanceof XmListView){ double fontSize = 14;
/* * MIT License * * Copyright (c) 2023 [email protected] / wechat: t5x5m5 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ package com.xm2013.jfx.control.listview; /** * 自定义ListCell,实现了根据主题色的变换 */ public class XmListCell<T> extends ListCell<T> { private static final String DEFAULT_STYLE_CLASS = "xm-list-cell"; class ListCellSkinInfo { public Paint fontColor; public Background background; public ListCellSkinInfo(Paint fontColor, Background background){ this.fontColor = fontColor; this.background = background; } } private Map<Integer, ListCellSkinInfo> infos = new LinkedHashMap<>(); private static PseudoClass odd = PseudoClass.getPseudoClass("odd"); private static PseudoClass selected = PseudoClass.getPseudoClass("selected"); private static PseudoClass filled = PseudoClass.getPseudoClass("filled"); private static PseudoClass hover = PseudoClass.getPseudoClass("hover"); private ClickAnimate clickAnimate = null; private double startRadius = 0.01; private double endRadius = 10; private boolean prevSelected = false; public XmListCell() { getStyleClass().addAll(DEFAULT_STYLE_CLASS); listViewProperty().addListener((ob, ov, nv)->{ updateSkin(0); }); ObservableSet<PseudoClass> pseudoClassStates = getPseudoClassStates(); pseudoClassStates.addListener((SetChangeListener<PseudoClass>) change -> { // System.out.println(getText()+": "+pseudoClassStates); boolean isOdd = pseudoClassStates.contains(odd); boolean isSelected = pseudoClassStates.contains(selected); // boolean isFilled = pseudoClassStates.contains(filled); boolean isHover = pseudoClassStates.contains(hover); if(isOdd){ if(!isSelected && !isHover){ updateSkin(1); prevSelected = false; return; } } if(isSelected){ if(!prevSelected){ updateSelectedStatus(); // updateSkin(2); } prevSelected = true; return; } prevSelected = false; if(isHover){ updateSkin(3); return; } updateSkin(0); }); } private void updateSelectedStatus(){ setTextFill(Color.WHITE); List<Stop> stops = new ArrayList<>(); Color color = ((XmListView)getListView()).getColorType().getFxColor(); stops.add(new Stop(0, color)); stops.add(new Stop(1, Color.TRANSPARENT)); startRadius = 0.01; AnimationTimer timer = new AnimationTimer() { final double frameDuration = 1_000_000_000.0 / 60; long lastUpdate = 0; @Override public void handle(long now) { double elapsedNanos = now - lastUpdate; if (elapsedNanos >= frameDuration) { startRadius += 0.25; if(startRadius<endRadius){ RadialGradient radialGradient = new RadialGradient(0, 0, 0, 0.5, startRadius,true, CycleMethod.NO_CYCLE, stops); setBackground(new Background(new BackgroundFill(radialGradient, CornerRadii.EMPTY, Insets.EMPTY))); if(!getPseudoClassStates().contains(selected)){ if(getPseudoClassStates().contains(odd)){ updateSkin(1); }else{ updateSkin(0); } stop(); } }else{ stop(); if(!getPseudoClassStates().contains(selected)){ if(getPseudoClassStates().contains(odd)){ updateSkin(1); }else{ updateSkin(0); } } } lastUpdate = now; } } }; timer.start(); } /** * 0-默认 * 1-odd * 2-selected * 3-hover * @param status int */ private void updateSkin(int status){ // setBackground(new Background(new BackgroundFill(Color.TRANSPARENT, CornerRadii.EMPTY, Insets.EMPTY))); ListCellSkinInfo info = getInfo(status); if(info == null){ return; } ListView<T> tv = listViewProperty().get(); if(tv instanceof XmListView){ double fontSize = 14;
SizeType sizeType = ((XmListView<T>) tv).getSizeType();
3
2023-10-17 08:57:08+00:00
12k
Dwight-Studio/JArmEmu
src/main/java/fr/dwightstudio/jarmemu/gui/factory/JArmEmuLineFactory.java
[ { "identifier": "Status", "path": "src/main/java/fr/dwightstudio/jarmemu/Status.java", "snippet": "public enum Status {\n INITIALIZING(\"Initializing\"),\n EDITING(\"Editing\"),\n SIMULATING(\"Simulating\"),\n ERROR(\"Error\");\n\n private final String desc;\n\n Status(String desc) {\n this.desc = desc;\n }\n\n @Override\n public String toString() {\n return desc;\n }\n}" }, { "identifier": "JArmEmuApplication", "path": "src/main/java/fr/dwightstudio/jarmemu/gui/JArmEmuApplication.java", "snippet": "public class JArmEmuApplication extends Application {\n\n public static final String OS_NAME = System.getProperty(\"os.name\").toLowerCase();\n public static final String OS_ARCH = System.getProperty(\"os.arch\").toLowerCase();\n public static final String OS_VERSION = System.getProperty(\"os.version\").toLowerCase();\n public static final String VERSION = JArmEmuApplication.class.getPackage().getImplementationVersion() != null ? JArmEmuApplication.class.getPackage().getImplementationVersion() : \"NotFound\" ;\n public static final Logger logger = Logger.getLogger(JArmEmuApplication.class.getName());\n\n // Controllers\n private JArmEmuController controller;\n\n private EditorController editorController;\n private MainMenuController mainMenuController;\n private MemoryDetailsController memoryDetailsController;\n private MemoryOverviewController memoryOverviewController;\n private RegistersController registersController;\n private SettingsController settingsController;\n private SimulationMenuController simulationMenuController;\n private StackController stackController;\n private SymbolsController symbolsController;\n private LabelsController labelsController;\n\n // Others\n private ShortcutHandler shortcutHandler;\n private SourceParser sourceParser;\n private CodeInterpreter codeInterpreter;\n private ExecutionWorker executionWorker;\n private JArmEmuDialogs dialogs;\n\n\n public Theme theme;\n public SimpleObjectProperty<Status> status;\n public Stage stage;\n public Scene scene;\n private String argSave;\n\n // TODO: Refaire les tests pour les initializers de données (pour un argument vide, plusieurs arguments, avec une section incorrecte etc)\n // TODO: Ajouter d'autres types de packages (ArchLinux, etc)\n\n @Override\n public void start(Stage stage) throws IOException {\n this.stage = stage;\n this.status = new SimpleObjectProperty<>(Status.INITIALIZING);\n\n logger.info(\"Starting up JArmEmu v\" + VERSION + \" on \" + OS_NAME + \" v\" + OS_VERSION + \" (\" + OS_ARCH + \")\");\n\n FXMLLoader fxmlLoader = new FXMLLoader(getResource(\"main-view.fxml\"));\n\n editorController = new EditorController(this);\n mainMenuController = new MainMenuController(this);\n memoryDetailsController = new MemoryDetailsController(this);\n memoryOverviewController = new MemoryOverviewController(this);\n registersController = new RegistersController(this);\n settingsController = new SettingsController(this);\n simulationMenuController = new SimulationMenuController(this);\n stackController = new StackController(this);\n symbolsController = new SymbolsController(this);\n labelsController = new LabelsController(this);\n dialogs = new JArmEmuDialogs(this);\n\n fxmlLoader.setController(new JArmEmuController(this));\n controller = fxmlLoader.getController();\n\n // Essayer d'ouvrir le fichier passé en paramètre\n if (!getParameters().getUnnamed().isEmpty()) {\n logger.info(\"Detecting file argument: \" + getParameters().getUnnamed().getFirst());\n argSave = getParameters().getUnnamed().getFirst();\n } else {\n argSave = null;\n }\n\n // Autres\n shortcutHandler = new ShortcutHandler(this);\n codeInterpreter = new CodeInterpreter();\n executionWorker = new ExecutionWorker(this);\n\n logger.info(\"Font \" + Font.loadFont(getResourceAsStream(\"fonts/Cantarell/Cantarell-Regular.ttf\"), 14).getFamily() + \" loaded\");\n logger.info(\"Font \" + Font.loadFont(getResourceAsStream(\"fonts/SourceCodePro/SourceCodePro-Regular.ttf\"), 14).getFamily() + \" loaded\");\n\n scene = new Scene(fxmlLoader.load(), 1280, 720);\n updateUserAgentStyle(getSettingsController().getThemeVariation(), getSettingsController().getThemeFamily());\n scene.getStylesheets().add(getResource(\"jarmemu-style.css\").toExternalForm());\n\n scene.setOnKeyPressed(shortcutHandler::handle);\n\n stage.setOnCloseRequest(this::onClosingRequest);\n stage.getIcons().addAll(\n new Image(getResourceAsStream(\"medias/[email protected]\")),\n new Image(getResourceAsStream(\"medias/[email protected]\")),\n new Image(getResourceAsStream(\"medias/[email protected]\")),\n new Image(getResourceAsStream(\"medias/[email protected]\")),\n new Image(getResourceAsStream(\"medias/[email protected]\")),\n new Image(getResourceAsStream(\"medias/[email protected]\")),\n new Image(getResourceAsStream(\"medias/logo.png\"))\n );\n\n status.addListener((observable -> updateTitle()));\n getSimulationMenuController().onStop();\n\n updateTitle();\n stage.setScene(scene);\n stage.show();\n\n SplashScreen splashScreen = SplashScreen.getSplashScreen();\n\n int scale = (int) (stage.getOutputScaleY() * 100);\n Preferences.userRoot().node(getClass().getPackage().getName().replaceAll(\"\\\\.\", \"/\")).putInt(\"scale\", scale);\n logger.info(\"Computing scale: \" + scale + \"%\");\n\n if (splashScreen != null) {\n splashScreen.close();\n }\n\n logger.info(\"Startup finished\");\n status.set(Status.EDITING);\n }\n\n public void updateTitle() {\n stage.setTitle(\"JArmEmu v\" + VERSION + \" - \" + status.get());\n }\n\n /**\n * Mise à jour du UserAgentStyle pour la modification du thème.\n *\n * @param variation l'indice de la variation\n * @param family l'indice' de la famille\n */\n public void updateUserAgentStyle(int variation, int family) {\n if (family == 0) {\n theme = (variation == 0) ? new PrimerDark() : new PrimerLight();\n } else if (family == 1) {\n theme = (variation == 0) ? new NordDark() : new NordLight();\n } else {\n theme = (variation == 0) ? new CupertinoDark() : new CupertinoLight();\n }\n\n Application.setUserAgentStylesheet(theme.getUserAgentStylesheet());\n }\n\n /**\n * Définie l'état de maximisation.\n *\n * @param maximized l'état de maximisation\n */\n public void setMaximized(boolean maximized) {\n stage.setMaximized(maximized);\n }\n\n /**\n * @return l'état de maximisation\n */\n public boolean isMaximized() {\n return stage.isMaximized();\n }\n\n public ReadOnlyBooleanProperty maximizedProperty() {\n return stage.maximizedProperty();\n }\n\n /**\n * Adapte le splashscreen à la dimension de l'écran.\n *\n * @param splashScreen l'instance du splashscreen\n */\n private static void adaptSplashScreen(SplashScreen splashScreen) {\n try {\n int scale = Preferences.userRoot().node(JArmEmuApplication.class.getPackage().getName().replaceAll(\"\\\\.\", \"/\")).getInt(\"scale\", 100);\n\n logger.info(\"Adapting SplashScreen to current screen scale (\" + scale + \"%)\");\n\n URL url;\n \n if (scale >= 125 && scale < 150) {\n url = getResource(\"medias/[email protected]\");\n } else if (scale >= 150 && scale < 200) {\n url = getResource(\"medias/[email protected]\");\n } else if (scale >= 200 && scale < 250) {\n url = getResource(\"medias/[email protected]\");\n } else if (scale >= 250 && scale < 300) {\n url = getResource(\"medias/[email protected]\");\n } else if (scale >= 300) {\n url = getResource(\"jarmemu/medias/[email protected]\");\n } else {\n url = getResource(\"medias/splash.png\");\n }\n\n logger.info(\"Loading SplashScreen: \" + url);\n splashScreen.setImageURL(url);\n } catch (Exception e) {\n logger.severe(ExceptionUtils.getStackTrace(e));\n }\n }\n\n @Override\n public void stop() {\n\n }\n\n public static void main(String[] args) {\n System.setProperty(\"prism.dirtyopts\", \"false\");\n SplashScreen splashScreen = SplashScreen.getSplashScreen();\n\n if (splashScreen != null) {\n adaptSplashScreen(splashScreen);\n }\n\n JArmEmuApplication.launch(args);\n }\n\n public void openURL(String url) {\n getHostServices().showDocument(url);\n }\n\n public JArmEmuController getController() {\n return controller;\n }\n\n public MainMenuController getMainMenuController() {\n return mainMenuController;\n }\n\n public MemoryDetailsController getMemoryDetailsController() {\n return memoryDetailsController;\n }\n\n public MemoryOverviewController getMemoryOverviewController() {\n return memoryOverviewController;\n }\n\n public RegistersController getRegistersController() {\n return registersController;\n }\n\n public SettingsController getSettingsController() {\n return settingsController;\n }\n\n public StackController getStackController() {\n return stackController;\n }\n\n public SymbolsController getSymbolsController() {\n return symbolsController;\n }\n\n public LabelsController getLabelsController() {\n return labelsController;\n }\n\n public SourceParser getSourceParser() {\n return sourceParser;\n }\n\n public CodeInterpreter getCodeInterpreter() {\n return codeInterpreter;\n }\n\n public ExecutionWorker getExecutionWorker() {\n return executionWorker;\n }\n\n public EditorController getEditorController() {\n return editorController;\n }\n\n public SimulationMenuController getSimulationMenuController() {\n return simulationMenuController;\n }\n\n public JArmEmuDialogs getDialogs() {\n return dialogs;\n }\n\n private void onClosingRequest(WindowEvent event) {\n event.consume();\n getMainMenuController().onExit();\n }\n\n public void newSourceParser() {\n if (getSettingsController().getSourceParserSetting() == 1) {\n sourceParser = new LegacySourceParser(new SourceScanner(\"\", null, 0));\n } else {\n sourceParser = new RegexSourceParser(new SourceScanner(\"\", null, 0));\n }\n }\n\n /**\n * @param data les données\n * @param format le format (0, 1, 2)\n * @return une version formatée du nombre en données\n */\n public String getFormattedData(int data, int format) {\n if (format == 2) {\n return String.format(SettingsController.DATA_FORMAT_DICT[format], (long) data & 0xFFFFFFFFL).toUpperCase();\n } else {\n return String.format(SettingsController.DATA_FORMAT_DICT[format], data).toUpperCase();\n\n }\n }\n\n /**\n * @param data les données\n * @return une version formatée du nombre en données\n */\n public String getFormattedData(int data) {\n return getFormattedData(data, getSettingsController().getDataFormat());\n }\n\n /**\n * @return le chemin vers le fichier passé en paramètre (ou null si rien n'est passé en paramètre)\n */\n public String getArgSave() {\n return argSave;\n }\n\n public static @NotNull URL getResource(String name) {\n return Objects.requireNonNull(JArmEmuApplication.class.getResource(\"/fr/dwightstudio/jarmemu/\" + name));\n }\n\n public static @NotNull InputStream getResourceAsStream(String name) {\n return Objects.requireNonNull(JArmEmuApplication.class.getResourceAsStream(\"/fr/dwightstudio/jarmemu/\" + name));\n }\n}" }, { "identifier": "FileEditor", "path": "src/main/java/fr/dwightstudio/jarmemu/gui/controllers/FileEditor.java", "snippet": "public class FileEditor extends AbstractJArmEmuModule {\n\n private Logger logger = Logger.getLogger(getClass().getName());\n\n // GUI\n private final CodeArea codeArea;\n private final VirtualizedScrollPane<CodeArea> editorScroll;\n private final StackPane stackPane;\n private final Tab fileTab;\n private final EditorContextMenu contextMenu;\n private final JArmEmuLineFactory lineFactory;\n private final ExecutorService executor;\n private final Subscription hightlightUpdateSubscription;\n\n // Propriétés du fichier\n private File path;\n private String lastSaveContent;\n private boolean saved;\n private boolean closed;\n\n\n public FileEditor(JArmEmuApplication application, String fileName, String content) {\n super(application);\n this.executor = Executors.newSingleThreadExecutor();\n codeArea = new CodeArea();\n editorScroll = new VirtualizedScrollPane<>(codeArea);\n stackPane = new StackPane(editorScroll);\n fileTab = new Tab(fileName, stackPane);\n\n Separator separator = new Separator(Orientation.VERTICAL);\n separator.setMouseTransparent(true);\n separator.setPadding(new Insets(0, 0, 0, 80));\n\n stackPane.setAlignment(Pos.CENTER_LEFT);\n stackPane.getChildren().add(separator);\n\n hightlightUpdateSubscription = codeArea.plainTextChanges().successionEnds(Duration.ofMillis(50))\n .retainLatestUntilLater(executor)\n .supplyTask(this::autoComputeHighlightingAsync)\n .awaitLatest(codeArea.plainTextChanges())\n .filterMap(t -> {\n if (t.isSuccess()) {\n return Optional.of(t.get());\n } else {\n logger.log(Level.WARNING, ExceptionUtils.getStackTrace(t.getFailure()));\n return Optional.empty();\n }\n }).subscribe((highlighting) -> codeArea.setStyleSpans(0, highlighting));\n\n fileTab.setOnCloseRequest(event -> {\n getController().filesTabPane.getSelectionModel().select(fileTab);\n if (!getSaveState()) {\n event.consume();\n getDialogs().unsavedAlert().thenAccept(rtn -> {\n switch (rtn) {\n case SAVE_AND_CONTINUE -> {\n getSimulationMenuController().onStop();\n save();\n close();\n getEditorController().cleanClosedEditors();\n }\n\n case DISCARD_AND_CONTINUE -> {\n getSimulationMenuController().onStop();\n close();\n getEditorController().cleanClosedEditors();\n }\n\n default -> {}\n }\n });\n } else {\n getSimulationMenuController().onStop();\n close();\n getEditorController().cleanClosedEditors();\n }\n });\n\n codeArea.replaceText(content);\n codeArea.getStylesheets().add(JArmEmuApplication.getResource(\"editor-style.css\").toExternalForm());\n\n contextMenu = new EditorContextMenu(codeArea);\n codeArea.setContextMenu(contextMenu);\n\n lineFactory = new JArmEmuLineFactory(getApplication(), this);\n codeArea.setParagraphGraphicFactory(lineFactory);\n\n getController().filesTabPane.getTabs().add(fileTab);\n\n // Indentation automatique\n final Pattern whiteSpace = Pattern.compile( \"^\\\\s+\" );\n codeArea.addEventHandler( KeyEvent.KEY_PRESSED, KE ->\n {\n if ( KE.getCode() == KeyCode.ENTER ) {\n int caretPosition = codeArea.getCaretPosition();\n int currentParagraph = codeArea.getCurrentParagraph();\n Matcher m0 = whiteSpace.matcher( codeArea.getParagraph( currentParagraph-1 ).getSegments().get( 0 ) );\n if ( m0.find() ) Platform.runLater( () -> codeArea.insertText( caretPosition, m0.group() ) );\n }\n });\n\n // Ajout automatique du caractère fermant\n codeArea.addEventHandler( KeyEvent.KEY_TYPED, KE ->\n {\n int caretPosition = codeArea.getCaretPosition();\n Platform.runLater( () -> {\n switch (KE.getCharacter()) {\n case \"[\" -> {\n codeArea.insertText( caretPosition,\"]\" );\n codeArea.moveTo(caretPosition);\n }\n\n case \"{\" -> {\n codeArea.insertText( caretPosition,\"}\" );\n codeArea.moveTo(caretPosition);\n }\n\n case \"\\\"\" -> {\n codeArea.insertText( caretPosition,\"\\\"\" );\n codeArea.moveTo(caretPosition);\n }\n }\n } );\n });\n\n setSaved();\n closed = false;\n }\n\n public FileEditor(JArmEmuApplication application, @NotNull File path) {\n this(application, path.getName(), \"\");\n this.path = path;\n reload();\n }\n\n public CodeArea getCodeArea() {\n return codeArea;\n }\n\n public VirtualizedScrollPane<CodeArea> getScrollPane() {\n return editorScroll;\n }\n\n public EditorContextMenu getContextMenu() {\n return contextMenu;\n }\n\n /**\n * @param line le numéro de la ligne\n * @return vrai si la ligne contient un breakpoint, faux sinon\n */\n public boolean hasBreakPoint(int line) {\n return lineFactory.hasBreakpoint(line);\n }\n\n /**\n * Nettoie le marquage des lignes.\n */\n public void clearLineMarkings() {\n this.lineFactory.clearMarkings();\n }\n\n /**\n * Marque comme executé la dernière ligne prévue tout en nettoyant l'ancienne ligne exécutée.\n */\n public void markExecuted() {\n this.lineFactory.markExecuted();\n }\n\n /**\n * Marque comme prévu une ligne tout en marquant executé l'ancienne ligne prévue.\n *\n * @param line le numéro de la ligne\n */\n public void markForward(int line) {\n if (line >= 0) {\n codeArea.moveTo(line, 0);\n codeArea.requestFollowCaret();\n\n this.lineFactory.markForward(line);\n }\n }\n\n /**\n * Déplace le curseur jusqu'à cette ligne.\n *\n * @param line le numéro de la ligne dans le fichier\n */\n public void goTo(int line) {\n codeArea.moveTo(line, 0);\n codeArea.requestFollowCaret();\n\n lineFactory.goTo(line);\n }\n\n /**\n * Nettoie la dernière ligne marquée comme exécutée.\n *\n * @apiNote Utile lors du changement d'éditeur\n */\n public void clearLastExecuted() {\n this.lineFactory.clearLastExecuted();\n }\n\n /**\n * Ferme le fichier\n */\n public void close() {\n logger.info(\"Closing \" + getFileName());\n getController().filesTabPane.getTabs().remove(fileTab);\n hightlightUpdateSubscription.unsubscribe();\n executor.close();\n this.closed = true;\n }\n\n public boolean isClosed() {\n return closed;\n }\n\n /**\n * Prépare la simulation (pré-géneration des lignes)\n */\n public void prepareSimulation() {\n int lineNum = codeArea.getParagraphs().size();\n logger.info(\"Pre-generate \" + lineNum + \" lines in \" + getFileName());\n lineFactory.pregen(codeArea.getParagraphs().size());\n Platform.runLater(this::clearLineMarkings);\n }\n\n /**\n * Sauvegarde le fichier\n */\n public void save() {\n if (!FileUtils.exists(path)) {\n saveAs();\n } else {\n try {\n logger.info(\"Saving file...\");\n getSourceScanner().exportCodeToFile(path);\n setSaved();\n logger.info(\"Saved at: \" + path.getAbsolutePath());\n } catch (Exception exception) {\n new ExceptionDialog(exception).show();\n logger.severe(ExceptionUtils.getStackTrace(exception));\n }\n }\n }\n\n /**\n * Sauvegarde le fichier sous un chemin spécifique\n */\n public void saveAs() {\n logger.info(\"Locating a new file to save...\");\n FileChooser fileChooser = new FileChooser();\n fileChooser.setTitle(\"Save Source File\");\n fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter(\"Assembly Source File\", \"*.s\"));\n if (FileUtils.exists(path)) {\n fileChooser.setInitialDirectory(path.isDirectory() ? path : path.getParentFile());\n }\n File file = fileChooser.showSaveDialog(application.stage);\n if (file != null && !file.isDirectory()) {\n try {\n if (!file.getAbsolutePath().endsWith(\".s\")) file = new File(file.getAbsolutePath() + \".s\");\n logger.info(\"File located: \" + file.getAbsolutePath());\n path = file;\n logger.info(\"Saving file...\");\n getSourceScanner().exportCodeToFile(path);\n setSaved();\n logger.info(\"Saved at: \" + path.getAbsolutePath());\n } catch (Exception exception) {\n new ExceptionDialog(exception).show();\n logger.severe(ExceptionUtils.getStackTrace(exception));\n }\n }\n }\n\n /**\n * Recharge le fichier depuis le disque\n */\n public void reload() {\n logger.info(\"Reloading file from disk\");\n if (FileUtils.isValidFile(path)) {\n try {\n SourceScanner scanner = new SourceScanner(path, getEditorController().getFileIndex(this));\n this.codeArea.replaceText(\"\");\n this.codeArea.replaceText(scanner.exportCode());\n setSaved();\n logger.info(\"File reloaded: \" + path.getAbsolutePath());\n } catch (Exception exception) {\n new ExceptionDialog(exception).show();\n logger.severe(ExceptionUtils.getStackTrace(exception));\n }\n }\n }\n\n /**\n * @return le nom du fichier ou \"New File\"\n */\n public String getFileName() {\n return FileUtils.isValidFile(path) ? path.getName() : \"New File\";\n }\n\n /**\n * Défini le contenu de la dernière sauvegarde\n *\n * @apiNote Sert à déterminer l'état actuel de la sauvegarde ('*' dans le titre)\n */\n private void setSaved() {\n saved = true;\n lastSaveContent = String.valueOf(codeArea.getText());\n fileTab.setText(getFileName());\n }\n\n /**\n * Met à jour l'état de sauvegarde\n */\n public void updateSaveState() {\n saved = codeArea.getText().equals(lastSaveContent);\n\n if (saved) {\n Platform.runLater(() -> fileTab.setText(getFileName()));\n } else {\n Platform.runLater(() -> fileTab.setText(getFileName() + \"*\"));\n }\n\n }\n\n public boolean getSaveState() {\n updateSaveState();\n return saved;\n }\n\n /**\n * @return un nouveau SourceScanner du fichier modifié\n */\n public SourceScanner getSourceScanner() {\n return new SourceScanner(codeArea.getText(), path == null ? \"New File\" : path.getName(), getEditorController().getFileIndex(this));\n }\n\n /**\n * Méthode utilisée pour automatiquement mettre à jour la colorimétrie\n *\n * @return la tache associée\n */\n private ComputeHightlightsTask autoComputeHighlightingAsync() {\n ComputeHightlightsTask task = new ComputeHightlightsTask(this);\n\n executor.execute(task);\n return task;\n }\n\n /**\n * @return le chemin d'accès du fichier\n */\n public @Nullable File getPath() {\n return path;\n }\n\n /**\n * @return l'indice visuel de l'éditeur\n */\n public int getVisualIndex() {\n return getController().filesTabPane.getTabs().indexOf(fileTab);\n }\n}" }, { "identifier": "LineStatus", "path": "src/main/java/fr/dwightstudio/jarmemu/gui/enums/LineStatus.java", "snippet": "public enum LineStatus {\n NONE,\n EXECUTED,\n SCHEDULED,\n FLAGGED;\n}" }, { "identifier": "FilePos", "path": "src/main/java/fr/dwightstudio/jarmemu/sim/obj/FilePos.java", "snippet": "public class FilePos {\n public static final FilePos ZERO = new FilePos(0, 0).freeze();\n\n private int file;\n private int pos;\n\n public FilePos(int file, int pos) {\n this.file = file;\n this.pos = pos;\n }\n\n public FilePos(FilePos filePos) {\n this.file = filePos.file;\n this.pos = filePos.pos;\n }\n\n @Override\n public String toString() {\n return file + \":\" + pos;\n }\n\n public int getFileIndex() {\n return file;\n }\n\n public int getPos() {\n return pos;\n }\n\n public int incrementPos(int i) {\n return pos += i;\n }\n\n public int incrementPos() {\n return incrementPos(1);\n }\n\n public void setPos(int i) {\n pos = i;\n }\n\n public int incrementFileIndex(int i) {\n return file += i;\n }\n\n public int incrementFileIndex() {\n return incrementFileIndex(1);\n }\n\n public void setFileIndex(int i) {\n file = i;\n }\n\n public int toByteValue() {\n return pos * 4;\n }\n\n public FilePos freeze(int offset) {\n return new FrozenFilePos(this, offset);\n }\n\n public FilePos freeze() {\n return new FrozenFilePos(this, 0);\n }\n\n @Override\n public boolean equals(Object obj) {\n if (obj instanceof FilePos position) {\n return position.getPos() == pos && position.getFileIndex() == file;\n } else {\n return false;\n }\n }\n\n public FilePos clone() {\n return new FilePos(this);\n }\n\n public static class FrozenFilePos extends FilePos {\n\n private final static String ERROR_MESSAGE = \"Can't modify frozen position\";\n\n private final int offset;\n\n\n public FrozenFilePos(FilePos filePos, int offset) {\n super(filePos.file, filePos.pos);\n this.offset = offset;\n }\n\n @Override\n public int getFileIndex() {\n return super.getFileIndex();\n }\n\n @Override\n public int getPos() {\n return super.getPos() + offset;\n }\n\n @Override\n public int incrementPos(int i) {\n throw new UnsupportedOperationException(ERROR_MESSAGE);\n }\n\n @Override\n public void setPos(int i) {\n throw new UnsupportedOperationException(ERROR_MESSAGE);\n }\n\n @Override\n public int incrementFileIndex(int i) {\n throw new UnsupportedOperationException(ERROR_MESSAGE);\n }\n\n @Override\n public void setFileIndex(int i) {\n throw new UnsupportedOperationException(ERROR_MESSAGE);\n }\n\n @Override\n public int toByteValue() {\n return getPos() * 4;\n }\n\n @Override\n public FilePos freeze() {\n return this;\n }\n }\n}" } ]
import fr.dwightstudio.jarmemu.Status; import fr.dwightstudio.jarmemu.gui.JArmEmuApplication; import fr.dwightstudio.jarmemu.gui.controllers.FileEditor; import fr.dwightstudio.jarmemu.gui.enums.LineStatus; import fr.dwightstudio.jarmemu.sim.obj.FilePos; import javafx.animation.KeyFrame; import javafx.animation.Timeline; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Node; import javafx.scene.input.MouseButton; import javafx.scene.layout.ColumnConstraints; import javafx.scene.layout.GridPane; import javafx.scene.layout.HBox; import javafx.scene.text.Text; import javafx.scene.text.TextAlignment; import javafx.util.Duration; import java.util.HashMap; import java.util.function.IntFunction;
8,229
/* * ____ _ __ __ _____ __ ___ * / __ \_ __(_)___ _/ /_ / /_ / ___// /___ ______/ (_)___ * / / / / | /| / / / __ `/ __ \/ __/ \__ \/ __/ / / / __ / / __ \ * / /_/ /| |/ |/ / / /_/ / / / / /_ ___/ / /_/ /_/ / /_/ / / /_/ / * /_____/ |__/|__/_/\__, /_/ /_/\__/ /____/\__/\__,_/\__,_/_/\____/ * /____/ * Copyright (C) 2023 Dwight Studio * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package fr.dwightstudio.jarmemu.gui.factory; public class JArmEmuLineFactory implements IntFunction<Node> { private final JArmEmuApplication application; private final HashMap<Integer, LineManager> managers; private LineManager lastScheduled; private LineManager lastExecuted; private final FileEditor fileEditor; public JArmEmuLineFactory(JArmEmuApplication application, FileEditor fileEditor) { this.application = application; this.managers = new HashMap<>(); this.fileEditor = fileEditor; } /** * Récupère une marge de ligne (dans le cache, ou fraiche). * * @param line le numéro de ligne * @return une marge de ligne */ @Override public Node apply(int line) { if (managers.containsKey(line)) { return managers.get(line).getNode(); } else { LineManager manager = new LineManager(line); return manager.getNode(); } } /** * Marque une ligne. * * @param line le numéro de la ligne * @param lineStatus le status de la ligne */ public void markLine(int line, LineStatus lineStatus) { if (managers.containsKey(line)) { LineManager manager = managers.get(line); manager.markLine(lineStatus); if (lineStatus == LineStatus.SCHEDULED) lastScheduled = manager; } } /** * Nettoie le marquage. */ public void clearMarkings() { managers.values().forEach(lineManager -> lineManager.markLine(LineStatus.NONE)); } /** * Marque comme executé la dernière ligne prévue tout en nettoyant l'ancienne ligne exécutée. */ public void markExecuted() { if (lastScheduled != null) lastScheduled.markLine(LineStatus.EXECUTED); if (lastExecuted != null && lastScheduled != lastExecuted) lastExecuted.markLine(LineStatus.NONE); lastExecuted = lastScheduled; } /** * Marque comme prévu une ligne tout en marquant executé l'ancienne ligne prévue. * * @param line le numéro de la ligne */ public void markForward(int line) { if (managers.containsKey(line)) { LineManager manager = managers.get(line); manager.markLine(LineStatus.SCHEDULED); markExecuted(); lastScheduled = manager; } } /** * Nettoie la dernière ligne marquée comme exécutée. * * @apiNote Utile lors du changement d'éditeur */ public void clearLastExecuted() { if (lastExecuted != null) lastExecuted.markLine(LineStatus.NONE); } /** * @param line le numéro de la ligne * @return vrai si la ligne contient un breakpoint, faux sinon */ public boolean hasBreakpoint(int line) { if (!managers.containsKey(line)) return false; return managers.get(line).hasBreakpoint(); } /** * Pré-génère des lignes pour améliorer les performances. * @param lineNum le numéro de la dernière ligne (exclusif) */ public void pregen(int lineNum) { for (int i = 0; i < lineNum; i++) { apply(i); } } public void goTo(int line) { LineManager manager = managers.get(line); new Timeline( new KeyFrame(Duration.millis(0), event -> manager.markLine(LineStatus.FLAGGED)), new KeyFrame(Duration.millis(500), event -> manager.markLine(LineStatus.NONE)), new KeyFrame(Duration.millis(1000), event -> manager.markLine(LineStatus.FLAGGED)), new KeyFrame(Duration.millis(1500), event -> manager.markLine(LineStatus.NONE)), new KeyFrame(Duration.millis(2000), event -> manager.markLine(LineStatus.FLAGGED)), new KeyFrame(Duration.millis(2500), event -> manager.markLine(LineStatus.NONE)) ).play(); } public class LineManager { private final int line; private final Text lineNo; private final Text linePos; private final GridPane grid; private final HBox hBox; private boolean breakpoint; private boolean show; private LineStatus status; public LineManager(int line) { this.line = line; breakpoint = false; show = false; status = LineStatus.NONE; grid = new GridPane(); grid.getStyleClass().add("none"); grid.setMaxWidth(80); grid.setPrefWidth(GridPane.USE_COMPUTED_SIZE); grid.setMinWidth(80); grid.setHgap(0); grid.setVgap(0); grid.setAlignment(Pos.CENTER_RIGHT); grid.getColumnConstraints().addAll(new ColumnConstraints(40), new ColumnConstraints(40)); grid.setPadding(new Insets(0, 5, 0, 0)); lineNo = new Text(); linePos = new Text(); lineNo.getStyleClass().add("lineno"); lineNo.setText(String.format("%4d", line)); lineNo.setTextAlignment(TextAlignment.RIGHT); linePos.getStyleClass().add("breakpoint"); linePos.setTextAlignment(TextAlignment.RIGHT); grid.add(lineNo, 0, 0); grid.add(linePos, 1, 0); hBox = new HBox(grid); HBox.setMargin(grid, new Insets(0, 5, 0, 0)); application.status.addListener((obs, oldVal, newVal) -> {
/* * ____ _ __ __ _____ __ ___ * / __ \_ __(_)___ _/ /_ / /_ / ___// /___ ______/ (_)___ * / / / / | /| / / / __ `/ __ \/ __/ \__ \/ __/ / / / __ / / __ \ * / /_/ /| |/ |/ / / /_/ / / / / /_ ___/ / /_/ /_/ / /_/ / / /_/ / * /_____/ |__/|__/_/\__, /_/ /_/\__/ /____/\__/\__,_/\__,_/_/\____/ * /____/ * Copyright (C) 2023 Dwight Studio * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package fr.dwightstudio.jarmemu.gui.factory; public class JArmEmuLineFactory implements IntFunction<Node> { private final JArmEmuApplication application; private final HashMap<Integer, LineManager> managers; private LineManager lastScheduled; private LineManager lastExecuted; private final FileEditor fileEditor; public JArmEmuLineFactory(JArmEmuApplication application, FileEditor fileEditor) { this.application = application; this.managers = new HashMap<>(); this.fileEditor = fileEditor; } /** * Récupère une marge de ligne (dans le cache, ou fraiche). * * @param line le numéro de ligne * @return une marge de ligne */ @Override public Node apply(int line) { if (managers.containsKey(line)) { return managers.get(line).getNode(); } else { LineManager manager = new LineManager(line); return manager.getNode(); } } /** * Marque une ligne. * * @param line le numéro de la ligne * @param lineStatus le status de la ligne */ public void markLine(int line, LineStatus lineStatus) { if (managers.containsKey(line)) { LineManager manager = managers.get(line); manager.markLine(lineStatus); if (lineStatus == LineStatus.SCHEDULED) lastScheduled = manager; } } /** * Nettoie le marquage. */ public void clearMarkings() { managers.values().forEach(lineManager -> lineManager.markLine(LineStatus.NONE)); } /** * Marque comme executé la dernière ligne prévue tout en nettoyant l'ancienne ligne exécutée. */ public void markExecuted() { if (lastScheduled != null) lastScheduled.markLine(LineStatus.EXECUTED); if (lastExecuted != null && lastScheduled != lastExecuted) lastExecuted.markLine(LineStatus.NONE); lastExecuted = lastScheduled; } /** * Marque comme prévu une ligne tout en marquant executé l'ancienne ligne prévue. * * @param line le numéro de la ligne */ public void markForward(int line) { if (managers.containsKey(line)) { LineManager manager = managers.get(line); manager.markLine(LineStatus.SCHEDULED); markExecuted(); lastScheduled = manager; } } /** * Nettoie la dernière ligne marquée comme exécutée. * * @apiNote Utile lors du changement d'éditeur */ public void clearLastExecuted() { if (lastExecuted != null) lastExecuted.markLine(LineStatus.NONE); } /** * @param line le numéro de la ligne * @return vrai si la ligne contient un breakpoint, faux sinon */ public boolean hasBreakpoint(int line) { if (!managers.containsKey(line)) return false; return managers.get(line).hasBreakpoint(); } /** * Pré-génère des lignes pour améliorer les performances. * @param lineNum le numéro de la dernière ligne (exclusif) */ public void pregen(int lineNum) { for (int i = 0; i < lineNum; i++) { apply(i); } } public void goTo(int line) { LineManager manager = managers.get(line); new Timeline( new KeyFrame(Duration.millis(0), event -> manager.markLine(LineStatus.FLAGGED)), new KeyFrame(Duration.millis(500), event -> manager.markLine(LineStatus.NONE)), new KeyFrame(Duration.millis(1000), event -> manager.markLine(LineStatus.FLAGGED)), new KeyFrame(Duration.millis(1500), event -> manager.markLine(LineStatus.NONE)), new KeyFrame(Duration.millis(2000), event -> manager.markLine(LineStatus.FLAGGED)), new KeyFrame(Duration.millis(2500), event -> manager.markLine(LineStatus.NONE)) ).play(); } public class LineManager { private final int line; private final Text lineNo; private final Text linePos; private final GridPane grid; private final HBox hBox; private boolean breakpoint; private boolean show; private LineStatus status; public LineManager(int line) { this.line = line; breakpoint = false; show = false; status = LineStatus.NONE; grid = new GridPane(); grid.getStyleClass().add("none"); grid.setMaxWidth(80); grid.setPrefWidth(GridPane.USE_COMPUTED_SIZE); grid.setMinWidth(80); grid.setHgap(0); grid.setVgap(0); grid.setAlignment(Pos.CENTER_RIGHT); grid.getColumnConstraints().addAll(new ColumnConstraints(40), new ColumnConstraints(40)); grid.setPadding(new Insets(0, 5, 0, 0)); lineNo = new Text(); linePos = new Text(); lineNo.getStyleClass().add("lineno"); lineNo.setText(String.format("%4d", line)); lineNo.setTextAlignment(TextAlignment.RIGHT); linePos.getStyleClass().add("breakpoint"); linePos.setTextAlignment(TextAlignment.RIGHT); grid.add(lineNo, 0, 0); grid.add(linePos, 1, 0); hBox = new HBox(grid); HBox.setMargin(grid, new Insets(0, 5, 0, 0)); application.status.addListener((obs, oldVal, newVal) -> {
show = (newVal == Status.SIMULATING);
0
2023-10-17 18:22:09+00:00
12k
GTNewHorizons/FarmingForEngineers
src/main/java/com/guigs44/farmingforengineers/FarmingForEngineers.java
[ { "identifier": "Compat", "path": "src/main/java/com/guigs44/farmingforengineers/compat/Compat.java", "snippet": "public class Compat {\n\n public static final String HARVESTCRAFT = \"harvestcraft\";\n public static final String MOUSETWEAKS = \"mousetweaks\";\n public static final String AGRICRAFT = \"agricraft\";\n public static final String FORESTRY = \"Forestry\";\n public static final String BIOMESOPLENTY = \"BiomesOPlenty\";\n public static final String NATURA = \"natura\";\n}" }, { "identifier": "VanillaAddon", "path": "src/main/java/com/guigs44/farmingforengineers/compat/VanillaAddon.java", "snippet": "public class VanillaAddon {\n\n private static final String[] ANIMALS = new String[] { \"Pig\", \"Sheep\", \"Cow\", \"Chicken\", \"EntityHorse\", \"Ocelot\",\n \"Rabbit\", \"PolarBear\", \"Wolf\" };\n\n public VanillaAddon() {\n MarketRegistry.registerDefaultHandler(\"Vanilla Seeds\", new MarketRegistryDefaultHandler() {\n\n @Override\n public void apply(MarketRegistry registry, ItemStack defaultPayment) {\n registry.registerEntry(new ItemStack(Items.wheat_seeds), defaultPayment, MarketEntry.EntryType.SEEDS);\n registry.registerEntry(new ItemStack(Items.melon_seeds), defaultPayment, MarketEntry.EntryType.SEEDS);\n registry.registerEntry(new ItemStack(Items.pumpkin_seeds), defaultPayment, MarketEntry.EntryType.SEEDS);\n }\n\n @Override\n public boolean isEnabledByDefault() {\n return true;\n }\n\n @Override\n public ItemStack getDefaultPayment() {\n return new ItemStack(Items.emerald);\n }\n });\n\n MarketRegistry.registerDefaultHandler(\"Vanilla Saplings\", new MarketRegistryDefaultHandler() {\n\n @Override\n public void apply(MarketRegistry registry, ItemStack defaultPayment) {\n\n for (int typeID = 0; typeID < BlockSapling.field_149882_a.length; typeID++) {\n registry.registerEntry(\n new ItemStack(Blocks.sapling, 1, typeID),\n defaultPayment,\n MarketEntry.EntryType.SAPLINGS);\n }\n }\n\n @Override\n public boolean isEnabledByDefault() {\n return true;\n }\n\n @Override\n public ItemStack getDefaultPayment() {\n return new ItemStack(Items.emerald);\n }\n });\n\n MarketRegistry.registerDefaultHandler(\"Bonemeal\", new MarketRegistryDefaultHandler() {\n\n @Override\n public void apply(MarketRegistry registry, ItemStack defaultPayment) {\n registry.registerEntry(\n new ItemStack(Items.dye, 1, EnumColor.WHITE.ordinal()),\n defaultPayment,\n MarketEntry.EntryType.OTHER);\n }\n\n @Override\n public boolean isEnabledByDefault() {\n return true;\n }\n\n @Override\n public ItemStack getDefaultPayment() {\n return new ItemStack(Items.emerald);\n }\n });\n\n MarketRegistry.registerDefaultHandler(\"Animal Eggs\", new MarketRegistryDefaultHandler() {\n\n @Override\n public void apply(MarketRegistry registry, ItemStack defaultPayment) {\n for (String animalName : ANIMALS) {\n ItemStack eggStack = new ItemStack(Items.spawn_egg);\n\n // \\o/ Praise SideOnly \\o/\n NBTTagCompound tagCompound = eggStack.getTagCompound();\n if (tagCompound == null) {\n tagCompound = new NBTTagCompound();\n }\n NBTTagCompound entityTag = new NBTTagCompound();\n entityTag.setString(\"id\", animalName);\n tagCompound.setTag(\"EntityTag\", entityTag);\n eggStack.setTagCompound(tagCompound);\n\n registry.registerEntry(eggStack, defaultPayment, MarketEntry.EntryType.OTHER);\n }\n }\n\n @Override\n public boolean isEnabledByDefault() {\n return false;\n }\n\n @Override\n public ItemStack getDefaultPayment() {\n return new ItemStack(Items.emerald);\n }\n });\n }\n}" }, { "identifier": "EntityMerchant", "path": "src/main/java/com/guigs44/farmingforengineers/entity/EntityMerchant.java", "snippet": "public class EntityMerchant extends EntityCreature implements INpc {\n\n public enum SpawnAnimationType {\n MAGIC,\n FALLING,\n DIGGING\n }\n\n private static final Random rand = new Random();\n public static final String[] NAMES = new String[] { \"Swap-O-Matic\", \"Emerald Muncher\", \"Back Alley Dealer\",\n \"Weathered Salesperson\" };\n\n // private BlockPos marketPos;\n private int marketX;\n private int marketY;\n private int marketZ;\n private EnumFacing facing;\n private boolean spawnDone;\n private SpawnAnimationType spawnAnimation = SpawnAnimationType.MAGIC;\n\n // private BlockPos marketEntityPos;\n private int diggingAnimation;\n // private IBlockState diggingBlockState;\n\n public EntityMerchant(World world) {\n super(world);\n setSize(0.6f, 1.95f);\n this.tasks.addTask(0, new EntityAISwimming(this));\n this.tasks.addTask(1, new EntityAIAvoidEntity(this, EntityZombie.class, 8f, 0.6, 0.6));\n this.tasks.addTask(5, new EntityAIMerchant(this, 0.6));\n }\n\n @Override\n protected void entityInit() {\n super.entityInit();\n }\n\n @Override\n protected void applyEntityAttributes() {\n super.applyEntityAttributes();\n getEntityAttribute(SharedMonsterAttributes.movementSpeed).setBaseValue(0.5);\n }\n\n @Override\n public boolean interact(EntityPlayer player) {\n if (isMarketValid()) {\n player.openGui(\n FarmingForEngineers.MOD_ID,\n GuiHandler.MARKET,\n worldObj,\n (int) marketX,\n (int) marketY,\n (int) marketZ);\n return true;\n }\n return super.interact(player);\n }\n\n @Override\n public void writeEntityToNBT(NBTTagCompound compound) {\n super.writeEntityToNBT(compound);\n // I wonder if using an integer won't be a problem\n compound.setInteger(\"MarketPosX\", marketX);\n compound.setInteger(\"MarketPosY\", marketY);\n compound.setInteger(\"MarketPosZ\", marketZ);\n\n // if(facing != null) {\n // compound.setByte(\"Facing\", (byte) facing.);\n // }\n compound.setBoolean(\"SpawnDone\", spawnDone);\n compound.setByte(\"SpawnAnimation\", (byte) spawnAnimation.ordinal());\n }\n\n @Override\n public void readEntityFromNBT(NBTTagCompound compound) {\n super.readEntityFromNBT(compound);\n if (!compound.hasKey(\"CustomName\")) {\n setCustomNameTag(NAMES[rand.nextInt(NAMES.length)]);\n }\n if (compound.hasKey(\"MarketPosX\")) {\n setMarket(marketX, marketY, marketZ, EnumFacing.getFront(compound.getByte(\"Facing\")));\n }\n spawnDone = compound.getBoolean(\"SpawnDone\");\n spawnAnimation = SpawnAnimationType.values()[compound.getByte(\"SpawnAnimation\")];\n }\n\n @Override\n protected boolean canDespawn() {\n return false;\n }\n\n @Override\n protected String getLivingSound() {\n return \"mob.villager.ambient\";\n } // TODO: Figure out what is the correct string\n\n @Override\n protected String getHurtSound() {\n return \"mob.villager.hit\";\n } // Works\n\n @Override\n protected String getDeathSound() {\n return \"mob.villager.death\";\n }// works\n\n @Override\n public void onEntityUpdate() {\n super.onEntityUpdate();\n if (!worldObj.isRemote) {\n if (ticksExisted % 20 == 0) {\n if (!isMarketValid()) {\n worldObj.setEntityState(this, (byte) 12);\n setDead();\n }\n }\n }\n\n if (!spawnDone && spawnAnimation == SpawnAnimationType.DIGGING) {\n worldObj.setEntityState(this, (byte) 13);\n spawnDone = true;\n }\n if (diggingAnimation > 0) {\n diggingAnimation--;\n for (int i = 0; i < 4; i++) {\n int stateId = 0;\n\n // Block.getStateId(diggingBlockState != null ? diggingBlockState : Blocks.dirt.get());\n // worldObj.spawnParticle(EnumParticleTypes.BLOCK_CRACK, posX, posY, posZ, Math.random() * 2 - 1,\n // Math.random() * 4, Math.random() * 2 - 1, stateId);\n // worldObj.spawnParticle(EnumParticleTypes.BLOCK_DUST, posX, posY, posZ, (Math.random() - 0.5) * 0.5,\n // Math.random() * 0.5f, (Math.random() - 0.5) * 0.5, stateId);\n }\n if (diggingAnimation % 2 == 0) {\n worldObj.playSound(posX, posY, posZ, \"block.gravel.hit\", 1f, (float) (Math.random() + 0.5), false);\n }\n }\n }\n\n // @Override\n // public void handleStatusUpdate(byte id) {\n // if(id == 12) {\n // disappear();\n // return;\n // } else if(id == 13) {\n // diggingBlockState = worldObj.getBlockState(getPosition().down());\n // diggingAnimation = 60;\n // return;\n // }\n // super.handleStatusUpdate(id);\n // }\n\n @Override\n protected void damageEntity(DamageSource damageSrc, float damageAmount) {\n if (!spawnDone && damageSrc == DamageSource.fall) {\n worldObj.playSound(posX, posY, posZ, getHurtSound(), 1f, 2f, false);\n spawnDone = true;\n return;\n }\n super.damageEntity(damageSrc, damageAmount);\n }\n\n @Override\n public float getEyeHeight() {\n return 1.62f;\n }\n\n @Nullable\n public IEntityLivingData onInitialSpawn(@Nullable IEntityLivingData livingData) {\n if (Math.random() < 0.001) {\n setCustomNameTag(Math.random() <= 0.5 ? \"Pam\" : \"Blay\");\n } else {\n setCustomNameTag(NAMES[rand.nextInt(NAMES.length)]);\n }\n setAlwaysRenderNameTag(true);\n return livingData;\n }\n\n // @Override\n // public boolean canBeLeashedTo(EntityPlayer player) {\n // return false;\n // }\n\n public void setMarket(int marketX, int marketY, int marketZ, EnumFacing facing) {\n this.marketX = marketX;\n this.marketY = marketY;\n this.marketZ = marketZ;\n // this.marketEntityPos = marketPos.offset(facing.getOpposite());\n this.facing = facing;\n }\n\n // @Nullable\n // public BlockPos getMarketEntityPosition() {\n // return marketEntityPos;\n // }\n\n public boolean isAtMarket() {\n // TODO: Implement\n // return marketEntityPos != null && getDistanceSq(marketEntityPos.offset(facing.getOpposite())) <= 1;\n return true;\n }\n\n private boolean isMarketValid() {\n // return marketPos != null && worldObj.getBlockState(marketPos).getBlock() == ModBlocks.market;\n return true;\n }\n\n public void setToFacingAngle() {\n float facingAngle = 0f; // facing.getHorizontalAngle();\n setRotation(facingAngle, 0f);\n setRotationYawHead(facingAngle);\n // setRenderYawOffset(facingAngle);\n }\n\n public void disappear() {\n worldObj.playSound(posX, posY, posZ, \"item.firecharge.use\", 1f, 1f, false);\n for (int i = 0; i < 50; i++) {\n worldObj.spawnParticle(\n \"firework\",\n posX,\n posY + 1,\n posZ,\n (Math.random() - 0.5) * 0.5f,\n (Math.random() - 0.5) * 0.5f,\n (Math.random() - 0.5) * 0.5f);\n }\n worldObj.spawnParticle(\"explosion\", posX, posY + 1, posZ, 0, 0, 0);\n setDead();\n }\n\n public void setSpawnAnimation(SpawnAnimationType spawnAnimation) {\n this.spawnAnimation = spawnAnimation;\n }\n\n public int getDiggingAnimation() {\n return diggingAnimation;\n }\n}" }, { "identifier": "GuiHandler", "path": "src/main/java/com/guigs44/farmingforengineers/network/GuiHandler.java", "snippet": "public class GuiHandler implements IGuiHandler {\n\n public static final int MARKET = 1;\n\n @Override\n @Nullable\n public Object getServerGuiElement(int id, EntityPlayer player, World world, int x, int y, int z) {\n if (id == MARKET) {\n TileEntity tileEntity = world.getTileEntity(x, y, z);\n if (tileEntity instanceof TileMarket) {\n return new ContainerMarket(player, x, y, z);\n }\n }\n return null;\n }\n\n @Override\n @Nullable\n public Object getClientGuiElement(int id, EntityPlayer player, World world, int x, int y, int z) {\n if (id == MARKET) {\n TileEntity tileEntity = world.getTileEntity(x, y, z);\n if (tileEntity instanceof TileMarket) {\n return new GuiMarket(new ContainerMarketClient(player, x, y, z));\n }\n }\n return null;\n }\n}" }, { "identifier": "NetworkHandler", "path": "src/main/java/com/guigs44/farmingforengineers/network/NetworkHandler.java", "snippet": "public class NetworkHandler {\n\n public static final SimpleNetworkWrapper instance = NetworkRegistry.INSTANCE\n .newSimpleChannel(FarmingForEngineers.MOD_ID);\n\n public static void init() {\n instance.registerMessage(HandlerMarketList.class, MessageMarketList.class, 0, Side.CLIENT);\n instance.registerMessage(HandlerMarketSelect.class, MessageMarketSelect.class, 1, Side.SERVER);\n }\n\n // public static Minecraft getThreadListener(MessageContext ctx) {\n // return ctx.side == Side.SERVER ? ctx.getServerHandler().playerEntity.worldObj : getClientThreadListener();\n // }\n\n @SideOnly(Side.CLIENT)\n public static Minecraft getClientThreadListener() {\n return Minecraft.getMinecraft();\n }\n}" }, { "identifier": "AbstractRegistry", "path": "src/main/java/com/guigs44/farmingforengineers/registry/AbstractRegistry.java", "snippet": "public abstract class AbstractRegistry {\n\n public static List<String> registryErrors = Lists.newArrayList();\n\n protected final String registryName;\n private boolean hasChanged;\n private boolean refuseSave;\n\n public AbstractRegistry(String registryName) {\n this.registryName = registryName;\n }\n\n public final void load(File configDir) {\n clear();\n Gson gson = new Gson();\n File configFile = new File(configDir, registryName + \".json\");\n if (!configFile.exists()) {\n try (JsonWriter jsonWriter = new JsonWriter(new FileWriter(configFile))) {\n jsonWriter.setIndent(\" \");\n gson.toJson(create(), jsonWriter);\n } catch (IOException e) {\n FarmingForEngineers.logger.error(\"Failed to create default {} registry: {}\", registryName, e);\n }\n }\n\n JsonObject root = null;\n try (JsonReader jsonReader = new JsonReader(new FileReader(configFile))) {\n jsonReader.setLenient(true);\n root = gson.fromJson(jsonReader, JsonObject.class);\n if (hasCustomLoader()) {\n load(root);\n } else {\n if (hasOptions()) {\n JsonObject options = tryGetObject(root, \"options\");\n loadOptions(options);\n }\n JsonObject defaults = tryGetObject(root, \"defaults\");\n registerDefaults(defaults);\n JsonObject custom = tryGetObject(root, \"custom\");\n JsonArray entries = tryGetArray(custom, \"entries\");\n for (int i = 0; i < entries.size(); i++) {\n JsonElement element = entries.get(i);\n if (element.isJsonObject()) {\n loadCustom(element.getAsJsonObject());\n } else {\n logError(\"Failed to load %s registry: entries must be an array of json objects\", registryName);\n }\n }\n }\n } catch (IOException | ClassCastException | JsonSyntaxException e) {\n logError(\"Failed to load %s registry: %s\", registryName, e);\n refuseSave = true;\n }\n if (root != null && hasChanged && !refuseSave) {\n try (JsonWriter jsonWriter = new JsonWriter(new FileWriter(configFile))) {\n jsonWriter.setIndent(\" \");\n gson.toJson(root, jsonWriter);\n } catch (IOException e) {\n FarmingForEngineers.logger.error(\"Failed to save updated {} registry: {}\", registryName, e);\n }\n }\n // MinecraftForge.EVENT_BUS.post(new ReloadRegistryEvent(this));\n }\n\n protected abstract void clear();\n\n protected abstract JsonObject create();\n\n protected void loadCustom(JsonObject entry) {}\n\n protected void registerDefaults(JsonObject defaults) {}\n\n protected void load(JsonObject root) {}\n\n protected boolean hasCustomLoader() {\n return false;\n }\n\n protected void loadOptions(JsonObject entry) {}\n\n protected boolean hasOptions() {\n return false;\n }\n\n protected final boolean tryGetBoolean(JsonObject root, String key, boolean defaultValue) {\n if (root.has(key)) {\n JsonElement element = root.get(key);\n if (element.isJsonPrimitive()) {\n return element.getAsBoolean();\n }\n }\n root.addProperty(key, defaultValue);\n hasChanged = true;\n return defaultValue;\n }\n\n protected final int tryGetInt(JsonObject root, String key, int defaultValue) {\n if (root.has(key)) {\n JsonElement element = root.get(key);\n if (element.isJsonPrimitive()) {\n return element.getAsInt();\n }\n }\n root.addProperty(key, defaultValue);\n hasChanged = true;\n return defaultValue;\n }\n\n protected final float tryGetFloat(JsonObject root, String key, float defaultValue) {\n if (root.has(key)) {\n JsonElement element = root.get(key);\n if (element.isJsonPrimitive()) {\n return element.getAsFloat();\n }\n }\n root.addProperty(key, defaultValue);\n hasChanged = true;\n return defaultValue;\n }\n\n protected final String tryGetString(JsonObject root, String key, String defaultValue) {\n if (root.has(key)) {\n JsonElement element = root.get(key);\n if (element.isJsonPrimitive()) {\n return element.getAsString();\n }\n }\n root.addProperty(key, defaultValue);\n hasChanged = true;\n return defaultValue;\n }\n\n protected final JsonObject tryGetObject(JsonObject root, String key) {\n if (root.has(key)) {\n JsonElement element = root.get(key);\n if (element.isJsonObject()) {\n return element.getAsJsonObject();\n } else {\n logError(\n \"Invalid configuration format: expected %s to be a json object in %s, but got %s\",\n key,\n registryName,\n element.getClass().toString());\n refuseSave = true;\n return new JsonObject();\n }\n }\n JsonObject newObject = new JsonObject();\n root.add(key, newObject);\n hasChanged = true;\n return newObject;\n }\n\n protected final JsonArray tryGetArray(JsonObject root, String key) {\n if (root.has(key)) {\n JsonElement element = root.get(key);\n if (element.isJsonArray()) {\n return element.getAsJsonArray();\n } else {\n logError(\n \"Invalid configuration format: expected %s to be a json array in %s, but got %s\",\n key,\n registryName,\n element.getClass().toString());\n refuseSave = true;\n return new JsonArray();\n }\n }\n JsonArray newArray = new JsonArray();\n root.add(key, newArray);\n hasChanged = true;\n return newArray;\n }\n\n protected final int tryParseInt(String s) {\n try {\n return Integer.parseInt(s);\n } catch (NumberFormatException e) {\n logError(\"Expected number but got %s, falling back to 0...\", s);\n refuseSave = true;\n return 0;\n }\n }\n\n protected final void logError(String format, Object... args) {\n String s = String.format(format, args);\n FarmingForEngineers.logger.error(s);\n registryErrors.add(s);\n }\n\n protected final void logWarning(String format, Object... args) {\n String s = String.format(format, args);\n FarmingForEngineers.logger.error(s);\n if (ModConfig.showRegistryWarnings) {\n registryErrors.add(s);\n }\n }\n\n protected final void logUnknownItem(ResourceLocation location) {\n String s = String.format(\"Unknown item '%s' in %s\", location, registryName);\n FarmingForEngineers.logger.error(s);\n registryErrors.add(s);\n }\n\n protected final void logUnknownFluid(String fluidName, ResourceLocation location) {\n String s = String.format(\"Unknown fluid '%s' when registering %s in %s\", fluidName, location, registryName);\n FarmingForEngineers.logger.error(s);\n registryErrors.add(s);\n }\n\n protected final void logUnknownOre(ResourceLocation location) {\n FarmingForEngineers.logger\n .warn(\"No ore dictionary entries found for {} in {}\", location.getResourcePath(), registryName);\n }\n}" }, { "identifier": "MarketRegistry", "path": "src/main/java/com/guigs44/farmingforengineers/registry/MarketRegistry.java", "snippet": "public class MarketRegistry extends AbstractRegistry {\n\n public static final MarketRegistry INSTANCE = new MarketRegistry();\n\n private static final Pattern ITEMSTACK_PATTERN = Pattern\n .compile(\"(?:([0-9]+)\\\\*)?(?:([\\\\w]+):)([\\\\w]+)(?::([0-9]+))?(?:@(.+))?\");\n\n private final List<MarketEntry> entries = Lists.newArrayList();\n\n private final Map<String, ItemStack> defaultPayments = Maps.newHashMap();\n private final Map<String, MarketRegistryDefaultHandler> defaultHandlers = Maps.newHashMap();\n\n public MarketRegistry() {\n super(\"Market\");\n }\n\n public void registerEntry(ItemStack outputItem, ItemStack costItem, MarketEntry.EntryType type) {\n entries.add(new MarketEntry(outputItem, costItem, type));\n }\n\n @Nullable\n public static MarketEntry getEntryFor(ItemStack outputItem) {\n for (MarketEntry entry : INSTANCE.entries) {\n if (entry.getOutputItem().isItemEqual(outputItem)\n && ItemStack.areItemStackTagsEqual(entry.getOutputItem(), outputItem)) {\n return entry;\n }\n }\n return null;\n }\n\n public static Collection<MarketEntry> getEntries() {\n return INSTANCE.entries;\n }\n\n @Override\n protected void clear() {\n entries.clear();\n }\n\n @Override\n protected JsonObject create() {\n JsonObject root = new JsonObject();\n\n JsonObject defaults = new JsonObject();\n defaults.addProperty(\n \"__comment\",\n \"You can disable defaults by setting these to false. Do *NOT* try to add additional entries here. You can add additional entries in the custom section.\");\n root.add(\"defaults\", defaults);\n\n JsonObject payment = new JsonObject();\n payment.addProperty(\"__comment\", \"You can define custom payment items for the default entries here.\");\n root.add(\"defaults payment\", payment);\n\n JsonArray blacklist = new JsonArray();\n blacklist.add(new JsonPrimitive(\"examplemod:example_item\"));\n root.add(\"defaults blacklist\", blacklist);\n\n JsonObject custom = new JsonObject();\n custom.addProperty(\n \"__comment\",\n \"You can define additional items to be sold by the Market here. Defaults can be overridden. Prefix with ! to blacklist instead.\");\n custom.addProperty(\"examplemod:example_item\", \"2*minecraft:emerald\");\n root.add(\"custom entries\", custom);\n\n return root;\n }\n\n @Override\n protected void load(JsonObject root) {\n JsonObject payments = tryGetObject(root, \"defaults payment\");\n loadDefaultPayments(payments);\n\n JsonObject defaults = tryGetObject(root, \"defaults\");\n registerDefaults(defaults);\n\n JsonArray blacklist = tryGetArray(root, \"defaults blacklist\");\n for (int i = 0; i < blacklist.size(); i++) {\n JsonElement element = blacklist.get(i);\n if (element.isJsonPrimitive()) {\n loadDefaultBlacklistEntry(element.getAsString());\n } else {\n logError(\"Failed to load %s registry: blacklist entries must be strings\", registryName);\n }\n }\n\n JsonObject custom = tryGetObject(root, \"custom entries\");\n for (Map.Entry<String, JsonElement> entry : custom.entrySet()) {\n if (entry.getValue().isJsonPrimitive()) {\n loadMarketEntry(entry.getKey(), entry.getValue().getAsString());\n } else {\n logError(\"Failed to load %s registry: entries must be strings\", registryName);\n }\n }\n }\n\n @Override\n protected boolean hasCustomLoader() {\n return true;\n }\n\n private void loadMarketEntry(String key, String value) {\n if (key.equals(\"__comment\") || key.equals(\"examplemod:example_item\")) {\n return;\n }\n\n ItemStack outputStack = parseItemStack(key);\n ItemStack costStack = parseItemStack(value);\n if (outputStack == null || costStack == null) {\n return;\n }\n\n tryRemoveEntry(outputStack);\n\n MarketEntry.EntryType type = MarketEntry.EntryType.OTHER;\n\n // outputStack.getItem().getRegistryName().getResourcePath().contains(\"sapling\") maybe\n if (outputStack.getItem().getUnlocalizedName().contains(\"sapling\")) {\n type = MarketEntry.EntryType.SAPLINGS;\n } else if (outputStack.getItem().getUnlocalizedName().contains(\"seed\")) {\n type = MarketEntry.EntryType.SEEDS;\n }\n\n registerEntry(outputStack, costStack, type);\n }\n\n private void loadDefaultBlacklistEntry(String input) {\n if (input.equals(\"examplemod:example_item\")) {\n return;\n }\n ItemStack itemStack = parseItemStack(input);\n if (itemStack != null) {\n if (!tryRemoveEntry(itemStack)) {\n logError(\"Could not find default entry for blacklisted item %s\", input);\n }\n }\n }\n\n private void loadDefaultPayments(JsonObject defaults) {\n for (Map.Entry<String, MarketRegistryDefaultHandler> entry : defaultHandlers.entrySet()) {\n String value = tryGetString(defaults, entry.getKey(), \"\");\n if (value.isEmpty()) {\n ItemStack defaultPayment = entry.getValue().getDefaultPayment();\n defaults.addProperty(\n entry.getKey(),\n String.format(\n \"%d*%s:%d\",\n defaultPayment.stackSize,\n defaultPayment.getItem().getUnlocalizedName(),\n defaultPayment.getItemDamage()));\n }\n ItemStack itemStack = !value.isEmpty() ? parseItemStack(value) : null;\n if (itemStack == null) {\n itemStack = entry.getValue().getDefaultPayment();\n }\n defaultPayments.put(entry.getKey(), itemStack);\n }\n }\n\n @Override\n protected void registerDefaults(JsonObject json) {\n for (Map.Entry<String, MarketRegistryDefaultHandler> entry : defaultHandlers.entrySet()) {\n if (tryGetBoolean(json, entry.getKey(), entry.getValue().isEnabledByDefault())) {\n entry.getValue().apply(this, INSTANCE.defaultPayments.get(entry.getKey()));\n }\n }\n }\n\n public static void registerDefaultHandler(String defaultKey, MarketRegistryDefaultHandler handler) {\n INSTANCE.defaultHandlers.put(defaultKey, handler);\n }\n\n private boolean tryRemoveEntry(ItemStack itemStack) {\n for (int i = entries.size() - 1; i >= 0; i--) {\n MarketEntry entry = entries.get(i);\n if (entry.getOutputItem().isItemEqual(itemStack)\n && ItemStack.areItemStackTagsEqual(entry.getOutputItem(), itemStack)) {\n entries.remove(i);\n return true;\n }\n }\n return false;\n }\n\n @Nullable\n private ItemStack parseItemStack(String input) {\n Matcher matcher = ITEMSTACK_PATTERN.matcher(input);\n if (!matcher.find()) {\n logError(\"Invalid item %s, format mismatch\", input);\n return null;\n }\n\n ResourceLocation resourceLocation = new ResourceLocation(matcher.group(2), matcher.group(3));\n Item item = (Item) Item.itemRegistry.getObject(resourceLocation.toString());\n if (item == null) {\n logUnknownItem(resourceLocation);\n return null;\n }\n int count = matcher.group(1) != null ? tryParseInt(matcher.group(1)) : 1;\n int meta = matcher.group(4) != null ? tryParseInt(matcher.group(4)) : 0;\n String nbt = matcher.group(5);\n NBTTagCompound tagCompound = null;\n if (nbt != null) {\n tagCompound = (NBTTagCompound) codechicken.nei.util.NBTJson.toNbt(JsonParser.parseString(nbt));\n }\n ItemStack itemStack = new ItemStack(item, count, meta);\n if (tagCompound != null) {\n itemStack.setTagCompound(tagCompound);\n }\n return itemStack;\n }\n}" }, { "identifier": "ChatComponentBuilder", "path": "src/main/java/com/guigs44/farmingforengineers/utilities/ChatComponentBuilder.java", "snippet": "public class ChatComponentBuilder {\n\n private final IChatComponent parent;\n\n private String text;\n private ChatStyle style;\n\n private ChatComponentBuilder(String text) {\n this(text, null, Inheritance.SHALLOW);\n }\n\n private ChatComponentBuilder(String text, IChatComponent parent, Inheritance inheritance) {\n this.parent = parent;\n this.text = text;\n\n switch (inheritance) {\n case DEEP:\n this.style = parent != null ? parent.getChatStyle() : new ChatStyle();\n break;\n default:\n case SHALLOW:\n this.style = new ChatStyle();\n break;\n case NONE:\n this.style = new ChatStyle().setColor(null).setBold(false).setItalic(false).setStrikethrough(false)\n .setUnderlined(false).setObfuscated(false).setChatClickEvent(null).setChatHoverEvent(null);\n break;\n }\n }\n\n public static ChatComponentBuilder of(String text) {\n return new ChatComponentBuilder(text);\n }\n\n public ChatComponentBuilder setColor(EnumChatFormatting color) {\n style.setColor(color);\n return this;\n }\n\n public ChatComponentBuilder setBold(boolean bold) {\n style.setBold(bold);\n return this;\n }\n\n public ChatComponentBuilder setItalic(boolean italic) {\n style.setItalic(italic);\n return this;\n }\n\n public ChatComponentBuilder setStrikethrough(boolean strikethrough) {\n style.setStrikethrough(strikethrough);\n return this;\n }\n\n public ChatComponentBuilder setUnderlined(boolean underlined) {\n style.setUnderlined(underlined);\n return this;\n }\n\n public ChatComponentBuilder setObfuscated(boolean obfuscated) {\n style.setObfuscated(obfuscated);\n return this;\n }\n\n public ChatComponentBuilder setClickEvent(ClickEvent.Action action, String value) {\n style.setChatClickEvent(new ClickEvent(action, value));\n return this;\n }\n\n public ChatComponentBuilder setHoverEvent(String value) {\n return this.setHoverEvent(new ChatComponentText(value));\n }\n\n public ChatComponentBuilder setHoverEvent(IChatComponent value) {\n return this.setHoverEvent(Action.SHOW_TEXT, value);\n }\n\n public ChatComponentBuilder setHoverEvent(HoverEvent.Action action, IChatComponent value) {\n style.setChatHoverEvent(new HoverEvent(action, value));\n return this;\n }\n\n public ChatComponentBuilder append(String text) {\n return this.append(text, Inheritance.SHALLOW);\n }\n\n public ChatComponentBuilder append(String text, Inheritance inheritance) {\n return new ChatComponentBuilder(text, this.build(), inheritance);\n }\n\n public IChatComponent build() {\n IChatComponent thisComponent = new ChatComponentText(text).setChatStyle(style);\n return parent != null ? parent.appendSibling(thisComponent) : thisComponent;\n }\n\n public enum Inheritance {\n DEEP,\n SHALLOW,\n NONE\n }\n}" } ]
import java.io.File; import java.util.Optional; import net.minecraft.block.Block; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.Item; import net.minecraftforge.common.config.Configuration; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import com.guigs44.farmingforengineers.compat.Compat; import com.guigs44.farmingforengineers.compat.VanillaAddon; import com.guigs44.farmingforengineers.entity.EntityMerchant; import com.guigs44.farmingforengineers.network.GuiHandler; import com.guigs44.farmingforengineers.network.NetworkHandler; import com.guigs44.farmingforengineers.registry.AbstractRegistry; import com.guigs44.farmingforengineers.registry.MarketRegistry; import com.guigs44.farmingforengineers.utilities.ChatComponentBuilder; import cpw.mods.fml.common.Loader; import cpw.mods.fml.common.Mod; import cpw.mods.fml.common.SidedProxy; import cpw.mods.fml.common.event.FMLInitializationEvent; import cpw.mods.fml.common.event.FMLPostInitializationEvent; import cpw.mods.fml.common.event.FMLPreInitializationEvent; import cpw.mods.fml.common.event.FMLServerStartingEvent; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import cpw.mods.fml.common.gameevent.PlayerEvent; import cpw.mods.fml.common.network.NetworkRegistry; import cpw.mods.fml.common.registry.EntityRegistry;
8,808
package com.guigs44.farmingforengineers; @Mod( modid = FarmingForEngineers.MOD_ID, name = "Farming for Engineers", dependencies = "after:mousetweaks[2.8,);after:forestry;after:agricraft") // @Mod.EventBusSubscriber public class FarmingForEngineers { public static final String MOD_ID = "farmingforengineers"; @Mod.Instance(MOD_ID) public static FarmingForEngineers instance; @SidedProxy( clientSide = "com.guigs44.farmingforengineers.client.ClientProxy", serverSide = "com.guigs44.farmingforengineers.CommonProxy") public static CommonProxy proxy; public static final Logger logger = LogManager.getLogger(); public static final CreativeTabs creativeTab = new CreativeTabs(MOD_ID) { @Override public Item getTabIconItem() { return Item.getItemFromBlock(FarmingForEngineers.blockMarket); } }; public static File configDir; public static Block blockMarket; @Mod.EventHandler public void preInit(FMLPreInitializationEvent event) { configDir = new File(event.getModConfigurationDirectory(), "FarmingForEngineers"); if (!configDir.exists() && !configDir.mkdirs()) { throw new RuntimeException("Couldn't create Farming for Engineers configuration directory"); } Configuration config = new Configuration(new File(configDir, "FarmingForEngineers.cfg")); config.load(); ModConfig.preInit(config); proxy.preInit(event); if (config.hasChanged()) { config.save(); } } @Mod.EventHandler public void init(FMLInitializationEvent event) { NetworkHandler.init(); NetworkRegistry.INSTANCE.registerGuiHandler(this, new GuiHandler()); new VanillaAddon(); buildSoftDependProxy(Compat.HARVESTCRAFT, "com.guigs44.farmingforengineers.compat.HarvestcraftAddon"); buildSoftDependProxy(Compat.FORESTRY, "com.guigs44.farmingforengineers.compat.ForestryAddon"); buildSoftDependProxy(Compat.AGRICRAFT, "com.guigs44.farmingforengineers.compat.AgriCraftAddon"); buildSoftDependProxy(Compat.BIOMESOPLENTY, "com.guigs44.farmingforengineers.compat.BiomesOPlentyAddon"); buildSoftDependProxy(Compat.NATURA, "com.guigs44.farmingforengineers.compat.NaturaAddon"); ModRecipes.init(); MarketRegistry.INSTANCE.load(configDir);
package com.guigs44.farmingforengineers; @Mod( modid = FarmingForEngineers.MOD_ID, name = "Farming for Engineers", dependencies = "after:mousetweaks[2.8,);after:forestry;after:agricraft") // @Mod.EventBusSubscriber public class FarmingForEngineers { public static final String MOD_ID = "farmingforengineers"; @Mod.Instance(MOD_ID) public static FarmingForEngineers instance; @SidedProxy( clientSide = "com.guigs44.farmingforengineers.client.ClientProxy", serverSide = "com.guigs44.farmingforengineers.CommonProxy") public static CommonProxy proxy; public static final Logger logger = LogManager.getLogger(); public static final CreativeTabs creativeTab = new CreativeTabs(MOD_ID) { @Override public Item getTabIconItem() { return Item.getItemFromBlock(FarmingForEngineers.blockMarket); } }; public static File configDir; public static Block blockMarket; @Mod.EventHandler public void preInit(FMLPreInitializationEvent event) { configDir = new File(event.getModConfigurationDirectory(), "FarmingForEngineers"); if (!configDir.exists() && !configDir.mkdirs()) { throw new RuntimeException("Couldn't create Farming for Engineers configuration directory"); } Configuration config = new Configuration(new File(configDir, "FarmingForEngineers.cfg")); config.load(); ModConfig.preInit(config); proxy.preInit(event); if (config.hasChanged()) { config.save(); } } @Mod.EventHandler public void init(FMLInitializationEvent event) { NetworkHandler.init(); NetworkRegistry.INSTANCE.registerGuiHandler(this, new GuiHandler()); new VanillaAddon(); buildSoftDependProxy(Compat.HARVESTCRAFT, "com.guigs44.farmingforengineers.compat.HarvestcraftAddon"); buildSoftDependProxy(Compat.FORESTRY, "com.guigs44.farmingforengineers.compat.ForestryAddon"); buildSoftDependProxy(Compat.AGRICRAFT, "com.guigs44.farmingforengineers.compat.AgriCraftAddon"); buildSoftDependProxy(Compat.BIOMESOPLENTY, "com.guigs44.farmingforengineers.compat.BiomesOPlentyAddon"); buildSoftDependProxy(Compat.NATURA, "com.guigs44.farmingforengineers.compat.NaturaAddon"); ModRecipes.init(); MarketRegistry.INSTANCE.load(configDir);
EntityRegistry.registerModEntity(EntityMerchant.class, "merchant", 0, this, 64, 3, true);
2
2023-10-17 00:25:50+00:00
12k
clclab/pcfg-lm
src/berkeley_parser/edu/berkeley/nlp/syntax/Trees.java
[ { "identifier": "CollectionUtils", "path": "src/berkeley_parser/edu/berkeley/nlp/util/CollectionUtils.java", "snippet": "public class CollectionUtils {\n\n\tpublic interface CollectionFactory<V> {\n\n\t\tCollection<V> newCollection();\n\n\t}\n\n\tpublic static <E extends Comparable<E>> List<E> sort(Collection<E> c) {\n\t\tList<E> list = new ArrayList<E>(c);\n\t\tCollections.sort(list);\n\t\treturn list;\n\t}\n\n\tpublic static <E> boolean isSublistOf(List<E> bigger, List<E> smaller) {\n\t\tif (smaller.size() > bigger.size())\n\t\t\treturn false;\n\t\tfor (int start = 0; start + smaller.size() <= bigger.size(); ++start) {\n\t\t\tList<E> sublist = bigger.subList(start, start + smaller.size());\n\t\t\tif (sublist.equals(bigger)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\tpublic static <E> List<E> sort(Collection<E> c, Comparator<E> r) {\n\t\tList<E> list = new ArrayList<E>(c);\n\t\tCollections.sort(list, r);\n\t\treturn list;\n\t}\n\n\tpublic static <K, V> void addToValueSet(Map<K, Set<V>> map, K key, V value) {\n\t\taddToValueSet(map, key, value, new SetFactory.HashSetFactory<V>());\n\t}\n\n\tpublic static <K, V extends Comparable<V>> void addToValueSortedSet(\n\t\t\tMap<K, SortedSet<V>> map, K key, V value) {\n\t\tSortedSet<V> values = map.get(key);\n\t\tif (values == null) {\n\t\t\tvalues = new TreeSet<V>();\n\t\t\tmap.put(key, values);\n\t\t}\n\t\tvalues.add(value);\n\t}\n\n\tpublic static <K, V> void addToValueSet(Map<K, Set<V>> map, K key, V value,\n\t\t\tSetFactory<V> mf) {\n\t\tSet<V> values = map.get(key);\n\t\tif (values == null) {\n\t\t\tvalues = mf.buildSet();\n\t\t\tmap.put(key, values);\n\t\t}\n\t\tvalues.add(value);\n\t}\n\n\tpublic static <K, V, T> Map<V, T> addToValueMap(Map<K, Map<V, T>> map,\n\t\t\tK key, V value, T value2) {\n\t\treturn addToValueMap(map, key, value, value2,\n\t\t\t\tnew MapFactory.HashMapFactory<V, T>());\n\t}\n\n\tpublic static <K, V, T> Map<V, T> addToValueMap(Map<K, Map<V, T>> map,\n\t\t\tK key, V value, T value2, MapFactory<V, T> mf) {\n\t\tMap<V, T> values = map.get(key);\n\t\tif (values == null) {\n\t\t\tvalues = mf.buildMap();\n\t\t\tmap.put(key, values);\n\t\t}\n\t\tvalues.put(value, value2);\n\t\treturn values;\n\t}\n\n\tpublic static <K, V> void addToValueList(Map<K, List<V>> map, K key, V value) {\n\t\tList<V> valueList = map.get(key);\n\t\tif (valueList == null) {\n\t\t\tvalueList = new ArrayList<V>();\n\t\t\tmap.put(key, valueList);\n\t\t}\n\t\tvalueList.add(value);\n\t}\n\n\tpublic static <K, V> void addToValueCollection(Map<K, Collection<V>> map,\n\t\t\tK key, V value, CollectionFactory<V> cf) {\n\t\tCollection<V> valueList = map.get(key);\n\t\tif (valueList == null) {\n\t\t\tvalueList = cf.newCollection();\n\t\t\tmap.put(key, valueList);\n\t\t}\n\t\tvalueList.add(value);\n\t}\n\n\tpublic static <K, V, C extends Collection<V>> void addToValueCollection(\n\t\t\tMap<K, C> map, K key, V value, Factory<C> fact) {\n\t\tC valueList = map.get(key);\n\t\tif (valueList == null) {\n\t\t\tvalueList = fact.newInstance();\n\t\t\tmap.put(key, valueList);\n\t\t}\n\t\tvalueList.add(value);\n\t}\n\n\tpublic static <K, V> List<V> getValueList(Map<K, List<V>> map, K key) {\n\t\tList<V> valueList = map.get(key);\n\t\tif (valueList == null)\n\t\t\treturn Collections.emptyList();\n\t\treturn valueList;\n\t}\n\n\tpublic static <K, V> Set<V> getValueSet(Map<K, Set<V>> map, K key) {\n\t\tSet<V> valueSet = map.get(key);\n\t\tif (valueSet == null)\n\t\t\treturn Collections.emptySet();\n\t\treturn valueSet;\n\t}\n\n\tpublic static <T> List<T> makeList(T... args) {\n\t\treturn new ArrayList<T>(Arrays.asList(args));\n\t}\n\n\tpublic static <T> Set<T> makeSet(T... args) {\n\t\treturn new HashSet<T>(Arrays.asList(args));\n\t}\n\n\tpublic static <T> void quicksort(T[] array, Comparator<? super T> c) {\n\n\t\tquicksort(array, 0, array.length - 1, c);\n\n\t}\n\n\tpublic static <T> void quicksort(T[] array, int left0, int right0,\n\t\t\tComparator<? super T> c) {\n\n\t\tint left, right;\n\t\tT pivot, temp;\n\t\tleft = left0;\n\t\tright = right0 + 1;\n\n\t\tfinal int pivotIndex = (left0 + right0) / 2;\n\t\tpivot = array[pivotIndex];\n\t\ttemp = array[left0];\n\t\tarray[left0] = pivot;\n\t\tarray[pivotIndex] = temp;\n\n\t\tdo {\n\n\t\t\tdo\n\t\t\t\tleft++;\n\t\t\twhile (left <= right0 && c.compare(array[left], pivot) < 0);\n\n\t\t\tdo\n\t\t\t\tright--;\n\t\t\twhile (c.compare(array[right], pivot) > 0);\n\n\t\t\tif (left < right) {\n\t\t\t\ttemp = array[left];\n\t\t\t\tarray[left] = array[right];\n\t\t\t\tarray[right] = temp;\n\t\t\t}\n\n\t\t} while (left <= right);\n\n\t\ttemp = array[left0];\n\t\tarray[left0] = array[right];\n\t\tarray[right] = temp;\n\n\t\tif (left0 < right)\n\t\t\tquicksort(array, left0, right, c);\n\t\tif (left < right0)\n\t\t\tquicksort(array, left, right0, c);\n\n\t}\n\n\tpublic static <S, T> Iterable<Pair<S, T>> getPairIterable(\n\t\t\tfinal Iterable<S> sIterable, final Iterable<T> tIterable) {\n\t\treturn new Iterable<Pair<S, T>>() {\n\t\t\tpublic Iterator<Pair<S, T>> iterator() {\n\t\t\t\tclass PairIterator implements Iterator<Pair<S, T>> {\n\n\t\t\t\t\tprivate Iterator<S> sIterator;\n\n\t\t\t\t\tprivate Iterator<T> tIterator;\n\n\t\t\t\t\tprivate PairIterator() {\n\t\t\t\t\t\tsIterator = sIterable.iterator();\n\t\t\t\t\t\ttIterator = tIterable.iterator();\n\t\t\t\t\t}\n\n\t\t\t\t\tpublic boolean hasNext() {\n\t\t\t\t\t\t// TODO Auto-generated method stub\n\t\t\t\t\t\treturn sIterator.hasNext() && tIterator.hasNext();\n\t\t\t\t\t}\n\n\t\t\t\t\tpublic Pair<S, T> next() {\n\t\t\t\t\t\t// TODO Auto-generated method stub\n\t\t\t\t\t\treturn Pair.newPair(sIterator.next(), tIterator.next());\n\t\t\t\t\t}\n\n\t\t\t\t\tpublic void remove() {\n\t\t\t\t\t\t// TODO Auto-generated method stub\n\t\t\t\t\t\tsIterator.remove();\n\t\t\t\t\t\ttIterator.remove();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t;\n\t\t\t\treturn new PairIterator();\n\t\t\t}\n\t\t};\n\t}\n\n\tpublic static <T> List<T> doubletonList(T t1, T t2) {\n\t\treturn new DoubletonList(t1, t2);\n\t}\n\n\tpublic static class MutableSingletonSet<E> extends AbstractSet<E> implements\n\t\t\tSerializable {\n\t\tprivate final class MutableSingletonSetIterator implements Iterator<E> {\n\t\t\tprivate boolean hasNext = true;\n\n\t\t\tpublic boolean hasNext() {\n\t\t\t\treturn hasNext;\n\t\t\t}\n\n\t\t\tpublic E next() {\n\t\t\t\tif (hasNext) {\n\t\t\t\t\thasNext = false;\n\t\t\t\t\treturn element;\n\t\t\t\t}\n\t\t\t\tthrow new NoSuchElementException();\n\t\t\t}\n\n\t\t\tpublic void remove() {\n\t\t\t\tthrow new UnsupportedOperationException();\n\t\t\t}\n\n\t\t\tpublic void reset() {\n\t\t\t\thasNext = true;\n\n\t\t\t}\n\t\t}\n\n\t\t// use serialVersionUID from JDK 1.2.2 for interoperability\n\t\tprivate static final long serialVersionUID = 3193687207550431679L;\n\n\t\tprivate E element;\n\n\t\tprivate final MutableSingletonSetIterator iter;\n\n\t\tpublic MutableSingletonSet(E o) {\n\t\t\telement = o;\n\t\t\tthis.iter = new MutableSingletonSetIterator();\n\t\t}\n\n\t\tpublic void set(E o) {\n\t\t\telement = o;\n\t\t}\n\n\t\t@Override\n\t\tpublic Iterator<E> iterator() {\n\t\t\titer.reset();\n\t\t\treturn iter;\n\t\t}\n\n\t\t@Override\n\t\tpublic int size() {\n\t\t\treturn 1;\n\t\t}\n\n\t\t@Override\n\t\tpublic boolean contains(Object o) {\n\t\t\treturn eq(o, element);\n\t\t}\n\t}\n\n\tprivate static class DoubletonList<E> extends AbstractList<E> implements\n\t\t\tRandomAccess, Serializable {\n\n\t\t/**\n\t\t * \n\t\t */\n\t\tprivate static final long serialVersionUID = -8444118491195689776L;\n\n\t\tprivate final E element1;\n\n\t\tprivate final E element2;\n\n\t\tDoubletonList(E e1, E e2) {\n\t\t\telement1 = e1;\n\t\t\telement2 = e2;\n\t\t}\n\n\t\t@Override\n\t\tpublic int size() {\n\t\t\treturn 2;\n\t\t}\n\n\t\t@Override\n\t\tpublic boolean contains(Object obj) {\n\t\t\treturn eq(obj, element1) || eq(obj, element2);\n\t\t}\n\n\t\t@Override\n\t\tpublic E get(int index) {\n\t\t\tif (index == 0)\n\t\t\t\treturn element1;\n\t\t\tif (index == 1)\n\t\t\t\treturn element2;\n\n\t\t\tthrow new IndexOutOfBoundsException(\"Index: \" + index + \", Size: 2\");\n\t\t}\n\t}\n\n\tprivate static boolean eq(Object o1, Object o2) {\n\t\treturn (o1 == null ? o2 == null : o1.equals(o2));\n\t}\n\n\tpublic static <K, V, V2> Map<V, V2> getOrCreateMap(Map<K, Map<V, V2>> map,\n\t\t\tK key) {\n\t\tMap<V, V2> r = map.get(key);\n\t\tif (r == null)\n\t\t\tmap.put(key, r = new HashMap<V, V2>());\n\t\treturn r;\n\t}\n\n\tpublic static Map getMapFromString(String s, Class keyClass,\n\t\t\tClass valueClass, MapFactory mapFactory)\n\t\t\tthrows ClassNotFoundException, NoSuchMethodException,\n\t\t\tIllegalAccessException, InvocationTargetException,\n\t\t\tInstantiationException {\n\t\tConstructor keyC = keyClass.getConstructor(new Class[] { Class\n\t\t\t\t.forName(\"java.lang.String\") });\n\t\tConstructor valueC = valueClass.getConstructor(new Class[] { Class\n\t\t\t\t.forName(\"java.lang.String\") });\n\t\tif (s.charAt(0) != '{')\n\t\t\tthrow new RuntimeException(\"\");\n\t\ts = s.substring(1); // get rid of first brace\n\t\tString[] fields = s.split(\"\\\\s+\");\n\t\tMap m = mapFactory.buildMap();\n\t\t// populate m\n\t\tfor (int i = 0; i < fields.length; i++) {\n\t\t\t// System.err.println(\"Parsing \" + fields[i]);\n\t\t\tfields[i] = fields[i].substring(0, fields[i].length() - 1); // get\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// rid\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// of\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// following\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// comma\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// or\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t// brace\n\t\t\tString[] a = fields[i].split(\"=\");\n\t\t\tObject key = keyC.newInstance(a[0]);\n\t\t\tObject value;\n\t\t\tif (a.length > 1) {\n\t\t\t\tvalue = valueC.newInstance(a[1]);\n\t\t\t} else {\n\t\t\t\tvalue = \"\";\n\t\t\t}\n\t\t\tm.put(key, value);\n\t\t}\n\t\treturn m;\n\t}\n\n\tpublic static <T> List<T> concatenateLists(List<? extends T>... lst) {\n\t\tList<T> finalList = new ArrayList<T>();\n\t\tfor (List<? extends T> ts : lst) {\n\t\t\tfinalList.addAll(ts);\n\t\t}\n\t\treturn finalList;\n\n\t}\n\n\tpublic static <T> List<T> truncateList(List<T> lst, int maxTrainDocs) {\n\t\tif (maxTrainDocs < lst.size()) {\n\t\t\treturn lst.subList(0, maxTrainDocs);\n\t\t}\n\t\treturn lst;\n\t}\n\n\t/**\n\t * Differs from Collections.shuffle by NOT being in place\n\t * \n\t * @param items\n\t * @param rand\n\t * @param <T>\n\t * @return\n\t */\n\tpublic static <T> List<T> shuffle(Collection<T> items, Random rand) {\n\t\tList<T> shuffled = new ArrayList(items);\n\t\tCollections.shuffle(shuffled, rand);\n\t\treturn shuffled;\n\t}\n\n}" }, { "identifier": "Filter", "path": "src/berkeley_parser/edu/berkeley/nlp/util/Filter.java", "snippet": "public interface Filter<T> {\n\tboolean accept(T t);\n}" }, { "identifier": "Pair", "path": "src/berkeley_parser/edu/berkeley/nlp/util/Pair.java", "snippet": "public class Pair<F, S> implements Serializable {\n\tstatic final long serialVersionUID = 42;\n\n\tF first;\n\tS second;\n\n\tpublic F getFirst() {\n\t\treturn first;\n\t}\n\n\tpublic S getSecond() {\n\t\treturn second;\n\t}\n\n\tpublic void setFirst(F pFirst) {\n\t\tfirst = pFirst;\n\t}\n\n\tpublic void setSecond(S pSecond) {\n\t\tsecond = pSecond;\n\t}\n\n\tpublic Pair<S, F> reverse() {\n\t\treturn new Pair<S, F>(second, first);\n\t}\n\n\t@Override\n\tpublic boolean equals(Object o) {\n\t\tif (this == o)\n\t\t\treturn true;\n\t\tif (!(o instanceof Pair))\n\t\t\treturn false;\n\n\t\tfinal Pair pair = (Pair) o;\n\n\t\tif (first != null ? !first.equals(pair.first) : pair.first != null)\n\t\t\treturn false;\n\t\tif (second != null ? !second.equals(pair.second) : pair.second != null)\n\t\t\treturn false;\n\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\tint result;\n\t\tresult = (first != null ? first.hashCode() : 0);\n\t\tresult = 29 * result + (second != null ? second.hashCode() : 0);\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"(\" + getFirst() + \", \" + getSecond() + \")\";\n\t}\n\n\tpublic Pair(F first, S second) {\n\t\tthis.first = first;\n\t\tthis.second = second;\n\t}\n\n\t// Compares only first values\n\tpublic static class FirstComparator<S extends Comparable<? super S>, T>\n\t\t\timplements Comparator<Pair<S, T>> {\n\t\tpublic int compare(Pair<S, T> p1, Pair<S, T> p2) {\n\t\t\treturn p1.getFirst().compareTo(p2.getFirst());\n\t\t}\n\t}\n\n\tpublic static class ReverseFirstComparator<S extends Comparable<? super S>, T>\n\t\t\timplements Comparator<Pair<S, T>> {\n\t\tpublic int compare(Pair<S, T> p1, Pair<S, T> p2) {\n\t\t\treturn p2.getFirst().compareTo(p1.getFirst());\n\t\t}\n\t}\n\n\t// Compares only second values\n\tpublic static class SecondComparator<S, T extends Comparable<? super T>>\n\t\t\timplements Comparator<Pair<S, T>> {\n\t\tpublic int compare(Pair<S, T> p1, Pair<S, T> p2) {\n\t\t\treturn p1.getSecond().compareTo(p2.getSecond());\n\t\t}\n\t}\n\n\tpublic static class ReverseSecondComparator<S, T extends Comparable<? super T>>\n\t\t\timplements Comparator<Pair<S, T>> {\n\t\tpublic int compare(Pair<S, T> p1, Pair<S, T> p2) {\n\t\t\treturn p2.getSecond().compareTo(p1.getSecond());\n\t\t}\n\t}\n\n\tpublic static <S, T> Pair<S, T> newPair(S first, T second) {\n\t\treturn new Pair<S, T>(first, second);\n\t}\n\n\t// Duplicate method to faccilitate backwards compatibility\n\t// - aria42\n\tpublic static <S, T> Pair<S, T> makePair(S first, T second) {\n\t\treturn new Pair<S, T>(first, second);\n\t}\n\n\tpublic static class LexicographicPairComparator<F, S> implements\n\t\t\tComparator<Pair<F, S>> {\n\t\tComparator<F> firstComparator;\n\t\tComparator<S> secondComparator;\n\n\t\tpublic int compare(Pair<F, S> pair1, Pair<F, S> pair2) {\n\t\t\tint firstCompare = firstComparator.compare(pair1.getFirst(),\n\t\t\t\t\tpair2.getFirst());\n\t\t\tif (firstCompare != 0)\n\t\t\t\treturn firstCompare;\n\t\t\treturn secondComparator.compare(pair1.getSecond(),\n\t\t\t\t\tpair2.getSecond());\n\t\t}\n\n\t\tpublic LexicographicPairComparator(Comparator<F> firstComparator,\n\t\t\t\tComparator<S> secondComparator) {\n\t\t\tthis.firstComparator = firstComparator;\n\t\t\tthis.secondComparator = secondComparator;\n\t\t}\n\t}\n\n\tpublic static class DefaultLexicographicPairComparator<F extends Comparable<F>, S extends Comparable<S>>\n\t\t\timplements Comparator<Pair<F, S>> {\n\n\t\tpublic int compare(Pair<F, S> o1, Pair<F, S> o2) {\n\t\t\tint firstCompare = o1.getFirst().compareTo(o2.getFirst());\n\t\t\tif (firstCompare != 0) {\n\t\t\t\treturn firstCompare;\n\t\t\t}\n\t\t\treturn o2.getSecond().compareTo(o2.getSecond());\n\t\t}\n\n\t}\n\n}" }, { "identifier": "StrUtils", "path": "src/berkeley_parser/edu/berkeley/nlp/util/StrUtils.java", "snippet": "public class StrUtils {\n\tpublic static String[] split(String s) {\n\t\t// Differs from Java's functions in that it returns String[0] on \"\"\n\t\treturn split(s, \" \");\n\t}\n\n\tpublic static String[] split(String s, String delim) {\n\t\treturn isEmpty(s) ? new String[0] : s.split(delim);\n\t}\n\n\t// delim is treated as a string, rather than a list of delimiters\n\tpublic static List<String> splitByStr(String s, String delim) {\n\t\tif (isEmpty(s))\n\t\t\treturn Collections.emptyList();\n\t\tArrayList<String> tokens = new ArrayList<String>();\n\t\tint i = 0;\n\t\twhile (i < s.length()) {\n\t\t\tint j = s.indexOf(delim, i);\n\t\t\tif (j == -1)\n\t\t\t\tbreak;\n\t\t\ttokens.add(s.substring(i, j));\n\t\t\ti = j + delim.length();\n\t\t}\n\t\ttokens.add(s.substring(i));\n\t\treturn tokens;\n\t}\n\n\t// Return the first occurrence of c that doesn't have an escape character in\n\t// front of it starting at position i\n\tpublic static int indexOfIgnoreEscaped(String s, char c) {\n\t\treturn indexOfIgnoreEscaped(s, c, 0);\n\t}\n\n\tpublic static int indexOfIgnoreEscaped(String s, char c, int i) {\n\t\treturn indexOfIgnoreEscaped(s, \"\" + c, i);\n\t}\n\n\t// Find first occurrence of some non-escaped character in cs\n\tpublic static int indexOfIgnoreEscaped(String s, String cs, int i) {\n\t\tboolean escape = false;\n\t\twhile (i < s.length()) {\n\t\t\tif (escape)\n\t\t\t\tescape = false;\n\t\t\telse {\n\t\t\t\tif (s.charAt(i) == '\\\\') // Enable escaping\n\t\t\t\t\tescape = true;\n\t\t\t\telse if (cs.indexOf(s.charAt(i)) != -1)\n\t\t\t\t\treturn i;\n\t\t\t}\n\t\t\ti++;\n\t\t}\n\t\treturn -1;\n\t}\n\n\t// Split, but mind the escaped delimiters.\n\t// Example: \"a\\ b c\" => \"a\\ b\" \"c\"\n\tpublic static List<String> splitIgnoreEscaped(String line, String delim) {\n\t\t// Split\n\t\tString[] tokens = StrUtils.split(line, delim);\n\t\t// But now, have to piece together the escaped delimiters\n\t\tList<String> newTokens = new ArrayList<String>();\n\t\tfor (int i = 0; i < tokens.length; i++) {\n\t\t\tif (tokens[i].endsWith(\"\\\\\") && i + 1 < tokens.length)\n\t\t\t\ttokens[i + 1] = tokens[i].substring(0, tokens[i].length() - 1)\n\t\t\t\t\t\t+ \"\\\\\" + delim + tokens[i + 1];\n\t\t\telse\n\t\t\t\tnewTokens.add(tokens[i]);\n\t\t}\n\t\treturn newTokens;\n\t}\n\n\tpublic static double[] doubleSplit(String s, String delim) {\n\t\tString[] tokens = split(s, delim);\n\t\tdouble[] data = new double[tokens.length];\n\t\tfor (int i = 0; i < tokens.length; i++)\n\t\t\tdata[i] = Double.parseDouble(tokens[i]);\n\t\treturn data;\n\t}\n\n\tpublic static double[] doubleSplit(String s) {\n\t\treturn doubleSplit(s, \" \");\n\t}\n\n\tpublic static int[] intSplit(String s, String delim) {\n\t\tString[] tokens = split(s, delim);\n\t\tint[] data = new int[tokens.length];\n\t\tfor (int i = 0; i < tokens.length; i++)\n\t\t\tdata[i] = Integer.parseInt(tokens[i]);\n\t\treturn data;\n\t}\n\n\tpublic static int[] intSplit(String s) {\n\t\treturn intSplit(s, \" \");\n\t}\n\n\tpublic static short[] shortSplit(String s, String delim) {\n\t\tString[] tokens = split(s, delim);\n\t\tshort[] data = new short[tokens.length];\n\t\tfor (int i = 0; i < tokens.length; i++)\n\t\t\tdata[i] = Short.parseShort(tokens[i]);\n\t\treturn data;\n\t}\n\n\tpublic static short[] shortSplit(String s) {\n\t\treturn shortSplit(s, \" \");\n\t}\n\n\tpublic static List<Integer> intSplitList(String s, String delim) {\n\t\tString[] tokens = split(s, delim);\n\t\tArrayList<Integer> data = new ArrayList<Integer>(tokens.length);\n\t\tfor (int i = 0; i < tokens.length; i++)\n\t\t\tdata.add(Integer.parseInt(tokens[i]));\n\t\treturn data;\n\t}\n\n\tpublic static List<Integer> intSplitList(String s) {\n\t\treturn intSplitList(s, \" \");\n\t}\n\n\t// Example: a=3 b=4\n\tpublic static Map<String, String> parseHashMap(String line,\n\t\t\tString keyValueDelim) {\n\t\treturn parseHashMap(line, keyValueDelim, \" \");\n\t}\n\n\tpublic static Map<String, String> parseHashMap(String line,\n\t\t\tString keyValueDelim, String entryDelim) {\n\t\treturn parseHashMap(Arrays.asList(StrUtils.split(line, entryDelim)),\n\t\t\t\tkeyValueDelim);\n\t}\n\n\tpublic static Map<String, String> parseHashMap(List<String> tokens,\n\t\t\tString keyValueDelim) {\n\t\tMap<String, String> map = new HashMap<String, String>();\n\t\tfor (String token : tokens) {\n\t\t\tString[] kv = token.split(keyValueDelim);\n\t\t\tif (kv.length != 2)\n\t\t\t\tcontinue; // Be silent?\n\t\t\tmap.put(kv[0], kv[1]);\n\t\t}\n\t\treturn map;\n\t}\n\n\t// public static TDoubleMap<String> parseTDoubleMap(String line, String\n\t// keyValueDelim) {\n\t// return parseTDoubleMap(line, keyValueDelim, \" \");\n\t// }\n\t// public static TDoubleMap<String> parseTDoubleMap(String line, String\n\t// keyValueDelim, String entryDelim) {\n\t// TDoubleMap<String> map = new TDoubleMap<String>();\n\t// String[] tokens = line.split(entryDelim);\n\t// for(String token : tokens) {\n\t// String[] kv = token.split(keyValueDelim);\n\t// if(kv.length != 2) continue; // Be silent?\n\t// map.put(kv[0], Double.parseDouble(kv[1]));\n\t// }\n\t// return map;\n\t// }\n\n\tpublic static <T> String join(double[] list) {\n\t\treturn join(list, \" \");\n\t}\n\n\tpublic static <T> String join(double[] list, String delim) {\n\t\tif (list == null)\n\t\t\treturn \"\";\n\t\tList<Double> objs = new ArrayList<Double>();\n\t\tfor (double x : list)\n\t\t\tobjs.add(x);\n\t\treturn join(objs, delim);\n\t}\n\n\tpublic static String join(int[] list) {\n\t\treturn join(list, \" \");\n\t}\n\n\tpublic static String join(int[] list, String delim) {\n\t\tif (list == null)\n\t\t\treturn \"\";\n\t\tList<Integer> objs = new ArrayList<Integer>();\n\t\tfor (int x : list)\n\t\t\tobjs.add(x);\n\t\treturn join(objs, delim);\n\t}\n\n\tpublic static String join(boolean[] list) {\n\t\treturn join(list, \" \");\n\t}\n\n\tpublic static String join(boolean[] list, String delim) {\n\t\tif (list == null)\n\t\t\treturn \"\";\n\t\tList<Boolean> objs = new ArrayList<Boolean>();\n\t\tfor (boolean x : list)\n\t\t\tobjs.add(x);\n\t\treturn join(objs, delim);\n\t}\n\n\tpublic static <T> String join(T[] objs) {\n\t\tif (objs == null)\n\t\t\treturn \"\";\n\t\treturn join(Arrays.asList(objs), \" \");\n\t}\n\n\tpublic static <T> String join(T[] objs, int start, int end) {\n\t\tif (objs == null)\n\t\t\treturn \"\";\n\t\treturn join(Arrays.asList(objs), \" \", start, end);\n\t}\n\n\tpublic static <T> String join(List<T> objs) {\n\t\treturn join(objs, \" \");\n\t}\n\n\tpublic static <T> String join(T[] objs, String delim) {\n\t\tif (objs == null)\n\t\t\treturn \"\";\n\t\treturn join(Arrays.asList(objs), delim);\n\t}\n\n\tpublic static <T> String join(List<T> objs, String delim) {\n\t\tif (objs == null)\n\t\t\treturn \"\";\n\t\treturn join(objs, delim, 0, objs.size());\n\t}\n\n\tpublic static <T> String join(List<T> objs, String delim, int start, int end) {\n\t\tif (objs == null)\n\t\t\treturn \"\";\n\t\tStringBuilder sb = new StringBuilder();\n\t\tboolean first = true;\n\t\tfor (int i = start; i < end; i++) {\n\t\t\tif (!first)\n\t\t\t\tsb.append(delim);\n\t\t\tsb.append(objs.get(i));\n\t\t\tfirst = false;\n\t\t}\n\t\treturn sb.toString();\n\t}\n\n\tpublic static <T> String join(Collection<T> objs, String delim) {\n\t\tif (objs == null)\n\t\t\treturn \"\";\n\t\tStringBuilder sb = new StringBuilder();\n\t\tboolean first = true;\n\t\tfor (T x : objs) {\n\t\t\tif (!first)\n\t\t\t\tsb.append(delim);\n\t\t\tsb.append(x);\n\t\t\tfirst = false;\n\t\t}\n\t\treturn sb.toString();\n\t}\n\n\tpublic static String join(int[] x, boolean withIndices,\n\t\t\tint magnitudeThreshold) {\n\t\tStringBuilder sb = new StringBuilder();\n\t\tfor (int i = 0; i < x.length; i++) {\n\t\t\tif (Math.abs(x[i]) < magnitudeThreshold)\n\t\t\t\tcontinue;\n\t\t\tif (i > 0)\n\t\t\t\tsb.append(' ');\n\t\t\tif (withIndices)\n\t\t\t\tsb.append(i + \":\");\n\t\t\tsb.append(x[i]);\n\t\t}\n\t\treturn sb.toString();\n\t}\n\n\tpublic static String joinWithIndices(int[] x) {\n\t\treturn join(x, true, 0);\n\t}\n\n\tpublic static String join(double[] x, boolean withIndices,\n\t\t\tdouble magnitudeThreshold) {\n\t\tStringBuilder sb = new StringBuilder();\n\t\tfor (int i = 0; i < x.length; i++) {\n\t\t\tif (Math.abs(x[i]) < magnitudeThreshold)\n\t\t\t\tcontinue;\n\t\t\tif (i > 0)\n\t\t\t\tsb.append(' ');\n\t\t\tif (withIndices)\n\t\t\t\tsb.append(i + \":\");\n\t\t\tsb.append(x[i]);\n\t\t}\n\t\treturn sb.toString();\n\t}\n\n\tpublic static String joinWithIndices(double[] x) {\n\t\treturn join(x, true, 0);\n\t}\n\n\t// Format a matrix with spaces and newlines\n\tpublic static <T> String join(T[][] data, String[] rowNames,\n\t\t\tString[] colNames) {\n\t\tint r0 = (colNames == null ? 0 : 1);\n\t\tint c0 = (rowNames == null ? 0 : 1);\n\t\tint R = data.length;\n\t\tint C = data[0].length;\n\t\tString[][] mat = new String[R + r0][C + r0];\n\t\tfor (int r = 0; r < R; r++)\n\t\t\tfor (int c = 0; c < C; c++)\n\t\t\t\tmat[r + r0][c + c0] = \"\" + data[r][c];\n\t\tif (rowNames != null)\n\t\t\tfor (int r = 0; r < R; r++)\n\t\t\t\tmat[r + r0][0] = rowNames[r];\n\t\tif (colNames != null)\n\t\t\tfor (int c = 0; c < C; c++)\n\t\t\t\tmat[0][c + c0] = colNames[c];\n\t\tint[] widths = new int[C + c0];\n\t\tfor (int c = 0; c < C + c0; c++) {\n\t\t\tfor (int r = 0; r < R + r0; r++) {\n\t\t\t\tif (mat[r][c] == null)\n\t\t\t\t\tmat[r][c] = \"\";\n\t\t\t\twidths[c] = Math.max(widths[c], mat[r][c].length());\n\t\t\t}\n\t\t}\n\t\tStringBuilder buf = new StringBuilder();\n\t\tfor (int r = 0; r < R + r0; r++) {\n\t\t\tfor (int c = 0; c < C + c0; c++) {\n\t\t\t\tString fmt = \"%-\" + (widths[c] + 1) + \"s\";\n\t\t\t\tbuf.append(String.format(fmt, mat[r][c]));\n\t\t\t}\n\t\t\tbuf.append(\"\\n\");\n\t\t}\n\t\treturn buf.toString();\n\t}\n\n\tpublic static String toString(Object o) {\n\t\treturn o == null ? null : o.toString();\n\t}\n\n\tpublic static boolean isEmpty(String s) {\n\t\treturn s == null || s.equals(\"\");\n\t}\n\n\tpublic static String repeat(String s, int n) {\n\t\tStringBuilder sb = new StringBuilder();\n\t\tfor (int i = 0; i < n; i++)\n\t\t\tsb.append(s);\n\t\treturn sb.toString();\n\t}\n\n\t// Regular expression\n\tpublic static Matcher match(String pattern, String s) {\n\t\treturn Pattern.compile(pattern).matcher(s);\n\t}\n\n\tpublic static String[] format(String fmt, Object... is) {\n\t\tint n = Array.getLength(is[0]);\n\t\tString[] out = new String[n];\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tObject[] args = new Object[is.length];\n\t\t\tfor (int j = 0; j < is.length; j++)\n\t\t\t\targs[j] = Array.get(is[j], i);\n\t\t\tout[i] = String.format(fmt, args);\n\t\t}\n\t\treturn out;\n\t}\n}" } ]
import java.io.IOException; import java.io.PushbackReader; import java.io.Reader; import java.io.StringReader; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.IdentityHashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import edu.berkeley.nlp.util.CollectionUtils; import edu.berkeley.nlp.util.Filter; import edu.berkeley.nlp.util.Pair; import edu.berkeley.nlp.util.StrUtils;
9,912
try { return parseHard(treeString, lowercase); } catch (RuntimeException e) { return null; } } /** * Reads a tree on a single line and returns null if there was a * problem. * * @param treeString */ public static Tree<String> parseEasy(String treeString) { return parseEasy(treeString, false); } private static Tree<String> parseHard(String treeString, boolean lowercase) { StringReader sr = new StringReader(treeString); PennTreeReader reader = new Trees.PennTreeReader(sr, lowercase); return reader.next(); } } /** * Renderer for pretty-printing trees according to the Penn Treebank * indenting guidelines (mutliline). Adapted from code originally written by * Dan Klein and modified by Chris Manning. */ public static class PennTreeRenderer { /** * Print the tree as done in Penn Treebank merged files. The formatting * should be exactly the same, but we don't print the trailing * whitespace found in Penn Treebank trees. The basic deviation from a * bracketed indented tree is to in general collapse the printing of * adjacent preterminals onto one line of tags and words. Additional * complexities are that conjunctions (tag CC) are not collapsed in this * way, and that the unlabeled outer brackets are collapsed onto the * same line as the next bracket down. */ public static <L> String render(Tree<L> tree) { final StringBuilder sb = new StringBuilder(); renderTree(tree, 0, false, false, false, true, sb); sb.append('\n'); return sb.toString(); } /** * Display a node, implementing Penn Treebank style layout */ private static <L> void renderTree(Tree<L> tree, int indent, boolean parentLabelNull, boolean firstSibling, boolean leftSiblingPreTerminal, boolean topLevel, StringBuilder sb) { // the condition for staying on the same line in Penn Treebank final boolean suppressIndent = (parentLabelNull || (firstSibling && tree.isPreTerminal()) || (leftSiblingPreTerminal && tree.isPreTerminal() && (tree.getLabel() == null || !tree .getLabel().toString().startsWith("CC")))); if (suppressIndent) { sb.append(' '); } else { if (!topLevel) { sb.append('\n'); } for (int i = 0; i < indent; i++) { sb.append(" "); } } if (tree.isLeaf() || tree.isPreTerminal()) { renderFlat(tree, sb); return; } sb.append('('); sb.append(tree.getLabel()); renderChildren(tree.getChildren(), indent + 1, tree.getLabel() == null || tree.getLabel().toString() == null, sb); sb.append(')'); } private static <L> void renderFlat(Tree<L> tree, StringBuilder sb) { if (tree.isLeaf()) { sb.append(tree.getLabel().toString()); return; } sb.append('('); if (tree.getLabel() == null) sb.append("<null>"); else sb.append(tree.getLabel().toString()); sb.append(' '); sb.append(tree.getChildren().get(0).getLabel().toString()); sb.append(')'); } private static <L> void renderChildren(List<Tree<L>> children, int indent, boolean parentLabelNull, StringBuilder sb) { boolean firstSibling = true; boolean leftSibIsPreTerm = true; // counts as true at beginning for (final Tree<L> child : children) { renderTree(child, indent, parentLabelNull, firstSibling, leftSibIsPreTerm, false, sb); leftSibIsPreTerm = child.isPreTerminal(); // CC is a special case if (child.getLabel() != null && child.getLabel().toString().startsWith("CC")) { leftSibIsPreTerm = false; } firstSibling = false; } } } public static void main(String[] args) { // Basic Test String parse = "((S (NP (DT the) (JJ quick) (JJ brown) (NN fox)) (VP (VBD jumped) (PP (IN over) (NP (DT the) (JJ lazy) (NN dog)))) (. .)))"; if (args.length > 0) {
package edu.berkeley.nlp.syntax; /** * Tools for displaying, reading, and modifying trees. * * @author Dan Klein */ public class Trees { public static interface TreeTransformer<E> { Tree<E> transformTree(Tree<E> tree); } public static class PunctuationStripper implements TreeTransformer<String> { public Tree<String> transformTree(Tree<String> tree) { return Trees.spliceNodes(tree, new Filter<String>() { public boolean accept(String t) { return (t.equals(".")); } }); } } public static <L> Tree<L> findNode(Tree<L> root, Filter<L> filter) { if (filter.accept(root.getLabel())) return root; for (Tree<L> node : root.getChildren()) { Tree<L> ret = findNode(node, filter); if (ret != null) return ret; } return null; } public static class FunctionNodeStripper implements TreeTransformer<String> { public Tree<String> transformTree(Tree<String> tree) { final String transformedLabel = transformLabel(tree); if (tree.isLeaf()) { return tree.shallowCloneJustRoot(); } final List<Tree<String>> transformedChildren = new ArrayList<Tree<String>>(); for (final Tree<String> child : tree.getChildren()) { transformedChildren.add(transformTree(child)); } return new Tree<String>(transformedLabel, transformedChildren); } /** * @param tree * @return */ public static String transformLabel(Tree<String> tree) { String transformedLabel = tree.getLabel(); int cutIndex = transformedLabel.indexOf('-'); int cutIndex2 = transformedLabel.indexOf('='); final int cutIndex3 = transformedLabel.indexOf('^'); if (cutIndex3 > 0 && (cutIndex3 < cutIndex2 || cutIndex2 == -1)) cutIndex2 = cutIndex3; if (cutIndex2 > 0 && (cutIndex2 < cutIndex || cutIndex <= 0)) cutIndex = cutIndex2; if (cutIndex > 0 && !tree.isLeaf()) { transformedLabel = new String(transformedLabel.substring(0, cutIndex)); } return transformedLabel; } } public static class EmptyNodeStripper implements TreeTransformer<String> { public Tree<String> transformTree(Tree<String> tree) { final String label = tree.getLabel(); if (label.equals("-NONE-")) { return null; } if (tree.isLeaf()) { return new Tree<String>(label); } final List<Tree<String>> children = tree.getChildren(); final List<Tree<String>> transformedChildren = new ArrayList<Tree<String>>(); for (final Tree<String> child : children) { final Tree<String> transformedChild = transformTree(child); if (transformedChild != null) transformedChildren.add(transformedChild); } if (transformedChildren.size() == 0) return null; return new Tree<String>(label, transformedChildren); } } public static class XOverXRemover<E> implements TreeTransformer<E> { public Tree<E> transformTree(Tree<E> tree) { final E label = tree.getLabel(); List<Tree<E>> children = tree.getChildren(); while (children.size() == 1 && !children.get(0).isLeaf() && label.equals(children.get(0).getLabel())) { children = children.get(0).getChildren(); } final List<Tree<E>> transformedChildren = new ArrayList<Tree<E>>(); for (final Tree<E> child : children) { transformedChildren.add(transformTree(child)); } return new Tree<E>(label, transformedChildren); } } public static class CoindexingStripper implements TreeTransformer<String> { public Tree<String> transformTree(Tree<String> tree) { final String transformedLabel = transformLabel(tree); if (tree.getLabel().equals("-NONE-")) { List<Tree<String>> child = new ArrayList<Tree<String>>(); child.add(new Tree<String>(transformLabel(tree.getChild(0)))); return new Tree<String>(tree.getLabel(), child); } if (tree.isLeaf()) { return tree.shallowCloneJustRoot(); } final List<Tree<String>> transformedChildren = new ArrayList<Tree<String>>(); for (final Tree<String> child : tree.getChildren()) { transformedChildren.add(transformTree(child)); } return new Tree<String>(transformedLabel, transformedChildren); } /** * @param tree * @return */ public static String transformLabel(Tree<String> tree) { String label = tree.getLabel(); if (label.equals("0")) return label; return label.replaceAll("\\d+", "XX"); } } public static class EmptyNodeRestorer implements TreeTransformer<String> { public Tree<String> transformTree(Tree<String> tree) { final String label = tree.getLabel(); if (tree.isLeaf()) { return new Tree<String>(label); } final List<Tree<String>> children = tree.getChildren(); final List<Tree<String>> transformedChildren = new LinkedList<Tree<String>>(); for (final Tree<String> child : children) { final Tree<String> transformedChild = transformTree(child); transformedChildren.add(transformedChild); } String newLabel = label.replace('_', '-').replace('+', '='); newLabel = addChildren(newLabel, transformedChildren); return new Tree<String>(newLabel, transformedChildren); } private String addChildren(String currentLabel, List<Tree<String>> children) { String newLabel = currentLabel; while (newLabel.contains("~")) { assert (newLabel.lastIndexOf(']') == newLabel.length() - 1); int bracketCount = 1; int p; for (p = newLabel.length() - 2; p >= 0 && bracketCount > 0; p--) { if (newLabel.charAt(p) == ']') { bracketCount++; } if (newLabel.charAt(p) == '[') { bracketCount--; } } assert (p > 0); assert (newLabel.charAt(p) == '~'); int q = newLabel.lastIndexOf('~', p - 1); int childIndex = Integer.parseInt(newLabel.substring(q + 1, p)); String childString = newLabel.substring(p + 2, newLabel.length() - 1); List<Tree<String>> newChildren = new LinkedList<Tree<String>>(); String childLabel = addChildren(childString, newChildren); int indexToUse = Math.min(childIndex, children.size()); if (childLabel.equals("NONE")) { childLabel = "-NONE-"; } children.add(indexToUse, new Tree<String>(childLabel, newChildren)); newLabel = newLabel.substring(0, q); } return newLabel; } } public static class EmptyNodeRelabeler implements TreeTransformer<String> { public Tree<String> transformTree(Tree<String> tree) { final String label = tree.getLabel(); if (tree.isLeaf()) { return new Tree<String>(label); } String newLabel = replaceNumbers(label); if (label.equals("-NONE-")) { String childLabel = replaceNumbers(tree.getChildren().get(0) .getLabel()); return new Tree<String>("NONE~0~[" + childLabel + "]"); } final List<Tree<String>> children = tree.getChildren(); final List<Tree<String>> transformedChildren = new ArrayList<Tree<String>>(); int index = 0; for (final Tree<String> child : children) { final Tree<String> transformedChild = transformTree(child); if (transformedChild.getLabel().contains("NONE~") && transformedChild.isLeaf()) { newLabel = newLabel + "~" + index + "~[" + transformedChild.getLabel() + "]"; } else { transformedChildren.add(transformedChild); index++; } } newLabel = newLabel.replace('-', '_').replace('=', '+'); return new Tree<String>(newLabel, transformedChildren); } private static String replaceNumbers(String label) { if (label.equals("0")) return label; return label.replaceAll("\\d+", "XX"); } } public static class CompoundTreeTransformer<T> implements TreeTransformer<T> { Collection<TreeTransformer<T>> transformers; public CompoundTreeTransformer( Collection<TreeTransformer<T>> transformers) { this.transformers = transformers; } public CompoundTreeTransformer() { this(new ArrayList<TreeTransformer<T>>()); } public void addTransformer(TreeTransformer<T> transformer) { transformers.add(transformer); } public Tree<T> transformTree(Tree<T> tree) { for (TreeTransformer<T> trans : transformers) { tree = trans.transformTree(tree); } return tree; } } public static class StandardTreeNormalizer implements TreeTransformer<String> { EmptyNodeStripper emptyNodeStripper = new EmptyNodeStripper(); XOverXRemover<String> xOverXRemover = new XOverXRemover<String>(); FunctionNodeStripper functionNodeStripper = new FunctionNodeStripper(); public Tree<String> transformTree(Tree<String> tree) { tree = functionNodeStripper.transformTree(tree); tree = emptyNodeStripper.transformTree(tree); tree = xOverXRemover.transformTree(tree); return tree; } } public static class FunctionLabelRetainingTreeNormalizer implements TreeTransformer<String> { EmptyNodeStripper emptyNodeStripper = new EmptyNodeStripper(); XOverXRemover<String> xOverXRemover = new XOverXRemover<String>(); public Tree<String> transformTree(Tree<String> tree) { tree = emptyNodeStripper.transformTree(tree); tree = xOverXRemover.transformTree(tree); return tree; } } public static class PennTreeReader implements Iterator<Tree<String>> { public static String ROOT_LABEL = "ROOT"; PushbackReader in; Tree<String> nextTree; int num = 0; int treeNum = 0; private boolean lowercase = false; private String name = ""; private String currTreeName; public boolean hasNext() { return (nextTree != null); } private static int x = 0; public Tree<String> next() { if (!hasNext()) throw new NoSuchElementException(); final Tree<String> tree = nextTree; // System.out.println(tree); nextTree = readRootTree(); return tree; } private Tree<String> readRootTree() { currTreeName = name + ":" + treeNum; try { readWhiteSpace(); if (!isLeftParen(peek())) return null; treeNum++; return readTree(true); } catch (final IOException e) { throw new RuntimeException(e); } } private Tree<String> readTree(boolean isRoot) throws IOException { readLeftParen(); String label = readLabel(); if (label.length() == 0 && isRoot) label = ROOT_LABEL; if (isRightParen(peek())) { // special case where terminal item is surround by brackets e.g. // '(1)' readRightParen(); return new Tree<String>(label); } final List<Tree<String>> children = readChildren(); readRightParen(); if (!lowercase || children.size() > 0) { return isRoot ? new NamedTree<String>(label, children, currTreeName) : new Tree<String>(label, children); } else { return isRoot ? new NamedTree<String>(label.toLowerCase() .intern(), children, currTreeName) : new Tree<String>( label.toLowerCase().intern(), children); } } private String readLabel() throws IOException { readWhiteSpace(); return readText(false); } private String readText(boolean atLeastOne) throws IOException { final StringBuilder sb = new StringBuilder(); int ch = in.read(); while (atLeastOne || (!isWhiteSpace(ch) && !isLeftParen(ch) && !isRightParen(ch) && ch != -1)) { sb.append((char) ch); ch = in.read(); atLeastOne = false; } in.unread(ch); return sb.toString().intern(); } private List<Tree<String>> readChildren() throws IOException { readWhiteSpace(); final List<Tree<String>> children = new ArrayList<Tree<String>>(); while (!isRightParen(peek()) || children.size() == 0) { readWhiteSpace(); if (isLeftParen(peek())) { if (isTextParen()) { children.add(readLeaf()); } else { children.add(readTree(false)); } } else if (peek() == 65535) { int peek = peek(); throw new RuntimeException( "Unmatched parentheses in tree input."); } else { children.add(readLeaf()); } readWhiteSpace(); } return children; } private boolean isTextParen() throws IOException { final int next = in.read(); final int postnext = in.read(); boolean isText = isLeftParen(next) && isRightParen(postnext); in.unread(postnext); in.unread(next); return isText; } private int peek() throws IOException { final int ch = in.read(); in.unread(ch); return ch; } private Tree<String> readLeaf() throws IOException { String label = readText(true); if (lowercase) label = label.toLowerCase(); return new Tree<String>(label.intern()); } private void readLeftParen() throws IOException { // System.out.println("Read left."); readWhiteSpace(); final int ch = in.read(); if (!isLeftParen(ch)) throw new RuntimeException("Format error reading tree."); } private void readRightParen() throws IOException { // System.out.println("Read right."); readWhiteSpace(); final int ch = in.read(); if (!isRightParen(ch)) throw new RuntimeException("Format error reading tree."); } private void readWhiteSpace() throws IOException { int ch = in.read(); while (isWhiteSpace(ch)) { ch = in.read(); } in.unread(ch); } private boolean isWhiteSpace(int ch) { return (ch == ' ' || ch == '\t' || ch == '\f' || ch == '\r' || ch == '\n'); } private boolean isLeftParen(int ch) { return ch == '('; } private boolean isRightParen(int ch) { return ch == ')'; } public void remove() { throw new UnsupportedOperationException(); } public PennTreeReader(Reader in) { this(in, "", false); } public PennTreeReader(Reader in, String name) { this(in, name, false); } public PennTreeReader(Reader in, String name, boolean lowercase) { this.lowercase = lowercase; this.name = name; this.in = new PushbackReader(in, 2); nextTree = readRootTree(); } public PennTreeReader(Reader in, boolean lowercase) { this(in, "", lowercase); } /** * Reads a tree on a single line and returns null if there was a * problem. * * @param lowercase */ public static Tree<String> parseEasy(String treeString, boolean lowercase) { try { return parseHard(treeString, lowercase); } catch (RuntimeException e) { return null; } } /** * Reads a tree on a single line and returns null if there was a * problem. * * @param treeString */ public static Tree<String> parseEasy(String treeString) { return parseEasy(treeString, false); } private static Tree<String> parseHard(String treeString, boolean lowercase) { StringReader sr = new StringReader(treeString); PennTreeReader reader = new Trees.PennTreeReader(sr, lowercase); return reader.next(); } } /** * Renderer for pretty-printing trees according to the Penn Treebank * indenting guidelines (mutliline). Adapted from code originally written by * Dan Klein and modified by Chris Manning. */ public static class PennTreeRenderer { /** * Print the tree as done in Penn Treebank merged files. The formatting * should be exactly the same, but we don't print the trailing * whitespace found in Penn Treebank trees. The basic deviation from a * bracketed indented tree is to in general collapse the printing of * adjacent preterminals onto one line of tags and words. Additional * complexities are that conjunctions (tag CC) are not collapsed in this * way, and that the unlabeled outer brackets are collapsed onto the * same line as the next bracket down. */ public static <L> String render(Tree<L> tree) { final StringBuilder sb = new StringBuilder(); renderTree(tree, 0, false, false, false, true, sb); sb.append('\n'); return sb.toString(); } /** * Display a node, implementing Penn Treebank style layout */ private static <L> void renderTree(Tree<L> tree, int indent, boolean parentLabelNull, boolean firstSibling, boolean leftSiblingPreTerminal, boolean topLevel, StringBuilder sb) { // the condition for staying on the same line in Penn Treebank final boolean suppressIndent = (parentLabelNull || (firstSibling && tree.isPreTerminal()) || (leftSiblingPreTerminal && tree.isPreTerminal() && (tree.getLabel() == null || !tree .getLabel().toString().startsWith("CC")))); if (suppressIndent) { sb.append(' '); } else { if (!topLevel) { sb.append('\n'); } for (int i = 0; i < indent; i++) { sb.append(" "); } } if (tree.isLeaf() || tree.isPreTerminal()) { renderFlat(tree, sb); return; } sb.append('('); sb.append(tree.getLabel()); renderChildren(tree.getChildren(), indent + 1, tree.getLabel() == null || tree.getLabel().toString() == null, sb); sb.append(')'); } private static <L> void renderFlat(Tree<L> tree, StringBuilder sb) { if (tree.isLeaf()) { sb.append(tree.getLabel().toString()); return; } sb.append('('); if (tree.getLabel() == null) sb.append("<null>"); else sb.append(tree.getLabel().toString()); sb.append(' '); sb.append(tree.getChildren().get(0).getLabel().toString()); sb.append(')'); } private static <L> void renderChildren(List<Tree<L>> children, int indent, boolean parentLabelNull, StringBuilder sb) { boolean firstSibling = true; boolean leftSibIsPreTerm = true; // counts as true at beginning for (final Tree<L> child : children) { renderTree(child, indent, parentLabelNull, firstSibling, leftSibIsPreTerm, false, sb); leftSibIsPreTerm = child.isPreTerminal(); // CC is a special case if (child.getLabel() != null && child.getLabel().toString().startsWith("CC")) { leftSibIsPreTerm = false; } firstSibling = false; } } } public static void main(String[] args) { // Basic Test String parse = "((S (NP (DT the) (JJ quick) (JJ brown) (NN fox)) (VP (VBD jumped) (PP (IN over) (NP (DT the) (JJ lazy) (NN dog)))) (. .)))"; if (args.length > 0) {
parse = StrUtils.join(args);
3
2023-10-22 13:13:22+00:00
12k
neftalito/R-Info-Plus
arbol/sentencia/primitiva/Iniciar.java
[ { "identifier": "DeclaracionProcesos", "path": "arbol/DeclaracionProcesos.java", "snippet": "public class DeclaracionProcesos extends AST {\n public ArrayList<Proceso> procesos;\n\n public ArrayList<Proceso> getProcesos() {\n return this.procesos;\n }\n\n public void setProcesos(final ArrayList<Proceso> procesos) {\n this.procesos = procesos;\n }\n\n public DeclaracionProcesos(final ArrayList<Proceso> procesos) {\n this.procesos = procesos;\n }\n\n public boolean estaProceso(final String spelling) {\n for (int i = 0; i < this.procesos.size(); ++i) {\n if (this.procesos.get(i).I.spelling.equals(spelling)) {\n return true;\n }\n }\n return false;\n }\n\n public Proceso getProceso(final String spelling) {\n final Proceso proc = null;\n for (int i = 0; i < this.procesos.size(); ++i) {\n if (this.procesos.get(i).I.spelling.equals(spelling)) {\n return this.procesos.get(i);\n }\n }\n return proc;\n }\n}" }, { "identifier": "Robot", "path": "form/Robot.java", "snippet": "public class Robot {\n private int ciclos;\n private ArrayList<Coord> misCalles;\n private DeclaracionProcesos procAST;\n private Cuerpo cueAST;\n private DeclaracionVariable varAST;\n private ImageIcon robotImage;\n private ArrayList<Coord> ruta;\n private ArrayList<ArrayList<Coord>> rutas;\n public int Av;\n public int Ca;\n private int direccion;\n private final PropertyChangeSupport pcs;\n private Ciudad city;\n private int floresEnBolsa;\n private int papelesEnBolsa;\n private int floresEnBolsaDeConfiguracion;\n private int papelesEnBolsaDeConfiguracion;\n private ArrayList<Area> areas;\n MonitorEsquinas esquinas;\n MonitorActualizarVentana esperarRefresco;\n public int id;\n private static int cant;\n public int offsetAv;\n public int offsetCa;\n public String dir;\n public MonitorMensajes monitor;\n String nombre;\n Color color;\n public String estado;\n\n public Robot(final Ciudad city, final String nombre) throws Exception {\n this.robotImage = new ImageIcon(this.getClass().getResource(\"/images/robotAbajo.png\"));\n this.ruta = new ArrayList<Coord>();\n this.rutas = new ArrayList<ArrayList<Coord>>();\n this.Av = 0;\n this.Ca = 0;\n this.direccion = 90;\n this.pcs = new PropertyChangeSupport(this);\n this.floresEnBolsa = 0;\n this.papelesEnBolsa = 0;\n this.floresEnBolsaDeConfiguracion = 0;\n this.papelesEnBolsaDeConfiguracion = 0;\n this.esquinas = MonitorEsquinas.getInstance();\n this.esperarRefresco = MonitorActualizarVentana.getInstance();\n this.offsetAv = 0;\n this.offsetCa = 0;\n this.misCalles = new ArrayList<Coord>();\n this.areas = new ArrayList<Area>();\n this.Av = 0;\n this.Ca = 0;\n this.getRuta().add(new Coord(this.Av, this.Ca));\n this.setNombre(nombre);\n this.city = city;\n this.rutas.add(this.ruta);\n this.id = this.getCity().robots.size();\n this.color = this.getColorById(this.id);\n this.setDireccion(90);\n this.setFlores(this.getFloresEnBolsaDeConfiguracion());\n this.setPapeles(this.getPapelesEnBolsaDeConfiguracion());\n this.estado = \"Nuevo \";\n }\n\n public void crear() throws UnknownHostException, IOException {\n this.dir = \"\";\n System.out.println(this.getId());\n if (this.id == 0) {\n final int puerto = 4000;\n File archivo = null;\n FileReader fr = null;\n BufferedReader br = null;\n archivo = new File(System.getProperty(\"user.dir\") + System.getProperty(\"file.separator\") + \"Conf.txt\");\n try {\n fr = new FileReader(archivo);\n } catch (FileNotFoundException ex) {\n Logger.getLogger(Mover.class.getName()).log(Level.SEVERE, null, ex);\n }\n br = new BufferedReader(fr);\n String ip = null;\n String linea;\n while ((linea = br.readLine()) != null) {\n System.out.println(linea);\n final String[] lineas = linea.split(\" \");\n final String robot = lineas[0];\n ip = lineas[1];\n System.out.println(\" el robot es : \" + robot + \" y la ip es : \" + ip);\n }\n this.dir = \"192.168.0.100\";\n this.dir = ip;\n } else {\n System.out.println(\"Entre al else\");\n this.dir = \"192.168.0.104\";\n final int puerto = 4000;\n }\n try (final Socket s = new Socket(this.dir, 4000)) {\n System.out.println(\"conectados\");\n final DataOutputStream dOut = new DataOutputStream(s.getOutputStream());\n dOut.writeByte(this.getId());\n dOut.flush();\n dOut.close();\n }\n }\n\n public int getCiclos() {\n return this.ciclos;\n }\n\n public void setCiclos(final int ciclos) {\n this.ciclos = ciclos;\n }\n\n public Color getColorById(final int id) {\n switch (id) {\n case 0: {\n return Color.RED;\n }\n case 1: {\n return new Color(0, 137, 221);\n }\n case 2: {\n return Color.PINK;\n }\n case 3: {\n return new Color(0, 153, 68);\n }\n case 4: {\n return Color.MAGENTA;\n }\n default: {\n final int max = 255;\n final int min = 1;\n final int x = (int) (Math.random() * (max - min + 1)) + min;\n final int y = (int) (Math.random() * (max - min + 1)) + min;\n final int z = (int) (Math.random() * (max - min + 1)) + min;\n return new Color(x, y, z);\n }\n }\n }\n\n public void almacenarMensaje(final String nombreDestino, final String valor) throws Exception {\n final Dato d = new Dato(valor, nombreDestino);\n final int id = this.getCity().getRobotByNombre(nombreDestino).id;\n this.monitor.llegoMensaje(id, d);\n }\n\n public void recibirMensaje(final Identificador nombreVariable, final int id, final Identificador NombreRobot)\n throws Exception {\n this.monitor.recibirMensaje(nombreVariable, id, NombreRobot);\n }\n\n public void Informar(final String msj) {\n this.getCity().Informar(msj, this.id);\n this.esperarRefresco.esperar(this.id);\n }\n\n public void bloquearEsquina(final int Av, final int Ca) {\n this.esquinas.bloquear(Av, Ca);\n this.esperarRefresco.esperar(this.id);\n this.getCity().form.jsp.refresh();\n }\n\n public void liberarEsquina(final int Av, final int Ca) {\n this.esquinas.liberar(Av, Ca);\n this.esperarRefresco.esperar(this.id);\n this.getCity().form.jsp.refresh();\n }\n\n public Cuerpo getCuerpo() {\n return this.cueAST;\n }\n\n public void agregarArea(final Area a) {\n this.areas.add(a);\n for (int i = a.getAv1(); i <= a.getAv2(); ++i) {\n for (int j = a.getCa1(); j <= a.getCa2(); ++j) {\n this.misCalles.add(new Coord(i, j));\n }\n }\n }\n\n public boolean esAreaVacia() {\n return this.areas.isEmpty();\n }\n\n public void crearMonitor(final int cant) {\n this.monitor = MonitorMensajes.crearMonitorActualizarVentana(cant, this);\n }\n\n public void setCuerpo(final Cuerpo cueAST) {\n this.cueAST = cueAST;\n }\n\n public DeclaracionVariable getVariables() {\n return this.varAST;\n }\n\n public void setVariables(final DeclaracionVariable varAST) {\n this.varAST = varAST;\n }\n\n public int getFloresEnBolsaDeConfiguracion() {\n return this.floresEnBolsaDeConfiguracion;\n }\n\n public void setFloresEnBolsaDeConfiguracion(final int floresEnBolsaDeConfiguracion) {\n this.setFlores(this.floresEnBolsaDeConfiguracion = floresEnBolsaDeConfiguracion);\n }\n\n public int getPapelesEnBolsaDeConfiguracion() {\n return this.papelesEnBolsaDeConfiguracion;\n }\n\n public void setPapelesEnBolsaDeConfiguracion(final int papelesEnBolsaDeConfiguracion) {\n this.setPapeles(this.papelesEnBolsaDeConfiguracion = papelesEnBolsaDeConfiguracion);\n }\n\n public void reset() {\n this.misCalles = new ArrayList<Coord>();\n this.ruta = new ArrayList<Coord>();\n this.rutas = new ArrayList<ArrayList<Coord>>();\n this.areas = new ArrayList<Area>();\n this.rutas.add(this.ruta);\n this.setFlores(this.getFloresEnBolsaDeConfiguracion());\n this.setPapeles(this.getPapelesEnBolsaDeConfiguracion());\n try {\n this.setAv(0);\n this.setCa(0);\n } catch (Exception ex) {\n Logger.getLogger(Robot.class.getName()).log(Level.SEVERE, null, ex);\n }\n this.setDireccion(90);\n }\n\n public Image getImage() {\n switch (this.getDireccion()) {\n case 0: {\n this.robotImage = new ImageIcon(this.getClass().getResource(\"/images/robotDerecha.png\"));\n break;\n }\n case 90: {\n this.robotImage = new ImageIcon(this.getClass().getResource(\"/images/robotArriba.png\"));\n break;\n }\n case 180: {\n this.robotImage = new ImageIcon(this.getClass().getResource(\"/images/robotIzquierda.png\"));\n break;\n }\n default: {\n this.robotImage = new ImageIcon(this.getClass().getResource(\"/images/robotAbajo.png\"));\n break;\n }\n }\n return this.robotImage.getImage();\n }\n\n public String getNombre() {\n return this.nombre;\n }\n\n public void setNombre(final String nombre) {\n this.nombre = nombre;\n }\n\n public void iniciar(final int x, final int y) throws Exception {\n this.Pos(x, y);\n this.setNewX(x);\n this.setNewY(y);\n this.setFlores(this.getFlores());\n this.setPapeles(this.getPapeles());\n this.getCity().form.jsp.refresh();\n }\n\n public void choque(final String nom, final int id, final int av, final int ca) throws Exception {\n for (final Robot r : this.getCity().robots) {\n if (r.id != id && r.Av == av && r.Ca == ca) {\n this.city.parseError(\" Se produjo un choque entre el robot \" + nom + \" y el robot \" + r.getNombre()\n + \" en la avenida \" + av + \" y la calle \" + ca);\n throw new Exception(\" Se produjo un choque entre el robot \" + nom + \" y el robot \" + r.getNombre()\n + \" en la avenida \" + av + \" y la calle \" + ca);\n }\n }\n }\n\n public void mover() throws Exception {\n int av = this.PosAv();\n int ca = this.PosCa();\n switch (this.getDireccion()) {\n case 0: {\n ++av;\n break;\n }\n case 180: {\n --av;\n break;\n }\n case 90: {\n ++ca;\n break;\n }\n case 270: {\n --ca;\n break;\n }\n }\n if (!this.puedeMover(av, ca, this.areas)) {\n this.city.parseError(\n \"No se puede ejecutar la instrucci\\u00f3n \\\"mover\\\" debido a que no corresponde a un area asignada del robot\");\n throw new Exception(\n \"No se puede ejecutar la instrucci\\u00f3n \\\"mover\\\" debido a que no corresponde a un area asignada del robot\");\n }\n if (this.getCity().isFreePos(ca, av)) {\n this.addPos(av, ca);\n this.setFlores(this.getFlores());\n this.setPapeles(this.getPapeles());\n this.choque(this.nombre, this.id, this.Av, this.Ca);\n this.esperarRefresco.esperar(this.id);\n this.getCity().form.jsp.refresh();\n return;\n }\n this.city.parseError(\"No se puede ejecutar la instrucci\\u00f3n \\\"mover\\\" debido a que hay un obst\\u00e1culo\");\n throw new Exception(\"No se puede ejecutar la instrucci\\u00f3n \\\"mover\\\" debido a que hay un obst\\u00e1culo\");\n }\n\n public boolean puedeMover(final int av, final int ca, final ArrayList<Area> areas) {\n for (final Coord c : this.misCalles) {\n if (c.getX() == av && c.getY() == ca) {\n return true;\n }\n }\n return false;\n }\n\n public int[] getXCoord() {\n final int[] x = new int[this.ruta.size()];\n for (int c = 0; c < this.ruta.size(); ++c) {\n final Coord p = this.ruta.get(c);\n x[c] = p.getX();\n }\n return x;\n }\n\n public int[] getYCoord() {\n final int[] y = new int[this.ruta.size() + 1];\n for (int c = 0; c < this.ruta.size(); ++c) {\n final Coord p = this.ruta.get(c);\n y[c] = p.getY();\n }\n return y;\n }\n\n public void addPos(final int av, final int ca) throws Exception {\n try {\n final int old = this.city.ciudad[av][ca].getFlores();\n this.setAv(av);\n this.setCa(ca);\n this.pcs.firePropertyChange(\"esquinaFlores\", old, this.city.ciudad[av][ca].getFlores());\n } catch (Exception e) {\n throw new Exception(\"Una de las nuevas coordenadas cae fuera de la ciudad.Av: \" + av + \" Ca: \" + ca\n + \" Calles: \" + this.city.getNumCa() + \" Avenidas: \" + this.city.getNumAv());\n }\n }\n\n public void setAv(final int av) throws Exception {\n if (av > this.city.getNumAv()) {\n throw new Exception();\n }\n if (av != this.PosAv()) {\n this.ruta.add(new Coord(av, this.PosCa()));\n if (av > this.PosAv()) {\n this.setDireccion(0);\n } else {\n this.setDireccion(180);\n }\n }\n this.setNewX(av);\n this.setNewY(this.Ca);\n }\n\n public void setNewX(final int av) {\n final int old = this.PosAv();\n this.Av = av;\n this.pcs.firePropertyChange(\"av\", old, av);\n }\n\n public void setNewY(final int ca) {\n final int old = this.PosCa();\n this.Ca = ca;\n this.pcs.firePropertyChange(\"ca\", old, ca);\n }\n\n public void setCa(final int ca) throws Exception {\n if (ca > this.city.getNumCa()) {\n throw new Exception();\n }\n if (ca != this.PosCa()) {\n this.ruta.add(new Coord(this.PosAv(), ca));\n if (ca < this.PosCa()) {\n this.setDireccion(270);\n } else {\n this.setDireccion(90);\n }\n }\n this.setNewY(ca);\n this.setNewX(this.Av);\n }\n\n public void setDireccion(final int direccion) {\n final int old = this.direccion;\n this.direccion = direccion;\n this.pcs.firePropertyChange(\"direccion\", old, direccion);\n }\n\n public void setEstado(final String str) {\n final String s = this.getEstado();\n this.estado = str;\n this.pcs.firePropertyChange(\"estado\", s, str);\n }\n\n public String getEstado() {\n return this.estado;\n }\n\n public int getDireccion() {\n return this.direccion;\n }\n\n public void addPropertyChangeListener(final PropertyChangeListener listener) {\n this.pcs.addPropertyChangeListener(listener);\n }\n\n public void removePropertyChangeListener(final PropertyChangeListener listener) {\n this.pcs.removePropertyChangeListener(listener);\n }\n\n public void mirarEnDireccion(final int direccion) throws Exception {\n int c;\n for (c = 0; c < 5 && this.getDireccion() != direccion; ++c) {\n this.derecha();\n }\n if (c == 5) {\n throw new Exception(\"La direcci\\u00f3n especificada no corresponde.\");\n }\n }\n\n public void izquierda() {\n switch (this.getDireccion()) {\n case 0: {\n this.setDireccion(90);\n break;\n }\n case 270: {\n this.setDireccion(0);\n break;\n }\n case 180: {\n this.setDireccion(270);\n break;\n }\n case 90: {\n this.setDireccion(180);\n break;\n }\n }\n this.esperarRefresco.esperar(this.id);\n this.getCity().form.jsp.refresh();\n }\n\n public void derecha() {\n switch (this.getDireccion()) {\n case 0: {\n this.setDireccion(270);\n break;\n }\n case 270: {\n this.setDireccion(180);\n break;\n }\n case 180: {\n this.setDireccion(90);\n break;\n }\n case 90: {\n this.setDireccion(0);\n break;\n }\n }\n this.esperarRefresco.esperar(this.id);\n this.getCity().form.jsp.refresh();\n }\n\n public int PosCa() {\n return this.Ca;\n }\n\n public int PosAv() {\n return this.Av;\n }\n\n public void Pos(final int Av, final int Ca) throws Exception {\n if (!this.puedeMover(Av, Ca, this.areas)) {\n this.city.parseError(\n \"No se puede ejecutar la instrucci\\u00f3n \\\"Pos\\\" debido a que no corresponde a un area asignada del robot\");\n throw new Exception(\n \"No se puede ejecutar la instrucci\\u00f3n \\\"Pos\\\" debido a que no corresponde a un area asignada del robot\");\n }\n if (this.getCity().isFreePos(Ca, Av)) {\n this.getRutas().add(this.getRuta());\n this.setRuta(new ArrayList<Coord>());\n this.getRuta().add(new Coord(Av, Ca));\n this.setNewX(Av);\n this.setNewY(Ca);\n this.choque(this.nombre, this.id, Av, Ca);\n this.esperarRefresco.esperar(this.id);\n this.getCity().form.jsp.refresh();\n return;\n }\n this.city.parseError(\"No se puede ejecutar la instrucci\\u00f3n \\\"Pos\\\" debido a que hay un obst\\u00e1culo\");\n throw new Exception(\"No se puede ejecutar la instrucci\\u00f3n \\\"Pos\\\" debido a que hay un obst\\u00e1culo\");\n }\n\n public ArrayList<Coord> getRuta() {\n return this.ruta;\n }\n\n public Ciudad getCity() {\n return this.city;\n }\n\n public void tomarFlor() throws Exception {\n if (this.getCity().levantarFlor(this.PosAv(), this.PosCa())) {\n this.setFlores(this.getFlores() + 1);\n this.esperarRefresco.esperar(this.id);\n return;\n }\n this.setFlores(this.getFlores());\n throw new Exception(\n \"No se puede ejecutar la instrucci\\u00f3n \\\"tomarFlor\\\" debido a que no hay ninguna flor en la esquina\");\n }\n\n public int getFlores() {\n return this.floresEnBolsa;\n }\n\n public void setFlores(final int flores) {\n final int old = this.getFlores();\n this.floresEnBolsa = flores;\n this.pcs.firePropertyChange(\"flores\", old, flores);\n }\n\n public void tomarPapel() throws Exception {\n if (this.getCity().levantarPapel(this.PosAv(), this.PosCa())) {\n this.setPapeles(this.getPapeles() + 1);\n this.esperarRefresco.esperar(this.id);\n return;\n }\n this.setPapeles(this.getPapeles());\n throw new Exception(\n \"No se puede ejecutar la instrucci\\u00f3n \\\"tomarPapel\\\" debido a que no hay ningun papel en la esquina\");\n }\n\n public boolean HayPapelEnLaBolsa() {\n return this.getPapeles() > 0;\n }\n\n public boolean HayFlorEnLaBolsa() {\n return this.getFlores() > 0;\n }\n\n public int getPapeles() {\n return this.papelesEnBolsa;\n }\n\n public void setColor(final Color col) {\n final Color old = this.color;\n this.color = col;\n this.pcs.firePropertyChange(\"color\", old, col);\n }\n\n public Color getColor() {\n return this.color;\n }\n\n public void setPapeles(final int papeles) {\n final int old = this.getPapeles();\n this.papelesEnBolsa = papeles;\n this.pcs.firePropertyChange(\"papeles\", old, papeles);\n }\n\n public void depositarPapel() throws Exception {\n if (this.getPapeles() > 0) {\n this.setPapeles(this.getPapeles() - 1);\n this.getCity().dejarPapel(this.PosAv(), this.PosCa());\n this.esperarRefresco.esperar(this.id);\n return;\n }\n this.city.parseError(\n \"No se puede ejecutar la instrucci\\u00f3n \\\"depositarPapel\\\" debido a que no hay ningun papel en la bolsa\");\n throw new Exception(\n \"No se puede ejecutar la instrucci\\u00f3n \\\"depositarPapel\\\" debido a que no hay ningun papel en la bolsa\");\n }\n\n public void depositarFlor() throws Exception {\n if (this.getFlores() > 0) {\n this.setFlores(this.getFlores() - 1);\n this.getCity().dejarFlor(this.PosAv(), this.PosCa());\n this.esperarRefresco.esperar(this.id);\n return;\n }\n this.city.parseError(\n \"No se puede ejecutar la instrucci\\u00f3n \\\"depositarFlor\\\" debido a que no hay ninguna en la bolsa de flores\");\n throw new Exception(\n \"No se puede ejecutar la instrucci\\u00f3n \\\"depositarFlor\\\" debido a que no hay ninguna en la bolsa de flores\");\n }\n\n public ArrayList<ArrayList<Coord>> getRutas() {\n return this.rutas;\n }\n\n public void setRuta(final ArrayList<Coord> ruta) {\n this.ruta = ruta;\n }\n\n public void setRutas(final ArrayList<ArrayList<Coord>> rutas) {\n this.rutas = rutas;\n }\n\n public DeclaracionProcesos getProcAST() {\n return this.procAST;\n }\n\n public void setProcAST(final DeclaracionProcesos procAST) throws CloneNotSupportedException {\n synchronized (this) {\n final ArrayList<Proceso> ps = new ArrayList<Proceso>();\n for (final Proceso j : procAST.getProcesos()) {\n final DeclaracionVariable ddvv = j.getDV();\n final Identificador I = new Identificador(j.getI().toString());\n final ArrayList<ParametroFormal> pfs = new ArrayList<ParametroFormal>();\n for (final ParametroFormal pformal : j.getPF()) {\n final Identificador In = new Identificador(pformal.getI().toString());\n final ParametroFormal pf = new ParametroFormal(In, pformal.getT(), pformal.getTA());\n pfs.add(pf);\n }\n final ArrayList<Sentencia> ss = new ArrayList<Sentencia>();\n for (final Sentencia sen : j.getC().getS()) {\n System.out.println(\"Sentencia : \" + sen.toString());\n final Sentencia s = (Sentencia) sen.clone();\n ss.add(s);\n }\n final ArrayList<Variable> dvs = new ArrayList<Variable>();\n for (final Variable v : ddvv.variables) {\n final Variable V = (Variable) v.clone();\n dvs.add(V);\n }\n final DeclaracionVariable ddvs = new DeclaracionVariable(dvs);\n final Cuerpo cue = new Cuerpo(ss, ddvs);\n final Proceso p = new Proceso(I, pfs, procAST, ddvs, cue);\n ps.add(p);\n }\n final DeclaracionProcesos dp = new DeclaracionProcesos(ps);\n this.procAST = dp;\n }\n }\n\n public DeclaracionVariable getVarAST() {\n return this.varAST;\n }\n\n public void setVarAST(final DeclaracionVariable varAST) {\n this.varAST = varAST;\n }\n\n public int getId() {\n return this.id;\n }\n\n public void setId(final int id) {\n this.id = id;\n }\n\n static {\n Robot.cant = 0;\n }\n}" }, { "identifier": "EjecucionRobot", "path": "form/EjecucionRobot.java", "snippet": "public class EjecucionRobot implements Runnable, PropertyChangeListener {\n Robot prgAST;\n MonitorActualizarVentana esperarRefresco;\n boolean pasoAPaso;\n CodePanel codigo;\n private final PropertyChangeSupport pcs;\n\n public EjecucionRobot(final Robot prg, final boolean paso_a_paso, final CodePanel code) {\n this.esperarRefresco = MonitorActualizarVentana.getInstance();\n this.pasoAPaso = false;\n this.pcs = new PropertyChangeSupport(this);\n this.pasoAPaso = paso_a_paso;\n this.prgAST = prg;\n this.codigo = code;\n }\n\n @Override\n public void run() {\n try {\n System.out.println(\"ejecutando robot: \" + this.prgAST.getNombre());\n this.prgAST.setEstado(\"ejecutandose\");\n this.prgAST.getCuerpo().ejecutar();\n if (this.esperarRefresco.termine_ejecucion()) {\n this.esperarRefresco.setEn_ejecucion(false);\n this.esperarRefresco.setApretoF7(false);\n this.esperarRefresco.setTimerOn(false);\n this.codigo.habilitarTodo();\n this.prgAST.getCity().Informar(\"Programa finalizado\", 0);\n } else {\n System.out.println(\"No soy el ultimo, pero termine :\" + this.prgAST.getNombre());\n }\n this.prgAST.setEstado(\"finalizado\");\n System.out.println(\"nombre de robot : \" + this.prgAST.getNombre() + \" termino \");\n } catch (Exception e) {\n System.out.println(e);\n this.prgAST.setEstado(\"error\");\n try {\n this.codigo.doStopError();\n this.prgAST.setEstado(\"error\");\n } catch (Exception ex) {\n this.prgAST.setEstado(\"error\");\n System.out.println(ex);\n Logger.getLogger(Ejecucion.class.getName()).log(Level.SEVERE, null, ex);\n }\n this.codigo.habilitarTodo();\n }\n }\n\n public void dormir() {\n this.esperarRefresco.dormir();\n }\n\n public void arrancar() {\n this.esperarRefresco.arrancar();\n }\n\n @Override\n public void propertyChange(final PropertyChangeEvent evt) {\n System.out.println(\"propertyChange event\");\n }\n}" }, { "identifier": "Cuerpo", "path": "arbol/Cuerpo.java", "snippet": "public class Cuerpo extends AST {\n private ArrayList<Sentencia> S;\n DeclaracionVariable varAST;\n Robot rob;\n\n public Cuerpo(final ArrayList<Sentencia> S, final DeclaracionVariable varAST) {\n this.setS(S);\n this.varAST = varAST;\n }\n\n public void ejecutar() throws Exception {\n for (final Sentencia single : this.S) {\n single.setDV(this.varAST);\n single.ejecutar();\n }\n }\n\n public Robot getRobot() {\n return this.rob;\n }\n\n public void setRobot(final Robot rob) {\n this.rob = rob;\n for (final Sentencia single : this.S) {\n single.setRobot(this.rob);\n }\n }\n\n public ArrayList<Sentencia> getS() {\n return this.S;\n }\n\n public void setS(final ArrayList<Sentencia> S) {\n this.S = S;\n }\n\n @Override\n public void setPrograma(final Programa P) {\n this.programa = P;\n for (final Sentencia single : this.S) {\n single.setPrograma(P);\n }\n }\n\n public void setDV(final DeclaracionVariable DV) {\n for (final Sentencia single : this.S) {\n single.setDV(DV);\n }\n }\n}" }, { "identifier": "Variable", "path": "arbol/Variable.java", "snippet": "public class Variable extends Expresion {\n private String value;\n private boolean editable;\n Robot rob;\n RobotAST r;\n private String nombreTipoRobot;\n DeclaracionRobots dr;\n\n public Variable(final Identificador I, final Tipo T, final DeclaracionVariable var, final DeclaracionRobots robAST,\n final String nombreTipoRobot) throws Exception {\n synchronized (this) {\n this.dr = robAST;\n this.DV = var;\n this.setI(I);\n this.value = \"Undefined\";\n if (T == null) {\n if (var.EstaVariable(I.toString())) {\n final Variable tmp = var.findByName(I.toString());\n this.setT(tmp.getT());\n if (this.getT().tipo == 19) {\n this.value = \"0\";\n }\n if (this.getT().tipo == 20) {\n this.value = \"F\";\n }\n }\n } else {\n this.setT(T);\n if (this.getT().tipo == 19) {\n this.value = \"0\";\n }\n if (this.getT().tipo == 20) {\n this.value = \"F\";\n }\n if (this.getT().tipo == 66) {\n this.r = robAST.getRobot(nombreTipoRobot);\n }\n }\n }\n }\n\n public RobotAST getR() {\n return this.r;\n }\n\n @Override\n public String getValue(final DeclaracionVariable var) throws Exception {\n String res = \"undefineD\";\n if (var.EstaParametro(this.I.toString())) {\n final Variable tmp = var.findByName(this.I.toString());\n res = tmp.getValor();\n return res;\n }\n this.reportError(\"Variable \" + this.getI().toString() + \" no declarada\");\n throw new Exception(\"Variable \" + this.getI().toString() + \" no declarada\");\n }\n\n public String getValor() {\n return this.value;\n }\n\n public void setValue(final String str) {\n this.value = str;\n }\n\n public boolean esEditable() {\n return this.editable;\n }\n\n public void setEditable(final boolean bool) {\n this.editable = bool;\n }\n\n @Override\n public void reportError(final String str) {\n JOptionPane.showMessageDialog(null, str, \"ERROR\", 0);\n }\n\n public boolean isCompatible(final Variable tmp) {\n switch (tmp.getT().getTipo()) {\n case 19:\n case 23: {\n return this.getT().getTipo() == 23 || this.getT().getTipo() == 19;\n }\n case 20:\n case 32:\n case 33: {\n return this.getT().getTipo() == 20 || this.getT().getTipo() == 32 || this.getT().getTipo() == 33;\n }\n default: {\n return false;\n }\n }\n }\n\n public void setTipoRobot(final String nombreTipoRobot) {\n this.nombreTipoRobot = nombreTipoRobot;\n }\n\n public String getTipoRobot() {\n return this.nombreTipoRobot;\n }\n\n @Override\n public Object clone() {\n synchronized (this) {\n Variable obj = null;\n try {\n obj = new Variable(this.I, this.T, this.DV, this.dr, null);\n obj.setValue(this.getValor());\n } catch (Exception ex) {\n System.out.println(\"error en el clone de Variable!\");\n Logger.getLogger(Variable.class.getName()).log(Level.SEVERE, null, ex);\n }\n return obj;\n }\n }\n}" }, { "identifier": "Sentencia", "path": "arbol/sentencia/Sentencia.java", "snippet": "public abstract class Sentencia extends AST {\n DeclaracionVariable varAST;\n Robot r;\n\n public Robot getRobot() {\n return this.r;\n }\n\n public void setRobot(final Robot r) {\n this.r = r;\n }\n\n public void ejecutar() throws Exception {\n }\n\n public void setDV(final DeclaracionVariable varAST) {\n this.varAST = varAST;\n }\n\n public DeclaracionVariable getDV() {\n return this.varAST;\n }\n\n @Override\n public void setPrograma(final Programa P) {\n this.programa = P;\n }\n\n @Override\n public Programa getPrograma() {\n return this.programa;\n }\n}" }, { "identifier": "DeclaracionVariable", "path": "arbol/DeclaracionVariable.java", "snippet": "public class DeclaracionVariable extends AST {\n public ArrayList<Variable> variables;\n\n public DeclaracionVariable(final ArrayList<Variable> var) {\n this.variables = var;\n }\n\n public void imprimir() {\n for (final Variable variable : this.variables) {\n System.out.println(variable.getI().toString());\n }\n }\n\n public boolean EstaParametro(final String act) throws Exception {\n int i;\n for (i = 0; i < this.variables.size(); ++i) {\n if (this.variables.get(i).getI().equals(act)) {\n return true;\n }\n }\n if (i == this.variables.size()) {\n this.reportError(\"Variable '\" + act + \"' no declarada.\");\n throw new Exception(\"Variable '\" + act + \"' no declarada.\");\n }\n return false;\n }\n\n public boolean EstaVariable(final String act) throws Exception {\n for (int i = 0; i < this.variables.size(); ++i) {\n if (this.variables.get(i).getI().equals(act)) {\n return true;\n }\n }\n return false;\n }\n\n @Override\n public void reportError(final String str) {\n JOptionPane.showMessageDialog(null, str, \"ERROR\", 0);\n }\n\n public Variable findByName(final String act) throws Exception {\n for (int i = 0; i < this.variables.size(); ++i) {\n if (this.variables.get(i).getI().toString().equals(act)) {\n return this.variables.get(i);\n }\n }\n this.reportError(\"Variable '\" + act + \"' no declarada.\");\n throw new Exception(\"Variable '\" + act + \"' no declarada.\");\n }\n}" }, { "identifier": "DeclaracionRobots", "path": "arbol/DeclaracionRobots.java", "snippet": "public class DeclaracionRobots {\n public ArrayList<RobotAST> robots;\n\n public DeclaracionRobots(final ArrayList<RobotAST> robots) {\n this.robots = robots;\n }\n\n public ArrayList<RobotAST> getRobots() {\n return this.robots;\n }\n\n public void setRobots(final ArrayList<RobotAST> robots) {\n this.robots = robots;\n }\n\n public boolean estaRobot(final String spelling) {\n for (int i = 0; i < this.robots.size(); ++i) {\n if (this.robots.get(i).getNombre().equals(spelling)) {\n return true;\n }\n }\n return false;\n }\n\n public RobotAST getRobot(final String spelling) {\n final RobotAST proc = null;\n for (int i = 0; i < this.robots.size(); ++i) {\n if (this.robots.get(i).getNombre().equals(spelling)) {\n return this.robots.get(i);\n }\n }\n System.out.println(\"No devolvi nada en el getRobot del Declaracion Robots\");\n return proc;\n }\n}" }, { "identifier": "Identificador", "path": "arbol/Identificador.java", "snippet": "public class Identificador extends AST {\n String spelling;\n\n public Identificador(final String spelling) {\n this.spelling = spelling;\n }\n\n public boolean equals(final String str) {\n return this.spelling.equals(str);\n }\n\n @Override\n public String toString() {\n return this.spelling;\n }\n}" }, { "identifier": "RobotAST", "path": "arbol/RobotAST.java", "snippet": "public class RobotAST extends AST {\n private Cuerpo cuerpo;\n private DeclaracionVariable DV;\n private String nombre;\n private DeclaracionProcesos procAST;\n\n public RobotAST(final Cuerpo c, final DeclaracionVariable dv, final String nom, final DeclaracionProcesos procAST) {\n this.cuerpo = c;\n this.DV = dv;\n this.nombre = nom;\n this.procAST = procAST;\n }\n\n public DeclaracionVariable getDV() {\n return this.DV;\n }\n\n public void setDV(final DeclaracionVariable DV) {\n this.DV = DV;\n }\n\n public Cuerpo getCuerpo() {\n return this.cuerpo;\n }\n\n public void setCuerpo(final Cuerpo cuerpo) {\n this.cuerpo = cuerpo;\n }\n\n public String getNombre() {\n return this.nombre;\n }\n\n public void setNombre(final String nombre) {\n this.nombre = nombre;\n }\n\n public DeclaracionProcesos getProcAST() {\n return this.procAST;\n }\n\n public void setProcAST(final DeclaracionProcesos procAST) {\n this.procAST = procAST;\n }\n}" } ]
import arbol.DeclaracionProcesos; import form.Robot; import form.EjecucionRobot; import arbol.Cuerpo; import arbol.Variable; import arbol.sentencia.Sentencia; import java.util.ArrayList; import arbol.DeclaracionVariable; import arbol.DeclaracionRobots; import arbol.Identificador; import arbol.RobotAST;
9,866
package arbol.sentencia.primitiva; public class Iniciar extends Primitiva { RobotAST r; int x; int y; Identificador Ident;
package arbol.sentencia.primitiva; public class Iniciar extends Primitiva { RobotAST r; int x; int y; Identificador Ident;
DeclaracionRobots robAST;
7
2023-10-20 15:45:37+00:00
12k
hmcts/opal-fines-service
src/main/java/uk/gov/hmcts/opal/service/DefendantAccountService.java
[ { "identifier": "AccountDetailsDto", "path": "src/main/java/uk/gov/hmcts/opal/dto/AccountDetailsDto.java", "snippet": "@Data\n@Builder\n@NoArgsConstructor\n@AllArgsConstructor\npublic class AccountDetailsDto implements ToJsonString {\n\n //defendant_accounts.account_number\n private String accountNumber;\n\n // parties.surname, parties,initials, parties.forenames, parties.title\n private String fullName;\n\n // business_units.business_unit_type\n private String accountCT;\n\n //parties.account_type\n private String accountType;\n\n //parties.address_line_(*)\n private String address;\n\n //parties.postcode\n private String postCode;\n\n //parties.birth_date\n private LocalDate dob;\n\n //defendant_accounts.last_changed_date\n private LocalDate detailsChanged;\n\n //defendant_accounts.last_hearing_date + defendant_accounts.last_hearing_court_id\n private String lastCourtAppAndCourtCode;\n\n //defendant_accounts.last_movement_date\n private LocalDate lastMovement;\n\n //notes.note_text\n private List<String> commentField;\n\n //defendant_accounts.prosecutor_case_reference\n private String pcr;\n\n //payment_terms.installment_amount / payment_terms.installment_period\n private String paymentDetails;\n\n //payment_terms.instalment_lump_sum\n private BigDecimal lumpSum;\n\n //payment_terms.effective_date\n private LocalDate commencing;\n\n //payment_terms.jail_days\n private int daysInDefault;\n\n //defendant_accounts.last_enforcement\n private String lastEnforcement;\n\n //defendant_accounts.enf_override_result_id\n private String override;\n\n //defendant_accounts.enf_override_enforcer_id\n private Short enforcer;\n\n //defendant_accounts.enforcing_court_id\n private int enforcementCourt;\n\n //defendant_accounts.amount_imposed\n private BigDecimal imposed;\n\n //defendant_accounts.amount_paid\n private BigDecimal amountPaid;\n\n //defendant_accounts.account_balance\n private BigDecimal arrears;\n\n //defendant_accounts.account_balance\n private BigDecimal balance;\n}" }, { "identifier": "AccountEnquiryDto", "path": "src/main/java/uk/gov/hmcts/opal/dto/AccountEnquiryDto.java", "snippet": "@Builder\n@Data\npublic class AccountEnquiryDto implements ToJsonString {\n\n @JsonProperty(\"businessUnitId\")\n private Short businessUnitId;\n @JsonProperty(\"accountNumber\")\n private String accountNumber;\n}" }, { "identifier": "AccountSearchDto", "path": "src/main/java/uk/gov/hmcts/opal/dto/AccountSearchDto.java", "snippet": "@Data\n@Builder\npublic class AccountSearchDto implements ToJsonString {\n /** The court (CT) or MET (metropolitan area). */\n private String court;\n /** Defendant Surname, Company Name or A/C number. */\n private String surname;\n /** Can be either Defendant, Minor Creditor or Company. */\n private String searchType;\n /** Defendant Forenames. */\n private String forename;\n /** Defendant Initials. */\n private String initials;\n /** Defendant Date of Birth. */\n private DateDto dateOfBirth;\n /** Defendant Address, typically just first line. */\n private String addressLineOne;\n /** National Insurance Number. */\n private String niNumber;\n /** Prosecutor Case Reference. */\n private String pcr;\n /** Major Creditor account selection. */\n private String majorCreditor;\n /** Unsure. */\n private String tillNumber;\n}" }, { "identifier": "AccountSearchResultsDto", "path": "src/main/java/uk/gov/hmcts/opal/dto/AccountSearchResultsDto.java", "snippet": "@Builder\n@Getter\n@NoArgsConstructor\n@AllArgsConstructor\n@EqualsAndHashCode\npublic class AccountSearchResultsDto implements ToJsonString {\n\n /** The number of AccountSummary objects returned within this response. */\n private Integer count;\n /** The total number of matching Accounts found in the database. */\n private Long totalCount;\n /** The position of the first AccountSummary in this response within the total search of the database. */\n private Integer cursor;\n /** The maximum number of AccountSummary objects that can be returned in a single search response. */\n private final Integer pageSize = 100;\n /** A list of AccountSummary objects, limited to a maximum of pageSize. */\n private List<AccountSummaryDto> searchResults;\n\n public static class AccountSearchResultsDtoBuilder {\n public AccountSearchResultsDtoBuilder searchResults(List<AccountSummaryDto> searchResults) {\n this.searchResults = searchResults;\n this.count(Optional.ofNullable(searchResults).map(List::size).orElse(0));\n return this;\n }\n\n private AccountSearchResultsDtoBuilder count(Integer count) {\n this.count = count;\n return this;\n }\n }\n}" }, { "identifier": "AccountSummaryDto", "path": "src/main/java/uk/gov/hmcts/opal/dto/AccountSummaryDto.java", "snippet": "@Data\n@NoArgsConstructor\n@AllArgsConstructor\n@Builder\npublic class AccountSummaryDto implements ToJsonString {\n /** The primary key to the entity in the database. */\n private Long defendantAccountId;\n /** The defendant account number. */\n private String accountNo;\n /** The name of the defendant, being an aggregation of surname, firstnames and title. */\n private String name;\n /** The date of birth of the defendant. */\n private LocalDate dateOfBirth;\n /** First line of the defendant's address. */\n private String addressLine1;\n /** The balance on the defendant account. */\n private BigDecimal balance;\n /** The Court (traditionally abbreviated to CT) 'Accounting Division' or 'Metropolitan Area' (MET). */\n private String court;\n}" }, { "identifier": "DefendantAccountEntity", "path": "src/main/java/uk/gov/hmcts/opal/entity/DefendantAccountEntity.java", "snippet": "@Entity\n@Data\n@Table(name = \"defendant_accounts\")\npublic class DefendantAccountEntity {\n\n @Id\n @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = \"defendant_account_id_seq\")\n @SequenceGenerator(name = \"defendant_account_id_seq\", sequenceName = \"defendant_account_id_seq\", allocationSize = 1)\n @Column(name = \"defendant_account_id\")\n private Long defendantAccountId;\n\n @ManyToOne\n @JoinColumn(name = \"business_unit_id\", referencedColumnName = \"business_unit_id\", nullable = false)\n private BusinessUnitsEntity businessUnitId;\n\n @Column(name = \"account_number\", length = 20)\n private String accountNumber;\n\n @Column(name = \"imposed_hearing_date\")\n @Temporal(TemporalType.DATE)\n private LocalDate imposedHearingDate;\n\n @Column(name = \"imposing_court_id\")\n private Long imposingCourtId;\n\n @Column(name = \"amount_imposed\", precision = 18, scale = 2)\n private BigDecimal amountImposed;\n\n @Column(name = \"amount_paid\", precision = 18, scale = 2)\n private BigDecimal amountPaid;\n\n @Column(name = \"account_balance\", precision = 18, scale = 2)\n private BigDecimal accountBalance;\n\n @Column(name = \"account_status\", length = 2)\n private String accountStatus;\n\n @Column(name = \"completed_date\")\n @Temporal(TemporalType.DATE)\n private LocalDate completedDate;\n\n @ManyToOne\n @JoinColumn(name = \"enforcing_court_id\", referencedColumnName = \"court_id\", nullable = false)\n private CourtsEntity enforcingCourtId;\n\n @ManyToOne\n @JoinColumn(name = \"last_hearing_court_id\", referencedColumnName = \"court_id\", nullable = false)\n private CourtsEntity lastHearingCourtId;\n\n @Column(name = \"last_hearing_date\")\n @Temporal(TemporalType.DATE)\n private LocalDate lastHearingDate;\n\n @Column(name = \"last_movement_date\")\n @Temporal(TemporalType.DATE)\n private LocalDate lastMovementDate;\n\n @Column(name = \"last_enforcement\", length = 6)\n private String lastEnforcement;\n\n @Column(name = \"last_changed_date\")\n @Temporal(TemporalType.DATE)\n private LocalDate lastChangedDate;\n\n @Column(name = \"originator_name\", length = 100)\n private String originatorName;\n\n @Column(name = \"originator_reference\", length = 40)\n private String originatorReference;\n\n @Column(name = \"originator_type\", length = 10)\n private String originatorType;\n\n @Column(name = \"allow_writeoffs\")\n private boolean allowWriteoffs;\n\n @Column(name = \"allow_cheques\")\n private boolean allowCheques;\n\n @Column(name = \"cheque_clearance_period\")\n private Short chequeClearancePeriod;\n\n @Column(name = \"credit_trans_clearance_period\")\n private Short creditTransferClearancePeriod;\n\n @Column(name = \"enf_override_result_id\", length = 10)\n private String enforcementOverrideResultId;\n\n @Column(name = \"enf_override_enforcer_id\")\n private Long enforcementOverrideEnforcerId;\n\n @Column(name = \"enf_override_tfo_lja_id\")\n private Short enforcementOverrideTfoLjaId;\n\n @Column(name = \"unit_fine_detail\", length = 100)\n private String unitFineDetail;\n\n @Column(name = \"unit_fine_value\", precision = 18, scale = 2)\n private BigDecimal unitFineValue;\n\n @Column(name = \"collection_order\")\n private boolean collectionOrder;\n\n @Column(name = \"collection_order_date\")\n @Temporal(TemporalType.DATE)\n private LocalDate collectionOrderEffectiveDate;\n\n @Column(name = \"further_steps_notice_date\")\n @Temporal(TemporalType.DATE)\n private LocalDate furtherStepsNoticeDate;\n\n @Column(name = \"confiscation_order_date\")\n @Temporal(TemporalType.DATE)\n private LocalDate confiscationOrderDate;\n\n @Column(name = \"fine_registration_date\")\n @Temporal(TemporalType.DATE)\n private LocalDate fineRegistrationDate;\n\n @Column(name = \"consolidated_account_type\", length = 1)\n private String consolidatedAccountType;\n\n @Column(name = \"payment_card_requested\")\n private boolean paymentCardRequested;\n\n @Column(name = \"payment_card_requested_date\")\n @Temporal(TemporalType.DATE)\n private LocalDate paymentCardRequestedDate;\n\n @Column(name = \"payment_card_requested_by\", length = 20)\n private String paymentCardRequestedBy;\n\n @Column(name = \"prosecutor_case_reference\", length = 40)\n private String prosecutorCaseReference;\n\n @Column(name = \"enforcement_case_status\", length = 10)\n private String enforcementCaseStatus;\n\n @OneToMany(mappedBy = \"defendantAccount\", cascade = CascadeType.ALL, fetch = FetchType.EAGER)\n private List<DefendantAccountPartiesEntity> parties;\n\n}" }, { "identifier": "DefendantAccountPartiesEntity", "path": "src/main/java/uk/gov/hmcts/opal/entity/DefendantAccountPartiesEntity.java", "snippet": "@Entity\n@Table(name = \"defendant_account_parties\")\n@Data\npublic class DefendantAccountPartiesEntity {\n\n @Id\n @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = \"defendant_account_party_id_seq\")\n @SequenceGenerator(name = \"defendant_account_party_id_seq\", sequenceName = \"defendant_account_party_id_seq\",\n allocationSize = 1)\n @Column(name = \"defendant_account_party_id\")\n private Long defendantAccountPartyId;\n\n @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n @JoinColumn(name = \"defendant_account_id\", nullable = false)\n private DefendantAccountEntity defendantAccount;\n\n @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)\n @JoinColumn(name = \"party_id\", nullable = false)\n private PartyEntity party;\n\n @Column(name = \"association_type\", nullable = false, length = 30)\n private String associationType;\n\n @Column(name = \"debtor\", nullable = false)\n private Boolean debtor;\n}" }, { "identifier": "DefendantAccountSummary", "path": "src/main/java/uk/gov/hmcts/opal/entity/DefendantAccountSummary.java", "snippet": "public interface DefendantAccountSummary {\n\n /** The defendant account id used as the primary key in the database. */\n Long getDefendantAccountId();\n\n /** The defendant account number. */\n String getAccountNumber();\n\n /** The balance on the defendant account. */\n BigDecimal getAccountBalance();\n\n /** The Court (traditionally abbreviated to CT) 'Accounting Division' or 'Metropolitan Area' (MET). */\n String getImposingCourtId();\n\n Set<PartyLink> getParties();\n\n interface PartyLink {\n PartyDefendantAccountSummary getParty();\n }\n\n public interface PartyDefendantAccountSummary {\n\n String getTitle();\n\n String getForenames();\n\n String getSurname();\n\n /** The name of the defendant, being an aggregation of surname, firstnames and title. */\n default String getName() {\n String title = Optional.ofNullable(getTitle()).map(s -> s.concat(\" \")).orElse(\"\");\n String forenames = Optional.ofNullable(getForenames()).map(s -> s.concat(\" \")).orElse(\"\");\n String surname = Optional.ofNullable(getSurname()).orElse(\"\");\n return title.concat(forenames).concat(surname);\n }\n\n /** The date of birth of the defendant. */\n LocalDate getDateOfBirth();\n\n /** First line of the defendant's address. */\n String getAddressLine1();\n\n }\n}" }, { "identifier": "EnforcersEntity", "path": "src/main/java/uk/gov/hmcts/opal/entity/EnforcersEntity.java", "snippet": "@Data\n@Entity\n@EqualsAndHashCode(callSuper = true)\n@Table(name = \"enforcers\")\npublic class EnforcersEntity extends EnforcersCourtsBaseEntity {\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n @Column(name = \"enforcer_id\", nullable = false)\n private Long enforcerId;\n\n @Column(name = \"enforcer_code\", nullable = false)\n private Short enforcerCode;\n\n @Column(name = \"warrant_reference_sequence\", length = 20)\n private String warrantReferenceSequence;\n\n @Column(name = \"warrant_register_sequence\")\n private Integer warrantRegisterSequence;\n}" }, { "identifier": "NoteEntity", "path": "src/main/java/uk/gov/hmcts/opal/entity/NoteEntity.java", "snippet": "@Entity\n@Table(name = \"notes\")\n@Data\n@Builder\npublic class NoteEntity {\n\n @Id\n @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = \"note_id_seq_generator\")\n @SequenceGenerator(name = \"note_id_seq_generator\", sequenceName = \"note_id_seq\", allocationSize = 1)\n private Long noteId;\n\n @Column(name = \"note_type\", length = 2)\n private String noteType;\n\n @Column(name = \"associated_record_type\", length = 30)\n private String associatedRecordType;\n\n @Column(name = \"associated_record_id\", length = 30)\n private String associatedRecordId;\n\n @Column(name = \"note_text\", columnDefinition = \"TEXT\")\n private String noteText;\n\n @Column(name = \"posted_date\")\n @Temporal(TemporalType.TIMESTAMP)\n private LocalDateTime postedDate;\n\n @Column(name = \"posted_by\", length = 20)\n private String postedBy;\n\n}" }, { "identifier": "PartyEntity", "path": "src/main/java/uk/gov/hmcts/opal/entity/PartyEntity.java", "snippet": "@Entity\n@Data\n@Table(name = \"parties\")\n@NoArgsConstructor\n@AllArgsConstructor\n@Builder\npublic class PartyEntity {\n\n @Id\n @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = \"party_id_seq\")\n @SequenceGenerator(name = \"party_id_seq\", sequenceName = \"party_id_seq\", allocationSize = 1)\n @Column(name = \"party_id\")\n private Long partyId;\n\n @Column(name = \"organisation\")\n private boolean organisation;\n\n @Column(name = \"organisation_name\", length = 80)\n private String organisationName;\n\n @Column(name = \"surname\", length = 50)\n private String surname;\n\n @Column(name = \"forenames\", length = 50)\n private String forenames;\n\n @Column(name = \"initials\", length = 2)\n private String initials;\n\n @Column(name = \"title\", length = 20)\n private String title;\n\n @Column(name = \"address_line_1\", length = 35)\n private String addressLine1;\n\n @Column(name = \"address_line_2\", length = 35)\n private String addressLine2;\n\n @Column(name = \"address_line_3\", length = 35)\n private String addressLine3;\n\n @Column(name = \"address_line_4\", length = 35)\n private String addressLine4;\n\n @Column(name = \"address_line_5\", length = 35)\n private String addressLine5;\n\n @Column(name = \"postcode\", length = 10)\n private String postcode;\n\n @Column(name = \"account_type\", length = 20)\n private String accountType;\n\n @Column(name = \"birth_date\")\n @Temporal(TemporalType.DATE)\n private LocalDate dateOfBirth;\n\n @Column(name = \"age\")\n private Short age;\n\n @Column(name = \"national_insurance_number\", length = 20)\n private String niNumber;\n\n @Column(name = \"last_changed_date\")\n @Temporal(TemporalType.TIMESTAMP)\n private LocalDateTime lastChangedDate;\n\n @OneToMany(mappedBy = \"party\", cascade = CascadeType.ALL, fetch = FetchType.EAGER)\n private List<DefendantAccountPartiesEntity> defendantAccounts;\n}" }, { "identifier": "PaymentTermsEntity", "path": "src/main/java/uk/gov/hmcts/opal/entity/PaymentTermsEntity.java", "snippet": "@Entity\n@Table(name = \"payment_terms\")\n@Data\npublic class PaymentTermsEntity {\n\n @Id\n @Column(name = \"payment_terms_id\")\n private Long paymentTermsId;\n\n @ManyToOne\n @JoinColumn(name = \"defendant_account_id\", referencedColumnName = \"defendant_account_id\", nullable = false)\n private DefendantAccountEntity defendantAccount;\n\n\n @Column(name = \"posted_date\", nullable = false)\n @Temporal(TemporalType.DATE)\n private LocalDate postedDate;\n\n @Column(name = \"posted_by\")\n private String postedBy;\n\n @Column(name = \"terms_type_code\", nullable = false)\n private String termsTypeCode;\n\n @Column(name = \"effective_date\")\n @Temporal(TemporalType.DATE)\n private LocalDate effectiveDate;\n\n @Column(name = \"instalment_period\")\n private String instalmentPeriod;\n\n @Column(name = \"instalment_amount\")\n private BigDecimal instalmentAmount;\n\n @Column(name = \"instalment_lump_sum\")\n private BigDecimal instalmentLumpSum;\n\n @Column(name = \"jail_days\")\n private Integer jailDays;\n\n @Column(name = \"extension\")\n private Boolean extension;\n\n @Column(name = \"account_balance\")\n private BigDecimal accountBalance;\n\n}" }, { "identifier": "DebtorDetailRepository", "path": "src/main/java/uk/gov/hmcts/opal/repository/DebtorDetailRepository.java", "snippet": "@Repository\npublic interface DebtorDetailRepository extends JpaRepository<DebtorDetailEntity, Long> {\n DebtorDetailEntity findByParty_PartyId(PartyEntity party);\n}" }, { "identifier": "DefendantAccountPartiesRepository", "path": "src/main/java/uk/gov/hmcts/opal/repository/DefendantAccountPartiesRepository.java", "snippet": "@Repository\npublic interface DefendantAccountPartiesRepository extends JpaRepository<DefendantAccountPartiesEntity, Long> {\n\n @Query(\"\"\"\n SELECT dap FROM DefendantAccountPartiesEntity dap\n JOIN dap.party p\n JOIN dap.defendantAccount da\n JOIN da.lastHearingCourtId c\n WHERE da.defendantAccountId = :defendantAccountId\"\"\")\n DefendantAccountPartiesEntity findByDefendantAccountId(@Param(\"defendantAccountId\") Long defendantAccountId);\n}" }, { "identifier": "DefendantAccountRepository", "path": "src/main/java/uk/gov/hmcts/opal/repository/DefendantAccountRepository.java", "snippet": "@Repository\npublic interface DefendantAccountRepository extends JpaRepository<DefendantAccountEntity, Long>,\n JpaSpecificationExecutor<DefendantAccountEntity> {\n\n DefendantAccountEntity findByBusinessUnitId_BusinessUnitIdAndAccountNumber(Short businessUnitId,\n String accountNumber);\n\n List<DefendantAccountEntity> findAllByBusinessUnitId_BusinessUnitId(Short businessUnitId);\n\n}" }, { "identifier": "EnforcersRepository", "path": "src/main/java/uk/gov/hmcts/opal/repository/EnforcersRepository.java", "snippet": "@Repository\npublic interface EnforcersRepository extends JpaRepository<EnforcersEntity, Long> {\n\n EnforcersEntity findByEnforcerId(Long enforcerId);\n}" }, { "identifier": "NoteRepository", "path": "src/main/java/uk/gov/hmcts/opal/repository/NoteRepository.java", "snippet": "@Repository\npublic interface NoteRepository extends JpaRepository<NoteEntity, Long> {\n\n List<NoteEntity> findByAssociatedRecordIdAndNoteType(String associatedRecordId, String noteType);\n\n}" }, { "identifier": "PaymentTermsRepository", "path": "src/main/java/uk/gov/hmcts/opal/repository/PaymentTermsRepository.java", "snippet": "@Repository\npublic interface PaymentTermsRepository extends JpaRepository<PaymentTermsEntity, Long> {\n\n PaymentTermsEntity findByDefendantAccount_DefendantAccountId(DefendantAccountEntity defendantAccount);\n}" }, { "identifier": "DefendantAccountSpecs", "path": "src/main/java/uk/gov/hmcts/opal/repository/jpa/DefendantAccountSpecs.java", "snippet": "public class DefendantAccountSpecs {\n\n public static Specification<DefendantAccountEntity> findByAccountSearch(AccountSearchDto accountSearchDto) {\n return Specification.allOf(specificationList(\n notBlank(accountSearchDto.getSurname()).map(DefendantAccountSpecs::likeSurname),\n notBlank(accountSearchDto.getForename()).map(DefendantAccountSpecs::likeForename),\n notBlank(accountSearchDto.getInitials()).map(DefendantAccountSpecs::likeInitials),\n notBlank(accountSearchDto.getNiNumber()).map(DefendantAccountSpecs::likeNiNumber),\n notBlank(accountSearchDto.getAddressLineOne()).map(DefendantAccountSpecs::likeAddressLine1),\n notNullLocalDate(accountSearchDto.getDateOfBirth()).map(DefendantAccountSpecs::equalsDateOfBirth),\n Optional.ofNullable(accountSearchDto.getCourt()).filter(s -> s.matches(\"[0-9]+\")).map(Long::parseLong)\n .map(DefendantAccountSpecs::equalsAnyCourtId)\n ));\n }\n\n @SafeVarargs\n public static List<Specification<DefendantAccountEntity>> specificationList(\n Optional<Specification<DefendantAccountEntity>>... optionalSpecs) {\n return Arrays.stream(optionalSpecs)\n .filter(Optional::isPresent)\n .map(Optional::get)\n .collect(Collectors.toList());\n }\n\n public static Optional<String> notBlank(String candidate) {\n return Optional.ofNullable(candidate).filter(s -> !s.isBlank());\n }\n\n public static Optional<LocalDate> notNullLocalDate(DateDto candidate) {\n return Optional.ofNullable(candidate).map(DateDto::toLocalDate);\n }\n\n public static Specification<DefendantAccountEntity> equalsAccountNumber(String accountNo) {\n return (root, query, builder) -> {\n return builder.equal(root.get(DefendantAccountEntity_.accountNumber), accountNo);\n };\n }\n\n public static Specification<DefendantAccountEntity> equalsAnyCourtId(Long courtId) {\n return Specification.anyOf(\n equalsImposingCourtId(courtId),\n equalsEnforcingCourtId(courtId),\n equalsLastHearingCourtId(courtId));\n }\n\n public static Specification<DefendantAccountEntity> equalsImposingCourtId(Long courtId) {\n return (root, query, builder) -> {\n return builder.equal(root.get(DefendantAccountEntity_.imposingCourtId), courtId);\n };\n }\n\n public static Specification<DefendantAccountEntity> equalsEnforcingCourtId(Long courtId) {\n return (root, query, builder) -> {\n return builder.equal(joinEnforcingCourt(root).get(CourtsEntity_.courtId), courtId);\n };\n }\n\n public static Specification<DefendantAccountEntity> equalsLastHearingCourtId(Long courtId) {\n return (root, query, builder) -> {\n return builder.equal(joinLastHearingCourt(root).get(CourtsEntity_.courtId), courtId);\n };\n }\n\n public static Specification<DefendantAccountEntity> likeSurname(String surname) {\n return (root, query, builder) -> {\n return builder.like(joinPartyOnAssociationType(root, builder, \"Defendant\")\n .get(PartyEntity_.surname), \"%\" + surname + \"%\");\n };\n }\n\n public static Specification<DefendantAccountEntity> likeForename(String forename) {\n return (root, query, builder) -> {\n return builder.like(joinPartyOnAssociationType(root, builder, \"Defendant\")\n .get(PartyEntity_.forenames), \"%\" + forename + \"%\");\n };\n }\n\n public static Specification<DefendantAccountEntity> likeOrganisationName(String organisation) {\n return (root, query, builder) -> {\n return builder.like(joinPartyOnAssociationType(root, builder, \"Defendant\")\n .get(PartyEntity_.organisationName), \"%\" + organisation + \"%\");\n };\n }\n\n public static Specification<DefendantAccountEntity> equalsDateOfBirth(LocalDate dob) {\n return (root, query, builder) -> {\n return builder.equal(joinPartyOnAssociationType(root, builder, \"Defendant\")\n .get(PartyEntity_.dateOfBirth), dob);\n };\n }\n\n public static Specification<DefendantAccountEntity> likeNiNumber(String niNumber) {\n return (root, query, builder) -> {\n return builder.like(joinPartyOnAssociationType(root, builder, \"Defendant\")\n .get(PartyEntity_.niNumber), \"%\" + niNumber + \"%\");\n };\n }\n\n public static Specification<DefendantAccountEntity> likeAddressLine1(String addressLine) {\n return (root, query, builder) -> {\n return builder.like(joinPartyOnAssociationType(root, builder, \"Defendant\")\n .get(PartyEntity_.addressLine1), \"%\" + addressLine + \"%\");\n };\n }\n\n public static Specification<DefendantAccountEntity> likeInitials(String initials) {\n return (root, query, builder) -> {\n return builder.like(joinPartyOnAssociationType(root, builder, \"Defendant\")\n .get(PartyEntity_.initials), \"%\" + initials + \"%\");\n };\n }\n\n public static Join<DefendantAccountEntity, CourtsEntity> joinEnforcingCourt(Root<DefendantAccountEntity> root) {\n return root.join(DefendantAccountEntity_.enforcingCourtId);\n }\n\n public static Join<DefendantAccountEntity, CourtsEntity> joinLastHearingCourt(Root<DefendantAccountEntity> root) {\n return root.join(DefendantAccountEntity_.lastHearingCourtId);\n }\n\n public static Join<DefendantAccountPartiesEntity, PartyEntity> joinPartyOnAssociationType(\n Root<DefendantAccountEntity> root, CriteriaBuilder builder, String type) {\n return onAssociationType(builder, root.join(DefendantAccountEntity_.parties), type)\n .join(DefendantAccountPartiesEntity_.party);\n }\n\n\n public static ListJoin<DefendantAccountEntity, DefendantAccountPartiesEntity> onAssociationType(\n CriteriaBuilder builder,\n ListJoin<DefendantAccountEntity, DefendantAccountPartiesEntity> parties,\n String type) {\n return parties.on(builder.equal(parties.get(DefendantAccountPartiesEntity_.associationType), type));\n }\n}" }, { "identifier": "PartyLink", "path": "src/main/java/uk/gov/hmcts/opal/entity/DefendantAccountSummary.java", "snippet": "interface PartyLink {\n PartyDefendantAccountSummary getParty();\n}" }, { "identifier": "PartyDefendantAccountSummary", "path": "src/main/java/uk/gov/hmcts/opal/entity/DefendantAccountSummary.java", "snippet": "public interface PartyDefendantAccountSummary {\n\n String getTitle();\n\n String getForenames();\n\n String getSurname();\n\n /** The name of the defendant, being an aggregation of surname, firstnames and title. */\n default String getName() {\n String title = Optional.ofNullable(getTitle()).map(s -> s.concat(\" \")).orElse(\"\");\n String forenames = Optional.ofNullable(getForenames()).map(s -> s.concat(\" \")).orElse(\"\");\n String surname = Optional.ofNullable(getSurname()).orElse(\"\");\n return title.concat(forenames).concat(surname);\n }\n\n /** The date of birth of the defendant. */\n LocalDate getDateOfBirth();\n\n /** First line of the defendant's address. */\n String getAddressLine1();\n\n}" }, { "identifier": "newObjectMapper", "path": "src/main/java/uk/gov/hmcts/opal/dto/ToJsonString.java", "snippet": "static ObjectMapper newObjectMapper() {\n return new ObjectMapper()\n .registerModule(new JavaTimeModule());\n}" } ]
import com.fasterxml.jackson.databind.ObjectMapper; import jakarta.transaction.Transactional; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import uk.gov.hmcts.opal.dto.AccountDetailsDto; import uk.gov.hmcts.opal.dto.AccountEnquiryDto; import uk.gov.hmcts.opal.dto.AccountSearchDto; import uk.gov.hmcts.opal.dto.AccountSearchResultsDto; import uk.gov.hmcts.opal.dto.AccountSummaryDto; import uk.gov.hmcts.opal.entity.DefendantAccountEntity; import uk.gov.hmcts.opal.entity.DefendantAccountPartiesEntity; import uk.gov.hmcts.opal.entity.DefendantAccountSummary; import uk.gov.hmcts.opal.entity.EnforcersEntity; import uk.gov.hmcts.opal.entity.NoteEntity; import uk.gov.hmcts.opal.entity.PartyEntity; import uk.gov.hmcts.opal.entity.PaymentTermsEntity; import uk.gov.hmcts.opal.repository.DebtorDetailRepository; import uk.gov.hmcts.opal.repository.DefendantAccountPartiesRepository; import uk.gov.hmcts.opal.repository.DefendantAccountRepository; import uk.gov.hmcts.opal.repository.EnforcersRepository; import uk.gov.hmcts.opal.repository.NoteRepository; import uk.gov.hmcts.opal.repository.PaymentTermsRepository; import uk.gov.hmcts.opal.repository.jpa.DefendantAccountSpecs; import uk.gov.hmcts.opal.entity.DefendantAccountSummary.PartyLink; import uk.gov.hmcts.opal.entity.DefendantAccountSummary.PartyDefendantAccountSummary; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import static uk.gov.hmcts.opal.dto.ToJsonString.newObjectMapper;
7,505
package uk.gov.hmcts.opal.service; @Service @Transactional @Slf4j @RequiredArgsConstructor public class DefendantAccountService { private final DefendantAccountRepository defendantAccountRepository; private final DefendantAccountPartiesRepository defendantAccountPartiesRepository; private final PaymentTermsRepository paymentTermsRepository; private final DebtorDetailRepository debtorDetailRepository; private final EnforcersRepository enforcersRepository; private final NoteRepository noteRepository; public DefendantAccountEntity getDefendantAccount(AccountEnquiryDto request) { return defendantAccountRepository.findByBusinessUnitId_BusinessUnitIdAndAccountNumber( request.getBusinessUnitId(), request.getAccountNumber()); } public DefendantAccountEntity putDefendantAccount(DefendantAccountEntity defendantAccountEntity) { return defendantAccountRepository.save(defendantAccountEntity); } public List<DefendantAccountEntity> getDefendantAccountsByBusinessUnit(Short businessUnitId) { log.info(":getDefendantAccountsByBusinessUnit: busUnit: {}", businessUnitId); return defendantAccountRepository.findAllByBusinessUnitId_BusinessUnitId(businessUnitId); }
package uk.gov.hmcts.opal.service; @Service @Transactional @Slf4j @RequiredArgsConstructor public class DefendantAccountService { private final DefendantAccountRepository defendantAccountRepository; private final DefendantAccountPartiesRepository defendantAccountPartiesRepository; private final PaymentTermsRepository paymentTermsRepository; private final DebtorDetailRepository debtorDetailRepository; private final EnforcersRepository enforcersRepository; private final NoteRepository noteRepository; public DefendantAccountEntity getDefendantAccount(AccountEnquiryDto request) { return defendantAccountRepository.findByBusinessUnitId_BusinessUnitIdAndAccountNumber( request.getBusinessUnitId(), request.getAccountNumber()); } public DefendantAccountEntity putDefendantAccount(DefendantAccountEntity defendantAccountEntity) { return defendantAccountRepository.save(defendantAccountEntity); } public List<DefendantAccountEntity> getDefendantAccountsByBusinessUnit(Short businessUnitId) { log.info(":getDefendantAccountsByBusinessUnit: busUnit: {}", businessUnitId); return defendantAccountRepository.findAllByBusinessUnitId_BusinessUnitId(businessUnitId); }
public AccountSearchResultsDto searchDefendantAccounts(AccountSearchDto accountSearchDto) {
2
2023-10-23 14:12:11+00:00
12k
moonstoneid/aero-cast
apps/feed-aggregator/src/main/java/com/moonstoneid/aerocast/aggregator/service/SubscriberService.java
[ { "identifier": "ConflictException", "path": "apps/feed-aggregator/src/main/java/com/moonstoneid/aerocast/aggregator/error/ConflictException.java", "snippet": "public class ConflictException extends RuntimeException {\n\n public ConflictException(String message) {\n super(message);\n }\n\n}" }, { "identifier": "NotFoundException", "path": "apps/feed-aggregator/src/main/java/com/moonstoneid/aerocast/aggregator/error/NotFoundException.java", "snippet": "public class NotFoundException extends RuntimeException {\n\n public NotFoundException(String message) {\n super(message);\n }\n\n}" }, { "identifier": "EthSubscriberAdapter", "path": "apps/feed-aggregator/src/main/java/com/moonstoneid/aerocast/aggregator/eth/EthSubscriberAdapter.java", "snippet": "@Component\n@Slf4j\npublic class EthSubscriberAdapter extends BaseEthAdapter {\n\n public interface EventCallback {\n void onCreateSubscription(String subContractAddr, String blockNumber, String pubContractAddr);\n void onRemoveSubscription(String subContractAddr, String blockNumber, String pubContractAddr);\n }\n\n private final Credentials credentials;\n private final String regContractAddr;\n\n private final MultiValueMap<String, Disposable> eventSubscribers = new LinkedMultiValueMap<>();\n\n public EthSubscriberAdapter(Web3j web3j, EthRegistryProperties ethRegistryProperties) {\n super(web3j);\n this.credentials = createDummyCredentials();\n this.regContractAddr = ethRegistryProperties.getContractAddress();\n }\n\n public String getSubscriberContractAddress(String subAccountAddr) {\n FeedRegistry contract = getRegistryContract();\n try {\n String subContractAddr = contract.getSubscriberContractByAddress(subAccountAddr)\n .sendAsync().get();\n if (!isValidAddress(subContractAddr)) {\n return null;\n }\n return subContractAddr;\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }\n\n public void registerSubscriptionEventListener(String subContractAddr, String blockNumber,\n EventCallback callback) {\n log.debug(\"Adding event listener on subscriber contract '{}'.\",\n EthUtil.shortenAddress(subContractAddr));\n\n FeedSubscriber contract = getSubscriberContract(subContractAddr);\n\n EthFilter subEventFilter = createEventFilter(subContractAddr, blockNumber,\n FeedSubscriber.CREATESUBSCRIPTION_EVENT);\n Disposable subEventSubscriber = contract.createSubscriptionEventFlowable(subEventFilter)\n .subscribe(r -> handleSubscribeEvent(subContractAddr, r, callback));\n eventSubscribers.add(subContractAddr, subEventSubscriber);\n\n EthFilter unsubEventFilter = createEventFilter(subContractAddr, blockNumber,\n FeedSubscriber.REMOVESUBSCRIPTION_EVENT);\n Disposable unsubEventSubscriber = contract.removeSubscriptionEventFlowable(unsubEventFilter)\n .subscribe(r -> handleUnsubscribeEvent(subContractAddr, r, callback));\n eventSubscribers.add(subContractAddr, unsubEventSubscriber);\n }\n\n private void handleSubscribeEvent(String subContractAddr,\n CreateSubscriptionEventResponse response, EventCallback callback) {\n String blockNumber = getBlockNumberFromEventResponse(response);\n String pubContractAddr = response.pubAddress;\n callback.onCreateSubscription(subContractAddr, blockNumber, pubContractAddr);\n }\n\n private void handleUnsubscribeEvent(String subContractAddr,\n RemoveSubscriptionEventResponse response, EventCallback callback) {\n String blockNumber = getBlockNumberFromEventResponse(response);\n String pubContractAddr = response.pubAddress;\n callback.onRemoveSubscription(subContractAddr, blockNumber, pubContractAddr);\n }\n\n public void unregisterSubscriptionEventListener(String subContractAddr) {\n log.debug(\"Removing event listener on subscriber contract '{}'.\",\n EthUtil.shortenAddress(subContractAddr));\n\n for (Disposable eventSubscriber : eventSubscribers.get(subContractAddr)) {\n eventSubscriber.dispose();\n }\n }\n\n public List<FeedSubscriber.Subscription> getSubscriberSubscriptions(String subContractAddr) {\n FeedSubscriber contract = getSubscriberContract(subContractAddr);\n try {\n return contract.getSubscriptions().sendAsync().get();\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }\n\n private FeedRegistry getRegistryContract() {\n return createRegistryContract(regContractAddr, credentials);\n }\n\n private FeedSubscriber getSubscriberContract(String contractAddr) {\n return createSubscriberContract(contractAddr, credentials);\n }\n\n}" }, { "identifier": "EthUtil", "path": "apps/feed-common/src/main/java/com/moonstoneid/aerocast/common/eth/EthUtil.java", "snippet": "public final class EthUtil {\n\n private EthUtil() {}\n\n public static String shortenAddress(String addr) {\n return addr.substring(0, 6) + \"...\" + addr.substring(addr.length() - 2);\n }\n\n}" }, { "identifier": "FeedSubscriber", "path": "apps/feed-common/src/main/java/com/moonstoneid/aerocast/common/eth/contracts/FeedSubscriber.java", "snippet": "@SuppressWarnings(\"rawtypes\")\npublic class FeedSubscriber extends Contract {\n public static final String BINARY = \"608060405234801561001057600080fd5b50600080546001600160a01b0319163317905561104a806100326000396000f3fe608060405234801561001057600080fd5b50600436106100885760003560e01c80637262561c1161005b5780637262561c146100e85780637358152a146100fb5780638b46a2b41461010e5780638da5cb5b1461012157600080fd5b80630472f4181461008d57806313af4035146100ab5780633b47a9ac146100c057806341a7726a146100d5575b600080fd5b61009561013c565b6040516100a29190610c87565b60405180910390f35b6100be6100b9366004610d2e565b6101f5565b005b6100c861024a565b6040516100a29190610d50565b6100be6100e3366004610d2e565b6102b6565b6100be6100f6366004610d2e565b610478565b6100be610109366004610da8565b610660565b6100be61011c366004610dd2565b61090b565b6000546040516001600160a01b0390911681526020016100a2565b60606003805480602002602001604051908101604052809291908181526020016000905b828210156101ec576000848152602090819020604080516080810182526004860290920180546001600160a01b03168352600180820154948401949094526002810154929390929184019160ff16908111156101be576101be610c71565b60018111156101cf576101cf610c71565b815260200160038201548152505081526020019060010190610160565b50505050905090565b6000546001600160a01b031633146102285760405162461bcd60e51b815260040161021f90610e16565b60405180910390fd5b600080546001600160a01b0319166001600160a01b0392909216919091179055565b60606001805480602002602001604051908101604052809291908181526020016000905b828210156101ec576000848152602090819020604080518082019091526002850290910180546001600160a01b0316825260019081015482840152908352909201910161026e565b6000546001600160a01b031633146102e05760405162461bcd60e51b815260040161021f90610e16565b604080518082019091526001600160a01b0382168152426020820152600061030783610baa565b6001600160a01b0381166000908152600260205260409020549091508015610385578260016103368184610e5e565b8154811061034657610346610e7f565b600091825260209182902083516002929092020180546001600160a01b0319166001600160a01b0390921691909117815591015160019091015561041b565b50600180548082018255600082815284517fb10e2d527612073b26eecdfd717e6a320cf44b4afac2b0732d9fcbe2b7fa0cf6600293840290810180546001600160a01b0319166001600160a01b039384161790556020808801517fb10e2d527612073b26eecdfd717e6a320cf44b4afac2b0732d9fcbe2b7fa0cf790920191909155935490851682529190925260409091208190555b61043e604051806060016040528060308152602001610f5b603091393386610bb4565b6040516001600160a01b038516907f6ff6eaed699c246ce4a81c625294e51377e7c325c1c73e5bfa3b44be72806d0290600090a250505050565b6000546001600160a01b031633146104a25760405162461bcd60e51b815260040161021f90610e16565b60006104ad82610baa565b6001600160a01b0381166000908152600260205260408120549192508190036104d557505050565b6001600160a01b0382166000908152600260205260408120556001805411156105c757600180546000919061050b908290610e5e565b8154811061051b5761051b610e7f565b600091825260208083206040805180820190915260029093020180546001600160a01b03168084526001909101549183019190915290925061055c90610baa565b905081600161056b8186610e5e565b8154811061057b5761057b610e7f565b600091825260208083208451600293840290910180546001600160a01b0319166001600160a01b0392831617815594820151600190950194909455939092168152915260409020829055505b60018054806105d8576105d8610e95565b6000828152602080822060026000199094019384020180546001600160a01b03191681556001019190915591556040805160608101909152603080825261062792610fe5908301393385610bb4565b6040516001600160a01b038416907fd4da1c95251a1c543838518bae8531facb525bc74cf1ac0ed8fb308479958c2e90600090a2505050565b6000546001600160a01b0316331461068a5760405162461bcd60e51b815260040161021f90610e16565b6000601083901b62010000600160b01b031682176001600160a01b0381166000908152600460205260408120549192508190036106c75750505050565b6001600160a01b0382166000908152600460205260408120556003546001101561084e5760038054600091906106ff90600190610e5e565b8154811061070f5761070f610e7f565b600091825260209182902060408051608081018252600490930290910180546001600160a01b03168352600180820154948401949094526002810154929390929184019160ff169081111561076657610766610c71565b600181111561077757610777610c71565b815260039182015460209182015282519083015192935060101b62010000600160b01b03169091179082906107ad600186610e5e565b815481106107bd576107bd610e7f565b600091825260209182902083516004929092020180546001600160a01b0319166001600160a01b039092169190911781559082015160018083019190915560408301516002830180549192909160ff191690838181111561082057610820610c71565b0217905550606091909101516003909101556001600160a01b03166000908152600460205260409020829055505b600380548061085f5761085f610e95565b6000828152602080822060046000199094019384020180546001600160a01b03191681556001810183905560028101805460ff191690556003019190915591556040805160608101909152602d8082526108c292610fb890830139338686610c00565b836001600160a01b03167f8f22061a7389d6620c735385174537c8baaf1439735a4a569906d00f95c04581846040516108fd91815260200190565b60405180910390a250505050565b6000546001600160a01b031633146109355760405162461bcd60e51b815260040161021f90610e16565b60006040518060800160405280856001600160a01b0316815260200184815260200183600181111561096957610969610c71565b81524260209091015290506000601085901b62010000600160b01b031684176001600160a01b0381166000908152600460205260409020549091508015610a42578260036109b8600184610e5e565b815481106109c8576109c8610e7f565b600091825260209182902083516004929092020180546001600160a01b0319166001600160a01b039092169190911781559082015160018083019190915560408301516002830180549192909160ff1916908381811115610a2b57610a2b610c71565b021790555060608201518160030155905050610b3b565b6003805460018181018355600092909252845160049091027fc2575a0e9e593c00f959f8c92f12db2869c3395a3b0502d05e2516446f71f85b810180546001600160a01b039093166001600160a01b031990931692909217825560208601517fc2575a0e9e593c00f959f8c92f12db2869c3395a3b0502d05e2516446f71f85c82015560408601517fc2575a0e9e593c00f959f8c92f12db2869c3395a3b0502d05e2516446f71f85d9091018054879460ff19909116908381811115610b0a57610b0a610c71565b021790555060609190910151600391820155546001600160a01b038316600090815260046020526040902081905590505b610b5f6040518060600160405280602d8152602001610f8b602d9139338888610c00565b856001600160a01b03167f66ddc840fe0c0e2d79e178ffe79c6ede8c6fcf1c61cf1edb4adb1d1e40ee327886604051610b9a91815260200190565b60405180910390a2505050505050565b6000815b92915050565b610bfb838383604051602401610bcc93929190610ef1565b60408051601f198184030181529190526020810180516001600160e01b03166307e763af60e51b179052610c4f565b505050565b610c4984848484604051602401610c1a9493929190610f24565b60408051601f198184030181529190526020810180516001600160e01b0316638ef3f39960e01b179052610c4f565b50505050565b80516a636f6e736f6c652e6c6f6790602083016000808383865afa5050505050565b634e487b7160e01b600052602160045260246000fd5b60208082528251828201819052600091906040908185019086840185805b83811015610d0457825180516001600160a01b0316865287810151888701528681015160028110610ce457634e487b7160e01b84526021600452602484fd5b868801526060908101519086015260809094019391860191600101610ca5565b509298975050505050505050565b80356001600160a01b0381168114610d2957600080fd5b919050565b600060208284031215610d4057600080fd5b610d4982610d12565b9392505050565b602080825282518282018190526000919060409081850190868401855b82811015610d9b57815180516001600160a01b03168552860151868501529284019290850190600101610d6d565b5091979650505050505050565b60008060408385031215610dbb57600080fd5b610dc483610d12565b946020939093013593505050565b600080600060608486031215610de757600080fd5b610df084610d12565b925060208401359150604084013560028110610e0b57600080fd5b809150509250925092565b60208082526028908201527f43616c6c6572206f66207468652066756e6374696f6e206973206e6f7420746860408201526765206f776e65722160c01b606082015260800190565b81810381811115610bae57634e487b7160e01b600052601160045260246000fd5b634e487b7160e01b600052603260045260246000fd5b634e487b7160e01b600052603160045260246000fd5b6000815180845260005b81811015610ed157602081850181015186830182015201610eb5565b506000602082860101526020601f19601f83011685010191505092915050565b606081526000610f046060830186610eab565b6001600160a01b0394851660208401529290931660409091015292915050565b608081526000610f376080830187610eab565b6001600160a01b039586166020840152939094166040820152606001529291505056fe4163636f756e74202573206372656174656420737562736372697074696f6e206f6e207075626c69736865722025732e4163636f756e742025732063726561746564207265616374696f6e206f6e20707562206974656d2025732f25644163636f756e742025732072656d6f766564207265616374696f6e206f6e20707562206974656d2025732f25644163636f756e742025732072656d6f76656420737562736372697074696f6e206f6e207075626c69736865722025732ea2646970667358221220f653a3f6306444d45301105417326b7702fe13fe4fc4a37c672bb68055b81dc864736f6c63430008130033\";\n\n public static final String FUNC_GETREACTIONS = \"getReactions\";\n\n public static final String FUNC_GETSUBSCRIPTIONS = \"getSubscriptions\";\n\n public static final String FUNC_OWNER = \"owner\";\n\n public static final String FUNC_REACT = \"react\";\n\n public static final String FUNC_SETOWNER = \"setOwner\";\n\n public static final String FUNC_SUBSCRIBE = \"subscribe\";\n\n public static final String FUNC_UNREACT = \"unreact\";\n\n public static final String FUNC_UNSUBSCRIBE = \"unsubscribe\";\n\n public static final Event CREATEREACTION_EVENT = new Event(\"CreateReaction\", \n Arrays.<TypeReference<?>>asList(new TypeReference<Address>(true) {}, new TypeReference<Uint256>() {}));\n ;\n\n public static final Event CREATESUBSCRIPTION_EVENT = new Event(\"CreateSubscription\", \n Arrays.<TypeReference<?>>asList(new TypeReference<Address>(true) {}));\n ;\n\n public static final Event REMOVEREACTION_EVENT = new Event(\"RemoveReaction\", \n Arrays.<TypeReference<?>>asList(new TypeReference<Address>(true) {}, new TypeReference<Uint256>() {}));\n ;\n\n public static final Event REMOVESUBSCRIPTION_EVENT = new Event(\"RemoveSubscription\", \n Arrays.<TypeReference<?>>asList(new TypeReference<Address>(true) {}));\n ;\n\n @Deprecated\n protected FeedSubscriber(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) {\n super(BINARY, contractAddress, web3j, credentials, gasPrice, gasLimit);\n }\n\n protected FeedSubscriber(String contractAddress, Web3j web3j, Credentials credentials, ContractGasProvider contractGasProvider) {\n super(BINARY, contractAddress, web3j, credentials, contractGasProvider);\n }\n\n @Deprecated\n protected FeedSubscriber(String contractAddress, Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) {\n super(BINARY, contractAddress, web3j, transactionManager, gasPrice, gasLimit);\n }\n\n protected FeedSubscriber(String contractAddress, Web3j web3j, TransactionManager transactionManager, ContractGasProvider contractGasProvider) {\n super(BINARY, contractAddress, web3j, transactionManager, contractGasProvider);\n }\n\n public List<CreateReactionEventResponse> getCreateReactionEvents(TransactionReceipt transactionReceipt) {\n List<EventValuesWithLog> valueList = extractEventParametersWithLog(CREATEREACTION_EVENT, transactionReceipt);\n ArrayList<CreateReactionEventResponse> responses = new ArrayList<CreateReactionEventResponse>(valueList.size());\n for (EventValuesWithLog eventValues : valueList) {\n CreateReactionEventResponse typedResponse = new CreateReactionEventResponse();\n typedResponse.log = eventValues.getLog();\n typedResponse.pubAddress = (String) eventValues.getIndexedValues().get(0).getValue();\n typedResponse._pubItemNum = (BigInteger) eventValues.getNonIndexedValues().get(0).getValue();\n responses.add(typedResponse);\n }\n return responses;\n }\n\n public Flowable<CreateReactionEventResponse> createReactionEventFlowable(EthFilter filter) {\n return web3j.ethLogFlowable(filter).map(new Function<Log, CreateReactionEventResponse>() {\n @Override\n public CreateReactionEventResponse apply(Log log) {\n EventValuesWithLog eventValues = extractEventParametersWithLog(CREATEREACTION_EVENT, log);\n CreateReactionEventResponse typedResponse = new CreateReactionEventResponse();\n typedResponse.log = log;\n typedResponse.pubAddress = (String) eventValues.getIndexedValues().get(0).getValue();\n typedResponse._pubItemNum = (BigInteger) eventValues.getNonIndexedValues().get(0).getValue();\n return typedResponse;\n }\n });\n }\n\n public Flowable<CreateReactionEventResponse> createReactionEventFlowable(DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) {\n EthFilter filter = new EthFilter(startBlock, endBlock, getContractAddress());\n filter.addSingleTopic(EventEncoder.encode(CREATEREACTION_EVENT));\n return createReactionEventFlowable(filter);\n }\n\n public List<CreateSubscriptionEventResponse> getCreateSubscriptionEvents(TransactionReceipt transactionReceipt) {\n List<EventValuesWithLog> valueList = extractEventParametersWithLog(CREATESUBSCRIPTION_EVENT, transactionReceipt);\n ArrayList<CreateSubscriptionEventResponse> responses = new ArrayList<CreateSubscriptionEventResponse>(valueList.size());\n for (EventValuesWithLog eventValues : valueList) {\n CreateSubscriptionEventResponse typedResponse = new CreateSubscriptionEventResponse();\n typedResponse.log = eventValues.getLog();\n typedResponse.pubAddress = (String) eventValues.getIndexedValues().get(0).getValue();\n responses.add(typedResponse);\n }\n return responses;\n }\n\n public Flowable<CreateSubscriptionEventResponse> createSubscriptionEventFlowable(EthFilter filter) {\n return web3j.ethLogFlowable(filter).map(new Function<Log, CreateSubscriptionEventResponse>() {\n @Override\n public CreateSubscriptionEventResponse apply(Log log) {\n EventValuesWithLog eventValues = extractEventParametersWithLog(CREATESUBSCRIPTION_EVENT, log);\n CreateSubscriptionEventResponse typedResponse = new CreateSubscriptionEventResponse();\n typedResponse.log = log;\n typedResponse.pubAddress = (String) eventValues.getIndexedValues().get(0).getValue();\n return typedResponse;\n }\n });\n }\n\n public Flowable<CreateSubscriptionEventResponse> createSubscriptionEventFlowable(DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) {\n EthFilter filter = new EthFilter(startBlock, endBlock, getContractAddress());\n filter.addSingleTopic(EventEncoder.encode(CREATESUBSCRIPTION_EVENT));\n return createSubscriptionEventFlowable(filter);\n }\n\n public List<RemoveReactionEventResponse> getRemoveReactionEvents(TransactionReceipt transactionReceipt) {\n List<EventValuesWithLog> valueList = extractEventParametersWithLog(REMOVEREACTION_EVENT, transactionReceipt);\n ArrayList<RemoveReactionEventResponse> responses = new ArrayList<RemoveReactionEventResponse>(valueList.size());\n for (EventValuesWithLog eventValues : valueList) {\n RemoveReactionEventResponse typedResponse = new RemoveReactionEventResponse();\n typedResponse.log = eventValues.getLog();\n typedResponse.pubAddress = (String) eventValues.getIndexedValues().get(0).getValue();\n typedResponse._pubItemNum = (BigInteger) eventValues.getNonIndexedValues().get(0).getValue();\n responses.add(typedResponse);\n }\n return responses;\n }\n\n public Flowable<RemoveReactionEventResponse> removeReactionEventFlowable(EthFilter filter) {\n return web3j.ethLogFlowable(filter).map(new Function<Log, RemoveReactionEventResponse>() {\n @Override\n public RemoveReactionEventResponse apply(Log log) {\n EventValuesWithLog eventValues = extractEventParametersWithLog(REMOVEREACTION_EVENT, log);\n RemoveReactionEventResponse typedResponse = new RemoveReactionEventResponse();\n typedResponse.log = log;\n typedResponse.pubAddress = (String) eventValues.getIndexedValues().get(0).getValue();\n typedResponse._pubItemNum = (BigInteger) eventValues.getNonIndexedValues().get(0).getValue();\n return typedResponse;\n }\n });\n }\n\n public Flowable<RemoveReactionEventResponse> removeReactionEventFlowable(DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) {\n EthFilter filter = new EthFilter(startBlock, endBlock, getContractAddress());\n filter.addSingleTopic(EventEncoder.encode(REMOVEREACTION_EVENT));\n return removeReactionEventFlowable(filter);\n }\n\n public List<RemoveSubscriptionEventResponse> getRemoveSubscriptionEvents(TransactionReceipt transactionReceipt) {\n List<EventValuesWithLog> valueList = extractEventParametersWithLog(REMOVESUBSCRIPTION_EVENT, transactionReceipt);\n ArrayList<RemoveSubscriptionEventResponse> responses = new ArrayList<RemoveSubscriptionEventResponse>(valueList.size());\n for (EventValuesWithLog eventValues : valueList) {\n RemoveSubscriptionEventResponse typedResponse = new RemoveSubscriptionEventResponse();\n typedResponse.log = eventValues.getLog();\n typedResponse.pubAddress = (String) eventValues.getIndexedValues().get(0).getValue();\n responses.add(typedResponse);\n }\n return responses;\n }\n\n public Flowable<RemoveSubscriptionEventResponse> removeSubscriptionEventFlowable(EthFilter filter) {\n return web3j.ethLogFlowable(filter).map(new Function<Log, RemoveSubscriptionEventResponse>() {\n @Override\n public RemoveSubscriptionEventResponse apply(Log log) {\n EventValuesWithLog eventValues = extractEventParametersWithLog(REMOVESUBSCRIPTION_EVENT, log);\n RemoveSubscriptionEventResponse typedResponse = new RemoveSubscriptionEventResponse();\n typedResponse.log = log;\n typedResponse.pubAddress = (String) eventValues.getIndexedValues().get(0).getValue();\n return typedResponse;\n }\n });\n }\n\n public Flowable<RemoveSubscriptionEventResponse> removeSubscriptionEventFlowable(DefaultBlockParameter startBlock, DefaultBlockParameter endBlock) {\n EthFilter filter = new EthFilter(startBlock, endBlock, getContractAddress());\n filter.addSingleTopic(EventEncoder.encode(REMOVESUBSCRIPTION_EVENT));\n return removeSubscriptionEventFlowable(filter);\n }\n\n public RemoteFunctionCall<List> getReactions() {\n final org.web3j.abi.datatypes.Function function = new org.web3j.abi.datatypes.Function(FUNC_GETREACTIONS, \n Arrays.<Type>asList(), \n Arrays.<TypeReference<?>>asList(new TypeReference<DynamicArray<Reaction>>() {}));\n return new RemoteFunctionCall<List>(function,\n new Callable<List>() {\n @Override\n @SuppressWarnings(\"unchecked\")\n public List call() throws Exception {\n List<Type> result = (List<Type>) executeCallSingleValueReturn(function, List.class);\n return convertToNative(result);\n }\n });\n }\n\n public RemoteFunctionCall<List> getSubscriptions() {\n final org.web3j.abi.datatypes.Function function = new org.web3j.abi.datatypes.Function(FUNC_GETSUBSCRIPTIONS, \n Arrays.<Type>asList(), \n Arrays.<TypeReference<?>>asList(new TypeReference<DynamicArray<Subscription>>() {}));\n return new RemoteFunctionCall<List>(function,\n new Callable<List>() {\n @Override\n @SuppressWarnings(\"unchecked\")\n public List call() throws Exception {\n List<Type> result = (List<Type>) executeCallSingleValueReturn(function, List.class);\n return convertToNative(result);\n }\n });\n }\n\n public RemoteFunctionCall<String> owner() {\n final org.web3j.abi.datatypes.Function function = new org.web3j.abi.datatypes.Function(FUNC_OWNER, \n Arrays.<Type>asList(), \n Arrays.<TypeReference<?>>asList(new TypeReference<Address>() {}));\n return executeRemoteCallSingleValueReturn(function, String.class);\n }\n\n public RemoteFunctionCall<TransactionReceipt> react(String pubAddr, BigInteger pubItemNum, BigInteger rating) {\n final org.web3j.abi.datatypes.Function function = new org.web3j.abi.datatypes.Function(\n FUNC_REACT, \n Arrays.<Type>asList(new Address(160, pubAddr),\n new Uint256(pubItemNum),\n new Uint8(rating)),\n Collections.<TypeReference<?>>emptyList());\n return executeRemoteCallTransaction(function);\n }\n\n public RemoteFunctionCall<TransactionReceipt> setOwner(String _newOwner) {\n final org.web3j.abi.datatypes.Function function = new org.web3j.abi.datatypes.Function(\n FUNC_SETOWNER, \n Arrays.<Type>asList(new Address(160, _newOwner)),\n Collections.<TypeReference<?>>emptyList());\n return executeRemoteCallTransaction(function);\n }\n\n public RemoteFunctionCall<TransactionReceipt> subscribe(String pubAddr) {\n final org.web3j.abi.datatypes.Function function = new org.web3j.abi.datatypes.Function(\n FUNC_SUBSCRIBE, \n Arrays.<Type>asList(new Address(160, pubAddr)),\n Collections.<TypeReference<?>>emptyList());\n return executeRemoteCallTransaction(function);\n }\n\n public RemoteFunctionCall<TransactionReceipt> unreact(String pubAddr, BigInteger pubItemNum) {\n final org.web3j.abi.datatypes.Function function = new org.web3j.abi.datatypes.Function(\n FUNC_UNREACT, \n Arrays.<Type>asList(new Address(160, pubAddr),\n new Uint256(pubItemNum)),\n Collections.<TypeReference<?>>emptyList());\n return executeRemoteCallTransaction(function);\n }\n\n public RemoteFunctionCall<TransactionReceipt> unsubscribe(String pubAddr) {\n final org.web3j.abi.datatypes.Function function = new org.web3j.abi.datatypes.Function(\n FUNC_UNSUBSCRIBE, \n Arrays.<Type>asList(new Address(160, pubAddr)),\n Collections.<TypeReference<?>>emptyList());\n return executeRemoteCallTransaction(function);\n }\n\n @Deprecated\n public static FeedSubscriber load(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) {\n return new FeedSubscriber(contractAddress, web3j, credentials, gasPrice, gasLimit);\n }\n\n @Deprecated\n public static FeedSubscriber load(String contractAddress, Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) {\n return new FeedSubscriber(contractAddress, web3j, transactionManager, gasPrice, gasLimit);\n }\n\n public static FeedSubscriber load(String contractAddress, Web3j web3j, Credentials credentials, ContractGasProvider contractGasProvider) {\n return new FeedSubscriber(contractAddress, web3j, credentials, contractGasProvider);\n }\n\n public static FeedSubscriber load(String contractAddress, Web3j web3j, TransactionManager transactionManager, ContractGasProvider contractGasProvider) {\n return new FeedSubscriber(contractAddress, web3j, transactionManager, contractGasProvider);\n }\n\n public static class Reaction extends StaticStruct {\n public String pubAddress;\n\n public BigInteger pubItemNum;\n\n public BigInteger rating;\n\n public BigInteger timestamp;\n\n public Reaction(String pubAddress, BigInteger pubItemNum, BigInteger rating, BigInteger timestamp) {\n super(new Address(160, pubAddress),\n new Uint256(pubItemNum),\n new Uint8(rating),\n new Uint256(timestamp));\n this.pubAddress = pubAddress;\n this.pubItemNum = pubItemNum;\n this.rating = rating;\n this.timestamp = timestamp;\n }\n\n public Reaction(Address pubAddress, Uint256 pubItemNum, Uint8 rating, Uint256 timestamp) {\n super(pubAddress, pubItemNum, rating, timestamp);\n this.pubAddress = pubAddress.getValue();\n this.pubItemNum = pubItemNum.getValue();\n this.rating = rating.getValue();\n this.timestamp = timestamp.getValue();\n }\n }\n\n public static class Subscription extends StaticStruct {\n public String pubAddress;\n\n public BigInteger timestamp;\n\n public Subscription(String pubAddress, BigInteger timestamp) {\n super(new Address(160, pubAddress),\n new Uint256(timestamp));\n this.pubAddress = pubAddress;\n this.timestamp = timestamp;\n }\n\n public Subscription(Address pubAddress, Uint256 timestamp) {\n super(pubAddress, timestamp);\n this.pubAddress = pubAddress.getValue();\n this.timestamp = timestamp.getValue();\n }\n }\n\n public static class CreateReactionEventResponse extends BaseEventResponse {\n public String pubAddress;\n\n public BigInteger _pubItemNum;\n }\n\n public static class CreateSubscriptionEventResponse extends BaseEventResponse {\n public String pubAddress;\n }\n\n public static class RemoveReactionEventResponse extends BaseEventResponse {\n public String pubAddress;\n\n public BigInteger _pubItemNum;\n }\n\n public static class RemoveSubscriptionEventResponse extends BaseEventResponse {\n public String pubAddress;\n }\n}" }, { "identifier": "Subscriber", "path": "apps/feed-aggregator/src/main/java/com/moonstoneid/aerocast/aggregator/model/Subscriber.java", "snippet": "@Data\n@Entity\n@Table(name = \"subscriber\")\npublic class Subscriber implements Serializable {\n\n @Id\n @Column(name = \"account_address\", length = 42, nullable = false)\n private String accountAddress;\n\n @Column(name = \"contract_address\", length = 42, nullable = false)\n private String contractAddress;\n\n @Column(name = \"block_number\", length = 42, nullable = false)\n private String blockNumber;\n\n}" }, { "identifier": "Subscription", "path": "apps/feed-aggregator/src/main/java/com/moonstoneid/aerocast/aggregator/model/Subscription.java", "snippet": "@Data\n@Entity\n@Table(name = \"subscription\")\n@IdClass(Subscription.SubscriptionId.class)\npublic class Subscription implements Serializable {\n\n @Id\n @Column(name = \"sub_contract_address\", length = 42, nullable = false)\n private String subContractAddress;\n\n @Id\n @Column(name = \"pub_contract_address\", length = 42, nullable = false)\n private String pubContractAddress;\n\n @Data\n @NoArgsConstructor\n @AllArgsConstructor\n public static class SubscriptionId implements Serializable {\n\n private String subContractAddress;\n private String pubContractAddress;\n\n }\n\n}" }, { "identifier": "SubscriberRepo", "path": "apps/feed-aggregator/src/main/java/com/moonstoneid/aerocast/aggregator/repo/SubscriberRepo.java", "snippet": "@Repository\npublic interface SubscriberRepo extends JpaRepository<Subscriber, String> {\n\n @Modifying\n @Transactional\n @Query(\"UPDATE Subscriber s \" +\n \"SET s.blockNumber = :blockNumber \" +\n \"WHERE s.contractAddress = :contractAddr\")\n void updateSubscriberBlockNumber(String contractAddr, String blockNumber);\n\n}" }, { "identifier": "SubscriptionRepo", "path": "apps/feed-aggregator/src/main/java/com/moonstoneid/aerocast/aggregator/repo/SubscriptionRepo.java", "snippet": "@Repository\npublic interface SubscriptionRepo extends JpaRepository<Subscription, String> {\n\n @Query(\"SELECT CASE WHEN COUNT(s) > 0 THEN TRUE ELSE FALSE END \" +\n \"FROM Subscription s \" +\n \"WHERE s.pubContractAddress IN (\" +\n \"SELECT p.contractAddress \" +\n \"FROM Publisher p \" +\n \"WHERE p.contractAddress = :pubContractAddr)\")\n boolean existsByPublisherContractAddress(String pubContractAddr);\n\n @Modifying\n @Transactional\n @Query(\"DELETE \" +\n \"FROM Subscription s \" +\n \"WHERE s.subContractAddress = :subContractAddr \" +\n \"AND s.pubContractAddress = :pubContractAddr\")\n void deleteById(String subContractAddr, String pubContractAddr);\n\n\n @Query(\"SELECT s \" +\n \"FROM Subscription s \" +\n \"WHERE s.pubContractAddress = :pubContractAddr\")\n List<Subscription> findAllByPublisherContractAddress(String pubContractAddr);\n\n}" } ]
import java.util.ArrayList; import java.util.List; import java.util.Optional; import com.moonstoneid.aerocast.aggregator.error.ConflictException; import com.moonstoneid.aerocast.aggregator.error.NotFoundException; import com.moonstoneid.aerocast.aggregator.eth.EthSubscriberAdapter; import com.moonstoneid.aerocast.common.eth.EthUtil; import com.moonstoneid.aerocast.common.eth.contracts.FeedSubscriber; import com.moonstoneid.aerocast.aggregator.model.Subscriber; import com.moonstoneid.aerocast.aggregator.model.Subscription; import com.moonstoneid.aerocast.aggregator.repo.SubscriberRepo; import com.moonstoneid.aerocast.aggregator.repo.SubscriptionRepo; import lombok.extern.slf4j.Slf4j; import org.springframework.boot.context.event.ApplicationReadyEvent; import org.springframework.stereotype.Service;
10,257
package com.moonstoneid.aerocast.aggregator.service; @Service @Slf4j public class SubscriberService implements EthSubscriberAdapter.EventCallback { public interface EventListener { void onSubscriptionChange(String subContractAddr); } private final SubscriberRepo subscriberRepo; private final SubscriptionRepo subscriptionRepo; private final PublisherService publisherService; private final EthSubscriberAdapter ethSubscriberAdapter; private final List<EventListener> eventListeners = new ArrayList<>(); public SubscriberService(SubscriberRepo subscriberRepo, SubscriptionRepo subscriptionRepo, PublisherService publisherService, EthSubscriberAdapter ethSubscriberAdapter) { this.subscriberRepo = subscriberRepo; this.subscriptionRepo = subscriptionRepo; this.publisherService = publisherService; this.ethSubscriberAdapter = ethSubscriberAdapter; } public void registerEventListener(EventListener listener) { eventListeners.add(listener); } public void unregisterEventListener(EventListener listener) { eventListeners.remove(listener); } // Register listeners after Spring Boot has started @org.springframework.context.event.EventListener(ApplicationReadyEvent.class) public void initEventListener() { getSubscribers().forEach(s -> ethSubscriberAdapter.registerSubscriptionEventListener( s.getContractAddress(), s.getBlockNumber(), this)); } @Override public void onCreateSubscription(String subContractAddr, String blockNumber, String pubContractAddr) { String contractAddr = subContractAddr.toLowerCase(); updateSubscriberEventBlockNumber(contractAddr, blockNumber); createSubscription(contractAddr, pubContractAddr); eventListeners.forEach(l -> l.onSubscriptionChange(subContractAddr)); } @Override public void onRemoveSubscription(String subContractAddr, String blockNumber, String pubContractAddr) { String contractAddr = subContractAddr.toLowerCase(); updateSubscriberEventBlockNumber(contractAddr, blockNumber); removeSubscription(contractAddr, pubContractAddr); eventListeners.forEach(l -> l.onSubscriptionChange(subContractAddr)); } public List<Subscriber> getSubscribers() { return subscriberRepo.findAll(); } private Optional<Subscriber> findSubscriber(String subAccountAddr) { String accountAddr = subAccountAddr.toLowerCase(); return subscriberRepo.findById(accountAddr); } public Subscriber getSubscriber(String subAccountAddr) { Optional<Subscriber> subscriber = findSubscriber(subAccountAddr); return subscriber .orElseThrow(() -> new NotFoundException("Subscriber was not found!")); } public void createSubscriber(String subAccountAddr) { String accountAddr = subAccountAddr.toLowerCase(); log.info("Trying to create subscriber '{}' ...", EthUtil.shortenAddress(accountAddr)); String currentBlockNum = ethSubscriberAdapter.getCurrentBlockNumber(); // Check if subscriber exists if (subscriberRepo.existsById(accountAddr)) { log.error("Subscriber '{}' already exists!", EthUtil.shortenAddress(subAccountAddr)); throw new ConflictException("Subscriber already exists!"); } // Get subscriber contract address String contractAddr = ethSubscriberAdapter.getSubscriberContractAddress(accountAddr); if (contractAddr == null) { log.error("Contract for subscriber '{}' was not found!", EthUtil.shortenAddress( accountAddr)); throw new NotFoundException("Subscriber was not found!"); } // Create subscriber Subscriber sub = new Subscriber(); sub.setAccountAddress(accountAddr); sub.setContractAddress(contractAddr); sub.setBlockNumber(currentBlockNum); subscriberRepo.save(sub); // Create subscriptions createSubscriptions(contractAddr, ethSubscriberAdapter.getSubscriberSubscriptions( contractAddr)); // Register subscriber event listener ethSubscriberAdapter.registerSubscriptionEventListener(contractAddr, currentBlockNum, this); log.info("Subscriber '{}' has been created.", EthUtil.shortenAddress(accountAddr)); } public void removeSubscriber(String subAccountAddr) { String accountAddr = subAccountAddr.toLowerCase(); log.info("Trying to remove subscriber '{}' ...", EthUtil.shortenAddress(accountAddr)); // Check if subscriber exists Optional<Subscriber> sub = findSubscriber(accountAddr); if (sub.isEmpty()) { log.error("Subscriber '{}' was not found!", EthUtil.shortenAddress(accountAddr)); return; } String subContractAddr = sub.get().getContractAddress(); // Unregister subscriber event listener ethSubscriberAdapter.unregisterSubscriptionEventListener(subContractAddr); // Remove subscriber subscriberRepo.deleteById(accountAddr); // Cleanup publishers publisherService.cleanupPublishers(); log.info("Subscriber '{}' has been removed.", EthUtil.shortenAddress(accountAddr)); } private void createSubscriptions(String subContractAddr,
package com.moonstoneid.aerocast.aggregator.service; @Service @Slf4j public class SubscriberService implements EthSubscriberAdapter.EventCallback { public interface EventListener { void onSubscriptionChange(String subContractAddr); } private final SubscriberRepo subscriberRepo; private final SubscriptionRepo subscriptionRepo; private final PublisherService publisherService; private final EthSubscriberAdapter ethSubscriberAdapter; private final List<EventListener> eventListeners = new ArrayList<>(); public SubscriberService(SubscriberRepo subscriberRepo, SubscriptionRepo subscriptionRepo, PublisherService publisherService, EthSubscriberAdapter ethSubscriberAdapter) { this.subscriberRepo = subscriberRepo; this.subscriptionRepo = subscriptionRepo; this.publisherService = publisherService; this.ethSubscriberAdapter = ethSubscriberAdapter; } public void registerEventListener(EventListener listener) { eventListeners.add(listener); } public void unregisterEventListener(EventListener listener) { eventListeners.remove(listener); } // Register listeners after Spring Boot has started @org.springframework.context.event.EventListener(ApplicationReadyEvent.class) public void initEventListener() { getSubscribers().forEach(s -> ethSubscriberAdapter.registerSubscriptionEventListener( s.getContractAddress(), s.getBlockNumber(), this)); } @Override public void onCreateSubscription(String subContractAddr, String blockNumber, String pubContractAddr) { String contractAddr = subContractAddr.toLowerCase(); updateSubscriberEventBlockNumber(contractAddr, blockNumber); createSubscription(contractAddr, pubContractAddr); eventListeners.forEach(l -> l.onSubscriptionChange(subContractAddr)); } @Override public void onRemoveSubscription(String subContractAddr, String blockNumber, String pubContractAddr) { String contractAddr = subContractAddr.toLowerCase(); updateSubscriberEventBlockNumber(contractAddr, blockNumber); removeSubscription(contractAddr, pubContractAddr); eventListeners.forEach(l -> l.onSubscriptionChange(subContractAddr)); } public List<Subscriber> getSubscribers() { return subscriberRepo.findAll(); } private Optional<Subscriber> findSubscriber(String subAccountAddr) { String accountAddr = subAccountAddr.toLowerCase(); return subscriberRepo.findById(accountAddr); } public Subscriber getSubscriber(String subAccountAddr) { Optional<Subscriber> subscriber = findSubscriber(subAccountAddr); return subscriber .orElseThrow(() -> new NotFoundException("Subscriber was not found!")); } public void createSubscriber(String subAccountAddr) { String accountAddr = subAccountAddr.toLowerCase(); log.info("Trying to create subscriber '{}' ...", EthUtil.shortenAddress(accountAddr)); String currentBlockNum = ethSubscriberAdapter.getCurrentBlockNumber(); // Check if subscriber exists if (subscriberRepo.existsById(accountAddr)) { log.error("Subscriber '{}' already exists!", EthUtil.shortenAddress(subAccountAddr)); throw new ConflictException("Subscriber already exists!"); } // Get subscriber contract address String contractAddr = ethSubscriberAdapter.getSubscriberContractAddress(accountAddr); if (contractAddr == null) { log.error("Contract for subscriber '{}' was not found!", EthUtil.shortenAddress( accountAddr)); throw new NotFoundException("Subscriber was not found!"); } // Create subscriber Subscriber sub = new Subscriber(); sub.setAccountAddress(accountAddr); sub.setContractAddress(contractAddr); sub.setBlockNumber(currentBlockNum); subscriberRepo.save(sub); // Create subscriptions createSubscriptions(contractAddr, ethSubscriberAdapter.getSubscriberSubscriptions( contractAddr)); // Register subscriber event listener ethSubscriberAdapter.registerSubscriptionEventListener(contractAddr, currentBlockNum, this); log.info("Subscriber '{}' has been created.", EthUtil.shortenAddress(accountAddr)); } public void removeSubscriber(String subAccountAddr) { String accountAddr = subAccountAddr.toLowerCase(); log.info("Trying to remove subscriber '{}' ...", EthUtil.shortenAddress(accountAddr)); // Check if subscriber exists Optional<Subscriber> sub = findSubscriber(accountAddr); if (sub.isEmpty()) { log.error("Subscriber '{}' was not found!", EthUtil.shortenAddress(accountAddr)); return; } String subContractAddr = sub.get().getContractAddress(); // Unregister subscriber event listener ethSubscriberAdapter.unregisterSubscriptionEventListener(subContractAddr); // Remove subscriber subscriberRepo.deleteById(accountAddr); // Cleanup publishers publisherService.cleanupPublishers(); log.info("Subscriber '{}' has been removed.", EthUtil.shortenAddress(accountAddr)); } private void createSubscriptions(String subContractAddr,
List<FeedSubscriber.Subscription> feedSubs) {
4
2023-10-23 20:33:07+00:00
12k
UnityFoundation-io/Libre311
app/src/main/java/app/service/servicerequest/ServiceRequestService.java
[ { "identifier": "DownloadRequestsArgumentsDTO", "path": "app/src/main/java/app/dto/download/DownloadRequestsArgumentsDTO.java", "snippet": "@Introspected\npublic class DownloadRequestsArgumentsDTO {\n\n @Nullable\n @QueryValue(value = \"jurisdiction_id\")\n private String jurisdictionId;\n\n @Nullable\n @QueryValue(value = \"service_name\")\n private String serviceName;\n\n @Nullable\n @QueryValue(value = \"start_date\")\n private Instant startDate;\n\n @Nullable\n @QueryValue(value = \"end_date\")\n private Instant endDate;\n\n @Nullable\n @QueryValue\n private ServiceRequestStatus status;\n\n\n public DownloadRequestsArgumentsDTO() {\n }\n\n @Nullable\n public String getServiceName() {\n return serviceName;\n }\n\n public void setServiceName(@Nullable String serviceName) {\n this.serviceName = serviceName;\n }\n\n @Nullable\n public Instant getStartDate() {\n return startDate;\n }\n\n public void setStartDate(@Nullable Instant startDate) {\n this.startDate = startDate;\n }\n\n @Nullable\n public Instant getEndDate() {\n return endDate;\n }\n\n public void setEndDate(@Nullable Instant endDate) {\n this.endDate = endDate;\n }\n\n @Nullable\n public ServiceRequestStatus getStatus() {\n return status;\n }\n\n public void setStatus(@Nullable ServiceRequestStatus status) {\n this.status = status;\n }\n\n @Nullable\n public String getJurisdictionId() {\n return jurisdictionId;\n }\n\n public void setJurisdictionId(@Nullable String jurisdictionId) {\n this.jurisdictionId = jurisdictionId;\n }\n}" }, { "identifier": "DownloadServiceRequestDTO", "path": "app/src/main/java/app/dto/download/DownloadServiceRequestDTO.java", "snippet": "@Introspected\npublic class DownloadServiceRequestDTO {\n\n @CsvBindByName(column = \"service_request_id\")\n private Long id;\n\n @CsvBindByName(column = \"jurisdiction_id\")\n private String jurisdictionId;\n\n @CsvDate(value = \"yyyy-MM-dd'T'HH:mm'Z'\")\n @CsvBindByName(column = \"requested_datetime\")\n private Instant dateCreated;\n\n @CsvDate(value = \"yyyy-MM-dd'T'HH:mm'Z'\")\n @CsvBindByName(column = \"updated_datetime\")\n private Instant dateUpdated;\n\n @CsvDate(value = \"yyyy-MM-dd'T'HH:mm'Z'\")\n @CsvBindByName(column = \"closed_datetime\")\n private Instant closedDate;\n\n @CsvBindByName(column = \"status_description\")\n private String statusDescription;\n\n @CsvBindByName(column = \"status_notes\")\n private String statusNotes;\n\n @CsvBindByName(column = \"service_name\")\n private String serviceName;\n\n @CsvBindByName\n private String description;\n\n @CsvBindByName(column = \"agency_responsible\")\n private String agencyResponsible;\n\n @CsvBindByName\n private String address;\n\n @CsvBindByName(column = \"lat\")\n private String latitude;\n\n @CsvBindByName(column = \"long\")\n private String longitude;\n\n @CsvBindByName(column = \"service_subtype\")\n private String serviceSubtype;\n\n @CsvBindByName\n private String email;\n\n @CsvBindByName(column = \"first_name\")\n private String firstName;\n\n @CsvBindByName(column = \"last_name\")\n private String lastName;\n\n @CsvBindByName\n private String phone;\n\n @CsvBindByName(column = \"media_url\")\n private String mediaUrl;\n\n public DownloadServiceRequestDTO(ServiceRequest serviceRequest) {\n this.id = serviceRequest.getId();\n this.dateCreated = serviceRequest.getDateCreated();\n this.dateUpdated = serviceRequest.getDateUpdated();\n this.closedDate = serviceRequest.getClosedDate();\n this.statusDescription = sanitize(serviceRequest.getStatus().toString());\n this.statusNotes = sanitize(serviceRequest.getStatusNotes());\n this.serviceName = sanitize(serviceRequest.getService().getServiceName());\n this.description = sanitize(serviceRequest.getDescription());\n this.agencyResponsible = sanitize(serviceRequest.getAgencyResponsible());\n this.address = sanitize(serviceRequest.getAddressString());\n this.latitude = sanitize(serviceRequest.getLatitude());\n this.longitude = sanitize(serviceRequest.getLongitude());\n this.email = sanitize(serviceRequest.getEmail());\n this.firstName = sanitize(serviceRequest.getFirstName());\n this.lastName = sanitize(serviceRequest.getLastName());\n this.phone = sanitize(serviceRequest.getPhone());\n this.mediaUrl = sanitize(serviceRequest.getMediaUrl());\n if (serviceRequest.getJurisdiction() != null) {\n this.jurisdictionId = serviceRequest.getJurisdiction().getId();\n }\n }\n\n public Long getId() {\n return id;\n }\n\n public void setId(Long id) {\n this.id = id;\n }\n\n public String getJurisdictionId() {\n return jurisdictionId;\n }\n\n public void setJurisdictionId(String jurisdictionId) {\n this.jurisdictionId = jurisdictionId;\n }\n\n public String getStatusNotes() {\n return statusNotes;\n }\n\n public void setStatusNotes(String statusNotes) {\n this.statusNotes = statusNotes;\n }\n\n public String getServiceName() {\n return serviceName;\n }\n\n public void setServiceName(String serviceName) {\n this.serviceName = serviceName;\n }\n\n public String getDescription() {\n return description;\n }\n\n public void setDescription(String description) {\n this.description = description;\n }\n\n public String getAgencyResponsible() {\n return agencyResponsible;\n }\n\n public void setAgencyResponsible(String agencyResponsible) {\n this.agencyResponsible = agencyResponsible;\n }\n\n public Instant getDateCreated() {\n return dateCreated;\n }\n\n public void setDateCreated(Instant dateCreated) {\n this.dateCreated = dateCreated;\n }\n\n public Instant getDateUpdated() {\n return dateUpdated;\n }\n\n public void setDateUpdated(Instant dateUpdated) {\n this.dateUpdated = dateUpdated;\n }\n\n public String getAddress() {\n return address;\n }\n\n public void setAddress(String address) {\n this.address = address;\n }\n\n public String getLatitude() {\n return latitude;\n }\n\n public void setLatitude(String latitude) {\n this.latitude = latitude;\n }\n\n public String getLongitude() {\n return longitude;\n }\n\n public void setLongitude(String longitude) {\n this.longitude = longitude;\n }\n\n public String getStatusDescription() {\n return statusDescription;\n }\n\n public void setStatusDescription(String statusDescription) {\n this.statusDescription = statusDescription;\n }\n\n public Instant getClosedDate() {\n return closedDate;\n }\n\n public void setClosedDate(Instant closedDate) {\n this.closedDate = closedDate;\n }\n\n public String getEmail() {\n return email;\n }\n\n public void setEmail(String email) {\n this.email = email;\n }\n\n public String getFirstName() {\n return firstName;\n }\n\n public void setFirstName(String firstName) {\n this.firstName = firstName;\n }\n\n public String getLastName() {\n return lastName;\n }\n\n public void setLastName(String lastName) {\n this.lastName = lastName;\n }\n\n public String getPhone() {\n return phone;\n }\n\n public void setPhone(String phone) {\n this.phone = phone;\n }\n\n public String getMediaUrl() {\n return mediaUrl;\n }\n\n public void setMediaUrl(String mediaUrl) {\n this.mediaUrl = mediaUrl;\n }\n\n public String getServiceSubtype() {\n return serviceSubtype;\n }\n\n public void setServiceSubtype(String serviceSubtype) {\n this.serviceSubtype = serviceSubtype;\n }\n\n private String sanitize(String value) {\n String csvInjectionRegex = \"^[=@+\\\\-\\t\\r].*\";\n\n if (value == null || !value.matches(csvInjectionRegex))\n return value;\n\n return \"'\" + value;\n }\n}" }, { "identifier": "Service", "path": "app/src/main/java/app/model/service/Service.java", "snippet": "@Entity\n@Table(name = \"services\")\npublic class Service {\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long id;\n\n @Column(unique = true)\n private String serviceCode;\n\n @ManyToOne\n @JoinColumn(name = \"jurisdiction_id\")\n private Jurisdiction jurisdiction;\n\n @Column(columnDefinition = \"TEXT\")\n private String serviceDefinitionJson;\n\n @Column(nullable = false, columnDefinition = \"TEXT\")\n private String serviceName;\n\n @Column(columnDefinition = \"TEXT\")\n private String description;\n\n private boolean metadata = false;\n\n @Enumerated(value = EnumType.STRING)\n private ServiceType type = ServiceType.REALTIME;\n\n @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, orphanRemoval = true, mappedBy = \"service\")\n @OnDelete(action = OnDeleteAction.CASCADE)\n private List<ServiceRequest> serviceRequests = new ArrayList<>();\n\n\n public Service(String serviceName) {\n this.serviceName = serviceName;\n }\n\n public Service() {}\n\n public String getServiceCode() {\n return serviceCode;\n }\n\n public void setServiceCode(String serviceCode) {\n this.serviceCode = serviceCode;\n }\n\n public Jurisdiction getJurisdiction() {\n return jurisdiction;\n }\n\n public void setJurisdiction(Jurisdiction jurisdiction) {\n this.jurisdiction = jurisdiction;\n }\n\n public String getServiceName() {\n return serviceName;\n }\n\n public void setServiceName(String serviceName) {\n this.serviceName = serviceName;\n }\n\n public String getDescription() {\n return description;\n }\n\n public void setDescription(String description) {\n this.description = description;\n }\n\n public boolean isMetadata() {\n return metadata;\n }\n\n public void setMetadata(boolean metadata) {\n this.metadata = metadata;\n }\n\n public ServiceType getType() {\n return type;\n }\n\n public void setType(ServiceType type) {\n this.type = type;\n }\n\n public String getServiceDefinitionJson() {\n return serviceDefinitionJson;\n }\n\n public void setServiceDefinitionJson(String serviceDefinitionJson) {\n this.serviceDefinitionJson = serviceDefinitionJson;\n }\n\n public Long getId() {\n return id;\n }\n\n public void setId(Long id) {\n this.id = id;\n }\n\n public List<ServiceRequest> getServiceRequests() {\n return serviceRequests;\n }\n\n public void setServiceRequests(List<ServiceRequest> serviceRequests) {\n this.serviceRequests = serviceRequests;\n }\n\n public void addServiceRequest(ServiceRequest serviceRequest) {\n serviceRequests.add(serviceRequest);\n }\n}" }, { "identifier": "ServiceRepository", "path": "app/src/main/java/app/model/service/ServiceRepository.java", "snippet": "@Repository\npublic interface ServiceRepository extends PageableRepository<Service, Long> {\n Optional<Service> findByServiceCode(String serviceCode);\n\n Page<Service> findAllByJurisdictionId(String jurisdictionId, Pageable pageable);\n\n Optional<Service> findByServiceCodeAndJurisdictionId(String serviceCode, String jurisdictionId);\n}" }, { "identifier": "AttributeDataType", "path": "app/src/main/java/app/model/service/servicedefinition/AttributeDataType.java", "snippet": "public enum AttributeDataType {\n STRING, NUMBER, DATETIME, TEXT, SINGLEVALUELIST, MULTIVALUELIST;\n\n @Override\n @JsonValue\n public String toString() {\n return name().toLowerCase();\n }\n}" }, { "identifier": "AttributeValue", "path": "app/src/main/java/app/model/service/servicedefinition/AttributeValue.java", "snippet": "@Introspected\npublic class AttributeValue {\n private String key;\n private String name;\n\n public AttributeValue() {\n }\n\n public AttributeValue(String key, String name) {\n this.key = key;\n this.name = name;\n }\n\n public String getKey() {\n return key;\n }\n\n public void setKey(String key) {\n this.key = key;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n}" }, { "identifier": "ServiceDefinition", "path": "app/src/main/java/app/model/service/servicedefinition/ServiceDefinition.java", "snippet": "@Introspected\n@JacksonXmlRootElement(localName = \"service_definitions\")\npublic class ServiceDefinition {\n\n @JsonProperty(\"service_code\")\n private String serviceCode;\n\n @JacksonXmlElementWrapper(localName = \"attributes\")\n @JacksonXmlProperty(localName = \"attribute\")\n private List<ServiceDefinitionAttribute> attributes;\n\n public ServiceDefinition() {\n }\n\n public List<ServiceDefinitionAttribute> getAttributes() {\n return attributes;\n }\n\n public void setAttributes(List<ServiceDefinitionAttribute> attributes) {\n this.attributes = attributes;\n }\n\n public String getServiceCode() {\n return serviceCode;\n }\n\n public void setServiceCode(String serviceCode) {\n this.serviceCode = serviceCode;\n }\n}" }, { "identifier": "ServiceDefinitionAttribute", "path": "app/src/main/java/app/model/service/servicedefinition/ServiceDefinitionAttribute.java", "snippet": "@Introspected\npublic class ServiceDefinitionAttribute {\n\n private String code;\n private boolean variable;\n private AttributeDataType datatype;\n private boolean required;\n private String description;\n\n @JsonProperty(\"order\")\n private int attributeOrder;\n\n @JsonProperty(\"datatype_description\")\n private String datatypeDescription;\n\n @JacksonXmlElementWrapper(localName = \"values\")\n @JacksonXmlProperty(localName = \"value\")\n private List<AttributeValue> values;\n\n public ServiceDefinitionAttribute() {\n }\n\n public boolean isVariable() {\n return variable;\n }\n\n public void setVariable(boolean variable) {\n this.variable = variable;\n }\n\n public AttributeDataType getDatatype() {\n return datatype;\n }\n\n public void setDatatype(AttributeDataType datatype) {\n this.datatype = datatype;\n }\n\n public boolean isRequired() {\n return required;\n }\n\n public void setRequired(boolean required) {\n this.required = required;\n }\n\n public String getDatatypeDescription() {\n return datatypeDescription;\n }\n\n public void setDatatypeDescription(String datatypeDescription) {\n this.datatypeDescription = datatypeDescription;\n }\n\n public int getAttributeOrder() {\n return attributeOrder;\n }\n\n public void setAttributeOrder(int attributeOrder) {\n this.attributeOrder = attributeOrder;\n }\n\n public String getDescription() {\n return description;\n }\n\n public void setDescription(String description) {\n this.description = description;\n }\n\n public List<AttributeValue> getValues() {\n return values;\n }\n\n public void setValues(List<AttributeValue> values) {\n this.values = values;\n }\n\n public String getCode() {\n return code;\n }\n\n public void setCode(String code) {\n this.code = code;\n }\n}" }, { "identifier": "ServiceRequest", "path": "app/src/main/java/app/model/servicerequest/ServiceRequest.java", "snippet": "@Entity\n@Table(name = \"service_requests\")\npublic class ServiceRequest {\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n private Long id;\n\n @ManyToOne\n @JoinColumn(name = \"services_id\", nullable = false)\n private Service service;\n\n @ManyToOne\n @JoinColumn(name = \"jurisdiction_id\")\n private Jurisdiction jurisdiction;\n\n @Nullable\n @Column(columnDefinition = \"TEXT\")\n private String attributesJson;\n\n // optional\n\n @Nullable\n private String latitude;\n\n @Nullable\n private String longitude;\n\n @Nullable\n private String addressString;\n\n // The internal address ID used by a jurisdiction’s master address repository or other addressing system.\n @Nullable\n private String addressId;\n\n @Nullable\n @Email(regexp = \"^[a-zA-Z0-9_+&*-]+(?:\\\\.[a-zA-Z0-9_+&*-]+)*@(?:[a-zA-Z0-9-]+\\\\.)+[a-zA-Z]{2,7}$\")\n private String email;\n\n // The unique device ID of the device submitting the request. This is usually only used for mobile devices.\n @Nullable\n private String deviceId;\n\n // The unique ID for the user account of the person submitting the request\n @Nullable\n private String accountId;\n\n @Nullable\n private String firstName;\n\n @Nullable\n private String lastName;\n\n @Nullable\n private String phone;\n\n @Nullable\n @Size(max = 4000)\n @Column(columnDefinition = \"TEXT\")\n private String description;\n\n @Nullable\n @Column(columnDefinition = \"TEXT\")\n private String mediaUrl;\n\n @Enumerated(EnumType.STRING)\n private ServiceRequestStatus status = ServiceRequestStatus.OPEN;\n\n @Nullable\n @Column(columnDefinition = \"TEXT\")\n private String statusNotes;\n\n @Nullable\n private String agencyResponsible;\n\n @Nullable\n private String serviceNotice;\n\n @Nullable\n @Pattern(regexp = \"^\\\\d{5}(?:[-\\\\s]\\\\d{4})?$\")\n private String zipCode;\n\n @Nullable\n private Instant expectedDate;\n\n @Nullable\n private Instant closedDate;\n\n @DateCreated\n private Instant dateCreated;\n\n @DateUpdated\n private Instant dateUpdated;\n\n public ServiceRequest() {\n }\n\n public void setId(Long id) {\n this.id = id;\n }\n\n public Long getId() {\n return id;\n }\n\n public Jurisdiction getJurisdiction() {\n return jurisdiction;\n }\n\n public void setJurisdiction(Jurisdiction jurisdiction) {\n this.jurisdiction = jurisdiction;\n }\n\n @Nullable\n public String getLatitude() {\n return latitude;\n }\n\n public void setLatitude(@Nullable String latitude) {\n this.latitude = latitude;\n }\n\n @Nullable\n public String getLongitude() {\n return longitude;\n }\n\n public void setLongitude(@Nullable String longitude) {\n this.longitude = longitude;\n }\n\n @Nullable\n public String getAddressString() {\n return addressString;\n }\n\n public void setAddressString(@Nullable String addressString) {\n this.addressString = addressString;\n }\n\n @Nullable\n public String getAddressId() {\n return addressId;\n }\n\n public void setAddressId(@Nullable String addressId) {\n this.addressId = addressId;\n }\n\n @Nullable\n public String getEmail() {\n return email;\n }\n\n public void setEmail(@Nullable String email) {\n this.email = email;\n }\n\n @Nullable\n public String getDeviceId() {\n return deviceId;\n }\n\n public void setDeviceId(@Nullable String deviceId) {\n this.deviceId = deviceId;\n }\n\n @Nullable\n public String getAccountId() {\n return accountId;\n }\n\n public void setAccountId(@Nullable String accountId) {\n this.accountId = accountId;\n }\n\n @Nullable\n public String getFirstName() {\n return firstName;\n }\n\n public void setFirstName(@Nullable String firstName) {\n this.firstName = firstName;\n }\n\n @Nullable\n public String getLastName() {\n return lastName;\n }\n\n public void setLastName(@Nullable String lastName) {\n this.lastName = lastName;\n }\n\n @Nullable\n public String getPhone() {\n return phone;\n }\n\n public void setPhone(@Nullable String phone) {\n this.phone = phone;\n }\n\n @Nullable\n public String getDescription() {\n return description;\n }\n\n public void setDescription(@Nullable String description) {\n this.description = description;\n }\n\n @Nullable\n public String getMediaUrl() {\n return mediaUrl;\n }\n\n public void setMediaUrl(@Nullable String mediaUrl) {\n this.mediaUrl = mediaUrl;\n }\n\n public ServiceRequestStatus getStatus() {\n return status;\n }\n\n public void setStatus(ServiceRequestStatus status) {\n this.status = status;\n }\n\n @Nullable\n public String getStatusNotes() {\n return statusNotes;\n }\n\n public void setStatusNotes(@Nullable String statusNotes) {\n this.statusNotes = statusNotes;\n }\n\n public Instant getDateCreated() {\n return dateCreated;\n }\n\n public void setDateCreated(Instant dateCreated) {\n this.dateCreated = dateCreated;\n }\n\n public Instant getDateUpdated() {\n return dateUpdated;\n }\n\n public void setDateUpdated(Instant dateUpdated) {\n this.dateUpdated = dateUpdated;\n }\n\n @Nullable\n public Instant getExpectedDate() {\n return expectedDate;\n }\n\n @Nullable\n public String getZipCode() {\n return zipCode;\n }\n\n public void setZipCode(@Nullable String zipCode) {\n this.zipCode = zipCode;\n }\n\n @Nullable\n public String getAgencyResponsible() {\n return agencyResponsible;\n }\n\n public void setAgencyResponsible(@Nullable String agencyResponsible) {\n this.agencyResponsible = agencyResponsible;\n }\n\n @Nullable\n public String getServiceNotice() {\n return serviceNotice;\n }\n\n public void setServiceNotice(@Nullable String serviceNotice) {\n this.serviceNotice = serviceNotice;\n }\n\n public Service getService() {\n return service;\n }\n\n public void setService(Service service) {\n this.service = service;\n }\n\n @Nullable\n public String getAttributesJson() {\n return attributesJson;\n }\n\n public void setAttributesJson(@Nullable String attributesJson) {\n this.attributesJson = attributesJson;\n }\n\n @Nullable\n public Instant getClosedDate() {\n return closedDate;\n }\n\n public void setClosedDate(@Nullable Instant closedDate) {\n this.closedDate = closedDate;\n }\n}" }, { "identifier": "ServiceRequestRepository", "path": "app/src/main/java/app/model/servicerequest/ServiceRequestRepository.java", "snippet": "@Repository\npublic interface ServiceRequestRepository extends PageableRepository<ServiceRequest, Long> {\n Page<ServiceRequest> findByIdIn(List<Long> serviceRequestIds, Pageable pageable);\n\n Page<ServiceRequest> findByServiceServiceCode(String serviceCode, Pageable pageable);\n List<ServiceRequest> findByServiceServiceCode(String serviceCode);\n Page<ServiceRequest> findByServiceServiceCodeAndDateCreatedBetween(String serviceCode, Instant start, Instant end, Pageable pageable);\n List<ServiceRequest> findByServiceServiceCodeAndDateCreatedBetween(String serviceCode, Instant start, Instant end);\n Page<ServiceRequest> findByServiceServiceCodeAndDateCreatedAfter(String serviceCode, Instant start, Pageable pageable);\n List<ServiceRequest> findByServiceServiceCodeAndDateCreatedAfter(String serviceCode, Instant start);\n Page<ServiceRequest> findByServiceServiceCodeAndDateCreatedBefore(String serviceCode, Instant end, Pageable pageable);\n List<ServiceRequest> findByServiceServiceCodeAndDateCreatedBefore(String serviceCode, Instant end);\n\n Page<ServiceRequest> findByStatus(ServiceRequestStatus status, Pageable pageable);\n List<ServiceRequest> findByStatus(ServiceRequestStatus status);\n Page<ServiceRequest> findByStatusAndDateCreatedBetween(ServiceRequestStatus status, Instant start, Instant end, Pageable pageable);\n List<ServiceRequest> findByStatusAndDateCreatedBetween(ServiceRequestStatus status, Instant start, Instant end);\n Page<ServiceRequest> findByStatusAndDateCreatedAfter(ServiceRequestStatus status, Instant start, Pageable pageable);\n List<ServiceRequest> findByStatusAndDateCreatedAfter(ServiceRequestStatus status, Instant start);\n Page<ServiceRequest> findByStatusAndDateCreatedBefore(ServiceRequestStatus status, Instant end, Pageable pageable);\n List<ServiceRequest> findByStatusAndDateCreatedBefore(ServiceRequestStatus status, Instant end);\n\n Page<ServiceRequest> findByServiceServiceCodeAndStatus(String serviceCode, ServiceRequestStatus status, Pageable pageable);\n List<ServiceRequest> findByServiceServiceCodeAndStatus(String serviceCode, ServiceRequestStatus status);\n Page<ServiceRequest> findByServiceServiceCodeAndStatusAndDateCreatedBetween(String serviceCode, ServiceRequestStatus status, Instant start, Instant end, Pageable pageable);\n List<ServiceRequest> findByServiceServiceCodeAndStatusAndDateCreatedBetween(String serviceCode, ServiceRequestStatus status, Instant start, Instant end);\n Page<ServiceRequest> findByServiceServiceCodeAndStatusAndDateCreatedAfter(String serviceCode, ServiceRequestStatus status, Instant start, Pageable pageable);\n List<ServiceRequest> findByServiceServiceCodeAndStatusAndDateCreatedAfter(String serviceCode, ServiceRequestStatus status, Instant start);\n Page<ServiceRequest> findByServiceServiceCodeAndStatusAndDateCreatedBefore(String serviceCode, ServiceRequestStatus status, Instant end, Pageable pageable);\n List<ServiceRequest> findByServiceServiceCodeAndStatusAndDateCreatedBefore(String serviceCode, ServiceRequestStatus status, Instant end);\n\n Page<ServiceRequest> findByDateCreatedBetween(Instant start, Instant end, Pageable pageable);\n List<ServiceRequest> findByDateCreatedBetween(Instant startDate, Instant endDate);\n Page<ServiceRequest> findByDateCreatedAfter(Instant start, Pageable pageable);\n List<ServiceRequest> findByDateCreatedAfter(Instant start);\n Page<ServiceRequest> findByDateCreatedBefore(Instant end, Pageable pageable);\n List<ServiceRequest> findByDateCreatedBefore(Instant end);\n\n Optional<ServiceRequest> findByServiceServiceNameIlike(String serviceName);\n\n // jurisdiction\n Optional<ServiceRequest> findByIdAndJurisdictionId(Long serviceRequestId, String jurisdictionId);\n Page<ServiceRequest> findAllByJurisdictionId(String jurisdictionId, Pageable pageable);\n List<ServiceRequest> findAllByJurisdictionId(String jurisdictionId);\n\n Page<ServiceRequest> findByJurisdictionIdAndServiceServiceCode(String jurisdictionId, String serviceCode, Pageable pageable);\n List<ServiceRequest> findByJurisdictionIdAndServiceServiceCode(String jurisdictionId, String serviceCode);\n Page<ServiceRequest> findByJurisdictionIdAndServiceServiceCodeAndDateCreatedBetween(String jurisdictionId, String serviceCode, Instant start, Instant end, Pageable pageable);\n List<ServiceRequest> findByJurisdictionIdAndServiceServiceCodeAndDateCreatedBetween(String jurisdictionId, String serviceCode, Instant start, Instant end);\n Page<ServiceRequest> findByJurisdictionIdAndServiceServiceCodeAndDateCreatedAfter(String jurisdictionId, String serviceCode, Instant start, Pageable pageable);\n List<ServiceRequest> findByJurisdictionIdAndServiceServiceCodeAndDateCreatedAfter(String jurisdictionId, String serviceCode, Instant start);\n Page<ServiceRequest> findByJurisdictionIdAndServiceServiceCodeAndDateCreatedBefore(String jurisdictionId, String serviceCode, Instant end, Pageable pageable);\n List<ServiceRequest> findByJurisdictionIdAndServiceServiceCodeAndDateCreatedBefore(String jurisdictionId, String serviceCode, Instant end);\n\n Page<ServiceRequest> findByJurisdictionIdAndStatus(String jurisdictionId, ServiceRequestStatus status, Pageable pageable);\n List<ServiceRequest> findByJurisdictionIdAndStatus(String jurisdictionId, ServiceRequestStatus status);\n Page<ServiceRequest> findByJurisdictionIdAndStatusAndDateCreatedBetween(String jurisdictionId, ServiceRequestStatus status, Instant start, Instant end, Pageable pageable);\n List<ServiceRequest> findByJurisdictionIdAndStatusAndDateCreatedBetween(String jurisdictionId, ServiceRequestStatus status, Instant start, Instant end);\n Page<ServiceRequest> findByJurisdictionIdAndStatusAndDateCreatedAfter(String jurisdictionId, ServiceRequestStatus status, Instant start, Pageable pageable);\n List<ServiceRequest> findByJurisdictionIdAndStatusAndDateCreatedAfter(String jurisdictionId, ServiceRequestStatus status, Instant start);\n Page<ServiceRequest> findByJurisdictionIdAndStatusAndDateCreatedBefore(String jurisdictionId, ServiceRequestStatus status, Instant end, Pageable pageable);\n List<ServiceRequest> findByJurisdictionIdAndStatusAndDateCreatedBefore(String jurisdictionId, ServiceRequestStatus status, Instant end);\n\n Page<ServiceRequest> findByJurisdictionIdAndServiceServiceCodeAndStatus(String jurisdictionId, String serviceCode, ServiceRequestStatus status, Pageable pageable);\n List<ServiceRequest> findByJurisdictionIdAndServiceServiceCodeAndStatus(String jurisdictionId, String serviceCode, ServiceRequestStatus status);\n Page<ServiceRequest> findByJurisdictionIdAndServiceServiceCodeAndStatusAndDateCreatedBetween(String jurisdictionId, String serviceCode, ServiceRequestStatus status, Instant start, Instant end, Pageable pageable);\n List<ServiceRequest> findByJurisdictionIdAndServiceServiceCodeAndStatusAndDateCreatedBetween(String jurisdictionId, String serviceCode, ServiceRequestStatus status, Instant start, Instant end);\n Page<ServiceRequest> findByJurisdictionIdAndServiceServiceCodeAndStatusAndDateCreatedAfter(String jurisdictionId, String serviceCode, ServiceRequestStatus status, Instant start, Pageable pageable);\n List<ServiceRequest> findByJurisdictionIdAndServiceServiceCodeAndStatusAndDateCreatedAfter(String jurisdictionId, String serviceCode, ServiceRequestStatus status, Instant start);\n Page<ServiceRequest> findByJurisdictionIdAndServiceServiceCodeAndStatusAndDateCreatedBefore(String jurisdictionId, String serviceCode, ServiceRequestStatus status, Instant end, Pageable pageable);\n List<ServiceRequest> findByJurisdictionIdAndServiceServiceCodeAndStatusAndDateCreatedBefore(String jurisdictionId, String serviceCode, ServiceRequestStatus status, Instant end);\n\n Page<ServiceRequest> findByJurisdictionIdAndDateCreatedBetween(String jurisdictionId, Instant start, Instant end, Pageable pageable);\n List<ServiceRequest> findByJurisdictionIdAndDateCreatedBetween(String jurisdictionId, Instant startDate, Instant endDate);\n Page<ServiceRequest> findByJurisdictionIdAndDateCreatedAfter(String jurisdictionId, Instant start, Pageable pageable);\n List<ServiceRequest> findByJurisdictionIdAndDateCreatedAfter(String jurisdictionId, Instant start);\n Page<ServiceRequest> findByJurisdictionIdAndDateCreatedBefore(String jurisdictionId, Instant end, Pageable pageable);\n List<ServiceRequest> findByJurisdictionIdAndDateCreatedBefore(String jurisdictionId, Instant end);\n}" }, { "identifier": "ServiceRequestStatus", "path": "app/src/main/java/app/model/servicerequest/ServiceRequestStatus.java", "snippet": "public enum ServiceRequestStatus {\n OPEN, CLOSED;\n\n @Override\n @JsonValue\n public String toString() {\n return name().toLowerCase();\n }\n}" }, { "identifier": "ReCaptchaService", "path": "app/src/main/java/app/recaptcha/ReCaptchaService.java", "snippet": "@Singleton\npublic class ReCaptchaService {\n\n @Inject\n ReCaptchaClient client;\n\n @Property(name = \"app.recaptcha.secret\")\n protected String secret;\n\n public Boolean verifyReCaptcha(String response) {\n Map map = client.verifyReCaptcha(this.secret, response);\n Boolean success = (Boolean) map.get(\"success\");\n return success;\n }\n}" }, { "identifier": "StorageUrlUtil", "path": "app/src/main/java/app/service/storage/StorageUrlUtil.java", "snippet": "@Singleton\npublic class StorageUrlUtil {\n\n @Property(name = \"app.image-storage.bucket-url-format\")\n private String bucketUrlFormat;\n\n @Property(name = \"app.image-storage.append-object-url-format\")\n private String appendObjectUrlFormat;\n\n @Property(name = \"app.image-storage.bucket\")\n private String bucketId;\n\n\n public String getObjectUrlString(String blobId) {\n return String.format(getBucketUrlString().concat(appendObjectUrlFormat), blobId);\n }\n\n public String getBucketUrlString() {\n return String.format(bucketUrlFormat, bucketId);\n }\n}" } ]
import app.dto.download.DownloadRequestsArgumentsDTO; import app.dto.download.DownloadServiceRequestDTO; import app.dto.servicerequest.*; import app.model.service.Service; import app.model.service.ServiceRepository; import app.model.service.servicedefinition.AttributeDataType; import app.model.service.servicedefinition.AttributeValue; import app.model.service.servicedefinition.ServiceDefinition; import app.model.service.servicedefinition.ServiceDefinitionAttribute; import app.model.servicerequest.ServiceRequest; import app.model.servicerequest.ServiceRequestRepository; import app.model.servicerequest.ServiceRequestStatus; import app.recaptcha.ReCaptchaService; import app.service.storage.StorageUrlUtil; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.opencsv.bean.StatefulBeanToCsv; import com.opencsv.bean.StatefulBeanToCsvBuilder; import com.opencsv.exceptions.CsvDataTypeMismatchException; import com.opencsv.exceptions.CsvRequiredFieldEmptyException; import io.micronaut.core.util.StringUtils; import io.micronaut.data.model.Page; import io.micronaut.data.model.Pageable; import io.micronaut.data.model.Sort; import io.micronaut.http.HttpRequest; import io.micronaut.http.server.types.files.StreamedFile; import jakarta.inject.Singleton; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.net.MalformedURLException; import java.time.Instant; import java.time.format.DateTimeParseException; import java.util.*; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream;
9,067
// Copyright 2023 Libre311 Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package app.service.servicerequest; @Singleton public class ServiceRequestService { private static final Logger LOG = LoggerFactory.getLogger(ServiceRequestService.class); private final ServiceRequestRepository serviceRequestRepository; private final ServiceRepository serviceRepository; private final ReCaptchaService reCaptchaService; private final StorageUrlUtil storageUrlUtil; public ServiceRequestService(ServiceRequestRepository serviceRequestRepository, ServiceRepository serviceRepository, ReCaptchaService reCaptchaService, StorageUrlUtil storageUrlUtil) { this.serviceRequestRepository = serviceRequestRepository; this.serviceRepository = serviceRepository; this.reCaptchaService = reCaptchaService; this.storageUrlUtil = storageUrlUtil; } private static ServiceRequestDTO convertToDTO(ServiceRequest serviceRequest) { ServiceRequestDTO serviceRequestDTO = new ServiceRequestDTO(serviceRequest); ObjectMapper objectMapper = new ObjectMapper(); String attributesJson = serviceRequest.getAttributesJson(); if (attributesJson != null) { try { ServiceDefinitionAttribute[] serviceDefinitionAttributes = objectMapper.readValue(attributesJson, ServiceDefinitionAttribute[].class); serviceRequestDTO.setSelectedValues(List.of(serviceDefinitionAttributes)); } catch (JsonProcessingException e) { throw new RuntimeException(e); } } return serviceRequestDTO; } public PostResponseServiceRequestDTO createServiceRequest(HttpRequest<?> request, PostRequestServiceRequestDTO serviceRequestDTO) { if (!reCaptchaService.verifyReCaptcha(serviceRequestDTO.getgRecaptchaResponse())) { LOG.error("ReCaptcha verification failed."); return null; } if (!validMediaUrl(serviceRequestDTO.getMediaUrl())) { LOG.error("Media URL is invalid."); return null; } Optional<Service> serviceByServiceCodeOptional = serviceRepository.findByServiceCode(serviceRequestDTO.getServiceCode()); if (serviceByServiceCodeOptional.isEmpty()) { LOG.error("Corresponding service not found."); return null; // todo return 'corresponding service not found } if (serviceRequestDTO.getJurisdictionId() != null && !serviceRequestDTO.getJurisdictionId().equals(serviceByServiceCodeOptional.get().getJurisdiction().getId())) { LOG.error("Mismatch between jurisdiction_id provided and Service's associated jurisdiction."); return null; } // validate if a location is provided boolean latLongProvided = StringUtils.hasText(serviceRequestDTO.getLatitude()) && StringUtils.hasText(serviceRequestDTO.getLongitude()); if (!latLongProvided && StringUtils.isEmpty(serviceRequestDTO.getAddressString()) && StringUtils.isEmpty(serviceRequestDTO.getAddressId())) { LOG.error("Address or lat/long not provided."); return null; // todo throw exception } // validate if additional attributes are required List<ServiceDefinitionAttribute> requestAttributes = null; Service service = serviceByServiceCodeOptional.get(); if (service.isMetadata()) { // get service definition String serviceDefinitionJson = service.getServiceDefinitionJson(); if (serviceDefinitionJson == null || serviceDefinitionJson.isBlank()) { LOG.error("Service definition does not exists despite service requiring it."); return null; // should not be in this state and admin needs to be aware. } requestAttributes = buildUserResponseAttributesFromRequest(request, serviceDefinitionJson); if (requestAttributes.isEmpty()) { LOG.error("Submitted Service Request does not contain any attribute values."); return null; // todo throw exception - must provide attributes } if (!requestAttributesHasAllRequiredServiceDefinitionAttributes(serviceDefinitionJson, requestAttributes)) { LOG.error("Submitted Service Request does not contain required attribute values."); return null; // todo throw exception (validation) } } ServiceRequest serviceRequest = transformDtoToServiceRequest(serviceRequestDTO, service); if (requestAttributes != null) { ObjectMapper objectMapper = new ObjectMapper(); try { serviceRequest.setAttributesJson(objectMapper.writeValueAsString(requestAttributes)); } catch (JsonProcessingException e) { throw new RuntimeException(e); } } return new PostResponseServiceRequestDTO(serviceRequestRepository.save(serviceRequest)); } private boolean validMediaUrl(String mediaUrl) { if (mediaUrl == null) return true; return mediaUrl.startsWith(storageUrlUtil.getBucketUrlString()); } private boolean requestAttributesHasAllRequiredServiceDefinitionAttributes(String serviceDefinitionJson, List<ServiceDefinitionAttribute> requestAttributes) { // deserialize ObjectMapper objectMapper = new ObjectMapper(); boolean containsAllRequiredAttrs = false; try { // collect all required attributes
// Copyright 2023 Libre311 Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package app.service.servicerequest; @Singleton public class ServiceRequestService { private static final Logger LOG = LoggerFactory.getLogger(ServiceRequestService.class); private final ServiceRequestRepository serviceRequestRepository; private final ServiceRepository serviceRepository; private final ReCaptchaService reCaptchaService; private final StorageUrlUtil storageUrlUtil; public ServiceRequestService(ServiceRequestRepository serviceRequestRepository, ServiceRepository serviceRepository, ReCaptchaService reCaptchaService, StorageUrlUtil storageUrlUtil) { this.serviceRequestRepository = serviceRequestRepository; this.serviceRepository = serviceRepository; this.reCaptchaService = reCaptchaService; this.storageUrlUtil = storageUrlUtil; } private static ServiceRequestDTO convertToDTO(ServiceRequest serviceRequest) { ServiceRequestDTO serviceRequestDTO = new ServiceRequestDTO(serviceRequest); ObjectMapper objectMapper = new ObjectMapper(); String attributesJson = serviceRequest.getAttributesJson(); if (attributesJson != null) { try { ServiceDefinitionAttribute[] serviceDefinitionAttributes = objectMapper.readValue(attributesJson, ServiceDefinitionAttribute[].class); serviceRequestDTO.setSelectedValues(List.of(serviceDefinitionAttributes)); } catch (JsonProcessingException e) { throw new RuntimeException(e); } } return serviceRequestDTO; } public PostResponseServiceRequestDTO createServiceRequest(HttpRequest<?> request, PostRequestServiceRequestDTO serviceRequestDTO) { if (!reCaptchaService.verifyReCaptcha(serviceRequestDTO.getgRecaptchaResponse())) { LOG.error("ReCaptcha verification failed."); return null; } if (!validMediaUrl(serviceRequestDTO.getMediaUrl())) { LOG.error("Media URL is invalid."); return null; } Optional<Service> serviceByServiceCodeOptional = serviceRepository.findByServiceCode(serviceRequestDTO.getServiceCode()); if (serviceByServiceCodeOptional.isEmpty()) { LOG.error("Corresponding service not found."); return null; // todo return 'corresponding service not found } if (serviceRequestDTO.getJurisdictionId() != null && !serviceRequestDTO.getJurisdictionId().equals(serviceByServiceCodeOptional.get().getJurisdiction().getId())) { LOG.error("Mismatch between jurisdiction_id provided and Service's associated jurisdiction."); return null; } // validate if a location is provided boolean latLongProvided = StringUtils.hasText(serviceRequestDTO.getLatitude()) && StringUtils.hasText(serviceRequestDTO.getLongitude()); if (!latLongProvided && StringUtils.isEmpty(serviceRequestDTO.getAddressString()) && StringUtils.isEmpty(serviceRequestDTO.getAddressId())) { LOG.error("Address or lat/long not provided."); return null; // todo throw exception } // validate if additional attributes are required List<ServiceDefinitionAttribute> requestAttributes = null; Service service = serviceByServiceCodeOptional.get(); if (service.isMetadata()) { // get service definition String serviceDefinitionJson = service.getServiceDefinitionJson(); if (serviceDefinitionJson == null || serviceDefinitionJson.isBlank()) { LOG.error("Service definition does not exists despite service requiring it."); return null; // should not be in this state and admin needs to be aware. } requestAttributes = buildUserResponseAttributesFromRequest(request, serviceDefinitionJson); if (requestAttributes.isEmpty()) { LOG.error("Submitted Service Request does not contain any attribute values."); return null; // todo throw exception - must provide attributes } if (!requestAttributesHasAllRequiredServiceDefinitionAttributes(serviceDefinitionJson, requestAttributes)) { LOG.error("Submitted Service Request does not contain required attribute values."); return null; // todo throw exception (validation) } } ServiceRequest serviceRequest = transformDtoToServiceRequest(serviceRequestDTO, service); if (requestAttributes != null) { ObjectMapper objectMapper = new ObjectMapper(); try { serviceRequest.setAttributesJson(objectMapper.writeValueAsString(requestAttributes)); } catch (JsonProcessingException e) { throw new RuntimeException(e); } } return new PostResponseServiceRequestDTO(serviceRequestRepository.save(serviceRequest)); } private boolean validMediaUrl(String mediaUrl) { if (mediaUrl == null) return true; return mediaUrl.startsWith(storageUrlUtil.getBucketUrlString()); } private boolean requestAttributesHasAllRequiredServiceDefinitionAttributes(String serviceDefinitionJson, List<ServiceDefinitionAttribute> requestAttributes) { // deserialize ObjectMapper objectMapper = new ObjectMapper(); boolean containsAllRequiredAttrs = false; try { // collect all required attributes
ServiceDefinition serviceDefinition = objectMapper.readValue(serviceDefinitionJson, ServiceDefinition.class);
6
2023-10-18 15:37:36+00:00
12k
JonnyOnlineYT/xenza
src/minecraft/net/minecraft/client/renderer/entity/RenderGiantZombie.java
[ { "identifier": "ModelBase", "path": "src/minecraft/net/minecraft/client/model/ModelBase.java", "snippet": "public abstract class ModelBase {\n public float swingProgress;\n public boolean isRiding;\n public boolean isChild = true;\n public List<ModelRenderer> boxList = Lists.newArrayList();\n private Map<String, TextureOffset> modelTextureMap = Maps.newHashMap();\n public int textureWidth = 64;\n public int textureHeight = 32;\n\n public void render(Entity entityIn, float p_78088_2_, float p_78088_3_, float p_78088_4_, float p_78088_5_, float p_78088_6_, float scale) {\n }\n\n public void setRotationAngles(float p_78087_1_, float p_78087_2_, float p_78087_3_, float p_78087_4_, float p_78087_5_, float p_78087_6_, Entity entityIn) {\n }\n\n public void setLivingAnimations(EntityLivingBase entitylivingbaseIn, float p_78086_2_, float p_78086_3_, float partialTickTime) {\n }\n\n public ModelRenderer getRandomModelBox(Random rand) {\n return this.boxList.get(rand.nextInt(this.boxList.size()));\n }\n\n protected void setTextureOffset(String partName, int x, int y) {\n this.modelTextureMap.put(partName, new TextureOffset(x, y));\n }\n\n public TextureOffset getTextureOffset(String partName) {\n return this.modelTextureMap.get(partName);\n }\n\n public static void copyModelAngles(ModelRenderer source, ModelRenderer dest) {\n dest.rotateAngleX = source.rotateAngleX;\n dest.rotateAngleY = source.rotateAngleY;\n dest.rotateAngleZ = source.rotateAngleZ;\n dest.rotationPointX = source.rotationPointX;\n dest.rotationPointY = source.rotationPointY;\n dest.rotationPointZ = source.rotationPointZ;\n }\n\n public void setModelAttributes(ModelBase model) {\n this.swingProgress = model.swingProgress;\n this.isRiding = model.isRiding;\n this.isChild = model.isChild;\n }\n}" }, { "identifier": "ModelZombie", "path": "src/minecraft/net/minecraft/client/model/ModelZombie.java", "snippet": "public class ModelZombie extends ModelBiped {\n public ModelZombie() {\n this(0.0F, false);\n }\n\n protected ModelZombie(float modelSize, float p_i1167_2_, int textureWidthIn, int textureHeightIn) {\n super(modelSize, p_i1167_2_, textureWidthIn, textureHeightIn);\n }\n\n public ModelZombie(float modelSize, boolean p_i1168_2_) {\n super(modelSize, 0.0F, 64, p_i1168_2_ ? 32 : 64);\n }\n\n @Override\n public void setRotationAngles(float p_78087_1_, float p_78087_2_, float p_78087_3_, float p_78087_4_, float p_78087_5_, float p_78087_6_, Entity entityIn) {\n super.setRotationAngles(p_78087_1_, p_78087_2_, p_78087_3_, p_78087_4_, p_78087_5_, p_78087_6_, entityIn);\n float f = MathHelper.sin(this.swingProgress * (float) Math.PI);\n float f1 = MathHelper.sin((1.0F - (1.0F - this.swingProgress) * (1.0F - this.swingProgress)) * (float) Math.PI);\n this.bipedRightArm.rotateAngleZ = 0.0F;\n this.bipedLeftArm.rotateAngleZ = 0.0F;\n this.bipedRightArm.rotateAngleY = -(0.1F - f * 0.6F);\n this.bipedLeftArm.rotateAngleY = 0.1F - f * 0.6F;\n this.bipedRightArm.rotateAngleX = (float) (-Math.PI / 2);\n this.bipedLeftArm.rotateAngleX = (float) (-Math.PI / 2);\n this.bipedRightArm.rotateAngleX -= f * 1.2F - f1 * 0.4F;\n this.bipedLeftArm.rotateAngleX -= f * 1.2F - f1 * 0.4F;\n this.bipedRightArm.rotateAngleZ += MathHelper.cos(p_78087_3_ * 0.09F) * 0.05F + 0.05F;\n this.bipedLeftArm.rotateAngleZ -= MathHelper.cos(p_78087_3_ * 0.09F) * 0.05F + 0.05F;\n this.bipedRightArm.rotateAngleX += MathHelper.sin(p_78087_3_ * 0.067F) * 0.05F;\n this.bipedLeftArm.rotateAngleX -= MathHelper.sin(p_78087_3_ * 0.067F) * 0.05F;\n }\n}" }, { "identifier": "GlStateManager", "path": "src/minecraft/net/minecraft/client/renderer/GlStateManager.java", "snippet": "public class GlStateManager {\n private static GlStateManager.AlphaState alphaState = new GlStateManager.AlphaState((GlStateManager.GlStateManager$1)null);\n private static GlStateManager.BooleanState lightingState = new GlStateManager.BooleanState(2896);\n private static GlStateManager.BooleanState[] lightState = new GlStateManager.BooleanState[8];\n private static GlStateManager.ColorMaterialState colorMaterialState = new GlStateManager.ColorMaterialState((GlStateManager.GlStateManager$1)null);\n private static GlStateManager.BlendState blendState = new GlStateManager.BlendState((GlStateManager.GlStateManager$1)null);\n private static GlStateManager.DepthState depthState = new GlStateManager.DepthState((GlStateManager.GlStateManager$1)null);\n private static GlStateManager.FogState fogState = new GlStateManager.FogState((GlStateManager.GlStateManager$1)null);\n private static GlStateManager.CullState cullState = new GlStateManager.CullState((GlStateManager.GlStateManager$1)null);\n private static GlStateManager.PolygonOffsetState polygonOffsetState = new GlStateManager.PolygonOffsetState((GlStateManager.GlStateManager$1)null);\n private static GlStateManager.ColorLogicState colorLogicState = new GlStateManager.ColorLogicState((GlStateManager.GlStateManager$1)null);\n private static GlStateManager.TexGenState texGenState = new GlStateManager.TexGenState((GlStateManager.GlStateManager$1)null);\n private static GlStateManager.ClearState clearState = new GlStateManager.ClearState((GlStateManager.GlStateManager$1)null);\n private static GlStateManager.StencilState stencilState = new GlStateManager.StencilState((GlStateManager.GlStateManager$1)null);\n private static GlStateManager.BooleanState normalizeState = new GlStateManager.BooleanState(2977);\n private static int activeTextureUnit = 0;\n private static GlStateManager.TextureState[] textureState = new GlStateManager.TextureState[32];\n private static int activeShadeModel = 7425;\n private static GlStateManager.BooleanState rescaleNormalState = new GlStateManager.BooleanState(32826);\n private static GlStateManager.ColorMask colorMaskState = new GlStateManager.ColorMask((GlStateManager.GlStateManager$1)null);\n private static GlStateManager.Color colorState = new GlStateManager.Color();\n private static final String __OBFID = \"CL_00002558\";\n public static boolean clearEnabled = true;\n\n public static void pushAttrib() {\n GL11.glPushAttrib(8256);\n }\n\n public static void popAttrib() {\n GL11.glPopAttrib();\n }\n\n public static void disableAlpha() {\n alphaState.field_179208_a.setDisabled();\n }\n\n public static void enableAlpha() {\n alphaState.field_179208_a.setEnabled();\n }\n\n public static void alphaFunc(int func, float ref) {\n if (func != alphaState.func || ref != alphaState.ref) {\n alphaState.func = func;\n alphaState.ref = ref;\n GL11.glAlphaFunc(func, ref);\n }\n }\n\n public static void enableLighting() {\n lightingState.setEnabled();\n }\n\n public static void disableLighting() {\n lightingState.setDisabled();\n }\n\n public static void enableLight(int light) {\n lightState[light].setEnabled();\n }\n\n public static void disableLight(int light) {\n lightState[light].setDisabled();\n }\n\n public static void enableColorMaterial() {\n colorMaterialState.field_179191_a.setEnabled();\n }\n\n public static void disableColorMaterial() {\n colorMaterialState.field_179191_a.setDisabled();\n }\n\n public static void colorMaterial(int face, int mode) {\n if (face != colorMaterialState.field_179189_b || mode != colorMaterialState.field_179190_c) {\n colorMaterialState.field_179189_b = face;\n colorMaterialState.field_179190_c = mode;\n GL11.glColorMaterial(face, mode);\n }\n }\n\n public static void disableDepth() {\n depthState.depthTest.setDisabled();\n }\n\n public static void enableDepth() {\n depthState.depthTest.setEnabled();\n }\n\n public static void depthFunc(int depthFunc) {\n if (depthFunc != depthState.depthFunc) {\n depthState.depthFunc = depthFunc;\n GL11.glDepthFunc(depthFunc);\n }\n }\n\n public static void depthMask(boolean flagIn) {\n if (flagIn != depthState.maskEnabled) {\n depthState.maskEnabled = flagIn;\n GL11.glDepthMask(flagIn);\n }\n }\n\n public static void disableBlend() {\n blendState.field_179213_a.setDisabled();\n }\n\n public static void enableBlend() {\n blendState.field_179213_a.setEnabled();\n }\n\n public static void blendFunc(int srcFactor, int dstFactor) {\n if (srcFactor != blendState.srcFactor || dstFactor != blendState.dstFactor) {\n blendState.srcFactor = srcFactor;\n blendState.dstFactor = dstFactor;\n GL11.glBlendFunc(srcFactor, dstFactor);\n }\n }\n\n public static void tryBlendFuncSeparate(int srcFactor, int dstFactor, int srcFactorAlpha, int dstFactorAlpha) {\n if (srcFactor != blendState.srcFactor\n || dstFactor != blendState.dstFactor\n || srcFactorAlpha != blendState.srcFactorAlpha\n || dstFactorAlpha != blendState.dstFactorAlpha) {\n blendState.srcFactor = srcFactor;\n blendState.dstFactor = dstFactor;\n blendState.srcFactorAlpha = srcFactorAlpha;\n blendState.dstFactorAlpha = dstFactorAlpha;\n OpenGlHelper.glBlendFunc(srcFactor, dstFactor, srcFactorAlpha, dstFactorAlpha);\n }\n }\n\n public static void enableFog() {\n fogState.field_179049_a.setEnabled();\n }\n\n public static void disableFog() {\n fogState.field_179049_a.setDisabled();\n }\n\n public static void setFog(int param) {\n if (param != fogState.field_179047_b) {\n fogState.field_179047_b = param;\n GL11.glFogi(2917, param);\n }\n }\n\n public static void setFogDensity(float param) {\n if (param != fogState.field_179048_c) {\n fogState.field_179048_c = param;\n GL11.glFogf(2914, param);\n }\n }\n\n public static void setFogStart(float param) {\n if (param != fogState.field_179045_d) {\n fogState.field_179045_d = param;\n GL11.glFogf(2915, param);\n }\n }\n\n public static void setFogEnd(float param) {\n if (param != fogState.field_179046_e) {\n fogState.field_179046_e = param;\n GL11.glFogf(2916, param);\n }\n }\n\n public static void enableCull() {\n cullState.field_179054_a.setEnabled();\n }\n\n public static void disableCull() {\n cullState.field_179054_a.setDisabled();\n }\n\n public static void cullFace(int mode) {\n if (mode != cullState.field_179053_b) {\n cullState.field_179053_b = mode;\n GL11.glCullFace(mode);\n }\n }\n\n public static void enablePolygonOffset() {\n polygonOffsetState.field_179044_a.setEnabled();\n }\n\n public static void disablePolygonOffset() {\n polygonOffsetState.field_179044_a.setDisabled();\n }\n\n public static void doPolygonOffset(float factor, float units) {\n if (factor != polygonOffsetState.field_179043_c || units != polygonOffsetState.field_179041_d) {\n polygonOffsetState.field_179043_c = factor;\n polygonOffsetState.field_179041_d = units;\n GL11.glPolygonOffset(factor, units);\n }\n }\n\n public static void enableColorLogic() {\n colorLogicState.field_179197_a.setEnabled();\n }\n\n public static void disableColorLogic() {\n colorLogicState.field_179197_a.setDisabled();\n }\n\n public static void colorLogicOp(int opcode) {\n if (opcode != colorLogicState.field_179196_b) {\n colorLogicState.field_179196_b = opcode;\n GL11.glLogicOp(opcode);\n }\n }\n\n public static void enableTexGenCoord(GlStateManager.TexGen p_179087_0_) {\n texGenCoord(p_179087_0_).field_179067_a.setEnabled();\n }\n\n public static void disableTexGenCoord(GlStateManager.TexGen p_179100_0_) {\n texGenCoord(p_179100_0_).field_179067_a.setDisabled();\n }\n\n public static void texGen(GlStateManager.TexGen p_179149_0_, int p_179149_1_) {\n GlStateManager.TexGenCoord glstatemanager$texgencoord = texGenCoord(p_179149_0_);\n if (p_179149_1_ != glstatemanager$texgencoord.field_179066_c) {\n glstatemanager$texgencoord.field_179066_c = p_179149_1_;\n GL11.glTexGeni(glstatemanager$texgencoord.field_179065_b, 9472, p_179149_1_);\n }\n }\n\n public static void func_179105_a(GlStateManager.TexGen p_179105_0_, int pname, FloatBuffer params) {\n GL11.glTexGen(texGenCoord(p_179105_0_).field_179065_b, pname, params);\n }\n\n private static GlStateManager.TexGenCoord texGenCoord(GlStateManager.TexGen p_179125_0_) {\n switch(GlStateManager.GlStateManager$1.field_179175_a[p_179125_0_.ordinal()]) {\n case 1:\n return texGenState.field_179064_a;\n case 2:\n return texGenState.field_179062_b;\n case 3:\n return texGenState.field_179063_c;\n case 4:\n return texGenState.field_179061_d;\n default:\n return texGenState.field_179064_a;\n }\n }\n\n public static void setActiveTexture(int texture) {\n if (activeTextureUnit != texture - OpenGlHelper.defaultTexUnit) {\n activeTextureUnit = texture - OpenGlHelper.defaultTexUnit;\n OpenGlHelper.setActiveTexture(texture);\n }\n }\n\n public static void enableTexture2D() {\n textureState[activeTextureUnit].texture2DState.setEnabled();\n }\n\n public static void disableTexture2D() {\n textureState[activeTextureUnit].texture2DState.setDisabled();\n }\n\n public static int generateTexture() {\n return GL11.glGenTextures();\n }\n\n public static void deleteTexture(int texture) {\n if (texture != 0) {\n GL11.glDeleteTextures(texture);\n\n for(GlStateManager.TextureState glstatemanager$texturestate : textureState) {\n if (glstatemanager$texturestate.textureName == texture) {\n glstatemanager$texturestate.textureName = 0;\n }\n }\n }\n }\n\n public static void bindTexture(int texture) {\n if (texture != textureState[activeTextureUnit].textureName) {\n textureState[activeTextureUnit].textureName = texture;\n GL11.glBindTexture(3553, texture);\n }\n }\n\n public static void bindCurrentTexture() {\n GL11.glBindTexture(3553, textureState[activeTextureUnit].textureName);\n }\n\n public static void enableNormalize() {\n normalizeState.setEnabled();\n }\n\n public static void disableNormalize() {\n normalizeState.setDisabled();\n }\n\n public static void shadeModel(int mode) {\n if (mode != activeShadeModel) {\n activeShadeModel = mode;\n GL11.glShadeModel(mode);\n }\n }\n\n public static void enableRescaleNormal() {\n rescaleNormalState.setEnabled();\n }\n\n public static void disableRescaleNormal() {\n rescaleNormalState.setDisabled();\n }\n\n public static void viewport(int x, int y, int width, int height) {\n GL11.glViewport(x, y, width, height);\n }\n\n public static void colorMask(boolean red, boolean green, boolean blue, boolean alpha) {\n if (red != colorMaskState.red || green != colorMaskState.green || blue != colorMaskState.blue || alpha != colorMaskState.alpha) {\n colorMaskState.red = red;\n colorMaskState.green = green;\n colorMaskState.blue = blue;\n colorMaskState.alpha = alpha;\n GL11.glColorMask(red, green, blue, alpha);\n }\n }\n\n public static void clearDepth(double depth) {\n if (depth != clearState.field_179205_a) {\n clearState.field_179205_a = depth;\n GL11.glClearDepth(depth);\n }\n }\n\n public static void clearColor(float red, float green, float blue, float alpha) {\n if (red != clearState.field_179203_b.red\n || green != clearState.field_179203_b.green\n || blue != clearState.field_179203_b.blue\n || alpha != clearState.field_179203_b.alpha) {\n clearState.field_179203_b.red = red;\n clearState.field_179203_b.green = green;\n clearState.field_179203_b.blue = blue;\n clearState.field_179203_b.alpha = alpha;\n GL11.glClearColor(red, green, blue, alpha);\n }\n }\n\n public static void clear(int mask) {\n if (clearEnabled) {\n GL11.glClear(mask);\n }\n }\n\n public static void matrixMode(int mode) {\n GL11.glMatrixMode(mode);\n }\n\n public static void loadIdentity() {\n GL11.glLoadIdentity();\n }\n\n public static void pushMatrix() {\n GL11.glPushMatrix();\n }\n\n public static void popMatrix() {\n GL11.glPopMatrix();\n }\n\n public static void getFloat(int pname, FloatBuffer params) {\n GL11.glGetFloat(pname, params);\n }\n\n public static void ortho(double left, double right, double bottom, double top, double zNear, double zFar) {\n GL11.glOrtho(left, right, bottom, top, zNear, zFar);\n }\n\n public static void rotate(float angle, float x, float y, float z) {\n GL11.glRotatef(angle, x, y, z);\n }\n\n public static void scale(float x, float y, float z) {\n GL11.glScalef(x, y, z);\n }\n\n public static void scale(double x, double y, double z) {\n GL11.glScaled(x, y, z);\n }\n\n public static void translate(float x, float y, float z) {\n GL11.glTranslatef(x, y, z);\n }\n\n public static void translate(double x, double y, double z) {\n GL11.glTranslated(x, y, z);\n }\n\n public static void multMatrix(FloatBuffer matrix) {\n GL11.glMultMatrix(matrix);\n }\n\n public static void color(float colorRed, float colorGreen, float colorBlue, float colorAlpha) {\n if (colorRed != colorState.red || colorGreen != colorState.green || colorBlue != colorState.blue || colorAlpha != colorState.alpha) {\n colorState.red = colorRed;\n colorState.green = colorGreen;\n colorState.blue = colorBlue;\n colorState.alpha = colorAlpha;\n GL11.glColor4f(colorRed, colorGreen, colorBlue, colorAlpha);\n }\n }\n\n public static void color(float colorRed, float colorGreen, float colorBlue) {\n color(colorRed, colorGreen, colorBlue, 1.0F);\n }\n\n public static void resetColor() {\n colorState.red = colorState.green = colorState.blue = colorState.alpha = -1.0F;\n }\n\n public static void callList(int list) {\n GL11.glCallList(list);\n }\n\n public static int getActiveTextureUnit() {\n return OpenGlHelper.defaultTexUnit + activeTextureUnit;\n }\n\n public static int getBoundTexture() {\n return textureState[activeTextureUnit].textureName;\n }\n\n public static void checkBoundTexture() {\n if (Config.isMinecraftThread()) {\n int i = GL11.glGetInteger(34016);\n int j = GL11.glGetInteger(32873);\n int k = getActiveTextureUnit();\n int l = getBoundTexture();\n if (l > 0 && (i != k || j != l)) {\n Config.dbg(\"checkTexture: act: \" + k + \", glAct: \" + i + \", tex: \" + l + \", glTex: \" + j);\n }\n }\n }\n\n public static void deleteTextures(IntBuffer p_deleteTextures_0_) {\n ((Buffer)p_deleteTextures_0_).rewind();\n\n while(p_deleteTextures_0_.position() < p_deleteTextures_0_.limit()) {\n int i = p_deleteTextures_0_.get();\n deleteTexture(i);\n }\n\n ((Buffer)p_deleteTextures_0_).rewind();\n }\n\n static {\n for(int i = 0; i < 8; ++i) {\n lightState[i] = new GlStateManager.BooleanState(16384 + i);\n }\n\n for(int j = 0; j < textureState.length; ++j) {\n textureState[j] = new GlStateManager.TextureState((GlStateManager.GlStateManager$1)null);\n }\n }\n\n static class AlphaState {\n public GlStateManager.BooleanState field_179208_a = new GlStateManager.BooleanState(3008);\n public int func = 519;\n public float ref = -1.0F;\n private static final String __OBFID = \"CL_00002556\";\n\n private AlphaState() {\n }\n\n AlphaState(GlStateManager.GlStateManager$1 p_i46489_1_) {\n this();\n }\n }\n\n static class BlendState {\n public GlStateManager.BooleanState field_179213_a = new GlStateManager.BooleanState(3042);\n public int srcFactor = 1;\n public int dstFactor = 0;\n public int srcFactorAlpha = 1;\n public int dstFactorAlpha = 0;\n private static final String __OBFID = \"CL_00002555\";\n\n private BlendState() {\n }\n\n BlendState(GlStateManager.GlStateManager$1 p_i46488_1_) {\n this();\n }\n }\n\n static class BooleanState {\n private final int capability;\n private boolean currentState = false;\n private static final String __OBFID = \"CL_00002554\";\n\n public BooleanState(int capabilityIn) {\n this.capability = capabilityIn;\n }\n\n public void setDisabled() {\n this.setState(false);\n }\n\n public void setEnabled() {\n this.setState(true);\n }\n\n public void setState(boolean state) {\n if (state != this.currentState) {\n this.currentState = state;\n if (state) {\n GL11.glEnable(this.capability);\n } else {\n GL11.glDisable(this.capability);\n }\n }\n }\n }\n\n static class ClearState {\n public double field_179205_a = 1.0;\n public GlStateManager.Color field_179203_b = new GlStateManager.Color(0.0F, 0.0F, 0.0F, 0.0F);\n public int field_179204_c = 0;\n private static final String __OBFID = \"CL_00002553\";\n\n private ClearState() {\n }\n\n ClearState(GlStateManager.GlStateManager$1 p_i46487_1_) {\n this();\n }\n }\n\n static class Color {\n public float red = 1.0F;\n public float green = 1.0F;\n public float blue = 1.0F;\n public float alpha = 1.0F;\n private static final String __OBFID = \"CL_00002552\";\n\n public Color() {\n }\n\n public Color(float redIn, float greenIn, float blueIn, float alphaIn) {\n this.red = redIn;\n this.green = greenIn;\n this.blue = blueIn;\n this.alpha = alphaIn;\n }\n }\n\n static class ColorLogicState {\n public GlStateManager.BooleanState field_179197_a = new GlStateManager.BooleanState(3058);\n public int field_179196_b = 5379;\n private static final String __OBFID = \"CL_00002551\";\n\n private ColorLogicState() {\n }\n\n ColorLogicState(GlStateManager.GlStateManager$1 p_i46486_1_) {\n this();\n }\n }\n\n static class ColorMask {\n public boolean red = true;\n public boolean green = true;\n public boolean blue = true;\n public boolean alpha = true;\n private static final String __OBFID = \"CL_00002550\";\n\n private ColorMask() {\n }\n\n ColorMask(GlStateManager.GlStateManager$1 p_i46485_1_) {\n this();\n }\n }\n\n static class ColorMaterialState {\n public GlStateManager.BooleanState field_179191_a = new GlStateManager.BooleanState(2903);\n public int field_179189_b = 1032;\n public int field_179190_c = 5634;\n private static final String __OBFID = \"CL_00002549\";\n\n private ColorMaterialState() {\n }\n\n ColorMaterialState(GlStateManager.GlStateManager$1 p_i46484_1_) {\n this();\n }\n }\n\n static class CullState {\n public GlStateManager.BooleanState field_179054_a = new GlStateManager.BooleanState(2884);\n public int field_179053_b = 1029;\n private static final String __OBFID = \"CL_00002548\";\n\n private CullState() {\n }\n\n CullState(GlStateManager.GlStateManager$1 p_i46483_1_) {\n this();\n }\n }\n\n static class DepthState {\n public GlStateManager.BooleanState depthTest = new GlStateManager.BooleanState(2929);\n public boolean maskEnabled = true;\n public int depthFunc = 513;\n private static final String __OBFID = \"CL_00002547\";\n\n private DepthState() {\n }\n\n DepthState(GlStateManager.GlStateManager$1 p_i46482_1_) {\n this();\n }\n }\n\n static class FogState {\n public GlStateManager.BooleanState field_179049_a = new GlStateManager.BooleanState(2912);\n public int field_179047_b = 2048;\n public float field_179048_c = 1.0F;\n public float field_179045_d = 0.0F;\n public float field_179046_e = 1.0F;\n private static final String __OBFID = \"CL_00002546\";\n\n private FogState() {\n }\n\n FogState(GlStateManager.GlStateManager$1 p_i46481_1_) {\n this();\n }\n }\n\n static final class GlStateManager$1 {\n static final int[] field_179175_a = new int[GlStateManager.TexGen.values().length];\n private static final String __OBFID = \"CL_00002557\";\n\n static {\n try {\n field_179175_a[GlStateManager.TexGen.S.ordinal()] = 1;\n } catch (NoSuchFieldError var4) {\n }\n\n try {\n field_179175_a[GlStateManager.TexGen.T.ordinal()] = 2;\n } catch (NoSuchFieldError var3) {\n }\n\n try {\n field_179175_a[GlStateManager.TexGen.R.ordinal()] = 3;\n } catch (NoSuchFieldError var2) {\n }\n\n try {\n field_179175_a[GlStateManager.TexGen.Q.ordinal()] = 4;\n } catch (NoSuchFieldError var1) {\n }\n }\n }\n\n static class PolygonOffsetState {\n public GlStateManager.BooleanState field_179044_a = new GlStateManager.BooleanState(32823);\n public GlStateManager.BooleanState field_179042_b = new GlStateManager.BooleanState(10754);\n public float field_179043_c = 0.0F;\n public float field_179041_d = 0.0F;\n private static final String __OBFID = \"CL_00002545\";\n\n private PolygonOffsetState() {\n }\n\n PolygonOffsetState(GlStateManager.GlStateManager$1 p_i46480_1_) {\n this();\n }\n }\n\n static class StencilFunc {\n public int field_179081_a = 519;\n public int field_179079_b = 0;\n public int field_179080_c = -1;\n private static final String __OBFID = \"CL_00002544\";\n\n private StencilFunc() {\n }\n\n StencilFunc(GlStateManager.GlStateManager$1 p_i46479_1_) {\n this();\n }\n }\n\n static class StencilState {\n public GlStateManager.StencilFunc field_179078_a = new GlStateManager.StencilFunc((GlStateManager.GlStateManager$1)null);\n public int field_179076_b = -1;\n public int field_179077_c = 7680;\n public int field_179074_d = 7680;\n public int field_179075_e = 7680;\n private static final String __OBFID = \"CL_00002543\";\n\n private StencilState() {\n }\n\n StencilState(GlStateManager.GlStateManager$1 p_i46478_1_) {\n this();\n }\n }\n\n public static enum TexGen {\n S(\"S\", 0),\n T(\"T\", 1),\n R(\"R\", 2),\n Q(\"Q\", 3);\n\n private static final GlStateManager.TexGen[] $VALUES = new GlStateManager.TexGen[]{S, T, R, Q};\n private static final String __OBFID = \"CL_00002542\";\n\n private TexGen(String p_i3_3_, int p_i3_4_) {\n }\n }\n\n static class TexGenCoord {\n public GlStateManager.BooleanState field_179067_a;\n public int field_179065_b;\n public int field_179066_c = -1;\n private static final String __OBFID = \"CL_00002541\";\n\n public TexGenCoord(int p_i46254_1_, int p_i46254_2_) {\n this.field_179065_b = p_i46254_1_;\n this.field_179067_a = new GlStateManager.BooleanState(p_i46254_2_);\n }\n }\n\n static class TexGenState {\n public GlStateManager.TexGenCoord field_179064_a = new GlStateManager.TexGenCoord(8192, 3168);\n public GlStateManager.TexGenCoord field_179062_b = new GlStateManager.TexGenCoord(8193, 3169);\n public GlStateManager.TexGenCoord field_179063_c = new GlStateManager.TexGenCoord(8194, 3170);\n public GlStateManager.TexGenCoord field_179061_d = new GlStateManager.TexGenCoord(8195, 3171);\n private static final String __OBFID = \"CL_00002540\";\n\n private TexGenState() {\n }\n\n TexGenState(GlStateManager.GlStateManager$1 p_i46477_1_) {\n this();\n }\n }\n\n static class TextureState {\n public GlStateManager.BooleanState texture2DState = new GlStateManager.BooleanState(3553);\n public int textureName = 0;\n private static final String __OBFID = \"CL_00002539\";\n\n private TextureState() {\n }\n\n TextureState(GlStateManager.GlStateManager$1 p_i46476_1_) {\n this();\n }\n }\n}" }, { "identifier": "LayerBipedArmor", "path": "src/minecraft/net/minecraft/client/renderer/entity/layers/LayerBipedArmor.java", "snippet": "public class LayerBipedArmor extends LayerArmorBase<ModelBiped> {\n public LayerBipedArmor(RendererLivingEntity<?> rendererIn) {\n super(rendererIn);\n }\n\n @Override\n protected void initArmor() {\n this.field_177189_c = new ModelBiped(0.5F);\n this.field_177186_d = new ModelBiped(1.0F);\n }\n\n protected void func_177179_a(ModelBiped p_177179_1_, int p_177179_2_) {\n this.func_177194_a(p_177179_1_);\n switch(p_177179_2_) {\n case 1:\n p_177179_1_.bipedRightLeg.showModel = true;\n p_177179_1_.bipedLeftLeg.showModel = true;\n break;\n case 2:\n p_177179_1_.bipedBody.showModel = true;\n p_177179_1_.bipedRightLeg.showModel = true;\n p_177179_1_.bipedLeftLeg.showModel = true;\n break;\n case 3:\n p_177179_1_.bipedBody.showModel = true;\n p_177179_1_.bipedRightArm.showModel = true;\n p_177179_1_.bipedLeftArm.showModel = true;\n break;\n case 4:\n p_177179_1_.bipedHead.showModel = true;\n p_177179_1_.bipedHeadwear.showModel = true;\n }\n }\n\n protected void func_177194_a(ModelBiped p_177194_1_) {\n p_177194_1_.setInvisible(false);\n }\n}" }, { "identifier": "LayerHeldItem", "path": "src/minecraft/net/minecraft/client/renderer/entity/layers/LayerHeldItem.java", "snippet": "public class LayerHeldItem implements LayerRenderer<EntityLivingBase> {\n private final RendererLivingEntity<?> livingEntityRenderer;\n\n public LayerHeldItem(RendererLivingEntity<?> livingEntityRendererIn) {\n this.livingEntityRenderer = livingEntityRendererIn;\n }\n\n @Override\n public void doRenderLayer(\n EntityLivingBase entitylivingbaseIn,\n float p_177141_2_,\n float p_177141_3_,\n float partialTicks,\n float p_177141_5_,\n float p_177141_6_,\n float p_177141_7_,\n float scale\n ) {\n ItemStack itemstack = entitylivingbaseIn.getHeldItem();\n if (itemstack != null) {\n GlStateManager.pushMatrix();\n if (this.livingEntityRenderer.getMainModel().isChild) {\n float f = 0.5F;\n GlStateManager.translate(0.0F, 0.625F, 0.0F);\n GlStateManager.rotate(-20.0F, -1.0F, 0.0F, 0.0F);\n GlStateManager.scale(f, f, f);\n }\n\n ((ModelBiped)this.livingEntityRenderer.getMainModel()).postRenderArm(0.0625F);\n GlStateManager.translate(-0.0625F, 0.4375F, 0.0625F);\n if (entitylivingbaseIn instanceof EntityPlayer && ((EntityPlayer)entitylivingbaseIn).fishEntity != null) {\n itemstack = new ItemStack(Items.fishing_rod, 0);\n }\n\n Item item = itemstack.getItem();\n Minecraft minecraft = Minecraft.getMinecraft();\n if (item instanceof ItemBlock && Block.getBlockFromItem(item).getRenderType() == 2) {\n GlStateManager.translate(0.0F, 0.1875F, -0.3125F);\n GlStateManager.rotate(20.0F, 1.0F, 0.0F, 0.0F);\n GlStateManager.rotate(45.0F, 0.0F, 1.0F, 0.0F);\n float f1 = 0.375F;\n GlStateManager.scale(-f1, -f1, f1);\n }\n\n if (entitylivingbaseIn.isSneaking()) {\n GlStateManager.translate(0.0F, 0.203125F, 0.0F);\n }\n\n minecraft.getItemRenderer().renderItem(entitylivingbaseIn, itemstack, ItemCameraTransforms.TransformType.THIRD_PERSON);\n GlStateManager.popMatrix();\n }\n }\n\n @Override\n public boolean shouldCombineTextures() {\n return false;\n }\n}" }, { "identifier": "EntityGiantZombie", "path": "src/minecraft/net/minecraft/entity/monster/EntityGiantZombie.java", "snippet": "public class EntityGiantZombie extends EntityMob {\n public EntityGiantZombie(World worldIn) {\n super(worldIn);\n this.setSize(this.width * 6.0F, this.height * 6.0F);\n }\n\n @Override\n public float getEyeHeight() {\n return 10.440001F;\n }\n\n @Override\n protected void applyEntityAttributes() {\n super.applyEntityAttributes();\n this.getEntityAttribute(SharedMonsterAttributes.maxHealth).setBaseValue(100.0);\n this.getEntityAttribute(SharedMonsterAttributes.movementSpeed).setBaseValue(0.5);\n this.getEntityAttribute(SharedMonsterAttributes.attackDamage).setBaseValue(50.0);\n }\n\n @Override\n public float getBlockPathWeight(BlockPos pos) {\n return this.worldObj.getLightBrightness(pos) - 0.5F;\n }\n}" }, { "identifier": "ResourceLocation", "path": "src/minecraft/net/minecraft/util/ResourceLocation.java", "snippet": "public class ResourceLocation\n{\n protected final String resourceDomain;\n protected final String resourcePath;\n\n protected ResourceLocation(int p_i45928_1_, String... resourceName)\n {\n this.resourceDomain = org.apache.commons.lang3.StringUtils.isEmpty(resourceName[0]) ? \"minecraft\" : resourceName[0].toLowerCase();\n this.resourcePath = resourceName[1];\n Validate.notNull(this.resourcePath);\n }\n\n public ResourceLocation(String resourceName)\n {\n this(0, splitObjectName(resourceName));\n }\n\n public ResourceLocation(String resourceDomainIn, String resourcePathIn)\n {\n this(0, new String[] {resourceDomainIn, resourcePathIn});\n }\n\n /**\n * Splits an object name (such as minecraft:apple) into the domain and path parts and returns these as an array of\n * length 2. If no colon is present in the passed value the returned array will contain {null, toSplit}.\n */\n protected static String[] splitObjectName(String toSplit)\n {\n String[] astring = new String[] {null, toSplit};\n int i = toSplit.indexOf(58);\n\n if (i >= 0)\n {\n astring[1] = toSplit.substring(i + 1, toSplit.length());\n\n if (i > 1)\n {\n astring[0] = toSplit.substring(0, i);\n }\n }\n\n return astring;\n }\n\n public String getResourcePath()\n {\n return this.resourcePath;\n }\n\n public String getResourceDomain()\n {\n return this.resourceDomain;\n }\n\n public String toString()\n {\n return this.resourceDomain + ':' + this.resourcePath;\n }\n\n public boolean equals(Object p_equals_1_)\n {\n if (this == p_equals_1_)\n {\n return true;\n }\n else if (!(p_equals_1_ instanceof ResourceLocation))\n {\n return false;\n }\n else\n {\n ResourceLocation resourcelocation = (ResourceLocation)p_equals_1_;\n return this.resourceDomain.equals(resourcelocation.resourceDomain) && this.resourcePath.equals(resourcelocation.resourcePath);\n }\n }\n\n public int hashCode()\n {\n return 31 * this.resourceDomain.hashCode() + this.resourcePath.hashCode();\n }\n}" } ]
import net.minecraft.client.model.ModelBase; import net.minecraft.client.model.ModelZombie; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.entity.layers.LayerBipedArmor; import net.minecraft.client.renderer.entity.layers.LayerHeldItem; import net.minecraft.entity.monster.EntityGiantZombie; import net.minecraft.util.ResourceLocation;
10,216
package net.minecraft.client.renderer.entity; public class RenderGiantZombie extends RenderLiving<EntityGiantZombie> { private static final ResourceLocation zombieTextures = new ResourceLocation("textures/entity/zombie/zombie.png"); private float scale;
package net.minecraft.client.renderer.entity; public class RenderGiantZombie extends RenderLiving<EntityGiantZombie> { private static final ResourceLocation zombieTextures = new ResourceLocation("textures/entity/zombie/zombie.png"); private float scale;
public RenderGiantZombie(RenderManager renderManagerIn, ModelBase modelBaseIn, float shadowSizeIn, float scaleIn) {
0
2023-10-15 00:21:15+00:00
12k
LeGhast/Miniaturise
src/main/java/de/leghast/miniaturise/command/CopyCommand.java
[ { "identifier": "Miniaturise", "path": "src/main/java/de/leghast/miniaturise/Miniaturise.java", "snippet": "public final class Miniaturise extends JavaPlugin {\n\n private MiniatureManager miniatureManager;\n private RegionManager regionManager;\n private SettingsManager settingsManager;\n\n @Override\n public void onEnable() {\n ConfigManager.setupConfig(this);\n initialiseManagers();\n registerListeners();\n setCommands();\n setTabCompleters();\n }\n\n @Override\n public void onDisable() {\n saveConfig();\n }\n\n private void initialiseManagers(){\n miniatureManager = new MiniatureManager(this);\n regionManager = new RegionManager(this);\n settingsManager = new SettingsManager(this);\n }\n\n private void registerListeners(){\n Bukkit.getPluginManager().registerEvents(new PlayerInteractListener(this), this);\n Bukkit.getPluginManager().registerEvents(new PlayerQuitListener(this), this);\n Bukkit.getPluginManager().registerEvents(new InventoryClickListener(this), this);\n }\n\n private void setCommands(){\n getCommand(\"select\").setExecutor(new SelectCommand(this));\n getCommand(\"scale\").setExecutor(new ScaleCommand(this));\n getCommand(\"cut\").setExecutor(new CutCommand(this));\n getCommand(\"tools\").setExecutor(new ToolsCommand(this));\n getCommand(\"paste\").setExecutor(new PasteCommand(this));\n getCommand(\"tool\").setExecutor(new ToolCommand(this));\n getCommand(\"delete\").setExecutor(new DeleteCommand(this));\n getCommand(\"copy\").setExecutor(new CopyCommand(this));\n getCommand(\"position\").setExecutor(new PositionCommand(this));\n getCommand(\"clear\").setExecutor(new ClearCommand(this));\n getCommand(\"adjust\").setExecutor(new AdjustCommand(this));\n getCommand(\"rotate\").setExecutor(new RotateCommand(this));\n }\n\n public void setTabCompleters(){\n getCommand(\"position\").setTabCompleter(new PositionTabCompleter());\n getCommand(\"scale\").setTabCompleter(new ScaleTabCompleter());\n getCommand(\"tool\").setTabCompleter(new ToolTabCompleter());\n getCommand(\"rotate\").setTabCompleter(new RotateTabCompleter());\n }\n\n /**\n * @return The MiniatureManager instance\n */\n public MiniatureManager getMiniatureManager(){\n return miniatureManager;\n }\n\n /**\n * @return The RegionManager instance\n */\n public RegionManager getRegionManager(){\n return regionManager;\n }\n\n public SettingsManager getSettingsManager(){\n return settingsManager;\n }\n\n}" }, { "identifier": "Miniature", "path": "src/main/java/de/leghast/miniaturise/instance/miniature/Miniature.java", "snippet": "public class Miniature {\n\n private List<MiniatureBlock> blocks;\n\n private double size;\n\n public Miniature(Region region, Location origin, double size){\n blocks = new ArrayList<>();\n for(Block block : region.getBlocks()){\n if(!block.getType().isAir() && (bordersAir(block) || bordersNotFullBlock(block))) {\n MiniatureBlock mb;\n mb = new MiniatureBlock(\n block.getX() - (int) origin.getX(),\n block.getY() - (int) origin.getY(),\n block.getZ() - (int) origin.getZ(),\n block.getBlockData(),\n size);\n blocks.add(mb);\n }\n }\n this.size = size;\n }\n\n public Miniature(PlacedMiniature placedMiniature, Location origin, double size){\n blocks = new ArrayList<>();\n if(!placedMiniature.getBlockDisplays().isEmpty()){\n for(BlockDisplay bd : placedMiniature.getBlockDisplays()){\n MiniatureBlock mb;\n mb = new MiniatureBlock(\n bd.getX() - origin.getX(),\n bd.getY() - origin.getY(),\n bd.getZ() - origin.getZ(),\n bd.getBlock(),\n size);\n blocks.add(mb);\n }\n this.size = size;\n }else{\n blocks = null;\n }\n }\n\n public void scaleUp(double scale){\n for(MiniatureBlock mb : blocks){\n mb.setX(mb.getX() * scale);\n mb.setY(mb.getY() * scale);\n mb.setZ(mb.getZ() * scale);\n mb.setSize(mb.getSize() * scale);\n }\n size *= scale;\n }\n\n public void scaleDown(double scale){\n for(MiniatureBlock mb : blocks){\n mb.setX(mb.getX() / scale);\n mb.setY(mb.getY() / scale);\n mb.setZ(mb.getZ() / scale);\n mb.setSize(mb.getSize() / scale);\n }\n size /= scale;\n }\n\n public double getSize(){\n return size;\n }\n\n public List<MiniatureBlock> getBlocks(){\n return blocks;\n }\n\n public int getBlockCount(){\n return blocks.size();\n }\n\n private boolean bordersAir(Block block) {\n return block.getRelative(0, 1, 0).getType().isAir() ||\n block.getRelative(0, -1, 0).getType().isAir() ||\n block.getRelative(1, 0, 0).getType().isAir() ||\n block.getRelative(-1, 0, 0).getType().isAir() ||\n block.getRelative(0, 0, 1).getType().isAir() ||\n block.getRelative(0, 0, -1).getType().isAir();\n }\n private boolean bordersNotFullBlock(Block block) {\n return isNotFullBlock(block.getRelative(0, 1, 0)) ||\n isNotFullBlock(block.getRelative(0, -1, 0)) ||\n isNotFullBlock(block.getRelative(1, 0, 0)) ||\n isNotFullBlock(block.getRelative(-1, 0, 0)) ||\n isNotFullBlock(block.getRelative(0, 0, 1)) ||\n isNotFullBlock(block.getRelative(0, 0, -1));\n }\n\n private boolean isNotFullBlock(Block block){\n VoxelShape collisionShape = block.getCollisionShape();\n if(collisionShape != null){\n double volume = 0;\n for(BoundingBox bb : collisionShape.getBoundingBoxes()){\n volume += bb.getVolume();\n }\n return volume != 1;\n }\n return true;\n }\n\n}" }, { "identifier": "PlacedMiniature", "path": "src/main/java/de/leghast/miniaturise/instance/miniature/PlacedMiniature.java", "snippet": "public class PlacedMiniature {\n\n private List<BlockDisplay> blockDisplays;\n private double blockSize;\n\n public PlacedMiniature(List<MiniatureBlock> blocks, Location origin) throws InvalidParameterException {\n if(!blocks.isEmpty()){\n blockDisplays = new ArrayList<>();\n blockSize = blocks.get(0).getSize();\n\n for(MiniatureBlock mb : blocks) {\n BlockDisplay bd;\n bd = (BlockDisplay) origin.getWorld().spawnEntity(new Location(\n origin.getWorld(),\n mb.getX() + ceil(origin.getX()),\n mb.getY() + ceil(origin.getY()),\n mb.getZ() + ceil(origin.getZ())),\n EntityType.BLOCK_DISPLAY);\n bd.setBlock(mb.getBlockData());\n Transformation transformation = bd.getTransformation();\n transformation.getScale().set(mb.getSize());\n bd.setTransformation(transformation);\n blockDisplays.add(bd);\n }\n }else{\n throw new InvalidParameterException(\"The miniature block list is empty\");\n }\n }\n\n public PlacedMiniature(List<BlockDisplay> blockDisplays) throws InvalidParameterException{\n this.blockDisplays = blockDisplays;\n if(!blockDisplays.isEmpty()){\n blockSize = blockDisplays.get(0).getTransformation().getScale().x;\n }else{\n throw new InvalidParameterException(\"The block display list is empty\");\n }\n }\n\n public void remove(){\n for(BlockDisplay bd : blockDisplays){\n bd.remove();\n }\n }\n\n public void scaleUp(double scale){\n Bukkit.getScheduler().runTaskAsynchronously(getMain(), () -> {\n Location origin = blockDisplays.get(0).getLocation();\n Miniature miniature = new Miniature(this, origin, blockSize);\n miniature.scaleUp(scale);\n rearrange(origin, miniature);\n blockSize *= scale;\n });\n }\n\n public void scaleDown(double scale){\n Bukkit.getScheduler().runTaskAsynchronously(getMain(), () -> {\n Location origin = blockDisplays.get(0).getLocation();\n Miniature miniature = new Miniature(this, origin, blockSize);\n miniature.scaleDown(scale);\n rearrange(origin, miniature);\n blockSize /= scale;\n });\n }\n\n private void rearrange(Location origin, Miniature miniature) {\n Bukkit.getScheduler().runTaskAsynchronously(getMain(), () -> {\n for(int i = 0; i < getBlockCount(); i++){\n BlockDisplay bd = blockDisplays.get(i);\n MiniatureBlock mb = miniature.getBlocks().get(i);\n Bukkit.getScheduler().scheduleSyncDelayedTask(getMain(), () -> {\n bd.teleport(new Location( bd.getWorld(),\n mb.getX() + origin.getX(),\n mb.getY() + origin.getY(),\n mb.getZ() + origin.getZ()));\n Transformation transformation = bd.getTransformation();\n transformation.getScale().set(mb.getSize());\n bd.setTransformation(transformation);\n });\n }\n });\n }\n\n public void rotate(Axis axis, float angle){\n Location origin = blockDisplays.get(0).getLocation();\n float finalAngle = (float) Math.toRadians(angle);\n Bukkit.getScheduler().runTaskAsynchronously(getMain(), () -> {\n\n for(BlockDisplay bd : blockDisplays){\n\n Transformation transformation = bd.getTransformation();\n\n switch (axis){\n case X -> transformation.getLeftRotation().rotateX(finalAngle);\n case Y -> transformation.getLeftRotation().rotateY(finalAngle);\n case Z -> transformation.getLeftRotation().rotateZ(finalAngle);\n }\n\n Vector3f newPositionVector = getRotatedPosition(\n bd.getLocation().toVector().toVector3f(),\n origin.toVector().toVector3f(),\n axis,\n finalAngle\n );\n\n Location newLocation = new Location(\n bd.getLocation().getWorld(),\n newPositionVector.x,\n newPositionVector.y,\n newPositionVector.z\n );\n Bukkit.getScheduler().scheduleSyncDelayedTask(getMain(), () -> {\n bd.setTransformation(transformation);\n bd.teleport(newLocation);\n });\n\n }\n });\n\n\n\n }\n\n private Vector3f getRotatedPosition(Vector3f pointToRotate, Vector3f origin, Axis axis, float angle){\n pointToRotate.sub(origin);\n Matrix3f rotationMatrix = new Matrix3f();\n\n switch (axis){\n case X -> rotationMatrix.rotationX(angle);\n case Y -> rotationMatrix.rotationY(angle);\n case Z -> rotationMatrix.rotationZ(angle);\n }\n\n rotationMatrix.transform(pointToRotate);\n\n pointToRotate.add(origin);\n\n return pointToRotate;\n }\n\n public void move(Vector addition){\n Bukkit.getScheduler().scheduleSyncDelayedTask(getMain(), () -> {\n for(BlockDisplay bd : blockDisplays){\n bd.teleport(bd.getLocation().add(addition));\n }\n });\n }\n\n public void move(Axis axis, double addition){\n switch (axis){\n case X -> move(new Vector(addition, 0, 0));\n case Y -> move(new Vector(0, addition, 0));\n case Z -> move(new Vector(0, 0, addition));\n }\n }\n\n public double getBlockSize() {\n return blockSize;\n }\n\n public int getBlockCount(){\n return blockDisplays.size();\n }\n\n public List<BlockDisplay> getBlockDisplays(){\n return blockDisplays;\n }\n\n private Miniaturise getMain(){\n return (Miniaturise) Bukkit.getPluginManager().getPlugin(\"Miniaturise\");\n }\n\n}" }, { "identifier": "Region", "path": "src/main/java/de/leghast/miniaturise/instance/region/Region.java", "snippet": "public class Region implements Iterable<Block>, Cloneable, ConfigurationSerializable {\n protected final String worldName;\n protected final int x1, y1, z1;\n protected final int x2, y2, z2;\n\n /**\n * Construct a region given two Location objects which represent any two corners of the region.\n * Note: The 2 locations must be on the same world.\n *\n * @param l1 - One of the corners\n * @param l2 - The other corner\n */\n public Region(Location l1, Location l2) {\n if (!l1.getWorld().equals(l2.getWorld())) throw new IllegalArgumentException(\"Locations must be on the same world\");\n this.worldName = l1.getWorld().getName();\n this.x1 = Math.min(l1.getBlockX(), l2.getBlockX());\n this.y1 = Math.min(l1.getBlockY(), l2.getBlockY());\n this.z1 = Math.min(l1.getBlockZ(), l2.getBlockZ());\n this.x2 = Math.max(l1.getBlockX(), l2.getBlockX());\n this.y2 = Math.max(l1.getBlockY(), l2.getBlockY());\n this.z2 = Math.max(l1.getBlockZ(), l2.getBlockZ());\n }\n\n /**\n * Construct a one-block region at the given Location of the region.\n *\n * @param l1 location of the region\n */\n public Region(Location l1) {\n this(l1, l1);\n }\n\n /**\n * Construct a region from an SelectedLocations object\n *\n * @param locations The SelectedLocations, that contains both necessary region locations\n * */\n public Region(SelectedLocations locations){\n this(locations.getLoc1(), locations.getLoc2());\n }\n\n /**\n * Copy constructor.\n *\n * @param other - The region to copy\n */\n public Region(Region other) {\n this(other.getWorld().getName(), other.x1, other.y1, other.z1, other.x2, other.y2, other.z2);\n }\n\n /**\n * Construct a region in the given World and xyz co-ordinates\n *\n * @param world - The region's world\n * @param x1 - X co-ordinate of corner 1\n * @param y1 - Y co-ordinate of corner 1\n * @param z1 - Z co-ordinate of corner 1\n * @param x2 - X co-ordinate of corner 2\n * @param y2 - Y co-ordinate of corner 2\n * @param z2 - Z co-ordinate of corner 2\n */\n public Region(World world, int x1, int y1, int z1, int x2, int y2, int z2) {\n this.worldName = world.getName();\n this.x1 = Math.min(x1, x2);\n this.x2 = Math.max(x1, x2);\n this.y1 = Math.min(y1, y2);\n this.y2 = Math.max(y1, y2);\n this.z1 = Math.min(z1, z2);\n this.z2 = Math.max(z1, z2);\n }\n\n /**\n * Construct a region in the given world name and xyz co-ordinates.\n *\n * @param worldName - The region's world name\n * @param x1 - X co-ordinate of corner 1\n * @param y1 - Y co-ordinate of corner 1\n * @param z1 - Z co-ordinate of corner 1\n * @param x2 - X co-ordinate of corner 2\n * @param y2 - Y co-ordinate of corner 2\n * @param z2 - Z co-ordinate of corner 2\n */\n private Region(String worldName, int x1, int y1, int z1, int x2, int y2, int z2) {\n this.worldName = worldName;\n this.x1 = Math.min(x1, x2);\n this.x2 = Math.max(x1, x2);\n this.y1 = Math.min(y1, y2);\n this.y2 = Math.max(y1, y2);\n this.z1 = Math.min(z1, z2);\n this.z2 = Math.max(z1, z2);\n }\n\n /**\n * Construct a region using a map with the following keys: worldName, x1, x2, y1, y2, z1, z2\n * @param map - The map of keys.\n */\n public Region(Map<String, Object> map) {\n this.worldName = (String) map.get(\"worldName\");\n this.x1 = (Integer) map.get(\"x1\");\n this.x2 = (Integer) map.get(\"x2\");\n this.y1 = (Integer) map.get(\"y1\");\n this.y2 = (Integer) map.get(\"y2\");\n this.z1 = (Integer) map.get(\"z1\");\n this.z2 = (Integer) map.get(\"z2\");\n }\n\n @Override\n public Map<String, Object> serialize() {\n Map<String, Object> map = new HashMap<String, Object>();\n map.put(\"worldName\", this.worldName);\n map.put(\"x1\", this.x1);\n map.put(\"y1\", this.y1);\n map.put(\"z1\", this.z1);\n map.put(\"x2\", this.x2);\n map.put(\"y2\", this.y2);\n map.put(\"z2\", this.z2);\n return map;\n }\n\n /**\n * Get the Location of the lower northeast corner of the region (minimum XYZ co-ordinates).\n *\n * @return Location of the lower northeast corner\n */\n public Location getLowerNE() {\n return new Location(this.getWorld(), this.x1, this.y1, this.z1);\n }\n\n /**\n * Get the Location of the upper southwest corner of the region (maximum XYZ co-ordinates).\n *\n * @return Location of the upper southwest corner\n */\n public Location getUpperSW() {\n return new Location(this.getWorld(), this.x2, this.y2, this.z2);\n }\n\n /**\n * Get the blocks in the region.\n *\n * @return The blocks in the region\n */\n public List<Block> getBlocks() {\n Iterator<Block> blockI = this.iterator();\n List<Block> copy = new ArrayList<Block>();\n while (blockI.hasNext())\n copy.add(blockI.next());\n return copy;\n }\n\n /**\n * Get the centre of the region.\n *\n * @return Location at the centre of the region\n */\n public Location getCenter() {\n int x1 = this.getUpperX() + 1;\n int y1 = this.getUpperY() + 1;\n int z1 = this.getUpperZ() + 1;\n return new Location(this.getWorld(), this.getLowerX() + (x1 - this.getLowerX()) / 2.0, this.getLowerY() + (y1 - this.getLowerY()) / 2.0, this.getLowerZ() + (z1 - this.getLowerZ()) / 2.0);\n }\n\n /**\n * Get the region's world.\n *\n * @return The World object representing this region's world\n * @throws IllegalStateException if the world is not loaded\n */\n public World getWorld() {\n World world = Bukkit.getWorld(this.worldName);\n if (world == null) throw new IllegalStateException(\"World '\" + this.worldName + \"' is not loaded\");\n return world;\n }\n\n /**\n * Get the size of this region along the X axis\n *\n * @return\tSize of region along the X axis\n */\n public int getSizeX() {\n return (this.x2 - this.x1) + 1;\n }\n\n /**\n * Get the size of this region along the Y axis\n *\n * @return\tSize of region along the Y axis\n */\n public int getSizeY() {\n return (this.y2 - this.y1) + 1;\n }\n\n /**\n * Get the size of this region along the Z axis\n *\n * @return\tSize of region along the Z axis\n */\n public int getSizeZ() {\n return (this.z2 - this.z1) + 1;\n }\n\n /**\n * Get the minimum X co-ordinate of this region\n *\n * @return\tthe minimum X co-ordinate\n */\n public int getLowerX() {\n return this.x1;\n }\n\n /**\n * Get the minimum Y co-ordinate of this region\n *\n * @return\tthe minimum Y co-ordinate\n */\n public int getLowerY() {\n return this.y1;\n }\n\n /**\n * Get the minimum Z co-ordinate of this region\n *\n * @return\tthe minimum Z co-ordinate\n */\n public int getLowerZ() {\n return this.z1;\n }\n\n /**\n * Get the maximum X co-ordinate of this region\n *\n * @return\tthe maximum X co-ordinate\n */\n public int getUpperX() {\n return this.x2;\n }\n\n /**\n * Get the maximum Y co-ordinate of this region\n *\n * @return\tthe maximum Y co-ordinate\n */\n public int getUpperY() {\n return this.y2;\n }\n\n /**\n * Get the maximum Z co-ordinate of this region\n *\n * @return\tthe maximum Z co-ordinate\n */\n public int getUpperZ() {\n return this.z2;\n }\n\n /**\n * Get the Blocks at the eight corners of the region.\n *\n * @return array of Block objects representing the region corners\n */\n public Block[] corners() {\n Block[] res = new Block[8];\n World w = this.getWorld();\n res[0] = w.getBlockAt(this.x1, this.y1, this.z1);\n res[1] = w.getBlockAt(this.x1, this.y1, this.z2);\n res[2] = w.getBlockAt(this.x1, this.y2, this.z1);\n res[3] = w.getBlockAt(this.x1, this.y2, this.z2);\n res[4] = w.getBlockAt(this.x2, this.y1, this.z1);\n res[5] = w.getBlockAt(this.x2, this.y1, this.z2);\n res[6] = w.getBlockAt(this.x2, this.y2, this.z1);\n res[7] = w.getBlockAt(this.x2, this.y2, this.z2);\n return res;\n }\n\n /**\n * Expand the region in the given direction by the given amount. Negative amounts will shrink the region in the given direction. Shrinking a region's face past the opposite face is not an error and will return a valid region.\n *\n * @param dir - The direction in which to expand\n * @param amount - The number of blocks by which to expand\n * @return A new region expanded by the given direction and amount\n */\n public Region expand(regionDirection dir, int amount) {\n switch (dir) {\n case North:\n return new Region(this.worldName, this.x1 - amount, this.y1, this.z1, this.x2, this.y2, this.z2);\n case South:\n return new Region(this.worldName, this.x1, this.y1, this.z1, this.x2 + amount, this.y2, this.z2);\n case East:\n return new Region(this.worldName, this.x1, this.y1, this.z1 - amount, this.x2, this.y2, this.z2);\n case West:\n return new Region(this.worldName, this.x1, this.y1, this.z1, this.x2, this.y2, this.z2 + amount);\n case Down:\n return new Region(this.worldName, this.x1, this.y1 - amount, this.z1, this.x2, this.y2, this.z2);\n case Up:\n return new Region(this.worldName, this.x1, this.y1, this.z1, this.x2, this.y2 + amount, this.z2);\n default:\n throw new IllegalArgumentException(\"Invalid direction \" + dir);\n }\n }\n\n /**\n * Shift the region in the given direction by the given amount.\n *\n * @param dir - The direction in which to shift\n * @param amount - The number of blocks by which to shift\n * @return A new region shifted by the given direction and amount\n */\n public Region shift(regionDirection dir, int amount) {\n return expand(dir, amount).expand(dir.opposite(), -amount);\n }\n\n /**\n * Outset (grow) the region in the given direction by the given amount.\n *\n * @param dir - The direction in which to outset (must be Horizontal, Vertical, or Both)\n * @param amount - The number of blocks by which to outset\n * @return A new region outset by the given direction and amount\n */\n public Region outset(regionDirection dir, int amount) {\n Region c;\n switch (dir) {\n case Horizontal:\n c = expand(regionDirection.North, amount).expand(regionDirection.South, amount).expand(regionDirection.East, amount).expand(regionDirection.West, amount);\n break;\n case Vertical:\n c = expand(regionDirection.Down, amount).expand(regionDirection.Up, amount);\n break;\n case Both:\n c = outset(regionDirection.Horizontal, amount).outset(regionDirection.Vertical, amount);\n break;\n default:\n throw new IllegalArgumentException(\"Invalid direction \" + dir);\n }\n return c;\n }\n\n /**\n * Inset (shrink) the region in the given direction by the given amount. Equivalent\n * to calling outset() with a negative amount.\n *\n * @param dir - The direction in which to inset (must be Horizontal, Vertical, or Both)\n * @param amount - The number of blocks by which to inset\n * @return A new region inset by the given direction and amount\n */\n public Region inset(regionDirection dir, int amount) {\n return this.outset(dir, -amount);\n }\n\n /**\n * Return true if the point at (x,y,z) is contained within this region.\n *\n * @param x\t- The X co-ordinate\n * @param y\t- The Y co-ordinate\n * @param z\t- The Z co-ordinate\n * @return true if the given point is within this region, false otherwise\n */\n public boolean contains(int x, int y, int z) {\n return x >= this.x1 && x <= this.x2 && y >= this.y1 && y <= this.y2 && z >= this.z1 && z <= this.z2;\n }\n\n /**\n * Check if the given Block is contained within this region.\n *\n * @param b\t- The Block to check for\n * @return true if the Block is within this region, false otherwise\n */\n public boolean contains(Block b) {\n return this.contains(b.getLocation());\n }\n\n /**\n * Check if the given Location is contained within this region.\n *\n * @param l\t- The Location to check for\n * @return true if the Location is within this region, false otherwise\n */\n public boolean contains(Location l) {\n if (!this.worldName.equals(l.getWorld().getName())) return false;\n return this.contains(l.getBlockX(), l.getBlockY(), l.getBlockZ());\n }\n\n /**\n * Get the volume of this region.\n *\n * @return The region volume, in blocks\n */\n public int getVolume() {\n return this.getSizeX() * this.getSizeY() * this.getSizeZ();\n }\n\n /**\n * Get the average light level of all empty (air) blocks in the region. Returns 0 if there are no empty blocks.\n *\n * @return The average light level of this region\n */\n public byte getAverageLightLevel() {\n long total = 0;\n int n = 0;\n for (Block b : this) {\n if (b.isEmpty()) {\n total += b.getLightLevel();\n ++n;\n }\n }\n return n > 0 ? (byte) (total / n) : 0;\n }\n\n /**\n * Contract the region, returning a region with any air around the edges removed, just large enough to include all non-air blocks.\n *\n * @return A new region with no external air blocks\n */\n public Region contract() {\n return this.contract(regionDirection.Down).contract(regionDirection.South).contract(regionDirection.East).contract(regionDirection.Up).contract(regionDirection.North).contract(regionDirection.West);\n }\n\n /**\n * Contract the region in the given direction, returning a new region which has no exterior empty space.\n * E.g. A direction of Down will push the top face downwards as much as possible.\n *\n * @param dir - The direction in which to contract\n * @return A new region contracted in the given direction\n */\n public Region contract(regionDirection dir) {\n Region face = getFace(dir.opposite());\n switch (dir) {\n case Down:\n while (face.containsOnly(Material.AIR) && face.getLowerY() > this.getLowerY()) {\n face = face.shift(regionDirection.Down, 1);\n }\n return new Region(this.worldName, this.x1, this.y1, this.z1, this.x2, face.getUpperY(), this.z2);\n case Up:\n while (face.containsOnly(Material.AIR) && face.getUpperY() < this.getUpperY()) {\n face = face.shift(regionDirection.Up, 1);\n }\n return new Region(this.worldName, this.x1, face.getLowerY(), this.z1, this.x2, this.y2, this.z2);\n case North:\n while (face.containsOnly(Material.AIR) && face.getLowerX() > this.getLowerX()) {\n face = face.shift(regionDirection.North, 1);\n }\n return new Region(this.worldName, this.x1, this.y1, this.z1, face.getUpperX(), this.y2, this.z2);\n case South:\n while (face.containsOnly(Material.AIR) && face.getUpperX() < this.getUpperX()) {\n face = face.shift(regionDirection.South, 1);\n }\n return new Region(this.worldName, face.getLowerX(), this.y1, this.z1, this.x2, this.y2, this.z2);\n case East:\n while (face.containsOnly(Material.AIR) && face.getLowerZ() > this.getLowerZ()) {\n face = face.shift(regionDirection.East, 1);\n }\n return new Region(this.worldName, this.x1, this.y1, this.z1, this.x2, this.y2, face.getUpperZ());\n case West:\n while (face.containsOnly(Material.AIR) && face.getUpperZ() < this.getUpperZ()) {\n face = face.shift(regionDirection.West, 1);\n }\n return new Region(this.worldName, this.x1, this.y1, face.getLowerZ(), this.x2, this.y2, this.z2);\n default:\n throw new IllegalArgumentException(\"Invalid direction \" + dir);\n }\n }\n\n /**\n * Get the region representing the face of this region. The resulting region will be one block thick in the axis perpendicular to the requested face.\n *\n * @param dir - which face of the region to get\n * @return The region representing this region's requested face\n */\n public Region getFace(regionDirection dir) {\n switch (dir) {\n case Down:\n return new Region(this.worldName, this.x1, this.y1, this.z1, this.x2, this.y1, this.z2);\n case Up:\n return new Region(this.worldName, this.x1, this.y2, this.z1, this.x2, this.y2, this.z2);\n case North:\n return new Region(this.worldName, this.x1, this.y1, this.z1, this.x1, this.y2, this.z2);\n case South:\n return new Region(this.worldName, this.x2, this.y1, this.z1, this.x2, this.y2, this.z2);\n case East:\n return new Region(this.worldName, this.x1, this.y1, this.z1, this.x2, this.y2, this.z1);\n case West:\n return new Region(this.worldName, this.x1, this.y1, this.z2, this.x2, this.y2, this.z2);\n default:\n throw new IllegalArgumentException(\"Invalid direction \" + dir);\n }\n }\n\n /**\n * Check if the region contains only blocks of the given type\n *\n * @param blockType - The block material to check for\n * @return true if this region contains only blocks of the given type\n */\n public boolean containsOnly(Material blockType) {\n for (Block b : this) {\n if (b.getType() != blockType) return false;\n }\n return true;\n }\n\n /**\n * Get the region big enough to hold both this region and the given one.\n *\n * @param other - The other region.\n * @return A new region large enough to hold this region and the given region\n */\n public Region getBoundingregion(Region other) {\n if (other == null) return this;\n\n int xMin = Math.min(this.getLowerX(), other.getLowerX());\n int yMin = Math.min(this.getLowerY(), other.getLowerY());\n int zMin = Math.min(this.getLowerZ(), other.getLowerZ());\n int xMax = Math.max(this.getUpperX(), other.getUpperX());\n int yMax = Math.max(this.getUpperY(), other.getUpperY());\n int zMax = Math.max(this.getUpperZ(), other.getUpperZ());\n\n return new Region(this.worldName, xMin, yMin, zMin, xMax, yMax, zMax);\n }\n\n /**\n * Get a block relative to the lower NE point of the region.\n *\n * @param x\t- The X co-ordinate\n * @param y\t- The Y co-ordinate\n * @param z\t- The Z co-ordinate\n * @return The block at the given position\n */\n public Block getRelativeBlock(int x, int y, int z) {\n return this.getWorld().getBlockAt(this.x1 + x, this.y1 + y, this.z1 + z);\n }\n\n /**\n * Get a block relative to the lower NE point of the region in the given World. This\n * version of getRelativeBlock() should be used if being called many times, to avoid\n * excessive calls to getWorld().\n *\n * @param w\t- The world\n * @param x\t- The X co-ordinate\n * @param y\t- The Y co-ordinate\n * @param z\t- The Z co-ordinate\n * @return The block at the given position\n */\n public Block getRelativeBlock(World w, int x, int y, int z) {\n return w.getBlockAt(this.x1 + x, y1 + y, this.z1 + z);\n }\n\n /**\n * Get a list of the chunks which are fully or partially contained in this region.\n *\n * @return A list of Chunk objects\n */\n public List<Chunk> getChunks() {\n List<Chunk> res = new ArrayList<Chunk>();\n\n World w = this.getWorld();\n int x1 = this.getLowerX() & ~0xf;\n int x2 = this.getUpperX() & ~0xf;\n int z1 = this.getLowerZ() & ~0xf;\n int z2 = this.getUpperZ() & ~0xf;\n for (int x = x1; x <= x2; x += 16) {\n for (int z = z1; z <= z2; z += 16) {\n res.add(w.getChunkAt(x >> 4, z >> 4));\n }\n }\n return res;\n }\n\n public Iterator<Block> iterator() {\n return new regionIterator(this.getWorld(), this.x1, this.y1, this.z1, this.x2, this.y2, this.z2);\n }\n\n @Override\n public Region clone() {\n return new Region(this);\n }\n\n @Override\n public String toString() {\n return new String(\"region: \" + this.worldName + \",\" + this.x1 + \",\" + this.y1 + \",\" + this.z1 + \"=>\" + this.x2 + \",\" + this.y2 + \",\" + this.z2);\n }\n\n public class regionIterator implements Iterator<Block> {\n private World w;\n private int baseX, baseY, baseZ;\n private int x, y, z;\n private int sizeX, sizeY, sizeZ;\n\n public regionIterator(World w, int x1, int y1, int z1, int x2, int y2, int z2) {\n this.w = w;\n this.baseX = x1;\n this.baseY = y1;\n this.baseZ = z1;\n this.sizeX = Math.abs(x2 - x1) + 1;\n this.sizeY = Math.abs(y2 - y1) + 1;\n this.sizeZ = Math.abs(z2 - z1) + 1;\n this.x = this.y = this.z = 0;\n }\n\n public boolean hasNext() {\n return this.x < this.sizeX && this.y < this.sizeY && this.z < this.sizeZ;\n }\n\n public Block next() {\n Block b = this.w.getBlockAt(this.baseX + this.x, this.baseY + this.y, this.baseZ + this.z);\n if (++x >= this.sizeX) {\n this.x = 0;\n if (++this.y >= this.sizeY) {\n this.y = 0;\n ++this.z;\n }\n }\n return b;\n }\n\n public void remove() {\n }\n }\n\n public enum regionDirection {\n North, East, South, West, Up, Down, Horizontal, Vertical, Both, Unknown;\n\n public regionDirection opposite() {\n switch (this) {\n case North:\n return South;\n case East:\n return West;\n case South:\n return North;\n case West:\n return East;\n case Horizontal:\n return Vertical;\n case Vertical:\n return Horizontal;\n case Up:\n return Down;\n case Down:\n return Up;\n case Both:\n return Both;\n default:\n return Unknown;\n }\n }\n\n }\n\n}" }, { "identifier": "Util", "path": "src/main/java/de/leghast/miniaturise/util/Util.java", "snippet": "public class Util {\n\n public static final String PREFIX = \"§7[§eMiniaturise§7] \";\n\n public static String getDimensionName(String string){\n switch (string){\n case \"NORMAL\" -> {\n return \"minecraft:overworld\";\n }\n case \"NETHER\" -> {\n return \"minecraft:the_nether\";\n }\n case \"THE_END\" -> {\n return \"minecraft:the_end\";\n }\n default -> {\n return \"Invalid dimension\";\n }\n }\n }\n\n public static List<BlockDisplay> getBlockDisplaysFromRegion(Player player, Region region){\n List<BlockDisplay> blockDisplays = new ArrayList<>();\n for(Chunk chunk : player.getWorld().getLoadedChunks()){\n for(Entity entity : chunk.getEntities()){\n if(entity instanceof BlockDisplay && region.contains(entity.getLocation())){\n blockDisplays.add((BlockDisplay) entity);\n }\n }\n }\n return blockDisplays;\n }\n\n public static void setCustomNumberInput(Miniaturise main, Player player, Page page){\n ItemStack output = new ItemStack(Material.PAPER);\n ItemMeta meta = output.getItemMeta();\n meta.setDisplayName(\"§eSet custom factor\");\n output.setItemMeta(meta);\n PageUtil.addGlint(output);\n\n new AnvilGUI.Builder()\n .title(\"§eEnter custom factor\")\n .text(\"1\")\n .onClick((slot, stateSnapshot) -> {\n if(slot == AnvilGUI.Slot.OUTPUT){\n AdjusterSettings settings = main.getSettingsManager().getAdjusterSettings(player.getUniqueId());\n switch (page){\n case POSITION -> settings.getPositionSettings().setFactor(stateSnapshot.getText());\n case SIZE -> settings.getSizeSettings().setFactor(stateSnapshot.getText());\n case ROTATION -> settings.getRotationSettings().setFactor(stateSnapshot.getText());\n }\n return Arrays.asList(AnvilGUI.ResponseAction.close());\n }\n return Arrays.asList(AnvilGUI.ResponseAction.updateTitle(\"§eEnter custom factor\", false));\n })\n .preventClose()\n .itemOutput(output)\n .plugin(main)\n .open(player);\n\n }\n\n}" } ]
import de.leghast.miniaturise.Miniaturise; import de.leghast.miniaturise.instance.miniature.Miniature; import de.leghast.miniaturise.instance.miniature.PlacedMiniature; import de.leghast.miniaturise.instance.region.Region; import de.leghast.miniaturise.util.Util; import org.bukkit.Bukkit; import org.bukkit.Chunk; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.BlockDisplay; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.List;
10,268
package de.leghast.miniaturise.command; public class CopyCommand implements CommandExecutor { private Miniaturise main; public CopyCommand(Miniaturise main){ this.main = main; } @Override public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String s, @NotNull String[] args) { if(sender instanceof Player player){ if(player.hasPermission("miniaturise.use")) { Bukkit.getScheduler().runTaskAsynchronously(main, () -> { try { Region region = new Region(main.getRegionManager().getSelectedLocations(player.getUniqueId())); if (main.getRegionManager().hasRegion(player.getUniqueId())) { main.getRegionManager().getRegions().replace(player.getUniqueId(), region); } else { main.getRegionManager().addRegion(player.getUniqueId(), region); } List<BlockDisplay> blockDisplays = Util.getBlockDisplaysFromRegion(player, region); if (!blockDisplays.isEmpty()) {
package de.leghast.miniaturise.command; public class CopyCommand implements CommandExecutor { private Miniaturise main; public CopyCommand(Miniaturise main){ this.main = main; } @Override public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String s, @NotNull String[] args) { if(sender instanceof Player player){ if(player.hasPermission("miniaturise.use")) { Bukkit.getScheduler().runTaskAsynchronously(main, () -> { try { Region region = new Region(main.getRegionManager().getSelectedLocations(player.getUniqueId())); if (main.getRegionManager().hasRegion(player.getUniqueId())) { main.getRegionManager().getRegions().replace(player.getUniqueId(), region); } else { main.getRegionManager().addRegion(player.getUniqueId(), region); } List<BlockDisplay> blockDisplays = Util.getBlockDisplaysFromRegion(player, region); if (!blockDisplays.isEmpty()) {
Miniature miniature = new Miniature(new PlacedMiniature(blockDisplays), player.getLocation(),
2
2023-10-15 09:08:33+00:00
12k
instrumental-id/iiq-common-public
src/com/identityworksllc/iiq/common/Utilities.java
[ { "identifier": "SLogger", "path": "src/com/identityworksllc/iiq/common/logging/SLogger.java", "snippet": "public class SLogger implements org.apache.commons.logging.Log {\n\t\n\t/**\n\t * Helper class to format an object for logging. The format is only derived\n\t * when the {@link #toString()} is called, meaning that if you log one of these\n\t * and the log level is not enabled, a slow string conversion will never occur.\n\t *\n\t * Null values are transformed into the special string '(null)'.\n\t *\n\t * Formatted values are cached after the first format operation, even if the\n\t * underlying object is modified.\n\t *\n\t * The following types are handled by the Formatter:\n\t *\n\t * - null\n\t * - Strings\n\t * - Arrays of Objects\n\t * - Arrays of StackTraceElements\n\t * - Collections of Objects\n\t * - Maps\n\t * - Dates and Calendars\n\t * - XML {@link Document}s\n\t * - Various SailPointObjects\n\t *\n\t * Nested objects are also passed through a Formatter.\n\t */\n\tpublic static class Formatter implements Supplier<String> {\n\n\t\t/**\n\t\t * The cached formatted value\n\t\t */\n\t\tprivate String formattedValue;\n\t\t/**\n\t\t * The object to format.\n\t\t */\n\t\tprivate final Object item;\n\n\t\t/**\n\t\t * Creates a new formatter.\n\t\t *\n\t\t * @param Item The item to format.\n\t\t */\n\t\tpublic Formatter(Object Item) {\n\t\t\tthis.item = Item;\n\t\t\tthis.formattedValue = null;\n\t\t}\n\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tprivate Map<String, Object> createLogMap(SailPointObject value) {\n\t\t\tMap<String, Object> map = new ListOrderedMap();\n\t\t\tmap.put(\"class\", value.getClass().getName());\n\t\t\tmap.put(\"id\", value.getId());\n\t\t\tmap.put(\"name\", value.getName());\n\t\t\treturn map;\n\t\t}\n\n\t\t/**\n\t\t * Formats an object.\n\t\t *\n\t\t * @param valueToFormat The object to format.\n\t\t * @return The formatted version of that object.\n\t\t */\n\t\tprivate String format(Object valueToFormat) {\n\t\t\treturn format(valueToFormat, false);\n\t\t}\n\n\t\t/**\n\t\t * Formats an object according to multiple type-specific format rules.\n\t\t *\n\t\t * @param valueToFormat The object to format.\n\t\t * @return The formatted version of that object.\n\t\t */\n\t\tprivate String format(Object valueToFormat, boolean indent) {\n\t\t\tStringBuilder value = new StringBuilder();\n\n\t\t\tif (valueToFormat == null) {\n\t\t\t\tvalue.append(\"(null)\");\n\t\t\t} else if (valueToFormat instanceof String) {\n\t\t\t\tvalue.append(valueToFormat);\n\t\t\t} else if (valueToFormat instanceof bsh.This) {\n\t\t\t\tString namespaceName = \"???\";\n\t\t\t\tif (((This) valueToFormat).getNameSpace() != null) {\n\t\t\t\t\tnamespaceName = ((This) valueToFormat).getNameSpace().getName();\n\t\t\t\t}\n\t\t\t\tvalue.append(\"bsh.This[namespace=\").append(namespaceName).append(\"]\");\n\t\t\t} else if (valueToFormat instanceof StackTraceElement[]) {\n\t\t\t\tfor (StackTraceElement element : (StackTraceElement[]) valueToFormat) {\n\t\t\t\t\tvalue.append(\"\\n at \");\n\t\t\t\t\tvalue.append(element);\n\t\t\t\t}\n\t\t\t} else if (valueToFormat instanceof Throwable) {\n\t\t\t\tThrowable t = (Throwable)valueToFormat;\n\t\t\t\ttry (StringWriter target = new StringWriter()) {\n\t\t\t\t\ttry (PrintWriter printWriter = new PrintWriter(target)) {\n\t\t\t\t\t\tt.printStackTrace(printWriter);\n\t\t\t\t\t}\n\t\t\t\t\tvalue.append(target);\n\t\t\t\t} catch(IOException e) {\n\t\t\t\t\treturn \"Exception printing object of type Throwable: \" + e;\n\t\t\t\t}\n\t\t\t} else if (valueToFormat.getClass().isArray()) {\n\t\t\t\tvalue.append(\"[\\n\");\n\t\t\t\tboolean first = true;\n\t\t\t\tint length = Array.getLength(valueToFormat);\n\t\t\t\tfor (int i = 0; i < length; i++) {\n\t\t\t\t\tif (!first) {\n\t\t\t\t\t\tvalue.append(\",\\n\");\n\t\t\t\t\t}\n\t\t\t\t\tvalue.append(\" \");\n\t\t\t\t\tvalue.append(format(Array.get(valueToFormat, i), true));\n\t\t\t\t\tfirst = false;\n\t\t\t\t}\n\t\t\t\tvalue.append(\"\\n]\");\n\t\t\t} else if (valueToFormat instanceof Collection) {\n\t\t\t\tvalue.append(\"[\\n\");\n\t\t\t\tboolean first = true;\n\t\t\t\tfor (Object arg : (Collection<?>) valueToFormat) {\n\t\t\t\t\tif (!first) {\n\t\t\t\t\t\tvalue.append(\",\\n\");\n\t\t\t\t\t}\n\t\t\t\t\tvalue.append(\" \").append(format(arg, true));\n\t\t\t\t\tfirst = false;\n\t\t\t\t}\n\t\t\t\tvalue.append(\"\\n]\");\n\t\t\t} else if (valueToFormat instanceof Map) {\n\t\t\t\tvalue.append(\"{\\n\");\n\t\t\t\tboolean first = true;\n\t\t\t\tfor (Map.Entry<?, ?> entry : new TreeMap<Object, Object>((Map<?, ?>) valueToFormat).entrySet()) {\n\t\t\t\t\tif (!first) {\n\t\t\t\t\t\tvalue.append(\",\\n\");\n\t\t\t\t\t}\n\t\t\t\t\tvalue.append(\" \");\n\t\t\t\t\tvalue.append(format(entry.getKey()));\n\t\t\t\t\tvalue.append(\"=\");\n\t\t\t\t\tvalue.append(format(entry.getValue(), true));\n\t\t\t\t\tfirst = false;\n\t\t\t\t}\n\t\t\t\tvalue.append(\"\\n}\");\n\t\t\t} else if (valueToFormat instanceof Date) {\n\t\t\t\tDateFormat format = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss z\");\n\t\t\t\tvalue.append(format.format((Date) valueToFormat));\n\t\t\t} else if (valueToFormat instanceof Calendar) {\n\t\t\t\tvalue.append(format(((Calendar) valueToFormat).getTime()));\n\t\t\t} else if (valueToFormat instanceof Document) {\n\t\t\t\ttry {\n\t\t\t\t\tTransformer transformer = TransformerFactory.newInstance().newTransformer();\n\t\t\t\t\ttransformer.setOutputProperty(OutputKeys.INDENT, \"yes\");\n\t\t\t\t\ttransformer.setOutputProperty(\"{http://xml.apache.org/xslt}indent-amount\", \"2\");\n\t\t\t\t\ttry (ByteArrayOutputStream output = new ByteArrayOutputStream()) {\n\t\t\t\t\t\ttransformer.transform(new DOMSource((Document) valueToFormat), new StreamResult(output));\n\t\t\t\t\t\tvalue.append(output);\n\t\t\t\t\t}\n\t\t\t\t} catch (Exception e) {\n\t\t\t\t\treturn \"Exception transforming object of type Document \" + e;\n\t\t\t\t}\n\t\t\t} else if (valueToFormat instanceof Identity) {\n\t\t\t\tvalue.append(\"Identity\").append(format(toLogMap((Identity) valueToFormat)));\n\t\t\t} else if (valueToFormat instanceof Bundle) {\n\t\t\t\tvalue.append(\"Bundle\").append(format(toLogMap((Bundle)valueToFormat)));\n\t\t\t} else if (valueToFormat instanceof ManagedAttribute) {\n\t\t\t\tvalue.append(\"ManagedAttribute\").append(format(toLogMap((ManagedAttribute) valueToFormat)));\n\t\t\t} else if (valueToFormat instanceof Link) {\n\t\t\t\tvalue.append(\"Link\").append(format(toLogMap((Link) valueToFormat)));\n\t\t\t} else if (valueToFormat instanceof Application) {\n\t\t\t\tvalue.append(\"Application\").append(format(toLogMap((Application) valueToFormat)));\n\t\t\t} else if (valueToFormat instanceof SailPointContext) {\n\t\t\t\tvalue.append(\"SailPointContext[\").append(valueToFormat.hashCode()).append(\", username = \").append(((SailPointContext) valueToFormat).getUserName()).append(\"]\");\n\t\t\t} else if (valueToFormat instanceof ProvisioningPlan) {\n\t\t\t\ttry {\n\t\t\t\t\tvalue.append(ProvisioningPlan.getLoggingPlan((ProvisioningPlan) valueToFormat).toXml());\n\t\t\t\t} catch (GeneralException e) {\n\t\t\t\t\treturn \"Exception transforming object of type \" + valueToFormat.getClass().getName() + \" to XML: \" + e;\n\t\t\t\t}\n\t\t\t} else if (valueToFormat instanceof Filter) {\n\t\t\t\tvalue.append(\"Filter[\").append(((Filter) valueToFormat).getExpression(true)).append(\"]\");\n\t\t\t} else if (valueToFormat instanceof AbstractXmlObject) {\n\t\t\t\ttry {\n\t\t\t\t\tvalue.append(((AbstractXmlObject)valueToFormat).toXml());\n\t\t\t\t} catch (GeneralException e) {\n\t\t\t\t\treturn \"Exception transforming object of type \" + valueToFormat.getClass().getName() + \" to XML: \" + e;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tvalue.append(valueToFormat);\n\t\t\t}\n\n\t\t\tString result = value.toString();\n\t\t\tif (indent) {\n\t\t\t\tresult = result.replace(\"\\n\", \"\\n \").trim();\n\t\t\t}\n\n\t\t\treturn result;\n\t\t}\n\n\t\t/**\n\t\t * Returns the formatted string of the item when invoked via the {@link Supplier} interface\n\t\t * @return The formatted string\n\t\t * @see Supplier#get()\n\t\t */\n\t\t@Override\n\t\tpublic String get() {\n\t\t\treturn toString();\n\t\t}\n\n\t\t/**\n\t\t * Converts the Identity to a Map for logging purposes\n\t\t * @param value The Identity convert\n\t\t * @return A Map containing some basic identity details\n\t\t */\n\t\tprivate Map<String, Object> toLogMap(Identity value) {\n\t\t\tMap<String, Object> map = createLogMap(value);\n\t\t\tmap.put(\"type\", value.getType());\n\t\t\tmap.put(\"displayName\", value.getDisplayName());\n\t\t\tmap.put(\"disabled\", value.isDisabled() || value.isInactive());\n\t\t\tmap.put(\"attributes\", format(value.getAttributes()));\n\t\t\treturn map;\n\t\t}\n\n\t\t/**\n\t\t * Converts the Link to a Map for logging purposes\n\t\t * @param value The Link to convert\n\t\t * @return A Map containing some basic Link details\n\t\t */\n\t\tprivate Map<String, Object> toLogMap(Link value) {\n\t\t\tMap<String, Object> map = createLogMap(value);\n\t\t\tmap.put(\"application\", value.getApplicationName());\n\t\t\tmap.put(\"nativeIdentity\", value.getNativeIdentity());\n\t\t\tmap.put(\"displayName\", value.getDisplayName());\n\t\t\tmap.put(\"disabled\", value.isDisabled());\n\t\t\treturn map;\n\t\t}\n\n\t\t/**\n\t\t * Converts the Application to a Map for logging purposes\n\t\t * @param value The Application to convert\n\t\t * @return A Map containing some basic Application details\n\t\t */\n\t\tprivate Map<String, Object> toLogMap(Application value) {\n\t\t\tMap<String, Object> map = createLogMap(value);\n\t\t\tmap.put(\"authoritative\", value.isAuthoritative());\n\t\t\tmap.put(\"connector\", value.getConnector());\n\t\t\tif (value.isInMaintenance()) {\n\t\t\t\tmap.put(\"maintenance\", true);\n\t\t\t}\n\t\t\treturn map;\n\t\t}\n\n\t\t/**\n\t\t * Converts the Bundle / Role to a Map for logging purposes\n\t\t * @param value The Bundle to convert\n\t\t * @return A Map containing some basic Bundle details\n\t\t */\n\t\tprivate Map<String, Object> toLogMap(Bundle value) {\n\t\t\tMap<String, Object> map = createLogMap(value);\n\t\t\tmap.put(\"type\", value.getType());\n\t\t\tmap.put(\"displayName\", value.getDisplayName());\n\t\t\treturn map;\n\t\t}\n\n\t\t/**\n\t\t * Converts the ManagedAttribute / Entitlement object to a Map for logging purposes\n\t\t * @param value The MA to convert\n\t\t * @return A Map containing some basic MA details\n\t\t */\n\t\tprivate Map<String, Object> toLogMap(ManagedAttribute value) {\n\t\t\tMap<String, Object> map = createLogMap(value);\n\t\t\tmap.put(\"application\", value.getApplication().getName());\n\t\t\tmap.put(\"attribute\", value.getAttribute());\n\t\t\tmap.put(\"value\", value.getValue());\n\t\t\tmap.put(\"displayName\", value.getDisplayName());\n\t\t\treturn map;\n\t\t}\n\n\t\t/**\n\t\t * If the formatted value exists, the cached version will be returned.\n\t\t * Otherwise, the format string will be calculated at this time, cached,\n\t\t * and then returned.\n\t\t *\n\t\t * @see java.lang.Object#toString()\n\t\t */\n\t\t@Override\n\t\tpublic String toString() {\n\t\t\tif (this.formattedValue == null) {\n\t\t\t\tthis.formattedValue = format(item);\n\t\t\t}\n\t\t\treturn this.formattedValue;\n\t\t}\n\t}\n\n\t/**\n\t * An enumeration of log levels to replace the one in log4j\n\t */\n\tpublic enum Level {\n\t\tTRACE,\n\t\tDEBUG,\n\t\tINFO,\n\t\tWARN,\n\t\tERROR,\n\t\tFATAL\n\t}\n\n\t/**\n\t * Wraps the arguments for future formatting. The format string is not resolved\n\t * at this time.\n\t *\n\t * NOTE: In newer versions of logging APIs, this would be accomplished\n\t * by passing a {@link Supplier} to the API. However, in Commons Logging 1.x,\n\t * this is not available. It is also not available in Beanshell, as it requires\n\t * lambda syntax. If that ever becomes available, this class will become\n\t * obsolete.\n\t *\n\t * @param args The arguments for any place-holders in the message template.\n\t * @return The formatted arguments.\n\t */\n\tpublic static SLogger.Formatter[] format(Object[] args) {\n\t\tif (args == null) {\n\t\t\treturn null;\n\t\t}\n\t\tFormatter[] argsCopy = new Formatter[args.length];\n\t\tfor (int i = 0; i < args.length; i++) {\n\t\t\targsCopy[i] = new Formatter(args[i]);\n\t\t}\n\t\treturn argsCopy;\n\t}\n\n\t/**\n\t * Renders the MessageTemplate using the given arguments\n\t * @param messageTemplate The message template\n\t * @param args The arguments\n\t * @return The resolved message template\n\t */\n\tpublic static String renderMessage(String messageTemplate, Object[] args) {\n\t\tif (args != null && args.length > 0) {\n\t\t\tMessageFormat template = new MessageFormat(messageTemplate);\n\t\t\treturn template.format(args);\n\t\t} else {\n\t\t\treturn messageTemplate;\n\t\t}\n\t}\n\n\t/**\n\t * The underlying logger to use.\n\t */\n\tprivate final Log logger;\n\t/**\n\t * The underlying output stream to use.\n\t */\n\tprivate final PrintStream out;\n\n\t/**\n\t * Creates a new logger.\n\t *\n\t * @param Owner The class to log messages for.\n\t */\n\tpublic SLogger(Class<?> Owner) {\n\t\tlogger = LogFactory.getLog(Owner);\n\t\tout = null;\n\t}\n\n\t/**\n\t * Wraps the given log4j logger with this logger\n\t *\n\t * @param WrapLog The logger to wrap\n\t */\n\tpublic SLogger(Log WrapLog) {\n\t\tlogger = WrapLog;\n\t\tout = null;\n\t}\n\n\t/**\n\t * Creates a new logger.\n\t *\n\t * @param Out The output stream to\n\t */\n\tpublic SLogger(PrintStream Out) {\n\t\tlogger = null;\n\t\tout = Out;\n\t}\n\t\n\t@Override\n\tpublic void debug(Object arg0) {\n\t\tdebug(\"{0}\", arg0);\n\t}\n\t\n\t@Override\n\tpublic void debug(Object arg0, Throwable arg1) {\n\t\tdebug(\"{0} {1}\", arg0, arg1);\n\t}\n\n\t/**\n\t * Logs an debugging message.\n\t *\n\t * @param MessageTemplate A message template, which can either be a plain string or contain place-holders like {0} and {1}.\n\t * @param Args The arguments for any place-holders in the message template.\n\t */\n\tpublic void debug(String MessageTemplate, Object... Args) {\n\t\tlog(Level.DEBUG, MessageTemplate, format(Args));\n\t}\n\n\t/**\n\t * @see Log#error(Object)\n\t */\n\t@Override\n\tpublic void error(Object arg0) {\n\t\terror(\"{0}\", arg0);\n\t}\n\n\t/**\n\t * @see Log#error(Object, Throwable)\n\t */\n\t@Override\n\tpublic void error(Object arg0, Throwable arg1) {\n\t\terror(\"{0}\", arg0);\n\t\thandleException(arg1);\n\t}\n\n\t/**\n\t * Logs an error message.\n\t *\n\t * @param MessageTemplate A message template, which can either be a plain string or contain place-holders like {0} and {1}.\n\t * @param Args The arguments for any place-holders in the message template.\n\t */\n\tpublic void error(String MessageTemplate, Object... Args) {\n\t\tlog(Level.ERROR, MessageTemplate, format(Args));\n\t}\n\n\t@Override\n\tpublic void fatal(Object arg0) {\n\t\tfatal(\"{0}\", arg0);\n\t}\n\n\t@Override\n\tpublic void fatal(Object arg0, Throwable arg1) {\n\t\tfatal(\"{0}\", arg0);\n\t\thandleException(arg1);\n\t}\n\n\t/**\n\t * Logs a fatal error message.\n\t *\n\t * @param MessageTemplate A message template, which can either be a plain string or contain place-holders like {0} and {1}.\n\t * @param Args The arguments for any place-holders in the message template.\n\t */\n\tpublic void fatal(String MessageTemplate, Object... Args) {\n\t\tlog(Level.FATAL, MessageTemplate, format(Args));\n\t}\n\n\t/**\n\t * Gets the internal Log object wrapped by this class\n\t * @return The internal log object\n\t */\n\t/*package*/ Log getLogger() {\n\t\treturn logger;\n\t}\n\n\t/**\n\t * Handles an exception.\n\t *\n\t * @param Error The exception to handle.\n\t */\n\tpublic synchronized void handleException(Throwable Error) {\n\t\tsave(Error);\n\t\tif (logger != null) {\n\t\t\tlogger.error(Error.toString(), Error);\n\t\t} else if (out != null) {\n\t\t\tError.printStackTrace(out);\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic void info(Object arg0) {\n\t\tinfo(\"{0}\", arg0);\n\t}\n\n\t@Override\n\tpublic void info(Object arg0, Throwable arg1) {\n\t\tinfo(\"{0} {1}\", arg0, arg1);\n\t}\n\n\t/**\n\t * Logs an informational message.\n\t *\n\t * @param MessageTemplate A message template, which can either be a plain string or contain place-holders like {0} and {1}.\n\t * @param Args The arguments for any place-holders in the message template.\n\t */\n\tpublic void info(String MessageTemplate, Object... Args) {\n\t\tlog(Level.INFO, MessageTemplate, format(Args));\n\t}\n\n\t/**\n\t * @see Log#isDebugEnabled()\n\t */\n\t@Override\n\tpublic boolean isDebugEnabled() {\n\t\tif (logger != null) {\n\t\t\treturn logger.isDebugEnabled();\n\t\t} else {\n\t\t\treturn true;\n\t\t}\n\t}\n\n\t/**\n\t * Returns true if the logger is enabled for the given level. Unfortunately, Commons Logging doesn't have a friendly isEnabledFor(Level) type API, since some of its downstream loggers may not either.\n\t *\n\t * @param log The logger to check\n\t * @param logLevel The level to check\n\t * @return true if the logger is enabled\n\t */\n\tprivate boolean isEnabledFor(Log log, Level logLevel) {\n\t\tswitch(logLevel) {\n\t\tcase TRACE:\n\t\t\treturn log.isTraceEnabled();\n\t\tcase DEBUG:\n\t\t\treturn log.isDebugEnabled();\n\t\tcase INFO:\n\t\t\treturn log.isInfoEnabled();\n\t\tcase WARN:\n\t\t\treturn log.isWarnEnabled();\n\t\tcase ERROR:\n\t\t\treturn log.isErrorEnabled();\n\t\tcase FATAL:\n\t\t\treturn log.isFatalEnabled();\n\t\t}\n\t\treturn false;\n\t}\n\n\t/**\n\t * @see Log#isErrorEnabled()\n\t */\n\t@Override\n\tpublic boolean isErrorEnabled() {\n\t\tif (logger != null) {\n\t\t\treturn logger.isErrorEnabled();\n\t\t} else {\n\t\t\treturn true;\n\t\t}\n\t}\n\n\t/**\n\t * @see Log#isFatalEnabled()\n\t */\n\t@Override\n\tpublic boolean isFatalEnabled() {\n\t\tif (logger != null) {\n\t\t\treturn logger.isFatalEnabled();\n\t\t} else {\n\t\t\treturn true;\n\t\t}\n\t}\n\n\t/**\n\t * @see Log#isInfoEnabled()\n\t */\n\t@Override\n\tpublic boolean isInfoEnabled() {\n\t\tif (logger != null) {\n\t\t\treturn logger.isInfoEnabled();\n\t\t} else {\n\t\t\treturn true;\n\t\t}\n\t}\n\n\t/**\n\t * @see Log#isTraceEnabled()\n\t */\n\t@Override\n\tpublic boolean isTraceEnabled() {\n\t\tif (logger != null) {\n\t\t\treturn logger.isTraceEnabled();\n\t\t} else {\n\t\t\treturn true;\n\t\t}\n\t}\n\n\t/**\n\t * @see Log#isWarnEnabled()\n\t */\n\t@Override\n\tpublic boolean isWarnEnabled() {\n\t\tif (logger != null) {\n\t\t\treturn logger.isWarnEnabled();\n\t\t} else {\n\t\t\treturn true;\n\t\t}\n\t}\n\n\t/**\n\t * Logs the message at the appropriate level according to the Commons Logging API\n\t * @param logLevel The log level to log at\n\t * @param message The message to log\n\t */\n\tpublic void log(Level logLevel, String message) {\n\t\tswitch(logLevel) {\n\t\tcase TRACE:\n\t\t\tlogger.trace(message);\n\t\t\tbreak;\n\t\tcase DEBUG:\n\t\t\tlogger.debug(message);\n\t\t\tbreak;\n\t\tcase INFO:\n\t\t\tlogger.info(message);\n\t\t\tbreak;\n\t\tcase WARN:\n\t\t\tlogger.warn(message);\n\t\t\tbreak;\n\t\tcase ERROR:\n\t\t\tlogger.error(message);\n\t\t\tbreak;\n\t\tcase FATAL:\n\t\t\tlogger.fatal(message);\n\t\t\tbreak;\n\t\t}\n\t}\n\n\t/**\n\t * Logs a message.\n\t *\n\t * @param logLevel The level to log the message at.\n\t * @param messageTemplate A message template, which can either be a plain string or contain place-holders like {0} and {1}.\n\t * @param args The arguments for any place-holders in the message template.\n\t */\n\tprivate void log(Level logLevel, String messageTemplate, Object... args) {\n\t\tsave(logLevel, messageTemplate, args);\n\t\tif (logger != null) {\n\t\t\tif (isEnabledFor(logger, logLevel)) {\n\t\t\t\tString message = renderMessage(messageTemplate, args);\n\t\t\t\tlog(logLevel, message);\n\t\t\t}\n\t\t} else if (out != null) {\n\t\t\tString message = renderMessage(messageTemplate, args);\n\t\t\tout.println(message);\n\t\t}\n\t}\n\n\t/**\n\t * Hook to allow log messages to be intercepted and saved.\n\t *\n\t * @param LogLevel The level to log the message at.\n\t * @param MessageTemplate A message template, which can either be a plain string or contain place-holders like {0} and {1}.\n\t * @param Args The arguments for any place-holders in the message template.\n\t */\n\tprotected void save(@SuppressWarnings(\"unused\") Level LogLevel, @SuppressWarnings(\"unused\") String MessageTemplate, @SuppressWarnings(\"unused\") Object[] Args) {\n\t\t/* Does Nothing */\n\t}\n\n\t/**\n\t * Hook to allow log messages to be intercepted and saved. In this version of this\n\t * class, this is a no-op.\n\t *\n\t * @param Error The exception to handle.\n\t */\n\tprotected void save(@SuppressWarnings(\"unused\") Throwable Error) {\n\t\t/* Does Nothing */\n\t}\n\n\t@Override\n\tpublic void trace(Object arg0) {\n\t\ttrace(\"{0}\", arg0);\n\t}\n\n\t@Override\n\tpublic void trace(Object arg0, Throwable arg1) {\n\t\ttrace(\"{0} {1}\", arg0, arg1);\n\t}\n\n\t/**\n\t * Logs a trace message.\n\t *\n\t * @param MessageTemplate A message template, which can either be a plain string or contain place-holders like {0} and {1}.\n\t * @param Args The arguments for any place-holders in the message template.\n\t */\n\tpublic void trace(String MessageTemplate, Object... Args) {\n\t\tlog(Level.TRACE, MessageTemplate, format(Args));\n\t}\n\n\t/**\n\t * @see Log#warn(Object)\n\t */\n\t@Override\n\tpublic void warn(Object arg0) {\n\t\twarn(\"{0}\", arg0);\n\t}\n\n\t/**\n\t * @see Log#warn(Object, Throwable)\n\t */\n\t@Override\n\tpublic void warn(Object arg0, Throwable arg1) {\n\t\twarn(\"{0} {1}\", arg0, arg1);\n\t}\n\n\t/**\n\t * Logs a warning message.\n\t *\n\t * @param MessageTemplate A message template, which can either be a plain string or contain place-holders like {0} and {1}.\n\t * @param Args The arguments for any place-holders in the message template.\n\t */\n\tpublic void warn(String MessageTemplate, Object... Args) {\n\t\tlog(Level.WARN, MessageTemplate, format(Args));\n\t}\n}" }, { "identifier": "ContextConnectionWrapper", "path": "src/com/identityworksllc/iiq/common/query/ContextConnectionWrapper.java", "snippet": "public class ContextConnectionWrapper {\n\n /**\n * Gets a new connection attached to the current SailPointContext.\n * @return The opened connection\n * @throws GeneralException if any failures occur opening the connection\n */\n public static Connection getConnection() throws GeneralException {\n return getConnection(null);\n }\n\n\n /**\n * Gets a new connection attached to the given SailPointContext, going directly to the\n * underlying Spring DataSource object rather than going through the context.\n *\n * @param context The context to which the open connection should be attached for logging, or null to use the current thread context\n * @return The opened connection\n * @throws GeneralException if any failures occur opening the connection\n */\n public static Connection getConnection(SailPointContext context) throws GeneralException {\n SailPointContext currentContext = SailPointFactory.peekCurrentContext();\n try {\n if (context != null) {\n SailPointFactory.setContext(context);\n }\n try {\n DataSource dataSource = Environment.getEnvironment().getSpringDataSource();\n if (dataSource == null) {\n throw new GeneralException(\"Unable to return connection, no DataSource defined!\");\n }\n\n return dataSource.getConnection();\n } catch (SQLException e) {\n throw new GeneralException(e);\n }\n } finally {\n SailPointFactory.setContext(currentContext);\n }\n }\n\n /**\n * Private utility constructor\n */\n private ContextConnectionWrapper() {\n\n }\n}" } ]
import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.util.DefaultIndenter; import com.fasterxml.jackson.core.util.DefaultPrettyPrinter; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.MapperFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.identityworksllc.iiq.common.logging.SLogger; import com.identityworksllc.iiq.common.query.ContextConnectionWrapper; import org.apache.commons.beanutils.PropertyUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.velocity.VelocityContext; import org.apache.velocity.app.Velocity; import sailpoint.api.MessageAccumulator; import sailpoint.api.ObjectAlreadyLockedException; import sailpoint.api.ObjectUtil; import sailpoint.api.PersistenceManager; import sailpoint.api.SailPointContext; import sailpoint.api.SailPointFactory; import sailpoint.object.*; import sailpoint.rest.BaseResource; import sailpoint.server.AbstractSailPointContext; import sailpoint.server.Environment; import sailpoint.server.SPKeyStore; import sailpoint.server.SailPointConsole; import sailpoint.tools.BrandingServiceFactory; import sailpoint.tools.Console; import sailpoint.tools.GeneralException; import sailpoint.tools.Message; import sailpoint.tools.RFC4180LineParser; import sailpoint.tools.Reflection; import sailpoint.tools.Util; import sailpoint.tools.VelocityUtil; import sailpoint.tools.xml.ConfigurationException; import sailpoint.tools.xml.XMLObjectFactory; import sailpoint.web.BaseBean; import sailpoint.web.UserContext; import sailpoint.web.util.WebUtil; import javax.faces.context.FacesContext; import javax.servlet.http.HttpSession; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.sql.Connection; import java.sql.SQLException; import java.text.MessageFormat; import java.text.SimpleDateFormat; import java.time.Duration; import java.time.Instant; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.Period; import java.time.ZoneId; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeParseException; import java.time.temporal.ChronoUnit; import java.util.*; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.ForkJoinPool; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.locks.Lock; import java.util.function.BiConsumer; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.Stream;
9,367
* null, otherwise returns the default value. * * @param maybeNull An object which may be null * @param defaultValue The value to return if the object is null * @param valueProducer The generator of the value to return if the value is not nothing * @param <T> The return type * @return The result of the value producer, or the default */ public static <T> T withDefault(Object maybeNull, T defaultValue, Functions.FunctionWithError<Object, T> valueProducer) { if (maybeNull != null) { try { return valueProducer.applyWithError(maybeNull); } catch(Error e) { throw e; } catch (Throwable throwable) { logger.debug("Caught an error in withDefault", throwable); } } return defaultValue; } /** * Safely handles the given iterator by passing it to the Consumer and, regardless * of outcome, by flushing it when the Consumer returns. * * @param iterator The iterator to process * @param iteratorConsumer The iterator consumer, which will be invoked with the iterator * @param <T> The iterator type * @throws GeneralException if any failures occur */ public static <T> void withIterator(Iterator<T> iterator, Functions.ConsumerWithError<Iterator<T>> iteratorConsumer) throws GeneralException { withIterator(() -> iterator, iteratorConsumer); } /** * Safely handles the given iterator by passing it to the Consumer and, regardless * of outcome, by flushing it when the Consumer returns. * * @param iteratorSupplier The iterator supplier, which will be invoked once * @param iteratorConsumer The iterator consumer, which will be invoked with the iterator * @param <T> The iterator type * @throws GeneralException if any failures occur */ public static <T> void withIterator(Functions.SupplierWithError<Iterator<T>> iteratorSupplier, Functions.ConsumerWithError<Iterator<T>> iteratorConsumer) throws GeneralException { try { Iterator<T> iterator = iteratorSupplier.getWithError(); if (iterator != null) { try { iteratorConsumer.acceptWithError(iterator); } finally { Util.flushIterator(iterator); } } } catch(GeneralException | RuntimeException | Error e) { throw e; } catch(Throwable t) { throw new GeneralException(t); } } /** * Obtains the lock, then executes the callback * @param lock The lock to lock before doing the execution * @param callback The callback to invoke after locking * @throws GeneralException if any failures occur or if the lock is interrupted */ public static void withJavaLock(Lock lock, Callable<?> callback) throws GeneralException { try { lock.lockInterruptibly(); try { callback.call(); } catch(InterruptedException | GeneralException e) { throw e; } catch (Exception e) { throw new GeneralException(e); } finally { lock.unlock(); } } catch(InterruptedException e) { throw new GeneralException(e); } } /** * Obtains the lock, then executes the callback * @param lock The lock to lock before doing the execution * @param timeoutMillis The timeout for the lock, in milliseconds * @param callback The callback to invoke after locking * @throws GeneralException if any failures occur or if the lock is interrupted */ public static void withJavaTimeoutLock(Lock lock, long timeoutMillis, Callable<?> callback) throws GeneralException { try { boolean locked = lock.tryLock(timeoutMillis, TimeUnit.MILLISECONDS); if (!locked) { throw new GeneralException("Unable to obtain the lock within timeout period " + timeoutMillis + " ms"); } try { callback.call(); } catch(InterruptedException | GeneralException e) { throw e; } catch (Exception e) { throw new GeneralException(e); } finally { lock.unlock(); } } catch(InterruptedException e) { throw new GeneralException(e); } } /** * Creates a new database connection using the context provided, sets its auto-commit * flag to false, then passes it to the consumer provided. The consumer is responsible * for committing. * * @param context The context to produce the connection * @param consumer The consumer lambda or class to handle the connection * @throws GeneralException on failures */ public static void withNoCommitConnection(SailPointContext context, Functions.ConnectionHandler consumer) throws GeneralException {
package com.identityworksllc.iiq.common; /** * Static utility methods that are useful throughout any IIQ codebase, supplementing * SailPoint's {@link Util} in many places. */ @SuppressWarnings("unused") public class Utilities { /** * Used as an indicator that the quick property lookup produced nothing. * All instances of this class are always identical via equals(). */ public static final class PropertyLookupNone { private PropertyLookupNone() { } @Override public boolean equals(Object o) { if (this == o) return true; return o instanceof PropertyLookupNone; } @Override public int hashCode() { return Objects.hash(""); } } /** * The name of the worker pool, stored in CustomGlobal by default */ public static final String IDW_WORKER_POOL = "idw.worker.pool"; /** * The key used to store the user's most recent locale on their UIPrefs, * captured by {@link #tryCaptureLocationInfo(SailPointContext, Identity)} */ public static final String MOST_RECENT_LOCALE = "mostRecentLocale"; /** * The key used to store the user's most recent timezone on their UIPrefs, * captured by {@link #tryCaptureLocationInfo(SailPointContext, Identity)} */ public static final String MOST_RECENT_TIMEZONE = "mostRecentTimezone"; /** * A magic constant for use with the {@link Utilities#getQuickProperty(Object, String)} method. * If the property is not an available 'quick property', this object will be returned. */ public static final Object NONE = new PropertyLookupNone(); private static final AtomicReference<ObjectMapper> DEFAULT_OBJECT_MAPPER = new AtomicReference<>(); /** * Indicates whether velocity has been initialized in this Utilities class */ private static final AtomicBoolean VELOCITY_INITIALIZED = new AtomicBoolean(); /** * The internal logger */ private static final Log logger = LogFactory.getLog(Utilities.class); /** * Adds the given value to a {@link Collection} at the given key in the map. * <p> * If the map does not have a {@link Collection} at the given key, a new {@link ArrayList} is added, then the value is added to that. * <p> * This method is null safe. If the map or key is null, this method has no effect. * * @param map The map to modify * @param key The map key that points to the list to add the value to * @param value The value to add to the list * @param <S> The key type * @param <T> The list element type */ @SuppressWarnings({"unchecked"}) public static <S, T extends Collection<S>> void addMapped(Map<String, T> map, String key, S value) { if (map != null && key != null) { if (!map.containsKey(key)) { map.put(key, (T) new ArrayList<>()); } map.get(key).add(value); } } /** * Adds a message banner to the current browser session which will show up at the * top of each page. This requires that a FacesContext exist in the current * session. You can't always assume this to be the case. * * If you're using the BaseCommonPluginResource class, it has a method to construct * a new FacesContext if one doesn't exist. * * @param context The IIQ context * @param message The Message to add * @throws GeneralException if anything goes wrong */ public static void addSessionMessage(SailPointContext context, Message message) throws GeneralException { FacesContext fc = FacesContext.getCurrentInstance(); if (fc != null) { try { BaseBean bean = (BaseBean) fc.getApplication().evaluateExpressionGet(fc, "#{base}", Object.class); bean.addMessageToSession(message); } catch (Exception e) { throw new GeneralException(e); } } } /** * Adds a new MatchTerm as an 'and' to an existing MatchExpression, transforming an * existing 'or' into a sub-expression if needed. * * @param input The input MatchExpression * @param newTerm The new term to 'and' with the existing expressions * @return The resulting match term */ public static IdentitySelector.MatchExpression andMatchTerm(IdentitySelector.MatchExpression input, IdentitySelector.MatchTerm newTerm) { if (input.isAnd()) { input.addTerm(newTerm); } else { IdentitySelector.MatchTerm bigOr = new IdentitySelector.MatchTerm(); for (IdentitySelector.MatchTerm existing : Util.safeIterable(input.getTerms())) { bigOr.addChild(existing); } bigOr.setContainer(true); bigOr.setAnd(false); List<IdentitySelector.MatchTerm> newChildren = new ArrayList<>(); newChildren.add(bigOr); newChildren.add(newTerm); input.setAnd(true); input.setTerms(newChildren); } return input; } /** * Boxes a primitive type into its java Object type * * @param prim The primitive type class * @return The boxed type */ /*package*/ static Class<?> box(Class<?> prim) { Objects.requireNonNull(prim, "The class to box must not be null"); if (prim.equals(Long.TYPE)) { return Long.class; } else if (prim.equals(Integer.TYPE)) { return Integer.class; } else if (prim.equals(Short.TYPE)) { return Short.class; } else if (prim.equals(Character.TYPE)) { return Character.class; } else if (prim.equals(Byte.TYPE)) { return Byte.class; } else if (prim.equals(Boolean.TYPE)) { return Boolean.class; } else if (prim.equals(Float.TYPE)) { return Float.class; } else if (prim.equals(Double.TYPE)) { return Double.class; } throw new IllegalArgumentException("Unrecognized primitive type: " + prim.getName()); } /** * Returns true if the collection contains the given value ignoring case * * @param collection The collection to check * @param value The value to check for * @return True if the collection contains the value, comparing case-insensitively */ public static boolean caseInsensitiveContains(Collection<? extends Object> collection, Object value) { if (collection == null || collection.isEmpty()) { return false; } // Most of the Set classes have efficient implementations // of contains which we should check first for case-sensitive matches. if (collection instanceof Set && collection.contains(value)) { return true; } if (value instanceof String) { String s2 = (String) value; for (Object o : collection) { if (o instanceof String) { String s1 = (String) o; if (s1.equalsIgnoreCase(s2)) { return true; } } } return false; } return collection.contains(value); } /** * Gets a global singleton value from CustomGlobal. If it doesn't exist, uses * the supplied factory (in a synchronized thread) to create it. * <p> * NOTE: This should NOT be an instance of a class defined in a plugin. If the * plugin is redeployed and its classloader refreshes, it will cause the return * value from this method to NOT match the "new" class in the new classloader, * causing ClassCastExceptions. * * @param key The key * @param factory The factory to use if the stored value is null * @param <T> the expected output type * @return the object from the global cache */ @SuppressWarnings("unchecked") public static <T> T computeGlobalSingleton(String key, Supplier<T> factory) { T output = (T) CustomGlobal.get(key); if (output == null && factory != null) { synchronized (CustomGlobal.class) { output = (T) CustomGlobal.get(key); if (output == null) { output = factory.get(); if (output != null) { CustomGlobal.put(key, output); } } } } return output; } /** * Invokes a command via the IIQ console which will run as though it was * typed at the command prompt * * @param command The command to run * @return the results of the command * @throws Exception if a failure occurs during run */ public static String consoleInvoke(String command) throws Exception { final Console console = new SailPointConsole(); final SailPointContext context = SailPointFactory.getCurrentContext(); try { SailPointFactory.setContext(null); try (StringWriter stringWriter = new StringWriter()) { try (PrintWriter writer = new PrintWriter(stringWriter)) { Method doCommand = console.getClass().getSuperclass().getDeclaredMethod("doCommand", String.class, PrintWriter.class); doCommand.setAccessible(true); doCommand.invoke(console, command, writer); } return stringWriter.getBuffer().toString(); } } finally { SailPointFactory.setContext(context); } } /** * Returns true if the Throwable message (or any of its causes) contain the given message * * @param t The throwable to check * @param cause The message to check for * @return True if the message appears anywhere */ public static boolean containsMessage(Throwable t, String cause) { if (t == null || t.toString() == null || cause == null || cause.isEmpty()) { return false; } if (t.toString().contains(cause)) { return true; } if (t.getCause() != null) { return containsMessage(t.getCause(), cause); } return false; } /** * Returns true if the given match expression references the given property anywhere. This is * mainly intended for one-off operations to find roles with particular selectors. * * @param input The filter input * @param property The property to check for * @return True if the MatchExpression references the given property anywhere in its tree */ public static boolean containsProperty(IdentitySelector.MatchExpression input, String property) { for (IdentitySelector.MatchTerm term : Util.safeIterable(input.getTerms())) { boolean contains = containsProperty(term, property); if (contains) { return true; } } return false; } /** * Returns true if the given match term references the given property anywhere. This is * mainly intended for one-off operations to find roles with particular selectors. * * @param term The MatchTerm to check * @param property The property to check for * @return True if the MatchTerm references the given property anywhere in its tree */ public static boolean containsProperty(IdentitySelector.MatchTerm term, String property) { if (term.isContainer()) { for (IdentitySelector.MatchTerm child : Util.safeIterable(term.getChildren())) { boolean contains = containsProperty(child, property); if (contains) { return true; } } } else { return Util.nullSafeCaseInsensitiveEq(term.getName(), property); } return false; } /** * Returns true if the given filter references the given property anywhere. This is * mainly intended for one-off operations to find roles with particular selectors. * <p> * If either the filter or the property is null, returns false. * * @param input The filter input * @param property The property to check for * @return True if the Filter references the given property anywhere in its tree */ public static boolean containsProperty(Filter input, String property) { if (Util.isNullOrEmpty(property)) { return false; } if (input instanceof Filter.CompositeFilter) { Filter.CompositeFilter compositeFilter = (Filter.CompositeFilter) input; for (Filter child : Util.safeIterable(compositeFilter.getChildren())) { boolean contains = containsProperty(child, property); if (contains) { return true; } } } else if (input instanceof Filter.LeafFilter) { Filter.LeafFilter leafFilter = (Filter.LeafFilter) input; return Util.nullSafeCaseInsensitiveEq(leafFilter.getProperty(), property) || Util.nullSafeCaseInsensitiveEq(leafFilter.getSubqueryProperty(), property); } return false; } /** * Converts the input object using the two date formats provided by invoking * the four-argument {@link #convertDateFormat(Object, String, String, ZoneId)}. * * The system default ZoneId will be used. * * @param something The input object, which can be a string or various date objects * @param inputDateFormat The input date format, which will be applied to a string input * @param outputDateFormat The output date format, which will be applied to the intermediate date * @return The input object formatted according to the output date format * @throws java.time.format.DateTimeParseException if there is a failure parsing the date */ public static String convertDateFormat(Object something, String inputDateFormat, String outputDateFormat) { return convertDateFormat(something, inputDateFormat, outputDateFormat, ZoneId.systemDefault()); } /** * Converts the input object using the two date formats provided. * * If the input object is a String (the most likely case), it will be * transformed into an intermediate date using the inputDateFormat. Date * type inputs (Date, LocalDate, LocalDateTime, and Long) will be * converted directly to an intermediate date. * * JDBC classes like Date and Timestamp extend java.util.Date, so that * logic would apply here. * * The intermediate date will then be formatted using the outputDateFormat * at the appropriate ZoneId. * * @param something The input object, which can be a string or various date objects * @param inputDateFormat The input date format, which will be applied to a string input * @param outputDateFormat The output date format, which will be applied to the intermediate date * @param zoneId The time zone to use for parsing and formatting * @return The input object formatted according to the output date format * @throws java.time.format.DateTimeParseException if there is a failure parsing the date */ public static String convertDateFormat(Object something, String inputDateFormat, String outputDateFormat, ZoneId zoneId) { if (something == null) { return null; } LocalDateTime intermediateDate; DateTimeFormatter inputFormat = DateTimeFormatter.ofPattern(inputDateFormat).withZone(zoneId); DateTimeFormatter outputFormat = DateTimeFormatter.ofPattern(outputDateFormat).withZone(zoneId); if (something instanceof String) { if (Util.isNullOrEmpty((String) something)) { return null; } String inputString = (String) something; intermediateDate = LocalDateTime.parse(inputString, inputFormat); } else if (something instanceof Date) { Date somethingDate = (Date) something; intermediateDate = somethingDate.toInstant().atZone(zoneId).toLocalDateTime(); } else if (something instanceof LocalDate) { intermediateDate = ((LocalDate) something).atStartOfDay(); } else if (something instanceof LocalDateTime) { intermediateDate = (LocalDateTime) something; } else if (something instanceof Number) { long timestamp = ((Number) something).longValue(); intermediateDate = Instant.ofEpochMilli(timestamp).atZone(zoneId).toLocalDateTime(); } else { throw new IllegalArgumentException("The input type is not valid (expected String, Date, LocalDate, LocalDateTime, or Long"); } return intermediateDate.format(outputFormat); } /** * Determines whether the test date is at least N days ago. * * @param testDate The test date * @param days The number of dates * @return True if this date is equal to or earlier than the calendar date N days ago */ public static boolean dateAtLeastDaysAgo(Date testDate, int days) { LocalDate ldt1 = testDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate(); LocalDate ldt2 = LocalDate.now().minus(days, ChronoUnit.DAYS); return !ldt1.isAfter(ldt2); } /** * Determines whether the test date is at least N years ago. * * NOTE: This method checks using actual calendar years, rather than * calculating a number of days and comparing that. It will take into * account leap years and other date weirdness. * * @param testDate The test date * @param years The number of years * @return True if this date is equal to or earlier than the calendar date N years ago */ public static boolean dateAtLeastYearsAgo(Date testDate, int years) { LocalDate ldt1 = testDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate(); LocalDate ldt2 = LocalDate.now().minus(years, ChronoUnit.YEARS); return !ldt1.isAfter(ldt2); } /** * Converts two Date objects to {@link LocalDate} at the system default * time zone and returns the number of days between them. * * If you pass the dates in the wrong order (first parameter is the later * date), they will be silently swapped before returning the Duration. * * @param firstTime The first time to compare * @param secondTime The second time to compare * @return The {@link Period} between the two days */ public static Period dateDifference(Date firstTime, Date secondTime) { if (firstTime == null || secondTime == null) { throw new IllegalArgumentException("Both arguments to dateDifference must be non-null"); } LocalDate ldt1 = firstTime.toInstant().atZone(ZoneId.systemDefault()).toLocalDate(); LocalDate ldt2 = secondTime.toInstant().atZone(ZoneId.systemDefault()).toLocalDate(); // Swap the dates if they're backwards if (ldt1.isAfter(ldt2)) { LocalDate tmp = ldt2; ldt2 = ldt1; ldt1 = tmp; } return Period.between(ldt1, ldt2); } /** * Coerces the long millisecond timestamps to Date objects, then returns the * result of {@link #dateDifference(Date, Date)}. * * @param firstTimeMillis The first time to compare * @param secondTimeMillis The second time to compare * @return The {@link Period} between the two days */ public static Period dateDifference(long firstTimeMillis, long secondTimeMillis) { return dateDifference(new Date(firstTimeMillis), new Date(secondTimeMillis)); } /** * Detaches the given object as much as possible from the database context by converting it to XML and back again. * <p> * Converting to XML requires resolving all Hibernate lazy-loaded references. * * @param context The context to use to parse the XML * @param o The object to detach * @return A reference to the object detached from any Hibernate session * @param <T> A class extending SailPointObject * @throws GeneralException if a parsing failure occurs */ public static <T extends SailPointObject> T detach(SailPointContext context, T o) throws GeneralException { @SuppressWarnings("unchecked") T retVal = (T) SailPointObject.parseXml(context, o.toXml()); context.decache(o); return retVal; } /** * Throws an exception if the string is null or empty * * @param values The strings to test */ public static void ensureAllNotNullOrEmpty(String... values) { if (values == null || Util.isAnyNullOrEmpty(values)) { throw new NullPointerException(); } } /** * Throws an exception if the string is null or empty * * @param value The string to test */ public static void ensureNotNullOrEmpty(String value) { if (Util.isNullOrEmpty(value)) { throw new NullPointerException(); } } /** * Uses reflection to evict the RuleRunner pool cache * * @throws Exception if anything goes wrong */ public static void evictRuleRunnerPool() throws Exception { RuleRunner ruleRunner = Environment.getEnvironment().getRuleRunner(); java.lang.reflect.Field _poolField = ruleRunner.getClass().getDeclaredField("_pool"); _poolField.setAccessible(true); Object poolObject = _poolField.get(ruleRunner); _poolField.setAccessible(false); java.lang.reflect.Method clearMethod = poolObject.getClass().getMethod("clear"); clearMethod.invoke(poolObject); } /** * Extracts the value of the given property from each item in the list and returns * a new list containing those property values. * <p> * If the input list is null or empty, an empty list will be returned. * <p> * This is roughly identical to * <p> * input.stream().map(item -> (T)Utilities.getProperty(item, property)).collect(Collectors.toList()) * * @param input The input list * @param property The property to extract * @param expectedType The expected type of the output objects * @param <S> The input type * @param <T> The output type * @return A list of the extracted values * @throws GeneralException if extraction goes wrong */ @SuppressWarnings("unchecked") public static <S, T> List<T> extractProperty(List<S> input, String property, Class<T> expectedType) throws GeneralException { List<T> output = new ArrayList<>(); for (S inputObject : Util.safeIterable(input)) { output.add((T) Utilities.getProperty(inputObject, property)); } return output; } /** * Transfors an input Filter into a MatchExpression * * @param input The Filter * @return The MatchExpression */ public static IdentitySelector.MatchExpression filterToMatchExpression(Filter input) { IdentitySelector.MatchExpression expression = new IdentitySelector.MatchExpression(); expression.addTerm(filterToMatchTerm(input)); return expression; } /** * Transfors an input Filter into a MatchTerm * * @param input The Filter * @return The MatchTerm */ public static IdentitySelector.MatchTerm filterToMatchTerm(Filter input) { IdentitySelector.MatchTerm matchTerm = null; if (input instanceof Filter.CompositeFilter) { matchTerm = new IdentitySelector.MatchTerm(); matchTerm.setContainer(true); Filter.CompositeFilter compositeFilter = (Filter.CompositeFilter) input; if (compositeFilter.getOperation().equals(Filter.BooleanOperation.AND)) { matchTerm.setAnd(true); } else if (compositeFilter.getOperation().equals(Filter.BooleanOperation.NOT)) { throw new UnsupportedOperationException("MatchExpressions do not support NOT filters"); } for (Filter child : Util.safeIterable(compositeFilter.getChildren())) { matchTerm.addChild(filterToMatchTerm(child)); } } else if (input instanceof Filter.LeafFilter) { matchTerm = new IdentitySelector.MatchTerm(); Filter.LeafFilter leafFilter = (Filter.LeafFilter) input; if (leafFilter.getOperation().equals(Filter.LogicalOperation.IN)) { matchTerm.setContainer(true); List<String> values = Util.otol(leafFilter.getValue()); if (values == null) { throw new IllegalArgumentException("For IN filters, only List<String> values are accepted"); } for (String value : values) { IdentitySelector.MatchTerm child = new IdentitySelector.MatchTerm(); child.setName(leafFilter.getProperty()); child.setValue(value); child.setType(IdentitySelector.MatchTerm.Type.Entitlement); matchTerm.addChild(child); } } else if (leafFilter.getOperation().equals(Filter.LogicalOperation.EQ)) { matchTerm.setName(leafFilter.getProperty()); matchTerm.setValue(Util.otoa(leafFilter.getValue())); matchTerm.setType(IdentitySelector.MatchTerm.Type.Entitlement); } else if (leafFilter.getOperation().equals(Filter.LogicalOperation.ISNULL)) { matchTerm.setName(leafFilter.getProperty()); matchTerm.setType(IdentitySelector.MatchTerm.Type.Entitlement); } else { throw new UnsupportedOperationException("MatchExpressions do not support " + leafFilter.getOperation() + " operations"); } } return matchTerm; } /** * Returns the first item in the list that is not null or empty. If all items are null * or empty, or the input is itself a null or empty array, an empty string will be returned. * This method will never return null. * * @param inputs The input strings * @return The first not null or empty item, or an empty string if none is found */ public static String firstNotNullOrEmpty(String... inputs) { if (inputs == null || inputs.length == 0) { return ""; } for (String in : inputs) { if (Util.isNotNullOrEmpty(in)) { return in; } } return ""; } /** * Formats the input message template using Java's MessageFormat class * and the SLogger.Formatter class. * <p> * If no parameters are provided, the message template is returned as-is. * * @param messageTemplate The message template into which parameters should be injected * @param params The parameters to be injected * @return The resulting string */ public static String format(String messageTemplate, Object... params) { if (params == null || params.length == 0) { return messageTemplate; } Object[] formattedParams = new Object[params.length]; for (int p = 0; p < params.length; p++) { formattedParams[p] = new SLogger.Formatter(params[p]); } return MessageFormat.format(messageTemplate, formattedParams); } /** * Retrieves a key from the given Map in a 'fuzzy' way. Keys will be matched * ignoring case and whitespace. * <p> * For example, given the actual key "toolboxConfig", the following inputs * would also match: * <p> * "toolbox config" * "Toolbox Config" * "ToolboxConfig" * <p> * The first matching key will be returned, so it is up to the caller to ensure * that the input does not match more than one actual key in the Map. For some * Map types, "first matching key" may be nondeterministic if more than one key * matches. * <p> * If either the provided key or the map is null, this method will return null. * * @param map The map from which to query the value * @param fuzzyKey The fuzzy key * @param <T> The return type, for convenience * @return The value from the map */ @SuppressWarnings("unchecked") public static <T> T fuzzyGet(Map<String, Object> map, String fuzzyKey) { if (map == null || map.isEmpty() || Util.isNullOrEmpty(fuzzyKey)) { return null; } // Quick exact match if (map.containsKey(fuzzyKey)) { return (T) map.get(fuzzyKey); } // Case-insensitive match for (String key : map.keySet()) { if (safeTrim(key).equalsIgnoreCase(safeTrim(fuzzyKey))) { return (T) map.get(key); } } // Whitespace and case insensitive match String collapsedKey = safeTrim(fuzzyKey.replaceAll("\\s+", "")); for (String key : map.keySet()) { if (safeTrim(key).equalsIgnoreCase(collapsedKey)) { return (T) map.get(key); } } return null; } /** * Gets the input object as a thread-safe Script. If the input is a String, it * will be interpreted as the source of a Script. If the input is already a Script * object, it will be copied for thread safety and the copy returned. * * @param input The input object, either a string or a script * @return The output */ public static Script getAsScript(Object input) { if (input instanceof Script) { Script copy = new Script(); Script os = (Script) input; copy.setSource(os.getSource()); copy.setIncludes(os.getIncludes()); copy.setLanguage(os.getLanguage()); return copy; } else if (input instanceof String) { Script tempScript = new Script(); tempScript.setSource(Util.otoa(input)); return tempScript; } return null; } /** * Gets the attributes of the given source object. If the source is not a Sailpoint * object, or if it's one of the objects without attributes, this method returns * null. * * @param source The source object, which may implement an Attributes container method * @return The attributes, if any, or null */ public static Attributes<String, Object> getAttributes(Object source) { if (source instanceof Identity) { Attributes<String, Object> attributes = ((Identity) source).getAttributes(); if (attributes == null) { return new Attributes<>(); } return attributes; } else if (source instanceof LinkInterface) { Attributes<String, Object> attributes = ((LinkInterface) source).getAttributes(); if (attributes == null) { return new Attributes<>(); } return attributes; } else if (source instanceof Bundle) { return ((Bundle) source).getAttributes(); } else if (source instanceof Custom) { return ((Custom) source).getAttributes(); } else if (source instanceof Configuration) { return ((Configuration) source).getAttributes(); } else if (source instanceof Application) { return ((Application) source).getAttributes(); } else if (source instanceof CertificationItem) { // This one returns a Map for some reason return new Attributes<>(((CertificationItem) source).getAttributes()); } else if (source instanceof CertificationEntity) { return ((CertificationEntity) source).getAttributes(); } else if (source instanceof Certification) { return ((Certification) source).getAttributes(); } else if (source instanceof CertificationDefinition) { return ((CertificationDefinition) source).getAttributes(); } else if (source instanceof TaskDefinition) { return ((TaskDefinition) source).getArguments(); } else if (source instanceof TaskItem) { return ((TaskItem) source).getAttributes(); } else if (source instanceof ManagedAttribute) { return ((ManagedAttribute) source).getAttributes(); } else if (source instanceof Form) { return ((Form) source).getAttributes(); } else if (source instanceof IdentityRequest) { return ((IdentityRequest) source).getAttributes(); } else if (source instanceof IdentitySnapshot) { return ((IdentitySnapshot) source).getAttributes(); } else if (source instanceof ResourceObject) { Attributes<String, Object> attributes = ((ResourceObject) source).getAttributes(); if (attributes == null) { attributes = new Attributes<>(); } return attributes; } else if (source instanceof Field) { return ((Field) source).getAttributes(); } else if (source instanceof ProvisioningPlan) { Attributes<String, Object> arguments = ((ProvisioningPlan) source).getArguments(); if (arguments == null) { arguments = new Attributes<>(); } return arguments; } else if (source instanceof IntegrationConfig) { return ((IntegrationConfig) source).getAttributes(); } else if (source instanceof ProvisioningProject) { return ((ProvisioningProject) source).getAttributes(); } else if (source instanceof ProvisioningTransaction) { return ((ProvisioningTransaction) source).getAttributes(); } else if (source instanceof ProvisioningPlan.AbstractRequest) { return ((ProvisioningPlan.AbstractRequest) source).getArguments(); } else if (source instanceof Rule) { return ((Rule) source).getAttributes(); } else if (source instanceof WorkItem) { return ((WorkItem) source).getAttributes(); } else if (source instanceof Entitlements) { return ((Entitlements) source).getAttributes(); } else if (source instanceof RpcRequest) { return new Attributes<>(((RpcRequest) source).getArguments()); } else if (source instanceof ApprovalItem) { return ((ApprovalItem) source).getAttributes(); } return null; } /** * Gets the time zone associated with the logged in user's session, based on a * UserContext or Identity. As a fallback, the {@link WebUtil} API is used to * try to retrieve the time zone from the HTTP session. * * You can use {@link #tryCaptureLocationInfo(SailPointContext, UserContext)} * in a plugin REST API or QuickLink textScript context to permanently store the * Identity's local time zone as a UI preference. * * @param userContext The user context to check for a time zone, or null * @param identity The identity to check for a time zone, or null * @return The time zone for this user */ public static TimeZone getClientTimeZone(Identity identity, UserContext userContext) { if (userContext != null) { return userContext.getUserTimeZone(); } else if (identity != null && identity.getUIPreference(MOST_RECENT_TIMEZONE) != null) { return TimeZone.getTimeZone((String) identity.getUIPreference(MOST_RECENT_TIMEZONE)); } else { return WebUtil.getTimeZone(TimeZone.getDefault()); } } /** * Extracts a list of all country names from the JDK's Locale class. This will * be as up-to-date as your JDK itself is. * * @return A sorted list of country names */ public static List<String> getCountryNames() { String[] countryCodes = Locale.getISOCountries(); List<String> countries = new ArrayList<>(); for (String countryCode : countryCodes) { Locale obj = new Locale("", countryCode); countries.add(obj.getDisplayCountry()); } Collections.sort(countries); return countries; } /** * Returns a default Jackson object mapper, independent of IIQ versions. * The template ObjectMapper is generated on the * * @return A copy of our cached ObjectMapper */ public static ObjectMapper getJacksonObjectMapper() { if (DEFAULT_OBJECT_MAPPER.get() == null) { synchronized (CustomGlobal.class) { if (DEFAULT_OBJECT_MAPPER.get() == null) { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); objectMapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true); objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true); DefaultPrettyPrinter.Indenter indenter = new DefaultIndenter(" ", DefaultIndenter.SYS_LF); DefaultPrettyPrinter printer = new DefaultPrettyPrinter(); printer.indentObjectsWith(indenter); printer.indentArraysWith(indenter); objectMapper.setDefaultPrettyPrinter(printer); DEFAULT_OBJECT_MAPPER.set(objectMapper); } } } return DEFAULT_OBJECT_MAPPER.get().copy(); } /** * Returns the first item in the input that is not nothing according to the {@link #isNothing(Object)} method. * * @param items The input items * @param <T> The superclass of all input items * @return if the item is not null or empty */ @SafeVarargs public static <T> T getFirstNotNothing(T... items) { if (items == null || items.length == 0) { return null; } for (T item : items) { if (!Utilities.isNothing(item)) { return item; } } return null; } /** * Returns the first item in the input that is not null, an empty Optional, * or a Supplier that returns null. * * @param items The input items * @param <T> The superclass of all input items * @return if the item is not null or empty */ public static <T> T getFirstNotNull(List<? extends T> items) { if (items == null) { return null; } for (T item : items) { boolean nullish = (item == null); if (!nullish && item instanceof Optional) { nullish = !((Optional<?>) item).isPresent(); } if (!nullish && item instanceof Supplier) { Object output = ((Supplier<?>) item).get(); if (output instanceof Optional) { nullish = !((Optional<?>) output).isPresent(); } else { nullish = (output == null); } } if (!nullish) { return item; } } return null; } /** * Returns the first item in the input that is not null, an empty Optional, * or a Supplier that returns null. * * @param items The input items * @param <T> The superclass of all input items * @return if the item is not null or empty */ @SafeVarargs public static <T> T getFirstNotNull(T... items) { return getFirstNotNull(Arrays.asList(items)); } /** * Gets the iiq.properties file contents (properly closing it, unlike IIQ...) * * @return The IIQ properties * @throws GeneralException if any load failures occur */ public static Properties getIIQProperties() throws GeneralException { Properties props = new Properties(); try (InputStream is = AbstractSailPointContext.class.getResourceAsStream("/" + BrandingServiceFactory.getService().getPropertyFile())) { props.load(is); } catch (IOException e) { throw new GeneralException(e); } return props; } /** * IIQ tries to display timestamps in a locale-specific way to the user. It does * this by storing the browser's time zone in the HTTP session and converting * dates to a local value before display. This includes things like scheduled * task execution times, etc. * * However, for date form fields, which should be timeless (i.e. just a date, no time * component), IIQ sends a value "of midnight at the browser's time zone". Depending * on the browser's offset from the server time, this can result (in the worst case) * in the actual selected instant being a full day ahead or behind the intended value. * * This method corrects the offset using Java 8's Time API, which allows for timeless * representations, to determine the date the user intended to select, then converting * that back to midnight in the server time zone. The result is stored back onto the Field. * * If the time is offset from midnight but the user time zone is the same as the server * time zone, it means we're in a weird context where IIQ does not know the user's time * zone, and we have to guess. We will guess up to +12 and -11 from the server timezone, * which should cover most cases. However, if you have users directly around the world * from your server timezone, you may see problems. * * If the input date is null, returns null. * * @param inputDate The input date for the user * @param identity The identity who has timezone information stored * @return The calculated local date, based on the input date and the Identity's time zone */ public static Date getLocalDate(Date inputDate, Identity identity) { if (inputDate == null) { return null; } Instant instant = Instant.ofEpochMilli(inputDate.getTime()); TimeZone userTimeZone = getClientTimeZone(identity, null); ZoneId userZoneId = userTimeZone.toZoneId(); ZoneId serverTimeZone = TimeZone.getDefault().toZoneId(); ZonedDateTime zonedDateTime = instant.atZone(userZoneId); if (zonedDateTime.getHour() != 0) { // Need to shift if (userZoneId.equals(serverTimeZone)) { // IIQ doesn't know where the user is located, so we have to guess // Note that this will fail for user-to-server shifts greater than +12 and -11 LocalDate timelessDate; if (zonedDateTime.getHour() >= 12) { // Assume that the user is located in a time zone ahead of the server (e.g. server is in UTC and user is in Calcutta), submitted time will appear to be before midnight in server time timelessDate = LocalDate.of(zonedDateTime.getYear(), zonedDateTime.getMonth(), zonedDateTime.getDayOfMonth()); timelessDate = timelessDate.plusDays(1); } else { // The user is located in a time zone behind the server (e.g. server is in UTC and user is in New York), submitted time will appear to be after midnight in server time timelessDate = LocalDate.of(zonedDateTime.getYear(), zonedDateTime.getMonth(), zonedDateTime.getDayOfMonth()); } return new Date(timelessDate.atStartOfDay(serverTimeZone).toInstant().toEpochMilli()); } else { // IIQ knows where the user is located and we can just directly convert LocalDate timelessDate = LocalDate.of(zonedDateTime.getYear(), zonedDateTime.getMonth(), zonedDateTime.getDayOfMonth()); return new Date(timelessDate.atStartOfDay(serverTimeZone).toInstant().toEpochMilli()); } } // If the zonedDateTime in user time is midnight, then the user and server are aligned return inputDate; } /** * Localizes a message based on the locale information captured on the * target Identity. This information can be captured in any plugin web * service or other session-attached code using {@link #tryCaptureLocationInfo(SailPointContext, UserContext)} * <p> * If no locale information has been captured, the system default will * be used instead. * * @param target The target user * @param message The non-null message to translate * @return The localized message */ public static String getLocalizedMessage(Identity target, Message message) { if (message == null) { throw new NullPointerException("message must not be null"); } TimeZone tz = TimeZone.getDefault(); if (target != null) { String mrtz = Util.otoa(target.getUIPreference(MOST_RECENT_TIMEZONE)); if (Util.isNotNullOrEmpty(mrtz)) { tz = TimeZone.getTimeZone(mrtz); } } Locale locale = Locale.getDefault(); if (target != null) { String mrl = Util.otoa(target.getUIPreference(MOST_RECENT_LOCALE)); if (Util.isNotNullOrEmpty(mrl)) { locale = Locale.forLanguageTag(mrl); } } return message.getLocalizedMessage(locale, tz); } /** * Gets the given property by introspection * * @param source The source object * @param paramPropertyPath The property path * @return The object at the given path * @throws GeneralException if a failure occurs */ public static Object getProperty(Object source, String paramPropertyPath) throws GeneralException { return getProperty(source, paramPropertyPath, false); } /** * Gets the given property by introspection and 'dot-walking' the given path. Paths have the * following semantics: * * - Certain common 'quick paths' will be recognized and returned immediately, rather than * using reflection to construct the output. * * - A dot '.' is used to separate path elements. Quotes are supported. * * - Paths are evaluated against the current context. * * - Elements within Collections and Maps can be addressed using three different syntaxes, * depending on your needs: list[1], list.1, or list._1. Similarly, map[key], map.key, or * map._key. Three options are available to account for Sailpoint's various parsers. * * - If an element is a Collection, the context object (and thus output) becomes a Collection. All * further properties (other than indexes) are evalulated against each item in the collection. * For example, on an Identity, the property 'links.application.name' resolves to a List of Strings. * * This does not cascade. For example, links.someMultiValuedAttribute will result in a List of Lists, * one for each item in 'links', rather than a single List containing all values of the attribute. * TODO improve nested expansion, if it makes sense. * * If you pass true for 'gracefulNulls', a null value or an invalid index at any point in the path * will simply result in a null output. If it is not set, a NullPointerException or IndexOutOfBoundsException * will be thrown as appropriate. * * @param source The context object against which to evaluate the path * @param paramPropertyPath The property path to evaluate * @param gracefulNulls If true, encountering a null or bad index mid-path will result in an overall null return value, not an exception * @return The object at the given path * @throws GeneralException if a failure occurs */ public static Object getProperty(Object source, String paramPropertyPath, boolean gracefulNulls) throws GeneralException { String propertyPath = paramPropertyPath.replaceAll("\\[(\\w+)]", ".$1"); Object tryQuick = getQuickProperty(source, propertyPath); // This returns Utilities.NONE if this isn't an available "quick property", because // a property can legitimately have the value null. if (!Util.nullSafeEq(tryQuick, NONE)) { return tryQuick; } RFC4180LineParser parser = new RFC4180LineParser('.'); List<String> tokens = parser.parseLine(propertyPath); Object current = source; StringBuilder filterString = new StringBuilder(); for(String property : Util.safeIterable(tokens)) { try { if (current == null) { if (gracefulNulls) { return null; } else { throw new NullPointerException("Found a nested null object at " + filterString); } } boolean found = false; // If this looks likely to be an index... if (current instanceof List) { if (property.startsWith("_") && property.length() > 1) { property = property.substring(1); } if (Character.isDigit(property.charAt(0))) { int index = Integer.parseInt(property); if (gracefulNulls) { current = Utilities.safeSubscript((List<?>) current, index); } else { current = ((List<?>) current).get(index); } found = true; } else { List<Object> result = new ArrayList<>(); for (Object input : (List<?>) current) { result.add(getProperty(input, property, gracefulNulls)); } current = result; found = true; } } else if (current instanceof Map) { if (property.startsWith("_") && property.length() > 1) { property = property.substring(1); } current = Util.get((Map<?, ?>) current, property); found = true; } if (!found) { // This returns Utilities.NONE if this isn't an available "quick property", because // a property can legitimately have the value null. Object result = getQuickProperty(current, property); if (Util.nullSafeEq(result, NONE)) { Method getter = Reflection.getGetter(current.getClass(), property); if (getter != null) { current = getter.invoke(current); } else { Attributes<String, Object> attrs = Utilities.getAttributes(current); if (attrs != null) { current = PropertyUtils.getProperty(attrs, property); } else { current = PropertyUtils.getProperty(current, property); } } } else { current = result; } } } catch (Exception e) { throw new GeneralException("Error resolving path '" + filterString + "." + property + "'", e); } filterString.append('.').append(property); } return current; } /** * Returns a "quick property" which does not involve introspection. If the * property is not in this list, the result will be {@link Utilities#NONE}. * * @param source The source object * @param propertyPath The property path to check * @return the object, if this is a known "quick property" or Utilities.NONE if not * @throws GeneralException if a failure occurs */ public static Object getQuickProperty(Object source, String propertyPath) throws GeneralException { // Giant ladders of if statements for common attributes will be much faster. if (source == null || propertyPath == null) { return null; } if (source instanceof SailPointObject) { if (propertyPath.equals("name")) { return ((SailPointObject) source).getName(); } else if (propertyPath.equals("id")) { return ((SailPointObject) source).getId(); } else if (propertyPath.equals("xml")) { return ((SailPointObject) source).toXml(); } else if (propertyPath.equals("owner.id")) { Identity other = ((SailPointObject) source).getOwner(); if (other != null) { return other.getId(); } else { return null; } } else if (propertyPath.equals("owner.name")) { Identity other = ((SailPointObject) source).getOwner(); if (other != null) { return other.getName(); } else { return null; } } else if (propertyPath.equals("owner")) { return ((SailPointObject) source).getOwner(); } else if (propertyPath.equals("created")) { return ((SailPointObject) source).getCreated(); } else if (propertyPath.equals("modified")) { return ((SailPointObject) source).getModified(); } } if (source instanceof Describable) { if (propertyPath.equals("description")) { return ((Describable) source).getDescription(Locale.getDefault()); } } if (source instanceof ManagedAttribute) { if (propertyPath.equals("value")) { return ((ManagedAttribute) source).getValue(); } else if (propertyPath.equals("attribute")) { return ((ManagedAttribute) source).getAttribute(); } else if (propertyPath.equals("application")) { return ((ManagedAttribute) source).getApplication(); } else if (propertyPath.equals("applicationId") || propertyPath.equals("application.id")) { return ((ManagedAttribute) source).getApplicationId(); } else if (propertyPath.equals("application.name")) { return ((ManagedAttribute) source).getApplication().getName(); } else if (propertyPath.equals("displayName")) { return ((ManagedAttribute) source).getDisplayName(); } else if (propertyPath.equals("displayableName")) { return ((ManagedAttribute) source).getDisplayableName(); } } else if (source instanceof Link) { if (propertyPath.equals("nativeIdentity")) { return ((Link) source).getNativeIdentity(); } else if (propertyPath.equals("displayName") || propertyPath.equals("displayableName")) { return ((Link) source).getDisplayableName(); } else if (propertyPath.equals("description")) { return ((Link) source).getDescription(); } else if (propertyPath.equals("applicationName") || propertyPath.equals("application.name")) { return ((Link) source).getApplicationName(); } else if (propertyPath.equals("applicationId") || propertyPath.equals("application.id")) { return ((Link) source).getApplicationId(); } else if (propertyPath.equals("application")) { return ((Link) source).getApplication(); } else if (propertyPath.equals("identity")) { return ((Link) source).getIdentity(); } else if (propertyPath.equals("permissions")) { return ((Link) source).getPermissions(); } } else if (source instanceof Identity) { if (propertyPath.equals("manager")) { return ((Identity) source).getManager(); } else if (propertyPath.equals("manager.name")) { Identity manager = ((Identity) source).getManager(); if (manager != null) { return manager.getName(); } else { return null; } } else if (propertyPath.equals("manager.id")) { Identity manager = ((Identity) source).getManager(); if (manager != null) { return manager.getId(); } else { return null; } } else if (propertyPath.equals("lastRefresh")) { return ((Identity) source).getLastRefresh(); } else if (propertyPath.equals("needsRefresh")) { return ((Identity) source).isNeedsRefresh(); } else if (propertyPath.equals("lastname")) { return ((Identity) source).getLastname(); } else if (propertyPath.equals("firstname")) { return ((Identity) source).getFirstname(); } else if (propertyPath.equals("type")) { return ((Identity) source).getType(); } else if (propertyPath.equals("displayName") || propertyPath.equals("displayableName")) { return ((Identity) source).getDisplayableName(); } else if (propertyPath.equals("roleAssignments")) { return nullToEmpty(((Identity) source).getRoleAssignments()); } else if (propertyPath.equals("roleDetections")) { return nullToEmpty(((Identity) source).getRoleDetections()); } else if (propertyPath.equals("assignedRoles")) { return nullToEmpty(((Identity) source).getAssignedRoles()); } else if (propertyPath.equals("assignedRoles.name")) { return safeStream(((Identity) source).getAssignedRoles()).map(Bundle::getName).collect(Collectors.toList()); } else if (propertyPath.equals("detectedRoles")) { return nullToEmpty(((Identity) source).getDetectedRoles()); } else if (propertyPath.equals("detectedRoles.name")) { return safeStream(((Identity) source).getDetectedRoles()).map(Bundle::getName).collect(Collectors.toList()); } else if (propertyPath.equals("links.application.name")) { return safeStream(((Identity) source).getLinks()).map(Link::getApplicationName).collect(Collectors.toList()); } else if (propertyPath.equals("links.application.id")) { return safeStream(((Identity) source).getLinks()).map(Link::getApplicationId).collect(Collectors.toList()); } else if (propertyPath.equals("links.application")) { return safeStream(((Identity) source).getLinks()).map(Link::getApplication).collect(Collectors.toList()); } else if (propertyPath.equals("links")) { return nullToEmpty(((Identity) source).getLinks()); } else if (propertyPath.equals("administrator")) { return ((Identity) source).getAdministrator(); } else if (propertyPath.equals("administrator.id")) { Identity other = ((Identity) source).getAdministrator(); if (other != null) { return other.getId(); } else { return null; } } else if (propertyPath.equals("administrator.name")) { Identity other = ((Identity) source).getAdministrator(); if (other != null) { return other.getName(); } else { return null; } } else if (propertyPath.equals("capabilities")) { return nullToEmpty(((Identity) source).getCapabilityManager().getEffectiveCapabilities()); } else if (propertyPath.equals("email")) { return ((Identity) source).getEmail(); } } else if (source instanceof Bundle) { if (propertyPath.equals("type")) { return ((Bundle) source).getType(); } } return NONE; } /** * Gets the shared background pool, an instance of {@link ForkJoinPool}. This is stored * in the core CustomGlobal class so that it can be shared across all IIQ classloader * contexts and will not leak when a new plugin is deployed. * <p> * The parallelism count can be changed in SystemConfiguration under the key 'commonThreadPoolParallelism'. * * @return An instance of the shared background pool */ public static ExecutorService getSharedBackgroundPool() { ExecutorService backgroundPool = (ExecutorService) CustomGlobal.get(IDW_WORKER_POOL); if (backgroundPool == null) { synchronized (CustomGlobal.class) { Configuration systemConfig = Configuration.getSystemConfig(); int parallelism = 8; if (systemConfig != null) { Integer configValue = systemConfig.getInteger("commonThreadPoolParallelism"); if (configValue != null && configValue > 1) { parallelism = configValue; } } backgroundPool = (ExecutorService) CustomGlobal.get(IDW_WORKER_POOL); if (backgroundPool == null) { backgroundPool = new ForkJoinPool(parallelism); CustomGlobal.put(IDW_WORKER_POOL, backgroundPool); } } } return backgroundPool; } /** * Returns true if parentClass is assignable from testClass, e.g. if the following code * would not fail to compile: * * TestClass ot = new TestClass(); * ParentClass tt = ot; * * This is also equivalent to 'b instanceof A' or 'B extends A'. * * Primitive types and their boxed equivalents have special handling. * * @param parentClass The first (parent-ish) class * @param testClass The second (child-ish) class * @param <A> The parent type * @param <B> The potential child type * @return True if parentClass is assignable from testClass */ public static <A, B> boolean isAssignableFrom(Class<A> parentClass, Class<B> testClass) { Class<?> targetType = Objects.requireNonNull(parentClass); Class<?> otherType = Objects.requireNonNull(testClass); if (targetType.isPrimitive() != otherType.isPrimitive()) { if (targetType.isPrimitive()) { targetType = box(targetType); } else { otherType = box(otherType); } } else if (targetType.isPrimitive()) { // We know the 'primitive' flags are the same, so they must both be primitive. if (targetType.equals(Long.TYPE)) { return otherType.equals(Long.TYPE) || otherType.equals(Integer.TYPE) || otherType.equals(Short.TYPE) || otherType.equals(Character.TYPE) || otherType.equals(Byte.TYPE); } else if (targetType.equals(Integer.TYPE)) { return otherType.equals(Integer.TYPE) || otherType.equals(Short.TYPE) || otherType.equals(Character.TYPE) || otherType.equals(Byte.TYPE); } else if (targetType.equals(Short.TYPE)) { return otherType.equals(Short.TYPE) || otherType.equals(Character.TYPE) || otherType.equals(Byte.TYPE); } else if (targetType.equals(Character.TYPE)) { return otherType.equals(Character.TYPE) || otherType.equals(Byte.TYPE); } else if (targetType.equals(Byte.TYPE)) { return otherType.equals(Byte.TYPE); } else if (targetType.equals(Boolean.TYPE)) { return otherType.equals(Boolean.TYPE); } else if (targetType.equals(Double.TYPE)) { return otherType.equals(Double.TYPE) || otherType.equals(Float.TYPE) || otherType.equals(Long.TYPE) || otherType.equals(Integer.TYPE) || otherType.equals(Short.TYPE) || otherType.equals(Character.TYPE) || otherType.equals(Byte.TYPE); } else if (targetType.equals(Float.TYPE)) { return otherType.equals(Float.TYPE) || otherType.equals(Long.TYPE) || otherType.equals(Integer.TYPE) || otherType.equals(Short.TYPE) || otherType.equals(Character.TYPE) || otherType.equals(Byte.TYPE); } else { throw new IllegalArgumentException("Unrecognized primitive target class: " + targetType.getName()); } } return targetType.isAssignableFrom(otherType); } /** * Returns the inverse of {@link #isFlagSet(Object)}. * * @param flagValue The flag value to check * @return True if the flag is NOT a 'true' value */ public static boolean isFlagNotSet(Object flagValue) { return !isFlagSet(flagValue); } /** * Forwards to {@link Utilities#isFlagSet(Object)} * * @param stringFlag The string to check against the set of 'true' values * @return True if the string input flag is set */ public static boolean isFlagSet(String stringFlag) { if (stringFlag == null) { return false; } return isFlagSet((Object)stringFlag); } /** * Check if a String, Boolean, or Number flag object should be considered equivalent to boolean true. * * For strings, true values are: (true, yes, 1, Y), all case-insensitive. All other strings are false. * * Boolean 'true' will also be interpreted as a true value. * * Numeric '1' will also be interpreted as a true value. * * All other values, including null, will always be false. * * @param flagValue String representation of a flag * @return if flag is true */ public static boolean isFlagSet(Object flagValue) { if (flagValue instanceof String) { String stringFlag = (String)flagValue; if (stringFlag.equalsIgnoreCase("true")) { return true; } else if (stringFlag.equalsIgnoreCase("yes")) { return true; } else if (stringFlag.equals("1")) { return true; } else if (stringFlag.equalsIgnoreCase("Y")) { return true; } } else if (flagValue instanceof Boolean) { return ((Boolean) flagValue); } else if (flagValue instanceof Number) { int numValue = ((Number) flagValue).intValue(); return (numValue == 1); } return false; } /** * Returns the inverse of {@link #isAssignableFrom(Class, Class)}. In * other words, returns true if the following code would fail to compile: * * TestClass ot = new TestClass(); * ParentClass tt = ot; * * @param parentClass The first (parent-ish) class * @param testClass The second (child-ish) class * @param <A> The parent type * @param <B> The potential child type * @return True if parentClass is NOT assignable from testClass */ public static <A, B> boolean isNotAssignableFrom(Class<A> parentClass, Class<B> testClass) { return !isAssignableFrom(parentClass, testClass); } /** * Returns true if the input is NOT an empty Map. * * @param map The map to check * @return True if the input is NOT an empty map */ public static boolean isNotEmpty(Map<?, ?> map) { return !Util.isEmpty(map); } /** * Returns true if the input is NOT an empty Collection. * * @param list The list to check * @return True if the input is NOT an empty collection */ public static boolean isNotEmpty(Collection<?> list) { return !Util.isEmpty(list); } /** * Returns true if the input string is not null and contains any non-whitespace * characters. * * @param input The input string to check * @return True if the input is not null, empty, or only whitespace */ public static boolean isNotNullEmptyOrWhitespace(String input) { return !isNullEmptyOrWhitespace(input); } /** * Returns true if the input is NOT only digits * * @param input The input to check * @return True if the input contains any non-digit characters */ public static boolean isNotNumber(String input) { return !isNumber(input); } /** * Returns true if the given object is 'nothing': a null, empty string, empty map, empty * Collection, empty Optional, or empty Iterable. If the given object is a Supplier, * returns true if {@link Supplier#get()} returns a 'nothing' result. * * Iterables will be flushed using {@link Util#flushIterator(Iterator)}. That means this may * be a slow process for Iterables. * * @param thing The object to test for nothingness * @return True if the object is nothing */ public static boolean isNothing(Object thing) { if (thing == null) { return true; } else if (thing instanceof String) { return ((String) thing).trim().isEmpty(); } else if (thing instanceof Object[]) { return (((Object[]) thing).length == 0); } else if (thing instanceof Collection) { return ((Collection<?>) thing).isEmpty(); } else if (thing instanceof Map) { return ((Map<?,?>) thing).isEmpty(); } else if (thing instanceof Iterable) { Iterator<?> i = ((Iterable<?>) thing).iterator(); boolean empty = !i.hasNext(); Util.flushIterator(i); return empty; } else if (thing instanceof Optional) { return !((Optional<?>) thing).isPresent(); } else if (thing instanceof Supplier) { Object output = ((Supplier<?>) thing).get(); return isNothing(output); } return false; } /** * Returns true if the input string is null, empty, or contains only whitespace * characters according to {@link Character#isWhitespace(char)}. * @param input The input string * @return True if the input is null, empty, or only whitespace */ public static boolean isNullEmptyOrWhitespace(String input) { if (input == null || input.isEmpty()) { return true; } for(char c : input.toCharArray()) { if (!Character.isWhitespace(c)) { return false; } } return true; } /** * Returns true if this string contains only digits * @param input The input string * @return True if this string contains only digits */ public static boolean isNumber(String input) { if (input == null || input.isEmpty()) { return false; } int nonDigits = 0; for(int i = 0; i < input.length(); ++i) { char ch = input.charAt(i); if (!Character.isDigit(ch)) { nonDigits++; break; } } return (nonDigits == 0); } /** * Returns true if {@link #isNothing(Object)} would return false. * * @param thing The thing to check * @return True if the object is NOT a 'nothing' value */ public static boolean isSomething(Object thing) { return !isNothing(thing); } /** * Returns the current time in the standard ISO offset (date T time+1:00) format * @return The formatted current time */ public static String isoOffsetTimestamp() { LocalDateTime now = LocalDateTime.now(); DateTimeFormatter formatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME; return now.format(formatter); } /** * Creates a MessageAccumulator that just inserts the message into the target list. * * @param target The target list, to which messages will be added. Must be thread-safe for add. * @param dated If true, messages will be prepended with the output of {@link #timestamp()} * @return The resulting MessageAccumulator implementation */ public static MessageAccumulator listMessageAccumulator(List<String> target, boolean dated) { return (msg) -> { String finalMessage = msg.getLocalizedMessage(); if (dated) { finalMessage = timestamp() + " " + finalMessage; } target.add(finalMessage); }; } /** * Returns a new *modifiable* list with the objects specified added to it. * A new list will be returned on each invocation. This method will never * return null. * * In Java 11+, the List.of() method constructs a list of arbitrary type, * which is not modifiable by default. * * @param objects The objects to add to the list * @param <T> The type of the list * @return A list containing each of the items */ @SafeVarargs public static <T> List<T> listOf(T... objects) { List<T> list = new ArrayList<>(); if (objects != null) { Collections.addAll(list, objects); } return list; } /** * Returns true if every key and value in the Map can be cast to the types given. * Passing a null for either Class parameter will ignore that check. * * A true result should guarantee no ClassCastExceptions will result from casting * the Map keys to any of the given values. * * If both expected types are null or equal to {@link Object}, this method will trivially * return true. If the map is null or empty, this method will trivially return true. * * NOTE that this method will iterate over all key-value pairs in the Map, so may * be quite expensive if the Map is large. * * @param inputMap The input map to check * @param expectedKeyType The type implemented or extended by all Map keys * @param expectedValueType The type implemented or exended by all Map values * @param <S> The map key type * @param <T> The map value type * @return True if all map keys and values will NOT throw an exception on being cast to either given type, false otherwise */ public static <S, T> boolean mapConformsToType(Map<?, ?> inputMap, Class<S> expectedKeyType, Class<T> expectedValueType) { if (inputMap == null || inputMap.isEmpty()) { // Trivially true, since nothing can throw a ClassCastException return true; } if ((expectedKeyType == null || Object.class.equals(expectedKeyType)) && (expectedValueType == null || Object.class.equals(expectedValueType))) { return true; } for(Map.Entry<?, ?> entry : inputMap.entrySet()) { Object key = entry.getKey(); if (key != null && expectedKeyType != null && !Object.class.equals(expectedKeyType) && !expectedKeyType.isAssignableFrom(key.getClass())) { return false; } Object value = entry.getValue(); if (value != null && expectedValueType != null && !Object.class.equals(expectedValueType) && !expectedValueType.isAssignableFrom(value.getClass())) { return false; } } return true; } /** * Creates a map from a varargs list of items, where every other item is a key or value. * * If the arguments list does not have enough items for the final value, null will be used. * * @param input The input items, alternating key and value * @param <S> The key type * @param <T> The value type * @return on failures */ @SuppressWarnings("unchecked") public static <S, T> Map<S, T> mapOf(Object... input) { Map<S, T> map = new HashMap<>(); if (input != null && input.length > 0) { for(int i = 0; i < input.length; i += 2) { S key = (S) input[i]; T value = null; if (input.length > (i + 1)) { value = (T) input[i + 1]; } map.put(key, value); } } return map; } /** * Transforms a MatchExpression selector into a CompoundFilter * @param input The input expression * @return The newly created CompoundFilter corresponding to the MatchExpression */ public static CompoundFilter matchExpressionToCompoundFilter(IdentitySelector.MatchExpression input) { CompoundFilter filter = new CompoundFilter(); List<Application> applications = new ArrayList<>(); Application expressionApplication = input.getApplication(); if (expressionApplication != null) { applications.add(expressionApplication); } List<Filter> filters = new ArrayList<>(); for(IdentitySelector.MatchTerm term : Util.safeIterable(input.getTerms())) { filters.add(matchTermToFilter(term, expressionApplication, applications)); } Filter mainFilter; if (filters.size() == 1) { mainFilter = filters.get(0); } else if (input.isAnd()) { mainFilter = Filter.and(filters); } else { mainFilter = Filter.or(filters); } filter.setFilter(mainFilter); filter.setApplications(applications); return filter; } /** * Create a MatchTerm from scratch * @param property The property to test * @param value The value to test * @param application The application to associate the term with (or null) * @return The newly created MatchTerm */ public static IdentitySelector.MatchTerm matchTerm(String property, Object value, Application application) { IdentitySelector.MatchTerm term = new IdentitySelector.MatchTerm(); term.setApplication(application); term.setName(property); term.setValue(Util.otoa(value)); term.setType(IdentitySelector.MatchTerm.Type.Entitlement); return term; } /** * Transforms a MatchTerm into a Filter, which can be useful for then modifying it * @param term The matchterm to transform * @param defaultApplication The default application if none is specified (may be null) * @param applications The list of applications * @return The new Filter object */ public static Filter matchTermToFilter(IdentitySelector.MatchTerm term, Application defaultApplication, List<Application> applications) { int applId = -1; Application appl = null; if (term.getApplication() != null) { appl = term.getApplication(); if (!applications.contains(appl)) { applications.add(appl); } applId = applications.indexOf(appl); } if (appl == null && defaultApplication != null) { appl = defaultApplication; applId = applications.indexOf(defaultApplication); } if (term.isContainer()) { List<Filter> filters = new ArrayList<>(); for(IdentitySelector.MatchTerm child : Util.safeIterable(term.getChildren())) { filters.add(matchTermToFilter(child, appl, applications)); } if (term.isAnd()) { return Filter.and(filters); } else { return Filter.or(filters); } } else { String filterProperty = term.getName(); if (applId >= 0) { filterProperty = applId + ":" + filterProperty; } if (Util.isNullOrEmpty(term.getValue())) { return Filter.isnull(filterProperty); } return Filter.eq(filterProperty, term.getValue()); } } /** * Returns the maximum of the given dates. If no values are passed, returns the * earliest possible date. * * @param dates The dates to find the max of * @return The maximum date in the array */ public static Date max(Date... dates) { Date maxDate = new Date(Long.MIN_VALUE); for(Date d : Objects.requireNonNull(dates)) { if (d.after(maxDate)) { maxDate = d; } } return new Date(maxDate.getTime()); } /** * Returns the maximum of the given dates. If no values are passed, returns the * latest possible date. The returned value is always a new object, not one * of the actual objects in the input. * * @param dates The dates to find the max of * @return The maximum date in the array */ public static Date min(Date... dates) { Date minDate = new Date(Long.MAX_VALUE); for(Date d : Objects.requireNonNull(dates)) { if (d.before(minDate)) { minDate = d; } } return new Date(minDate.getTime()); } /** * Returns true if {@link Util#nullSafeEq(Object, Object)} would return * false and vice versa. Two null values will be considered equal. * * @param a The first value * @param b The second value * @return True if the values are NOT equal */ public static boolean nullSafeNotEq(Object a, Object b) { return !Util.nullSafeEq(a, b, true); } /** * Returns the input string if it is not null. Otherwise, returns an empty string. * * @param maybeNull The input string, which is possibly null * @return The input string or an empty string */ public static String nullToEmpty(String maybeNull) { if (maybeNull == null) { return ""; } return maybeNull; } /** * Converts the given collection to an empty Attributes, if a null object is passed, * the input object (if an Attributes is passed), or a new Attributes containing all * elements from the input Map (if any other type of Map is passed). * * @param input The input map or attributes * @return The result as described above */ @SuppressWarnings("unchecked") public static Attributes<String, Object> nullToEmpty(Map<String, ? extends Object> input) { if (input == null) { return new Attributes<>(); } else if (input instanceof Attributes) { return (Attributes<String, Object>) input; } else { return new Attributes<>(input); } } /** * Converts the given collection to an empty list (if a null value is passed), * the input object (if a List is passed), or a copy of the input object in a * new ArrayList (if any other Collection is passed). * * @param input The input collection * @param <T> The type of the list * @return The result as described above */ public static <T> List<T> nullToEmpty(Collection<T> input) { if (input == null) { return new ArrayList<>(); } else if (input instanceof List) { return (List<T>)input; } else { return new ArrayList<>(input); } } /** * Returns the input string if it is not null, explicitly noting the input as a String to * make Beanshell happy at runtime. * * Identical to {@link Utilities#nullToEmpty(String)}, except Beanshell can't decide * which of the method variants to call when the input is null. This leads to scripts * sometimes calling {@link Utilities#nullToEmpty(Map)} instead. (Java would be able * to infer the overload to invoke at compile time by using the variable type.) * * @param maybeNull The input string, which is possibly null * @return The input string or an empty string */ public static String nullToEmptyString(String maybeNull) { return Utilities.nullToEmpty(maybeNull); } /** * Parses the input string into a LocalDateTime, returning an {@link Optional} * if the date parses properly. If the date does not parse properly, or if the * input is null, returns an {@link Optional#empty()}. * * @param inputString The input string * @param format The format used to parse the input string per {@link DateTimeFormatter} rules * @return The parsed string */ public static Optional<LocalDateTime> parseDateString(String inputString, String format) { if (Util.isNullOrEmpty(inputString) || Util.isNullOrEmpty(format)) { return Optional.empty(); } try { DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format); return Optional.of(LocalDateTime.parse(inputString, formatter)); } catch(DateTimeParseException e) { if (logger.isDebugEnabled()) { logger.debug("Failed to parse date [" + inputString + "] according to format [" + format + "]"); } return Optional.empty(); } } /** * Constructs a new map with each key having the prefix added to it. This can be * used to merge two maps without overwriting keys from either one, for example. * * @param map The input map, which will not be modified * @param prefix The prefix to add to each key * @param <V> The value type of the map * @return A new {@link HashMap} with each key prefixed by the given prefix */ public static <V> Map<String, V> prefixMap(Map<String, V> map, String prefix) { Map<String, V> newMap = new HashMap<>(); for(String key : map.keySet()) { newMap.put(prefix + key, map.get(key)); } return newMap; } /** * Attempts to dynamically evaluate whatever thing is passed in and return the * output of running the thing. If the thing is not of a known type, this method * silently returns null. * * The following types of things are accept3ed: * * - sailpoint.object.Rule: Evaluates as a SailPoint rule * - sailpoint.object.Script: Evaluates as a SailPoint script after being cloned * - java.lang.String: Evaluates as a SailPoint script * - java.util.function.Function: Accepts the Map of parameters, returns a value * - java.util.function.Consumer: Accepts the Map of parameters * - sailpoint.object.JavaRuleExecutor: Evaluates as a Java rule * * For Function and Consumer things, the context and a log will be added to the * params. * * @param context The sailpoint context * @param thing The thing to run * @param params The parameters to pass to the thing, if any * @param <T> the context-sensitive type of the return * @return The return value from the thing executed, or null * @throws GeneralException if any failure occurs */ @SuppressWarnings("unchecked") public static <T> T quietRun(SailPointContext context, Object thing, Map<String, Object> params) throws GeneralException { if (thing instanceof Rule) { Rule rule = (Rule)thing; return (T)context.runRule(rule, params); } else if (thing instanceof String || thing instanceof Script) { Script safeScript = getAsScript(thing); return (T) context.runScript(safeScript, params); } else if (thing instanceof Reference) { SailPointObject ref = ((Reference) thing).resolve(context); return quietRun(context, ref, params); } else if (thing instanceof Callable) { try { Callable<T> callable = (Callable<T>)thing; return callable.call(); } catch (Exception e) { throw new GeneralException(e); } } else if (thing instanceof Function) { Function<Map<String, Object>, T> function = (Function<Map<String, Object>, T>) thing; params.put("context", context); params.put("log", LogFactory.getLog(thing.getClass())); return function.apply(params); } else if (thing instanceof Consumer) { Consumer<Map<String, Object>> consumer = (Consumer<Map<String, Object>>) thing; params.put("context", context); params.put("log", LogFactory.getLog(thing.getClass())); consumer.accept(params); } else if (thing instanceof JavaRuleExecutor) { JavaRuleExecutor executor = (JavaRuleExecutor)thing; JavaRuleContext javaRuleContext = new JavaRuleContext(context, params); try { return (T)executor.execute(javaRuleContext); } catch(GeneralException e) { throw e; } catch(Exception e) { throw new GeneralException(e); } } return null; } /** * Safely casts the given input to the target type. * * If the object cannot be cast to the target type, this method returns null instead of throwing a ClassCastException. * * If the input object is null, this method returns null. * * If the targetClass is null, this method throws a {@link NullPointerException}. * * @param input The input object to cast * @param targetClass The target class to which it should be cast * @param <T> The expected return type * @return The object cast to the given type, or null if it cannot be cast */ public static <T> T safeCast(Object input, Class<T> targetClass) { if (input == null) { return null; } Objects.requireNonNull(targetClass, "targetClass must not be null"); if (targetClass.isAssignableFrom(input.getClass())) { return targetClass.cast(input); } return null; } /** * Returns the class name of the object, or the string 'null', suitable for logging safely * @param any The object to get the type of * @return The class name, or the string 'null' */ public static String safeClassName(Object any) { if (any == null) { return "null"; } else { return any.getClass().getName(); } } /** * Returns true if the bigger collection contains all elements in the smaller * collection. If the inputs are null, the comparison will always be false. * If the inputs are not collections, they will be coerced to collections * before comparison. * * @param maybeBiggerCollection An object that may be the bigger collection * @param maybeSmallerCollection AN object that may be the smaller collection * @return True if the bigger collection contains all elements of the smaller collection */ public static boolean safeContainsAll(Object maybeBiggerCollection, Object maybeSmallerCollection) { if (maybeBiggerCollection == null || maybeSmallerCollection == null) { return false; } List<Object> biggerCollection = new ArrayList<>(); if (maybeBiggerCollection instanceof Collection) { biggerCollection.addAll((Collection<?>) maybeBiggerCollection); } else if (maybeBiggerCollection instanceof Object[]) { biggerCollection.addAll(Arrays.asList((Object[])maybeBiggerCollection)); } else { biggerCollection.add(maybeBiggerCollection); } List<Object> smallerCollection = new ArrayList<>(); if (maybeSmallerCollection instanceof Collection) { smallerCollection.addAll((Collection<?>) maybeSmallerCollection); } else if (maybeSmallerCollection instanceof Object[]) { smallerCollection.addAll(Arrays.asList((Object[])maybeSmallerCollection)); } else { smallerCollection.add(maybeSmallerCollection); } return new HashSet<>(biggerCollection).containsAll(smallerCollection); } /** * Returns a long timestamp for the input Date, returning {@link Long#MIN_VALUE} if the * Date is null. * * @param input The input date * @return The timestamp of the date, or Long.MIN_VALUE if it is null */ public static long safeDateTimestamp(Date input) { if (input == null) { return Long.MIN_VALUE; } return input.getTime(); } /** * Invokes an action against each key-value pair in the Map. If the Map is null, * or if the function is null, no action is taken and no exception is thrown. * * @param map The map * @param function A BiConsumer that will be applied to each key-avlue pair in the Map * @param <A> The type of the map's keys * @param <B> The type of the map's values */ public static <A, B> void safeForeach(Map<A, B> map, BiConsumer<A, B> function) { if (map == null || function == null) { return; } for(Map.Entry<A, B> entry : map.entrySet()) { function.accept(entry.getKey(), entry.getValue()); } } /** * Returns a stream for the given map's keys if it's not null, or an empty stream if it is * @param map The map * @param <T> The type of the map's keys * @return A stream from the map's keys, or an empty stream */ public static <T> Stream<T> safeKeyStream(Map<T, ?> map) { if (map == null) { return Stream.empty(); } return map.keySet().stream(); } /** * Safely converts the given input to a List. * * If the input is a String, it will be added to a new List and returned. * * If the input is a Number, Boolean, or {@link Message}, it will be converted to String, added to a List, and returned. * * If the input is already a List, the input object will be returned as-is. * * If the input is an array of strings, they will be added to a new list and returned. * * If the input is an array of any other type of object, they will be converted to strings, added to a new list, and returned. * * If the input is any other kind of Collection, all elements will be added to a new List and returned. * * If the input is a {@link Stream}, all elements will be converted to Strings using {@link Utilities#safeString(Object)}, then added to a new List and returned. * * All other values result in an empty list. * * This method never returns null. * * Unlike {@link Util#otol(Object)}, this method does not split strings as CSVs. * * It's not my problem if your existing lists have something other than Strings in them. * * @param value The value to listify * @return The resulting List */ @SuppressWarnings("unchecked") public static List<String> safeListify(Object value) { if (value instanceof String) { List<String> single = new ArrayList<>(); single.add((String) value); return single; } else if (value instanceof Number || value instanceof Boolean) { List<String> single = new ArrayList<>(); single.add(String.valueOf(value)); return single; } else if (value instanceof Message) { List<String> single = new ArrayList<>(); single.add(((Message) value).getLocalizedMessage()); return single; } else if (value instanceof String[]) { String[] strings = (String[])value; return new ArrayList<>(Arrays.asList(strings)); } else if (value instanceof Object[]) { Object[] objs = (Object[])value; return Arrays.stream(objs).map(Utilities::safeString).collect(Collectors.toCollection(ArrayList::new)); } else if (value instanceof List) { return (List<String>)value; } else if (value instanceof Collection) { return new ArrayList<>((Collection<String>)value); } else if (value instanceof Stream) { return ((Stream<?>)value).map(Utilities::safeString).collect(Collectors.toList()); } return new ArrayList<>(); } /** * Returns a Map cast to the given generic types if and only if it passes the check in * {@link #mapConformsToType(Map, Class, Class)} for the same type parameters. * * If the input is not a Map or if the key/value types do not conform to the expected * types, this method returns null. * * @param input The input map * @param keyType The key type * @param valueType The value type * @param <S> The resulting key type * @param <T> The resulting value type * @return The resulting Map */ @SuppressWarnings("unchecked") public static <S, T> Map<S, T> safeMapCast(Object input, Class<S> keyType, Class<T> valueType) { if (!(input instanceof Map)) { return null; } boolean conforms = mapConformsToType((Map<?, ?>) input, keyType, valueType); if (conforms) { return (Map<S, T>)input; } else { return null; } } /** * Returns the size of the input array, returning 0 if the array is null * @param input The array to get the size of * @param <T> The type of the array (just for compiler friendliness) * @return The size of the array */ public static <T> int safeSize(T[] input) { if (input == null) { return 0; } return input.length; } /** * Returns the size of the input collection, returning 0 if the collection is null * @param input The collection to get the size of * @return The size of the collection */ public static int safeSize(Collection<?> input) { if (input == null) { return 0; } return input.size(); } /** * Returns the length of the input string, returning 0 if the string is null * @param input The string to get the length of * @return The size of the string */ public static int safeSize(String input) { if (input == null) { return 0; } return input.length(); } /** * Returns a stream for the given array if it's not null, or an empty stream if it is * @param array The array * @param <T> The type of the array * @return A stream from the array, or an empty stream */ public static <T> Stream<T> safeStream(T[] array) { if (array == null || array.length == 0) { return Stream.empty(); } return Arrays.stream(array); } /** * Returns a stream for the given list if it's not null, or an empty stream if it is * @param list The list * @param <T> The type of the list * @return A stream from the list, or an empty stream */ public static <T> Stream<T> safeStream(List<T> list) { if (list == null) { return Stream.empty(); } return list.stream(); } /** * Returns a stream for the given set if it's not null, or an empty stream if it is * @param set The list * @param <T> The type of the list * @return A stream from the list, or an empty stream */ public static <T> Stream<T> safeStream(Set<T> set) { if (set == null) { return Stream.empty(); } return set.stream(); } /** * Returns the given value as a "safe string". If the value is null, it will be returned as an empty string. If the value is already a String, it will be returned as-is. If the value is anything else, it will be passed through {@link String#valueOf(Object)}. * * If the input is an array, it will be converted to a temporary list for String.valueOf() output. * * The output will never be null. * * @param whatever The thing to return * @return The string */ public static String safeString(Object whatever) { if (whatever == null) { return ""; } if (whatever instanceof String) { return (String)whatever; } // If we've got an array, make it a list for a nicer toString() if (whatever.getClass().isArray()) { Object[] array = (Object[])whatever; whatever = Arrays.stream(array).collect(Collectors.toCollection(ArrayList::new)); } return String.valueOf(whatever); } /** * Performs a safe subscript operation against the given array. * * If the array is null, or if the index is out of bounds, this method * returns null instead of throwing an exception. * * @param list The array to get the value from * @param index The index from which to get the value. * @param <T> The expected return type * @return The value at the given index in the array, or null */ public static <T, S extends T> T safeSubscript(S[] list, int index) { return safeSubscript(list, index, null); } /** * Performs a safe subscript operation against the given array. * * If the array is null, or if the index is out of bounds, this method returns * the default instead of throwing an exception. * * @param list The array to get the value from * @param index The index from which to get the value. * @param defaultValue The default value to return if the input is null * @param <T> The expected return type * @return The value at the given index in the array, or null */ public static <T, S extends T> T safeSubscript(S[] list, int index, T defaultValue) { if (list == null) { return defaultValue; } if (index >= list.length || index < 0) { return defaultValue; } return list[index]; } /** * Performs a safe subscript operation against the given {@link List}. * * If the list is null, or if the index is out of bounds, this method returns null instead of throwing an exception. * * Equivalent to safeSubscript(list, index, null). * * @param list The List to get the value from * @param index The index from which to get the value. * @param <T> The expected return type * @return The value at the given index in the List, or null */ public static <T, S extends T> T safeSubscript(List<S> list, int index) { return safeSubscript(list, index, null); } /** * Performs a safe subscript operation against the given {@link List}. * * If the list is null, or if the index is out of bounds, this method returns the given default object instead of throwing an exception. * * @param list The List to get the value from * @param index The index from which to get the value. * @param defaultObject The default object to return in null or out-of-bounds cases * @param <S> The actual type of the list, which must be a subclass of T * @param <T> The expected return type * @return The value at the given index in the List, or null */ public static <T, S extends T> T safeSubscript(List<S> list, int index, T defaultObject) { if (list == null) { return defaultObject; } if (index >= list.size() || index < 0) { return defaultObject; } return list.get(index); } /** * Safely substring the given input String, accounting for odd index situations. * This method should never throw a StringIndexOutOfBounds exception. * * Negative values will be interpreted as distance from the end, like Python. * * If the start index is higher than the end index, or if the start index is * higher than the string length, the substring is not defined and an empty * string will be returned. * * If the end index is higher than the length of the string, the whole * remaining string after the start index will be returned. * * @param input The input string to substring * @param start The start index * @param end The end index * @return The substring */ public static String safeSubstring(String input, int start, int end) { if (input == null) { return null; } if (end < 0) { end = input.length() + end; } if (start < 0) { start = input.length() + start; } if (end > input.length()) { end = input.length(); } if (start > end) { return ""; } if (start < 0) { start = 0; } if (end < 0) { end = 0; } return input.substring(start, end); } /** * Returns a trimmed version of the input string, returning an empty * string if it is null. * @param input The input string to trim * @return A non-null trimmed copy of the input string */ public static String safeTrim(String input) { if (input == null) { return ""; } return input.trim(); } /** * Sets the given attribute on the given object, if it supports attributes. The * attributes on some object types may be called other things like arguments. * * @param source The source object, which may implement an Attributes container method * @param attributeName The name of the attribute to set * @param value The value to set in that attribute */ public static void setAttribute(Object source, String attributeName, Object value) { /* * In Java 8+, using instanceof is about as fast as using == and way faster than * reflection and possibly throwing an exception, so this is the best way to get * attributes if we aren't sure of the type of the object. * * Most classes have their attributes exposed via getAttributes, but some have * them exposed via something like getArguments. This method will take care of * the difference for you. * * Did I miss any? Probably. But this is a lot. */ Objects.requireNonNull(source, "You cannot set an attribute on a null object"); Objects.requireNonNull(attributeName, "Attribute names must not be null"); Attributes<String, Object> existing = null; if (!(source instanceof Custom || source instanceof Configuration || source instanceof Identity || source instanceof Link || source instanceof Bundle || source instanceof Application || source instanceof TaskDefinition || source instanceof TaskItem)) { existing = getAttributes(source); if (existing == null) { existing = new Attributes<>(); } if (value == null) { existing.remove(attributeName); } else { existing.put(attributeName, value); } } if (source instanceof Identity) { // This does special stuff ((Identity) source).setAttribute(attributeName, value); } else if (source instanceof Link) { ((Link) source).setAttribute(attributeName, value); } else if (source instanceof Bundle) { ((Bundle) source).setAttribute(attributeName, value); } else if (source instanceof Custom) { // Custom objects are gross ((Custom) source).put(attributeName, value); } else if (source instanceof Configuration) { ((Configuration) source).put(attributeName, value); } else if (source instanceof Application) { ((Application) source).setAttribute(attributeName, value); } else if (source instanceof CertificationItem) { // This one returns a Map for some reason ((CertificationItem) source).setAttributes(existing); } else if (source instanceof CertificationEntity) { ((CertificationEntity) source).setAttributes(existing); } else if (source instanceof Certification) { ((Certification) source).setAttributes(existing); } else if (source instanceof CertificationDefinition) { ((CertificationDefinition) source).setAttributes(existing); } else if (source instanceof TaskDefinition) { ((TaskDefinition) source).setArgument(attributeName, value); } else if (source instanceof TaskItem) { ((TaskItem) source).setAttribute(attributeName, value); } else if (source instanceof ManagedAttribute) { ((ManagedAttribute) source).setAttributes(existing); } else if (source instanceof Form) { ((Form) source).setAttributes(existing); } else if (source instanceof IdentityRequest) { ((IdentityRequest) source).setAttributes(existing); } else if (source instanceof IdentitySnapshot) { ((IdentitySnapshot) source).setAttributes(existing); } else if (source instanceof ResourceObject) { ((ResourceObject) source).setAttributes(existing); } else if (source instanceof Field) { ((Field) source).setAttributes(existing); } else if (source instanceof ProvisioningPlan) { ((ProvisioningPlan) source).setArguments(existing); } else if (source instanceof IntegrationConfig) { ((IntegrationConfig) source).setAttributes(existing); } else if (source instanceof ProvisioningProject) { ((ProvisioningProject) source).setAttributes(existing); } else if (source instanceof ProvisioningTransaction) { ((ProvisioningTransaction) source).setAttributes(existing); } else if (source instanceof ProvisioningPlan.AbstractRequest) { ((ProvisioningPlan.AbstractRequest) source).setArguments(existing); } else if (source instanceof Rule) { ((Rule) source).setAttributes(existing); } else if (source instanceof WorkItem) { ((WorkItem) source).setAttributes(existing); } else if (source instanceof RpcRequest) { ((RpcRequest) source).setArguments(existing); } else if (source instanceof ApprovalItem) { ((ApprovalItem) source).setAttributes(existing); } else { throw new UnsupportedOperationException("This method does not support objects of type " + source.getClass().getName()); } } /** * Returns a new *modifiable* set with the objects specified added to it. * A new set will be returned on each invocation. This method will never * return null. * * @param objects The objects to add to the set * @param <T> The type of each item * @return A set containing each of the items */ @SafeVarargs public static <T> Set<T> setOf(T... objects) { Set<T> set = new HashSet<>(); if (objects != null) { Collections.addAll(set, objects); } return set; } /** * Adds the given key and value to the Map if no existing value for the key is * present. The Map will be synchronized so that only one thread is guaranteed * to be able to insert the initial value. * * If possible, you should use a {@link java.util.concurrent.ConcurrentMap}, which * already handles this situation with greater finesse. * * @param target The target Map to which the value should be inserted if missing * @param key The key to insert * @param value A supplier for the value to insert * @param <S> The key type * @param <T> The value type */ public static <S, T> void synchronizedPutIfAbsent(final Map<S, T> target, final S key, final Supplier<T> value) { Objects.requireNonNull(target, "The Map passed to synchronizedPutIfAbsent must not be null"); if (!target.containsKey(key)) { synchronized(target) { if (!target.containsKey(key)) { T valueObj = value.get(); target.put(key, valueObj); } } } } /** * Converts two Date objects to {@link LocalDateTime} at the system default * time zone and returns the {@link Duration} between them. * * If you pass the dates in the wrong order (first parameter is the later * date), they will be silently swapped before returning the Duration. * * @param firstTime The first time to compare * @param secondTime The second time to compare * @return The {@link Period} between the two days */ public static Duration timeDifference(Date firstTime, Date secondTime) { if (firstTime == null || secondTime == null) { throw new IllegalArgumentException("Both arguments to dateDifference must be non-null"); } LocalDateTime ldt1 = firstTime.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime(); LocalDateTime ldt2 = secondTime.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime(); // Swap the dates if they're backwards if (ldt1.isAfter(ldt2)) { LocalDateTime tmp = ldt2; ldt2 = ldt1; ldt1 = tmp; } return Duration.between(ldt1, ldt2); } /** * Coerces the millisecond timestamps to Date objects, then invokes the API * {@link #timeDifference(Date, Date)}. * * @param firstTime The first millisecond timestamp * @param secondTime The second millisecond timestamp * @return The difference between the two times as a {@link Duration}. * * @see #timeDifference(Date, Date) */ public static Duration timeDifference(long firstTime, long secondTime) { return timeDifference(new Date(firstTime), new Date(secondTime)); } /** * Returns the current time in a standard format * @return The current time */ public static String timestamp() { SimpleDateFormat formatter = new SimpleDateFormat(CommonConstants.STANDARD_TIMESTAMP); formatter.setTimeZone(TimeZone.getDefault()); return formatter.format(new Date()); } /** * Translates the input to XML, if a serializer is registered for it. In * general, this can be anything in 'sailpoint.object', a Map, a List, a * String, or other primitives. * * @param input The object to serialize * @return the output XML * @throws ConfigurationException if the object type cannot be serialized */ public static String toXml(Object input) throws ConfigurationException { if (input == null) { return null; } XMLObjectFactory xmlObjectFactory = XMLObjectFactory.getInstance(); return xmlObjectFactory.toXml(input); } /** * Attempts to capture the user's time zone information from the current JSF * context / HTTP session, if one is available. The time zone and locale will * be captured to the user's UIPreferences as 'mostRecentTimezone' and * 'mostRecentLocale'. * * If a session is not available, this method does nothing. * * The JSF session is available in a subset of rule contexts, most notably the * QuickLink textScript context, which runs on each load of the user's home.jsf page. * * If you are trying to capture a time zone in a plugin REST API call, you should * use {@link #tryCaptureLocationInfo(SailPointContext, UserContext)}, passing the * plugin resource itself as a {@link UserContext}. * * @param context The current IIQ context * @param currentUser The user to modify with the detected information */ public static void tryCaptureLocationInfo(SailPointContext context, Identity currentUser) { Objects.requireNonNull(currentUser, "A non-null Identity must be provided"); TimeZone tz = null; Locale locale = null; FacesContext fc = FacesContext.getCurrentInstance(); if (fc != null) { if (fc.getViewRoot() != null) { locale = fc.getViewRoot().getLocale(); } HttpSession session = (HttpSession)fc.getExternalContext().getSession(true); if (session != null) { tz = (TimeZone)session.getAttribute("timeZone"); } } boolean save = false; if (tz != null) { save = true; currentUser.setUIPreference(MOST_RECENT_TIMEZONE, tz.getID()); } if (locale != null) { currentUser.setUIPreference(MOST_RECENT_LOCALE, locale.toLanguageTag()); save = true; } if (save) { try { context.saveObject(currentUser); context.saveObject(currentUser.getUIPreferences()); context.commitTransaction(); } catch(Exception e) { /* Ignore this */ } } } /** * Attempts to capture the user's time zone information from the user context. This could be used via a web services call where the {@link BaseResource} class is a {@link UserContext}. * * @param context The current IIQ context * @param currentUser The current user context * @throws GeneralException if there is no currently logged in user */ public static void tryCaptureLocationInfo(SailPointContext context, UserContext currentUser) throws GeneralException { TimeZone tz = currentUser.getUserTimeZone(); Locale locale = currentUser.getLocale(); boolean save = false; if (tz != null) { save = true; currentUser.getLoggedInUser().setUIPreference(MOST_RECENT_TIMEZONE, tz.getID()); } if (locale != null) { currentUser.getLoggedInUser().setUIPreference(MOST_RECENT_LOCALE, locale.toLanguageTag()); save = true; } if (save) { try { context.saveObject(currentUser.getLoggedInUser()); context.saveObject(currentUser.getLoggedInUser().getUIPreferences()); context.commitTransaction(); } catch(Exception e) { /* Ignore this */ } } } /** * Attempts to get the SPKeyStore, a class whose getInstance() is for some * reason protected. * @return The keystore, if we could get it * @throws GeneralException If the keystore could not be retrieved */ public static SPKeyStore tryGetKeystore() throws GeneralException { SPKeyStore result; try { Method getMethod = SPKeyStore.class.getDeclaredMethod("getInstance"); try { getMethod.setAccessible(true); result = (SPKeyStore) getMethod.invoke(null); } finally { getMethod.setAccessible(false); } } catch(NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { throw new GeneralException(e); } return result; } /** * Renders the given template using Velocity, passing the given arguments to the renderer. * Velocity will be initialized on the first invocation of this method. * * TODO invoke the Sailpoint utility in versions over 8.2 * * @param template The VTL template string * @param args The arguments to pass to the template renderer * @return The rendered string * @throws IOException if any Velocity failures occur */ public static String velocityRender(String template, Map<String, ?> args) throws IOException { if (!VELOCITY_INITIALIZED.get()) { synchronized (VELOCITY_INITIALIZED) { if (!VELOCITY_INITIALIZED.get()) { Velocity.setProperty("runtime.log.logsystem.class", "org.apache.velocity.runtime.log.AvalonLogChute,org.apache.velocity.runtime.log.Log4JLogChute,org.apache.velocity.runtime.log.JdkLogChute"); Velocity.setProperty("ISO-8859-1", "UTF-8"); Velocity.setProperty("output.encoding", "UTF-8"); Velocity.setProperty("resource.loader", "classpath"); Velocity.setProperty("classpath.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); Velocity.init(); VELOCITY_INITIALIZED.set(true); } } } Map<String, Object> params = new HashMap<>(args); params.put("escapeTools", new VelocityEscapeTools()); params.put("spTools", new VelocityUtil.SailPointVelocityTools(Locale.getDefault(), TimeZone.getDefault())); VelocityContext velocityContext = new VelocityContext(params); try (StringWriter writer = new StringWriter()) { String tag = "anonymous"; boolean success = Velocity.evaluate(velocityContext, writer, tag, template); if (!success) { throw new IOException("Velocity rendering did not succeed"); } writer.flush(); return writer.toString(); } } /** * Transforms a wildcard like 'a*' to a Filter. This method cannot support mid-string * cases like 'a*a' at this time. * * @param property The property being filtered * @param input The input (e.g., 'a*' * @param caseInsensitive Whether the Filter should be case-insensitive * @return A filter matching the given wildcard */ public static Filter wildcardToFilter(String property, String input, boolean caseInsensitive) { Filter output = null; // Simple cases if (input.replace("*", "").isEmpty()) { output = Filter.notnull(property); } else if (input.startsWith("*") && !input.substring(1).contains("*")) { output = Filter.like(property, input.substring(1), Filter.MatchMode.END); } else if (input.endsWith("*") && !input.substring(0, input.length() - 1).contains("*")) { output = Filter.like(property, input.substring(0, input.length() - 1), Filter.MatchMode.START); } else if (input.length() > 2 && input.startsWith("*") && input.endsWith("*") && !input.substring(1, input.length() - 1).contains("*")) { output = Filter.like(property, input.substring(1, input.length() - 1), Filter.MatchMode.ANYWHERE); } else { output = Filter.like(property, input, Filter.MatchMode.ANYWHERE); } // TODO complex cases like `*a*b*` if (output instanceof Filter.LeafFilter && caseInsensitive) { output = Filter.ignoreCase(output); } return output; } /** * Uses the valueProducer to extract the value from the input object if it is not * null, otherwise returns the default value. * * @param maybeNull An object which may be null * @param defaultValue The value to return if the object is null * @param valueProducer The generator of the value to return if the value is not nothing * @param <T> The return type * @return The result of the value producer, or the default */ public static <T> T withDefault(Object maybeNull, T defaultValue, Functions.FunctionWithError<Object, T> valueProducer) { if (maybeNull != null) { try { return valueProducer.applyWithError(maybeNull); } catch(Error e) { throw e; } catch (Throwable throwable) { logger.debug("Caught an error in withDefault", throwable); } } return defaultValue; } /** * Safely handles the given iterator by passing it to the Consumer and, regardless * of outcome, by flushing it when the Consumer returns. * * @param iterator The iterator to process * @param iteratorConsumer The iterator consumer, which will be invoked with the iterator * @param <T> The iterator type * @throws GeneralException if any failures occur */ public static <T> void withIterator(Iterator<T> iterator, Functions.ConsumerWithError<Iterator<T>> iteratorConsumer) throws GeneralException { withIterator(() -> iterator, iteratorConsumer); } /** * Safely handles the given iterator by passing it to the Consumer and, regardless * of outcome, by flushing it when the Consumer returns. * * @param iteratorSupplier The iterator supplier, which will be invoked once * @param iteratorConsumer The iterator consumer, which will be invoked with the iterator * @param <T> The iterator type * @throws GeneralException if any failures occur */ public static <T> void withIterator(Functions.SupplierWithError<Iterator<T>> iteratorSupplier, Functions.ConsumerWithError<Iterator<T>> iteratorConsumer) throws GeneralException { try { Iterator<T> iterator = iteratorSupplier.getWithError(); if (iterator != null) { try { iteratorConsumer.acceptWithError(iterator); } finally { Util.flushIterator(iterator); } } } catch(GeneralException | RuntimeException | Error e) { throw e; } catch(Throwable t) { throw new GeneralException(t); } } /** * Obtains the lock, then executes the callback * @param lock The lock to lock before doing the execution * @param callback The callback to invoke after locking * @throws GeneralException if any failures occur or if the lock is interrupted */ public static void withJavaLock(Lock lock, Callable<?> callback) throws GeneralException { try { lock.lockInterruptibly(); try { callback.call(); } catch(InterruptedException | GeneralException e) { throw e; } catch (Exception e) { throw new GeneralException(e); } finally { lock.unlock(); } } catch(InterruptedException e) { throw new GeneralException(e); } } /** * Obtains the lock, then executes the callback * @param lock The lock to lock before doing the execution * @param timeoutMillis The timeout for the lock, in milliseconds * @param callback The callback to invoke after locking * @throws GeneralException if any failures occur or if the lock is interrupted */ public static void withJavaTimeoutLock(Lock lock, long timeoutMillis, Callable<?> callback) throws GeneralException { try { boolean locked = lock.tryLock(timeoutMillis, TimeUnit.MILLISECONDS); if (!locked) { throw new GeneralException("Unable to obtain the lock within timeout period " + timeoutMillis + " ms"); } try { callback.call(); } catch(InterruptedException | GeneralException e) { throw e; } catch (Exception e) { throw new GeneralException(e); } finally { lock.unlock(); } } catch(InterruptedException e) { throw new GeneralException(e); } } /** * Creates a new database connection using the context provided, sets its auto-commit * flag to false, then passes it to the consumer provided. The consumer is responsible * for committing. * * @param context The context to produce the connection * @param consumer The consumer lambda or class to handle the connection * @throws GeneralException on failures */ public static void withNoCommitConnection(SailPointContext context, Functions.ConnectionHandler consumer) throws GeneralException {
try (Connection connection = ContextConnectionWrapper.getConnection(context)) {
1
2023-10-20 15:20:16+00:00
12k
mosaic-addons/traffic-state-estimation
src/main/java/com/dcaiti/mosaic/app/tse/processors/SpatioTemporalProcessor.java
[ { "identifier": "FcdRecord", "path": "src/main/java/com/dcaiti/mosaic/app/fxd/data/FcdRecord.java", "snippet": "public class FcdRecord extends FxdRecord {\n\n /**\n * List of vehicles perceived during the collection of FCD in the form of {@link VehicleObject VehicleObjects}.\n */\n private final List<VehicleObject> perceivedVehicles;\n\n /**\n * Constructor for a {@link FcdRecord}.\n *\n * @param timeStamp time of creation\n * @param position position at creation\n * @param connectionId connection at creation\n * @param speed spot speed at creation\n * @param offset driven distance on current connection\n * @param perceivedVehicles list of surrounding vehicles\n */\n private FcdRecord(long timeStamp, GeoPoint position, String connectionId,\n double speed, double offset, double heading, List<VehicleObject> perceivedVehicles) {\n super(timeStamp, position, connectionId, speed, offset, heading);\n this.perceivedVehicles = perceivedVehicles;\n }\n\n public List<VehicleObject> getPerceivedVehicles() {\n return perceivedVehicles;\n }\n\n @Override\n public String toString() {\n return new ToStringBuilder(this, SHORT_PREFIX_STYLE)\n .appendSuper(super.toString())\n .append(\n \"perceivedVehicles\",\n perceivedVehicles == null\n ? \"disabled perception\" : perceivedVehicles.stream().map(VehicleObject::getId).collect(Collectors.toList())\n )\n .toString();\n }\n\n @Override\n public long calculateRecordSize() {\n return super.calculateRecordSize()\n + (getPerceivedVehicles() != null ? getPerceivedVehicles().size() * 50L : 0); // each perceived vehicle will require around 50 Bytes\n }\n\n public static class Builder extends AbstractRecordBuilder<Builder, FcdRecord> {\n\n private List<VehicleObject> perceivedVehicles;\n\n public Builder(long timeStamp, GeoPoint position, String connectionId) {\n super(timeStamp, position, connectionId);\n }\n\n public Builder(FcdRecord record) {\n super(record);\n perceivedVehicles = record.perceivedVehicles;\n }\n\n public Builder withPerceivedVehicles(List<VehicleObject> perceivedVehicles) {\n this.perceivedVehicles = perceivedVehicles;\n return getThis();\n }\n\n @Override\n protected Builder getThis() {\n return this;\n }\n\n @Override\n protected FcdRecord internalBuild() {\n return new FcdRecord(timeStamp, position, connectionId, speed, offset, heading, perceivedVehicles);\n }\n }\n}" }, { "identifier": "FcdTraversal", "path": "src/main/java/com/dcaiti/mosaic/app/fxd/data/FcdTraversal.java", "snippet": "public class FcdTraversal extends FxdTraversal<FcdRecord, FcdTraversal> {\n public FcdTraversal(String connectionId, List<FcdRecord> traversal, FcdRecord previousRecord, FcdRecord followingRecord) {\n super(connectionId, traversal, previousRecord, followingRecord);\n }\n\n @Override\n public FcdTraversal copy() {\n return new FcdTraversal(connectionId, Lists.newArrayList(traversal), previousRecord, followingRecord);\n }\n}" }, { "identifier": "TseServerApp", "path": "src/main/java/com/dcaiti/mosaic/app/tse/TseServerApp.java", "snippet": "public class TseServerApp\n extends FxdReceiverApp<FcdRecord, FcdTraversal, FcdUpdateMessage, CTseServerApp, TseKernel> {\n\n /**\n * Storage field, allowing to persist TSE results as well as data exchange between processors.\n * Default value will be a {@link FcdDatabaseHelper}\n */\n private FcdDataStorage fcdDataStorage;\n\n public TseServerApp() {\n super(CTseServerApp.class);\n }\n\n @Override\n public void enableCellModule() {\n getOs().getCellModule().enable();\n }\n\n\n /**\n * Initializes the {@link TseKernel} by\n * <ul>\n * <li>validating that processors for minimal function are configured,</li>\n * <li> reading the scenario database for access to network specific data,</li>\n * <li>and setting up the {@link #fcdDataStorage} to persist TSE metrics.</li>\n * </ul>\n *\n * @param eventManager the {@link EventManager} to enable the kernel with event handling capabilities\n * @param config configuration for the server\n * @return the initialized {@link TseKernel}\n */\n @Override\n protected TseKernel initKernel(EventManager eventManager, CTseServerApp config) {\n addRequiredProcessors(config);\n Database networkDatabase = ScenarioDatabaseHelper.getNetworkDbFromFile(getOs());\n String databaseDirectory = config.databasePath == null ? getOs().getConfigurationPath().getPath() : getConfiguration().databasePath;\n String databaseFileName = getConfiguration().databaseFileName == null ? \"FcdData.sqlite\" : getConfiguration().databaseFileName;\n Path databasePath = Paths.get(databaseDirectory, databaseFileName);\n // set data storage to configured type else use default FcdDatabaseHelper\n fcdDataStorage = config.fcdDataStorage == null ? new FcdDatabaseHelper() : config.fcdDataStorage;\n fcdDataStorage.initialize(databasePath, networkDatabase, config.isPersistent, getLog());\n return new TseKernel(eventManager, getLog(), config, fcdDataStorage, networkDatabase);\n }\n\n private void addRequiredProcessors(CTseServerApp config) {\n if (config.traversalBasedProcessors == null) {\n config.traversalBasedProcessors = Lists.newArrayList(new SpatioTemporalProcessor());\n } else if (config.traversalBasedProcessors.stream().noneMatch(processor -> processor instanceof SpatioTemporalProcessor)) {\n config.traversalBasedProcessors.add(new SpatioTemporalProcessor());\n }\n if (config.timeBasedProcessors == null) {\n config.timeBasedProcessors = Lists.newArrayList(new ThresholdProcessor());\n } else if (config.timeBasedProcessors.stream().noneMatch(processor -> processor instanceof ThresholdProcessor)) {\n config.timeBasedProcessors.add(new ThresholdProcessor());\n }\n }\n\n @Override\n protected boolean instanceOfUpdate(V2xMessage message) {\n return message instanceof FcdUpdateMessage;\n }\n\n @Override\n protected FcdUpdateMessage castUpdate(V2xMessage message) {\n return (FcdUpdateMessage) message;\n }\n\n @Override\n public void onShutdown() {\n super.onShutdown();\n getLog().info(fcdDataStorage.getStatisticsString());\n fcdDataStorage.shutdown();\n }\n}" }, { "identifier": "DatabaseAccess", "path": "src/main/java/com/dcaiti/mosaic/app/tse/data/DatabaseAccess.java", "snippet": "public interface DatabaseAccess {\n /**\n * Method giving processors access to the {@link Database Network Database} and the {@link FcdDataStorage}.\n *\n * @param networkDatabase reference to the {@link Database Network Database}\n * @param fcdDatabaseHelper reference to the {@link FcdDataStorage}\n */\n void withDataStorage(Database networkDatabase, FcdDataStorage fcdDatabaseHelper);\n}" }, { "identifier": "FcdDataStorage", "path": "src/main/java/com/dcaiti/mosaic/app/tse/persistence/FcdDataStorage.java", "snippet": "@JsonAdapter(FcdDataStorageTypeAdapterFactory.class)\npublic interface FcdDataStorage {\n /**\n * Inits the DB connection and sets up tables and the cache.\n *\n * @param databasePath path to fcd database\n * @param networkDatabase the scenario database object\n * @param isPersistent flag indicating whether tables shall be cleared at startup\n * @param log to log errors while writing to/reading from {@link FcdDataStorage}\n */\n void initialize(Path databasePath, Database networkDatabase, boolean isPersistent, UnitLogger log);\n\n /**\n * Does all operations to shut down the DataStorage.\n */\n void shutdown();\n\n String getStatisticsString();\n\n void insertFcdRecords(String vehicleId, Collection<FcdRecord> records);\n\n void insertTraversalMetrics(String vehicleId, long timestamp, String connectionId, String nextConnection,\n double spatialMeanSpeed, double temporalMeanSpeed, double naiveMeanSpeed,\n float relativeMetric, long traversalTime);\n\n void updateTraversalMetrics(ArrayList<TraversalStatistics> traversals);\n\n void insertThresholds(Map<String, Double> temporal, Map<String, Double> spatial, long simulationTime);\n\n void insertSampledMeanSpeeds(IMetricsBuffer metricsBuffer);\n\n Pair<Double, Double> getThresholds(String connectionId);\n\n Map<String, List<Long>> getTraversalTimes();\n\n Map<String, ArrayList<Pair<Double, Double>>> getMeanSpeeds();\n\n ArrayList<TraversalStatistics> getTraversalMetrics();\n\n TraversalStatistics getClosestTraversalData(String connectionId, long timestamp);\n\n Map<String, TraversalStatistics> getAveragesForInterval(long timestamp, long interval);\n\n boolean gotThresholdFor(String connectionId);\n}" }, { "identifier": "FcdDatabaseHelper", "path": "src/main/java/com/dcaiti/mosaic/app/tse/persistence/FcdDatabaseHelper.java", "snippet": "public class FcdDatabaseHelper implements FcdDataStorage {\n // DB strings\n private static final String TABLE_RECORDS = \"fcd_records\";\n private static final String TABLE_TRAVERSAL_METRICS = \"traversal_metrics\";\n private static final String TABLE_THRESHOLDS = \"thresholds_for_connections\";\n private static final String TABLE_CONNECTIONS = \"connection_data\";\n private static final String COLUMN_NEXT_CONNECTION_ID = \"nextConnectionID\";\n protected static final String COLUMN_CONNECTION_ID = \"connectionID\";\n protected static final String COLUMN_TIME_STAMP = \"timeStamp\";\n private static final String COLUMN_TEMPORAL_MEAN_SPEED = \"temporalMeanSpeed\";\n private static final String COLUMN_SPATIAL_MEAN_SPEED = \"spatialMeanSpeed\";\n private static final String COLUMN_TIME_OF_INSERTION = \"timeOfInsertionUTC\";\n private static final String COLUMN_VEH_ID = \"vehID\";\n private static final String COLUMN_TRAVERSAL_TIME = \"traversalTime\";\n private static final String COLUMN_NAIVE_MEAN_SPEED = \"naiveMeanSpeed\";\n private static final String COLUMN_MAX_ALLOWED_SPEED = \"maxSpeed\";\n private static final String COLUMN_LENGTH_BY_NODES = \"length\";\n private static final String COLUMN_OFFSET = \"offset\";\n private static final String COLUMN_LATITUDE = \"latitude\";\n private static final String COLUMN_LONGITUDE = \"longitude\";\n private static final String COLUMN_SPEED = \"speed\";\n private static final String COLUMN_TEMPORAL_THRESHOLD = \"temporalThreshold\";\n private static final String COLUMN_SPATIAL_THRESHOLD = \"spatialThreshold\";\n private static final String COLUMN_RELATIVE_TRAFFIC_METRIC = \"relativeTrafficStatusMetric\";\n /**\n * Configurable parameter using the {@link CTseServerApp#fcdDataStorage}\n * type-based config. If this is set to {@code true} all sqlite transactions will be handled in-memory, which may lead to increased\n * RAM usage but could also gain performance improvements.\n * Note: if simulation crashes during execution, all data will be lost as the backup is executed in the {@link #shutdown()} method.\n */\n @Experimental\n public boolean inMemory = false;\n /**\n * The {@link Database Network Database}.\n */\n private Database networkDb;\n /**\n * Path of the FCD database.\n */\n private Path databasePath;\n /**\n * Caches the thresholds to not always load them from the database.\n */\n private final Map<String, Pair<Double, Double>> thresholdCache = new HashMap<>();\n /**\n * Logger for errors during writing to/reading from databases.\n */\n private UnitLogger logger;\n /**\n * needed to determine if a record is from this simulation, or a prior one, if running in persistent mode.\n */\n private long startTime;\n /**\n * Field for the {@link Connection Database connection} we keep this connection alive throughout the simulation to reduce overhead\n * through connect/close calls.\n */\n protected Connection connection;\n\n /**\n * Inits the DB connection and sets up tables and the cache.\n *\n * @param databasePath path to fcd database\n * @param networkDatabase the scenario database object\n * @param isPersistent flag indicating whether tables shall be cleared at startup\n * @param logger to log errors while writing to/reading from {@link FcdDataStorage}\n */\n @Override\n public void initialize(Path databasePath, Database networkDatabase, boolean isPersistent, UnitLogger logger) {\n this.databasePath = databasePath;\n this.startTime = System.currentTimeMillis() / 1000L;\n this.networkDb = networkDatabase;\n this.logger = logger;\n connection = getConnection();\n try {\n createTables(isPersistent);\n } catch (SQLException exception) {\n logErrorAndThrowRuntimeException(exception, \"TABLE CREATION\");\n throw new RuntimeException(\"Couldn't create database tables:\", exception);\n }\n initializeCache();\n copyConnectionsData(networkDatabase);\n\n }\n\n /**\n * Establish connection to DB.\n *\n * @return Connection to SQLiteDB\n */\n private Connection getConnection() {\n try {\n if (connection == null || connection.isClosed()) {\n String url = \"jdbc:sqlite:\";\n if (!inMemory) {\n url += databasePath;\n }\n connection = DriverManager.getConnection(url);\n }\n } catch (SQLException exception) {\n logErrorAndThrowRuntimeException(exception, \"CONNECT\");\n }\n return connection;\n }\n\n @Override\n public void shutdown() {\n String backupSql = \"BACKUP TO \" + databasePath.toAbsolutePath().normalize();\n if (inMemory) {\n try (Statement statement = connection.createStatement()) {\n connection.setAutoCommit(false);\n statement.executeUpdate(backupSql);\n connection.commit();\n connection.setAutoCommit(true);\n } catch (SQLException exception) {\n logErrorAndThrowRuntimeException(exception, \"WRITING IN-MEMORY DB\");\n }\n }\n try {\n if (connection != null && !connection.isClosed()) {\n connection.close();\n }\n } catch (SQLException exception) {\n logErrorAndThrowRuntimeException(exception, \"CLOSE\");\n }\n }\n\n /**\n * Creates database tables. Overwrites traversal {@link #TABLE_RECORDS}, {@link #TABLE_CONNECTIONS}, {@link #TABLE_TRAVERSAL_METRICS},\n * and {@link #TABLE_THRESHOLDS} if the database is set to be non-persistent.\n *\n * @param isPersistent flag indicating whether tables shall be cleared at startup\n */\n protected void createTables(boolean isPersistent) throws SQLException {\n String recordsSql =\n \"CREATE TABLE IF NOT EXISTS \" + TABLE_RECORDS + \" (\"\n + COLUMN_VEH_ID + \" TEXT NOT NULL, \"\n + COLUMN_TIME_STAMP + \" INTEGER NOT NULL, \"\n + COLUMN_LATITUDE + \" REAL NO NULL, \"\n + COLUMN_LONGITUDE + \" REAL NO NULL, \"\n + COLUMN_CONNECTION_ID + \" TEXT NOT NULL, \"\n + COLUMN_OFFSET + \" INTEGER NOT NULL, \"\n + COLUMN_SPEED + \" INTEGER NOT NULL, \"\n + \"PRIMARY KEY (\" + COLUMN_CONNECTION_ID + \", \" + COLUMN_TIME_STAMP + \", \" + COLUMN_VEH_ID + \")\"\n + \"); \"\n + \"CREATE INDEX timeStamp_index ON \" + TABLE_RECORDS + \" (\" + COLUMN_TIME_STAMP + \"); \"\n + \"CREATE INDEX connection_index ON \" + TABLE_RECORDS + \" (\" + COLUMN_CONNECTION_ID + \"); \";\n String traversalMetricsSql =\n \"CREATE TABLE IF NOT EXISTS \" + TABLE_TRAVERSAL_METRICS + \" (\"\n + COLUMN_VEH_ID + \" TEXT NOT NULL, \"\n + COLUMN_TIME_STAMP + \" INTEGER NOT NULL, \"\n + COLUMN_CONNECTION_ID + \" TEXT NOT NULL, \"\n + COLUMN_NEXT_CONNECTION_ID + \" TEXT, \"\n + COLUMN_TEMPORAL_MEAN_SPEED + \" INTEGER NOT NULL, \"\n + COLUMN_SPATIAL_MEAN_SPEED + \" INTEGER NOT NULL, \"\n + COLUMN_RELATIVE_TRAFFIC_METRIC + \" INTEGER, \"\n + COLUMN_TRAVERSAL_TIME + \" INTEGER NOT NULL,\"\n + COLUMN_NAIVE_MEAN_SPEED + \" INTEGER NOT NULL,\"\n + COLUMN_TIME_OF_INSERTION + \" DATETIME DEFAULT CURRENT_TIMESTAMP\"\n + \"); \"\n + \"CREATE INDEX timeStamp_index ON \" + TABLE_TRAVERSAL_METRICS + \" (\" + COLUMN_TIME_STAMP + \"); \"\n + \"CREATE INDEX connection_index ON \" + TABLE_TRAVERSAL_METRICS + \" (\" + COLUMN_CONNECTION_ID + \"); \"\n + \"CREATE INDEX insertion_index ON \" + TABLE_TRAVERSAL_METRICS + \" (\" + COLUMN_TIME_OF_INSERTION + \"); \";\n String thresholdsSql =\n \"CREATE TABLE IF NOT EXISTS \" + TABLE_THRESHOLDS + \" (\"\n + COLUMN_CONNECTION_ID + \" TEXT NOT NULL, \"\n + COLUMN_TEMPORAL_THRESHOLD + \" INTEGER NOT NULL, \"\n + COLUMN_SPATIAL_THRESHOLD + \" INTEGER NOT NULL,\"\n + COLUMN_TIME_STAMP + \" INTEGER NOT NULL,\"\n + COLUMN_TIME_OF_INSERTION + \" DATETIME DEFAULT CURRENT_TIMESTAMP\"\n + \");\"\n + \"CREATE INDEX connection_index ON \" + TABLE_THRESHOLDS + \" (\" + COLUMN_CONNECTION_ID + \"); \"\n + \"CREATE INDEX insertion_index ON \" + TABLE_THRESHOLDS + \" (\" + COLUMN_TIME_OF_INSERTION + \"); \";\n String connectionsTableSql =\n \"CREATE TABLE IF NOT EXISTS \" + TABLE_CONNECTIONS + \" (\"\n + COLUMN_CONNECTION_ID + \" TEXT NOT NULL, \"\n + COLUMN_MAX_ALLOWED_SPEED + \" INTEGER NOT NULL, \"\n + COLUMN_LENGTH_BY_NODES + \" INTEGER NOT NULL\"\n + \"); \"\n + \"DELETE FROM \" + TABLE_CONNECTIONS + \"; \"\n + \"CREATE INDEX connection_index ON \" + TABLE_CONNECTIONS + \" (\" + COLUMN_CONNECTION_ID + \"); \";\n if (inMemory) { // read from existing backup if a database exists\n String restoreDatabaseSql = \"RESTORE FROM \" + databasePath;\n if (Files.exists(databasePath.toAbsolutePath().normalize())) {\n try (Statement statement = connection.createStatement()) {\n statement.executeUpdate(restoreDatabaseSql);\n }\n }\n }\n if (!isPersistent) {\n try (Statement statement = connection.createStatement()) {\n statement.execute(\"DROP TABLE IF EXISTS \" + TABLE_RECORDS + \" ;\");\n statement.execute(\"DROP TABLE IF EXISTS \" + TABLE_CONNECTIONS + \";\");\n statement.execute(\"DROP TABLE IF EXISTS \" + TABLE_TRAVERSAL_METRICS + \";\");\n statement.execute(\"DROP TABLE IF EXISTS \" + TABLE_THRESHOLDS + \";\");\n }\n }\n try (Statement statement = connection.createStatement()) {\n statement.execute(recordsSql);\n statement.execute(traversalMetricsSql);\n statement.execute(thresholdsSql);\n statement.execute(connectionsTableSql);\n }\n }\n\n /**\n * Inserts raw unprocessed fcd records that were received into the database.\n *\n * @param vehicleId id of the vehicle\n * @param records records to be inserted\n */\n @Override\n public void insertFcdRecords(String vehicleId, Collection<FcdRecord> records) {\n String sqlRecordInsert = \"REPLACE INTO \" + TABLE_RECORDS + \"(\"\n + COLUMN_VEH_ID + \",\"\n + COLUMN_TIME_STAMP + \",\"\n + COLUMN_LATITUDE + \",\"\n + COLUMN_LONGITUDE + \",\"\n + COLUMN_CONNECTION_ID + \",\"\n + COLUMN_OFFSET + \",\"\n + COLUMN_SPEED + \")\"\n + \" VALUES(?,?,?,?,?,?,?)\";\n\n try (PreparedStatement statement = connection.prepareStatement(sqlRecordInsert)) {\n connection.setAutoCommit(false);\n int i = 0;\n for (FcdRecord record : records) {\n statement.setString(1, vehicleId);\n statement.setLong(2, record.getTimeStamp());\n statement.setDouble(3, record.getPosition().getLatitude());\n statement.setDouble(4, record.getPosition().getLongitude());\n statement.setString(5, record.getConnectionId());\n statement.setDouble(6, record.getOffset());\n statement.setDouble(7, record.getSpeed());\n statement.addBatch();\n i++;\n if (i % 1000 == 0 || i == records.size()) {\n statement.executeBatch();\n connection.commit();\n }\n }\n statement.executeBatch();\n connection.commit();\n connection.setAutoCommit(true);\n } catch (SQLException exception) {\n logErrorAndThrowRuntimeException(exception, \"RECORD INSERTION\");\n }\n }\n\n /**\n * Insert the given metrics as a traversal in the database.\n *\n * @param vehicleId id of the Veh\n * @param timestamp timestamp of last record of this traversal\n * @param connectionId id of the connection\n * @param nextConnection id of the connection onto which the veh left this one\n * @param spatialMeanSpeed mean speed over equidistant points on the connection\n * @param temporalMeanSpeed mean speed over the hole traversal as length/traversal time\n * @param naiveMeanSpeed averaged speeds of the records\n * @param relativeMetric relative traffic metric as proposed by Yoon et. al.\n * @param traversalTime time it took to traverse this connection\n */\n @Override\n public void insertTraversalMetrics(String vehicleId, long timestamp, String connectionId,\n String nextConnection, double spatialMeanSpeed, double temporalMeanSpeed,\n double naiveMeanSpeed, float relativeMetric, long traversalTime) {\n String sqlSubMetricInsert = \"INSERT INTO \" + TABLE_TRAVERSAL_METRICS + \"(\"\n + COLUMN_VEH_ID + \",\"\n + COLUMN_TIME_STAMP + \",\"\n + COLUMN_CONNECTION_ID + \",\"\n + COLUMN_NEXT_CONNECTION_ID + \",\"\n + COLUMN_SPATIAL_MEAN_SPEED + \",\"\n + COLUMN_TEMPORAL_MEAN_SPEED + \",\"\n + COLUMN_RELATIVE_TRAFFIC_METRIC + \",\"\n + COLUMN_TRAVERSAL_TIME + \", \"\n + COLUMN_NAIVE_MEAN_SPEED + \")\"\n + \" VALUES(?,?,?,?,?,?,?,?,?)\";\n try (PreparedStatement statement = connection.prepareStatement(sqlSubMetricInsert)) {\n statement.setString(1, vehicleId);\n statement.setLong(2, timestamp);\n statement.setString(3, connectionId);\n statement.setString(4, nextConnection);\n statement.setDouble(5, spatialMeanSpeed);\n statement.setDouble(6, temporalMeanSpeed);\n statement.setFloat(7, relativeMetric);\n statement.setLong(8, traversalTime);\n statement.setDouble(9, naiveMeanSpeed);\n statement.execute();\n } catch (SQLException exception) {\n logErrorAndThrowRuntimeException(exception, \"TRAVERSAL METRIC INSERTION\");\n }\n }\n\n /**\n * Updates traversal metrics with relative traffic metric.\n *\n * @param traversals a list of FcdTraversals with RTSMs to update them in the DB\n */\n @Override\n public void updateTraversalMetrics(ArrayList<TraversalStatistics> traversals) {\n String thresholdInsertSql = \"UPDATE \" + TABLE_TRAVERSAL_METRICS + \" SET \"\n + COLUMN_RELATIVE_TRAFFIC_METRIC + \" = ?\"\n + \" WHERE ROWID = ?\";\n try (PreparedStatement statement = connection.prepareStatement(thresholdInsertSql)) {\n connection.setAutoCommit(false);\n int i = 0;\n for (TraversalStatistics traversal : traversals) {\n if (traversal.getRelativeTrafficStatusMetric() == null) {\n continue;\n }\n statement.setFloat(1, traversal.getRelativeTrafficStatusMetric());\n statement.setInt(2, traversal.getTraversalId());\n statement.addBatch();\n i++;\n if (i % 1000 == 0 || i == traversals.size()) {\n statement.executeBatch();\n connection.commit();\n }\n }\n statement.executeBatch();\n connection.commit();\n connection.setAutoCommit(true);\n } catch (SQLException exception) {\n logErrorAndThrowRuntimeException(exception, \"TRAVERSAL METRIC UPDATE\");\n }\n }\n\n /**\n * inserts thresholds into THRESHOLDS_TABLE in DB and update {@code thresholdsCache}.\n *\n * @param temporalThresholds mapping of connectionID to a temporal threshold\n * @param spatialThresholds mapping of connectionID to a spatial threshold\n * @param simulationTime Time at which the threshold computation started. Needed for further analysis of the resulting data.\n */\n @Override\n public void insertThresholds(Map<String, Double> temporalThresholds, Map<String, Double> spatialThresholds, long simulationTime) {\n String thresholdInsertSql = \"INSERT INTO \" + TABLE_THRESHOLDS + \"(\"\n + COLUMN_CONNECTION_ID + \",\"\n + COLUMN_TEMPORAL_THRESHOLD + \",\"\n + COLUMN_SPATIAL_THRESHOLD + \",\"\n + COLUMN_TIME_STAMP + \")\"\n + \" VALUES(?,?,?,?)\";\n try (PreparedStatement statement = connection.prepareStatement(thresholdInsertSql)) {\n connection.setAutoCommit(false);\n int i = 0;\n for (Map.Entry<String, Double> temporalThreshold : temporalThresholds.entrySet()) {\n statement.setString(1, temporalThreshold.getKey());\n statement.setDouble(2, temporalThreshold.getValue());\n statement.setDouble(3, spatialThresholds.get(temporalThreshold.getKey()));\n statement.setLong(4, simulationTime);\n statement.addBatch();\n i++;\n if (i % 1000 == 0 || i == temporalThresholds.entrySet().size()) {\n statement.executeBatch();\n connection.commit();\n }\n }\n statement.executeBatch();\n connection.commit();\n connection.setAutoCommit(true);\n } catch (SQLException exception) {\n logErrorAndThrowRuntimeException(exception, \"THRESHOLD INSERTION\");\n }\n // cache thresholds in the threshold cache\n temporalThresholds.forEach((conn, tempT) -> thresholdCache.put(conn, new Pair<>(tempT, spatialThresholds.get(conn))));\n }\n\n @Override\n public void insertSampledMeanSpeeds(IMetricsBuffer metricsBuffer) {\n // part of closed source\n }\n\n /**\n * Used to copy information about the connections from mosaic DB to the FcdDatabase.\n * This Data is needed for evaluation of the results.\n *\n * @param mosaicDatabase The DB containing data about the road network.\n */\n private void copyConnectionsData(Database mosaicDatabase) {\n String conDataSql = \"INSERT OR IGNORE INTO \" + TABLE_CONNECTIONS + \"(\"\n + COLUMN_CONNECTION_ID + \",\"\n + COLUMN_MAX_ALLOWED_SPEED + \",\"\n + COLUMN_LENGTH_BY_NODES + \")\"\n + \" VALUES(?,?,?)\";\n try (PreparedStatement statement = connection.prepareStatement(conDataSql)) {\n connection.setAutoCommit(false);\n Collection<org.eclipse.mosaic.lib.database.road.Connection> connections = mosaicDatabase.getConnections();\n int i = 0;\n for (org.eclipse.mosaic.lib.database.road.Connection roadConnection : connections) {\n statement.setString(1, roadConnection.getId());\n statement.setDouble(2, roadConnection.getMaxSpeedInMs());\n statement.setDouble(3, ScenarioDatabaseHelper.calcLengthByNodes(roadConnection));\n statement.addBatch();\n i++;\n if (i % 1000 == 0 || i == connections.size()) {\n statement.executeBatch();\n connection.commit();\n }\n }\n statement.executeBatch();\n connection.commit();\n connection.setAutoCommit(true);\n } catch (SQLException exception) {\n logErrorAndThrowRuntimeException(exception, \"SCENARIO DB COPYING\");\n }\n }\n\n /**\n * Returns most recent thresholds for connection from cache or DB, if not in cache.\n *\n * @param connectionId for which thresholds shall be returned\n * @return a {@link Pair} of the temporal and spatial threshold\n */\n public Pair<Double, Double> getThresholds(String connectionId) {\n if (thresholdCache.containsKey(connectionId)) {\n return thresholdCache.get(connectionId);\n }\n String thresholdSql = \"SELECT \"\n + COLUMN_TEMPORAL_THRESHOLD + \", \" + COLUMN_SPATIAL_THRESHOLD\n + \" FROM \" + TABLE_THRESHOLDS\n + \" WHERE \" + COLUMN_CONNECTION_ID + \" = ? \"\n + \" ORDER BY \" + COLUMN_TIME_OF_INSERTION + \" DESC \"\n + \"LIMIT 1;\";\n\n try (PreparedStatement statement = connection.prepareStatement(thresholdSql)) {\n statement.setString(1, connectionId);\n try (ResultSet rs = statement.executeQuery()) {\n if (!rs.next()) {\n return null;\n }\n Pair<Double, Double> thresholdPair =\n new Pair<>(rs.getDouble(COLUMN_TEMPORAL_THRESHOLD), rs.getDouble(COLUMN_SPATIAL_THRESHOLD));\n thresholdCache.put(connectionId, thresholdPair);\n return thresholdPair;\n }\n } catch (SQLException exception) {\n logErrorAndThrowRuntimeException(exception, \"THRESHOLD RETRIEVAL\");\n return null;\n }\n }\n\n /**\n * retrieves all traversal times inserted since the start of this simulation as a mapping of connectionID to a list of traversalTimes.\n *\n * @return mapping of connectionID to List of traversalTimes\n */\n public Map<String, List<Long>> getTraversalTimes() {\n String traversalsSql = \"SELECT \"\n + COLUMN_CONNECTION_ID + \", \" + COLUMN_TRAVERSAL_TIME\n + \" FROM \" + TABLE_TRAVERSAL_METRICS\n + \" ORDER BY \" + COLUMN_CONNECTION_ID\n + \";\";\n try (PreparedStatement statement = connection.prepareStatement(traversalsSql)) {\n try (ResultSet rs = statement.executeQuery()) {\n Map<String, List<Long>> timeResults = new HashMap<>();\n while (rs.next()) {\n timeResults.putIfAbsent(rs.getString(COLUMN_CONNECTION_ID), new ArrayList<>());\n timeResults.get(rs.getString(COLUMN_CONNECTION_ID)).add(rs.getLong(COLUMN_TRAVERSAL_TIME));\n }\n return timeResults;\n }\n } catch (SQLException exception) {\n logErrorAndThrowRuntimeException(exception, \"TRAVERSAL TIME RETRIEVAL\");\n return null;\n }\n }\n\n\n /**\n * Returns all spatio-temporal mean speeds for each connection from the DB.\n *\n * @return map of connection ids to a list of {@link Pair pairs} of temporal and spatial mean speeds\n */\n @Override\n public Map<String, ArrayList<Pair<Double, Double>>> getMeanSpeeds() {\n String percentRanksSql = \"SELECT \"\n + COLUMN_CONNECTION_ID + \", \" + COLUMN_TEMPORAL_MEAN_SPEED + \", \" + COLUMN_SPATIAL_MEAN_SPEED\n + \" FROM \" + TABLE_TRAVERSAL_METRICS\n + \" ORDER BY \" + COLUMN_CONNECTION_ID\n + \";\";\n try (PreparedStatement statement = connection.prepareStatement(percentRanksSql)) {\n try (ResultSet rs = statement.executeQuery()) {\n Map<String, ArrayList<Pair<Double, Double>>> tempThreshResults = new HashMap<>();\n while (rs.next()) {\n tempThreshResults.putIfAbsent(rs.getString(COLUMN_CONNECTION_ID), new ArrayList<>());\n tempThreshResults.get(rs.getString(COLUMN_CONNECTION_ID))\n .add(new Pair<>(rs.getDouble(COLUMN_TEMPORAL_MEAN_SPEED), rs.getDouble(COLUMN_SPATIAL_MEAN_SPEED)));\n }\n return tempThreshResults;\n }\n } catch (SQLException exception) {\n logErrorAndThrowRuntimeException(exception, \"MEAN SPEED RETRIEVAL\");\n return null;\n }\n }\n\n /**\n * Retrieves all traversal metrics from the database that were added during this simulation.\n *\n * @return an ArrayList of FcdTraversals\n */\n @Override\n public ArrayList<TraversalStatistics> getTraversalMetrics() {\n String traversalMetricsSql = \"SELECT \"\n + COLUMN_CONNECTION_ID + \", ROWID AS travID , \" + COLUMN_TIME_STAMP\n + \", \" + COLUMN_TEMPORAL_MEAN_SPEED + \", \" + COLUMN_SPATIAL_MEAN_SPEED\n + \" FROM \" + TABLE_TRAVERSAL_METRICS\n + \" WHERE \" + COLUMN_TIME_OF_INSERTION + \" >= DATETIME(\" + startTime + \", 'unixepoch') \"\n + \" ORDER BY \" + COLUMN_CONNECTION_ID\n + \";\";\n try (PreparedStatement statement = connection.prepareStatement(traversalMetricsSql)) {\n try (ResultSet rs = statement.executeQuery()) {\n ArrayList<TraversalStatistics> results = new ArrayList<>();\n while (rs.next()) {\n results.add(\n new TraversalStatistics(\n rs.getString(COLUMN_CONNECTION_ID), rs.getInt(\"travID\"),\n rs.getLong(COLUMN_TIME_STAMP), rs.getDouble(COLUMN_TEMPORAL_MEAN_SPEED),\n rs.getDouble(COLUMN_SPATIAL_MEAN_SPEED)\n )\n );\n }\n return results;\n }\n } catch (SQLException exception) {\n logErrorAndThrowRuntimeException(exception, \"TRAVERSAL METRIC RETRIEVAL\");\n return null;\n }\n }\n\n /**\n * Retrieves the closest traversal data for a given connection and time.\n *\n * @param connectionId of connection\n * @param timestamp to get the closest data for\n * @return an FcdTraversal with the retrieved data\n */\n @Override\n public TraversalStatistics getClosestTraversalData(String connectionId, long timestamp) {\n String traversalDataSql = \"WITH connTravs AS (\"\n + \"SELECT ROWID AS travID, * FROM \" + TABLE_TRAVERSAL_METRICS\n + \" WHERE \" + COLUMN_CONNECTION_ID + \" = '?' \"\n + \")\"\n + \"SELECT \" + COLUMN_CONNECTION_ID + \", travID, \" + COLUMN_TIME_STAMP + \", \" + COLUMN_TEMPORAL_MEAN_SPEED\n + \", \" + COLUMN_SPATIAL_MEAN_SPEED + \", \" + COLUMN_RELATIVE_TRAFFIC_METRIC\n + \" FROM (\"\n + \"SELECT max(\" + COLUMN_TIME_STAMP + \") AS ts, * FROM connTravs WHERE \" + COLUMN_TIME_STAMP + \" <= ?\"\n + \" UNION \"\n + \"SELECT min(\" + COLUMN_TIME_STAMP + \") AS ts, * FROM connTravs WHERE \" + COLUMN_TIME_STAMP + \" <= ?\"\n + \")\"\n + \"WHERE \" + COLUMN_TIME_STAMP + \" is not null \"\n + \"ORDER BY abs(?-ts) LIMIT 1;\";\n try (PreparedStatement statement = connection.prepareStatement(traversalDataSql)) {\n statement.setString(1, connectionId);\n statement.setLong(2, timestamp);\n statement.setLong(3, timestamp);\n statement.setLong(4, timestamp);\n try (ResultSet rs = statement.executeQuery(traversalDataSql)) {\n if (rs.next()) {\n return new TraversalStatistics(\n rs.getString(COLUMN_CONNECTION_ID), rs.getInt(\"travID\"),\n rs.getLong(COLUMN_TIME_STAMP), rs.getDouble(COLUMN_TEMPORAL_MEAN_SPEED),\n rs.getDouble(COLUMN_SPATIAL_MEAN_SPEED), rs.getFloat(COLUMN_RELATIVE_TRAFFIC_METRIC),\n getSpeedPerformanceIndexFor(rs.getDouble(COLUMN_TEMPORAL_MEAN_SPEED), rs.getString(COLUMN_CONNECTION_ID))\n );\n } else {\n return null;\n }\n }\n } catch (SQLException exception) {\n logErrorAndThrowRuntimeException(exception, \"CONNECTION TRAVERSAL DATA RETRIEVAL\");\n return null;\n }\n }\n\n /**\n * Gets a map of connection ids to FcdTraversals containing the AVGs over the given interval.\n *\n * @param timestamp start of the interval\n * @param interval interval length\n * @return mapping of connection IDs to FcdTraversal\n */\n @Override\n public Map<String, TraversalStatistics> getAveragesForInterval(long timestamp, long interval) throws RuntimeException {\n String avgDataSql = \"select \" + COLUMN_CONNECTION_ID + \", \"\n + \"count(\" + COLUMN_CONNECTION_ID + \") as samples , \"\n + \"avg(\" + COLUMN_TEMPORAL_MEAN_SPEED + \") as temporalMS_avg, \"\n + \"avg(\" + COLUMN_SPATIAL_MEAN_SPEED + \") as spatialMS_avg, \"\n + \"avg(\" + COLUMN_NAIVE_MEAN_SPEED + \") as naiveMS_avg, \"\n + \"avg(\" + COLUMN_TRAVERSAL_TIME + \") as travTime_avg, \"\n + \"avg(\" + COLUMN_RELATIVE_TRAFFIC_METRIC + \") as rtsm_avg \"\n + \"from \" + TABLE_TRAVERSAL_METRICS + \" \"\n + \"where \"\n + COLUMN_TIME_STAMP + \" > \" + timestamp + \" AND \" + COLUMN_TIME_STAMP + \" < \" + (timestamp + interval) + \" \"\n + \"group by \" + COLUMN_CONNECTION_ID + \";\";\n try (PreparedStatement statement = connection.prepareStatement(avgDataSql)) {\n try (ResultSet rs = statement.executeQuery()) {\n Map<String, TraversalStatistics> results = new HashMap<>();\n while (rs.next()) {\n TraversalStatistics traversalStatistics = new TraversalStatistics(\n rs.getString(COLUMN_CONNECTION_ID),\n timestamp,\n rs.getInt(\"samples\"),\n rs.getDouble(\"temporalMS_avg\"),\n rs.getDouble(\"spatialMS_avg\"),\n rs.getDouble(\"naiveMS_avg\"),\n rs.getFloat(\"rtsm_avg\"),\n getSpeedPerformanceIndexFor(rs.getDouble(\"temporalMS_avg\"), rs.getString(COLUMN_CONNECTION_ID)));\n results.putIfAbsent(traversalStatistics.getConnectionId(), traversalStatistics);\n }\n return results;\n }\n } catch (SQLException exception) {\n logErrorAndThrowRuntimeException(exception, \"STATISTICS COMPUTATION\");\n return null;\n }\n }\n\n /**\n * Initializes the cache for the thresholds with data from the database file.\n */\n private void initializeCache() {\n String thresholdSql = \"SELECT \"\n + COLUMN_CONNECTION_ID + \", \"\n + COLUMN_TEMPORAL_THRESHOLD + \", \"\n + COLUMN_SPATIAL_THRESHOLD\n + \" FROM \"\n + TABLE_THRESHOLDS\n + \" GROUP BY \" + COLUMN_CONNECTION_ID\n + \" HAVING \"\n + \"MAX(\" + COLUMN_TIME_OF_INSERTION + \") = \" + COLUMN_TIME_OF_INSERTION + \";\";\n try (PreparedStatement statement = connection.prepareStatement(thresholdSql)) {\n try (ResultSet rs = statement.executeQuery()) {\n while (rs.next()) {\n thresholdCache.put(\n rs.getString(COLUMN_CONNECTION_ID),\n new Pair<>(rs.getDouble(COLUMN_TEMPORAL_THRESHOLD), rs.getDouble(COLUMN_SPATIAL_THRESHOLD))\n );\n }\n }\n } catch (SQLException exception) {\n logErrorAndThrowRuntimeException(exception, \"CACHE INITIALIZATION\");\n }\n }\n\n /**\n * Computes the Speed Performance Index as speed over max allowed speed on the connection.\n *\n * @param speed for which the index will be computed\n * @param connectionId ID of the connection\n * @return the Speed Performance Index as a value between 0 and 1\n */\n private Double getSpeedPerformanceIndexFor(Double speed, String connectionId) {\n return speed / networkDb.getConnection(connectionId).getMaxSpeedInMs();\n }\n\n /**\n * Checks if there is thresholds data for the current connection in the cache.\n *\n * @param connectionId for which to check\n * @return true if present, else false\n */\n @Override\n public boolean gotThresholdFor(String connectionId) {\n return thresholdCache.containsKey(connectionId);\n }\n\n @Override\n public String getStatisticsString() {\n String statisticsString = \"Statistics for FCD Database:\";\n statisticsString += System.lineSeparator() + \"Record Amount: \" + getRowAmount(TABLE_RECORDS);\n statisticsString += System.lineSeparator() + \"Traversal Amount: \" + getRowAmount(TABLE_TRAVERSAL_METRICS);\n statisticsString += System.lineSeparator() + \"Threshold Amount: \" + getRowAmount(TABLE_THRESHOLDS);\n statisticsString += System.lineSeparator() + \"Connection Amount: \" + getRowAmount(TABLE_CONNECTIONS);\n return statisticsString;\n }\n\n protected int getRowAmount(String table) {\n return getRowAmount(table, \"\");\n }\n\n protected int getRowAmount(String table, String condition) throws RuntimeException {\n String rowAmountSql = \"SELECT COUNT(*) FROM \" + table + \" \" + condition + \";\";\n int rowAmount = 0;\n try (PreparedStatement statement = connection.prepareStatement(rowAmountSql)) {\n try (ResultSet rs = statement.executeQuery()) {\n rowAmount = rs.getInt(1);\n }\n } catch (SQLException exception) {\n logErrorAndThrowRuntimeException(exception, \"ROW COUNT\");\n }\n return rowAmount;\n }\n\n protected void logErrorAndThrowRuntimeException(Exception exception, String reason) throws RuntimeException {\n if (logger != null) {\n logger.error(\"FCD Database Error during {}: {}\", reason, exception.getMessage());\n }\n throw new RuntimeException(exception);\n }\n}" }, { "identifier": "ScenarioDatabaseHelper", "path": "src/main/java/com/dcaiti/mosaic/app/tse/persistence/ScenarioDatabaseHelper.java", "snippet": "public final class ScenarioDatabaseHelper {\n\n /**\n * Creates a Database object from the Mosaic DB file.\n *\n * @param os operating system\n * @return The Mosaic Database.\n */\n public static Database getNetworkDbFromFile(OperatingSystem os) {\n if (SimulationKernel.SimulationKernel.getCentralNavigationComponent().getRouting() instanceof DatabaseRouting) {\n return ((DatabaseRouting) SimulationKernel.SimulationKernel.getCentralNavigationComponent().getRouting()).getScenarioDatabase();\n }\n File[] dbFiles = os.getConfigurationPath().listFiles((f, n) -> n.endsWith(\".db\") || n.endsWith(\".sqlite\"));\n if (dbFiles != null && dbFiles.length > 0) {\n return Database.loadFromFile(dbFiles[0]);\n }\n throw new RuntimeException(\"Cant find network database. Searching in \" + os.getConfigurationPath().getAbsolutePath());\n }\n\n\n /**\n * Calculates the length of a {@link Connection} by adding up the distance between its {@link Node Nodes}.\n * This is required as the length stored in DB is not always accurate.\n *\n * @param connection for which the length needs to be calculated\n * @return length of connection\n */\n public static double calcLengthByNodes(Connection connection) {\n List<Node> nodes = connection.getNodes();\n double length = 0.0;\n Node prev = null;\n for (Node curr : nodes) {\n if (prev != null) {\n length += prev.getPosition().distanceTo(curr.getPosition());\n }\n prev = curr;\n }\n return length;\n }\n\n}" } ]
import com.dcaiti.mosaic.app.fxd.data.FcdRecord; import com.dcaiti.mosaic.app.fxd.data.FcdTraversal; import com.dcaiti.mosaic.app.tse.TseServerApp; import com.dcaiti.mosaic.app.tse.data.DatabaseAccess; import com.dcaiti.mosaic.app.tse.persistence.FcdDataStorage; import com.dcaiti.mosaic.app.tse.persistence.FcdDatabaseHelper; import com.dcaiti.mosaic.app.tse.persistence.ScenarioDatabaseHelper; import org.eclipse.mosaic.fed.application.ambassador.util.UnitLogger; import org.eclipse.mosaic.lib.database.Database; import org.eclipse.mosaic.lib.util.gson.UnitFieldAdapter; import org.eclipse.mosaic.rti.TIME; import com.google.common.collect.Iterables; import com.google.gson.annotations.JsonAdapter; import org.apache.commons.math3.analysis.interpolation.LinearInterpolator; import org.apache.commons.math3.analysis.polynomials.PolynomialSplineFunction; import org.apache.commons.math3.exception.OutOfRangeException; import java.util.ArrayList; import java.util.LinkedList; import java.util.List;
10,470
/* * Copyright (c) 2021 Fraunhofer FOKUS and others. All rights reserved. * * See the NOTICE file(s) distributed with this work for additional * information regarding copyright ownership. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 * * Contact: [email protected] */ package com.dcaiti.mosaic.app.tse.processors; /** * Processes new FCD data. Holds methods to compute base-metrics and handles the record-buffer-queue for each veh. * It mainly handles computing the spatial and temporal mean speeds, once a veh leaves a connection. * This Data needs to be preprocessed, as it is the base from which the thresholds are derived. * * @see FcdDatabaseHelper * @see TseServerApp */ public class SpatioTemporalProcessor implements TraversalBasedProcessor<FcdRecord, FcdTraversal>, DatabaseAccess { private final static int CONNECTION_LENGTH_THRESHOLD = 5; /** * Each connection will be dissected into parts of this length and * the spatial mean speed will be averaged over measurements on these points. [m] */ @JsonAdapter(UnitFieldAdapter.DistanceMeters.class) public double spatialMeanSpeedChunkSize = 15; private UnitLogger logger; private Database networkDatabase; /** * needed to store and retrieve any data from the FcdDatabase. */
/* * Copyright (c) 2021 Fraunhofer FOKUS and others. All rights reserved. * * See the NOTICE file(s) distributed with this work for additional * information regarding copyright ownership. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 * * Contact: [email protected] */ package com.dcaiti.mosaic.app.tse.processors; /** * Processes new FCD data. Holds methods to compute base-metrics and handles the record-buffer-queue for each veh. * It mainly handles computing the spatial and temporal mean speeds, once a veh leaves a connection. * This Data needs to be preprocessed, as it is the base from which the thresholds are derived. * * @see FcdDatabaseHelper * @see TseServerApp */ public class SpatioTemporalProcessor implements TraversalBasedProcessor<FcdRecord, FcdTraversal>, DatabaseAccess { private final static int CONNECTION_LENGTH_THRESHOLD = 5; /** * Each connection will be dissected into parts of this length and * the spatial mean speed will be averaged over measurements on these points. [m] */ @JsonAdapter(UnitFieldAdapter.DistanceMeters.class) public double spatialMeanSpeedChunkSize = 15; private UnitLogger logger; private Database networkDatabase; /** * needed to store and retrieve any data from the FcdDatabase. */
private FcdDataStorage fcdDataStorage;
4
2023-10-23 16:39:40+00:00
12k
Primogem-Craft-Development/Primogem-Craft-Fabric
src/main/java/com/primogemstudio/primogemcraft/items/PrimogemCraftItems.java
[ { "identifier": "PrimogemCraftMobEffects", "path": "src/main/java/com/primogemstudio/primogemcraft/effects/PrimogemCraftMobEffects.java", "snippet": "public class PrimogemCraftMobEffects {\n public static final AbnormalDiseaseMobEffect ABNORMAL_DISEASE = register(\"abnormal_disease\", new AbnormalDiseaseMobEffect());\n public static final PastMobEffect PAST = register(\"past\", new PastMobEffect());\n public static final AmulateMobEffect AMULATE = register(\"amulate\", new AmulateMobEffect());\n public static final AThousandNightsDawnsongMobEffect DAWNSONG = register(\"a_thousand_nights_dawnsong\", new AThousandNightsDawnsongMobEffect());\n public static final AThousandNightsDawnsongCooldownMobEffect DAWNSONG_COOLDOWN = register(\"a_thousand_nights_dawnsong_cooldown\", new AThousandNightsDawnsongCooldownMobEffect());\n public static final FlyingMobEffect FLYING = register(\"flying\", new FlyingMobEffect());\n public static final BurnMobEffect BURN = register(\"burn\", new BurnMobEffect());\n public static void init() {\n }\n\n public static <T extends MobEffect> T register(String id, T effect) {\n return Registry.register(BuiltInRegistries.MOB_EFFECT, new ResourceLocation(MOD_ID, id), effect);\n }\n}" }, { "identifier": "SocietyTicketItem", "path": "src/main/java/com/primogemstudio/primogemcraft/items/instances/curios/SocietyTicketItem.java", "snippet": "public class SocietyTicketItem extends Item {\n public SocietyTicketItem() {\n super(new Item.Properties().stacksTo(1).fireResistant().rarity(Rarity.COMMON));\n }\n\n @Override\n public void appendHoverText(ItemStack itemstack, Level world, List<Component> list, TooltipFlag flag) {\n list.add(Component.translatable(\"tooltip.primogemcraft.society_ticket.line1\"));\n list.add(Component.translatable(\"tooltip.primogemcraft.society_ticket.line2\"));\n }\n}" }, { "identifier": "SmithingTemplateElement1Item", "path": "src/main/java/com/primogemstudio/primogemcraft/items/instances/templates/SmithingTemplateElement1Item.java", "snippet": "public class SmithingTemplateElement1Item extends Item {\n public SmithingTemplateElement1Item() {\n super(new Item.Properties().stacksTo(64).fireResistant().rarity(Rarity.COMMON));\n }\n\n @Override\n public void appendHoverText(ItemStack itemstack, Level world, List<Component> list, TooltipFlag flag) {\n super.appendHoverText(itemstack, world, list, flag);\n list.add(Component.translatable(\"tooltip.primogemcraft.smithing_template_element1.line1\"));\n list.add(Component.translatable(\"tooltip.primogemcraft.smithing_template_element1.line2\"));\n list.add(Component.translatable(\"tooltip.primogemcraft.smithing_template_element1.line3\"));\n list.add(Component.translatable(\"tooltip.primogemcraft.smithing_template_element1.line4\"));\n list.add(Component.translatable(\"tooltip.primogemcraft.smithing_template_element1.line5\"));\n list.add(Component.translatable(\"tooltip.primogemcraft.smithing_template_element1.line6\"));\n }\n}" }, { "identifier": "SmithingTemplateElement2Item", "path": "src/main/java/com/primogemstudio/primogemcraft/items/instances/templates/SmithingTemplateElement2Item.java", "snippet": "public class SmithingTemplateElement2Item extends Item {\n public SmithingTemplateElement2Item() {\n super(new Item.Properties().durability(2).fireResistant().rarity(Rarity.COMMON));\n }\n\n @Override\n public boolean hasCraftingRemainingItem() {\n return true;\n }\n\n @Override\n public void appendHoverText(ItemStack itemstack, Level world, List<Component> list, TooltipFlag flag) {\n super.appendHoverText(itemstack, world, list, flag);\n list.add(Component.translatable(\"tooltip.primogemcraft.smithing_template_element2.line1\"));\n list.add(Component.translatable(\"tooltip.primogemcraft.smithing_template_element2.line2\"));\n list.add(Component.translatable(\"tooltip.primogemcraft.smithing_template_element2.line3\"));\n list.add(Component.translatable(\"tooltip.primogemcraft.smithing_template_element2.line4\"));\n list.add(Component.translatable(\"tooltip.primogemcraft.smithing_template_element2.line5\"));\n list.add(Component.translatable(\"tooltip.primogemcraft.smithing_template_element2.line6\"));\n }\n}" }, { "identifier": "SmithingTemplateMoraItem", "path": "src/main/java/com/primogemstudio/primogemcraft/items/instances/templates/SmithingTemplateMoraItem.java", "snippet": "public class SmithingTemplateMoraItem extends Item {\n public SmithingTemplateMoraItem() {\n super(new Item.Properties().stacksTo(64).rarity(Rarity.COMMON));\n }\n\n @Override\n public void appendHoverText(ItemStack itemstack, Level world, List<Component> list, TooltipFlag flag) {\n list.add(Component.translatable(\"tooltip.primogemcraft.smithing_template_mora.line1\"));\n list.add(Component.translatable(\"tooltip.primogemcraft.smithing_template_mora.line2\"));\n list.add(Component.translatable(\"tooltip.primogemcraft.smithing_template_mora.line3\"));\n list.add(Component.translatable(\"tooltip.primogemcraft.smithing_template_mora.line4\"));\n list.add(Component.translatable(\"tooltip.primogemcraft.smithing_template_mora.line5\"));\n list.add(Component.translatable(\"tooltip.primogemcraft.smithing_template_mora.line6\"));\n }\n}" }, { "identifier": "MOD_ID", "path": "src/main/java/com/primogemstudio/primogemcraft/PrimogemCraftFabric.java", "snippet": "public static final String MOD_ID = \"primogemcraft\";" } ]
import com.primogemstudio.primogemcraft.effects.PrimogemCraftMobEffects; import com.primogemstudio.primogemcraft.items.instances.*; import com.primogemstudio.primogemcraft.items.instances.curios.SocietyTicketItem; import com.primogemstudio.primogemcraft.items.instances.materials.agnidus.*; import com.primogemstudio.primogemcraft.items.instances.materials.nagadus.*; import com.primogemstudio.primogemcraft.items.instances.materials.vajrada.*; import com.primogemstudio.primogemcraft.items.instances.materials.vayuda.*; import com.primogemstudio.primogemcraft.items.instances.mora.*; import com.primogemstudio.primogemcraft.items.instances.primogem.*; import com.primogemstudio.primogemcraft.items.instances.records.*; import com.primogemstudio.primogemcraft.items.instances.templates.SmithingTemplateElement1Item; import com.primogemstudio.primogemcraft.items.instances.templates.SmithingTemplateElement2Item; import com.primogemstudio.primogemcraft.items.instances.templates.SmithingTemplateMoraItem; import net.minecraft.core.Registry; import net.minecraft.core.registries.BuiltInRegistries; import net.minecraft.resources.ResourceLocation; import net.minecraft.world.item.Item; import net.minecraft.world.item.Rarity; import static com.primogemstudio.primogemcraft.PrimogemCraftFabric.MOD_ID;
8,723
public static final Item VAYUDA_TURQUOISE_GEMSTONE_PIECE_ITEM = register("vayuda_turquoise_gemstone_piece", new Item(new Item.Properties())); public static final Item VAYUDA_TURQUOISE_GEMSTONE_FRAGMENT_ITEM = register("vayuda_turquoise_gemstone_fragment", new Item(new Item.Properties().rarity(Rarity.UNCOMMON))); public static final Item VAYUDA_TURQUOISE_GEMSTONE_SLIVER_ITEM = register("vayuda_turquoise_gemstone_sliver", new Item(new Item.Properties().rarity(Rarity.UNCOMMON))); public static final VayudaTurquoiseGemstoneHoeItem VAYUDA_TURQUOISE_GEMSTONE_HOE_ITEM = register("vayuda_turquoise_gemstone_hoe", new VayudaTurquoiseGemstoneHoeItem()); public static final VayudaTurquoiseGemstoneAxeItem VAYUDA_TURQUOISE_GEMSTONE_AXE_ITEM = register("vayuda_turquoise_gemstone_axe", new VayudaTurquoiseGemstoneAxeItem()); public static final VayudaTurquoiseGemstonePickaxeItem VAYUDA_TURQUOISE_GEMSTONE_PICKAXE_ITEM = register("vayuda_turquoise_gemstone_pickaxe", new VayudaTurquoiseGemstonePickaxeItem()); public static final VayudaTurquoiseGemstoneShovelItem VAYUDA_TURQUOISE_GEMSTONE_SHOVEL_ITEM = register("vayuda_turquoise_gemstone_shovel", new VayudaTurquoiseGemstoneShovelItem()); public static final VayudaTurquoiseGemstoneIronItem VAYUDA_TURQUOISE_GEMSTONE_IRON_ITEM = register("vayuda_turquoise_gemstone_iron", new VayudaTurquoiseGemstoneIronItem()); public static final VayudaTurquoiseGemstoneDiamondItem VAYUDA_TURQUOISE_GEMSTONE_DIAMOND_ITEM = register("vayuda_turquoise_gemstone_diamond", new VayudaTurquoiseGemstoneDiamondItem()); public static final VayudaTurquoiseGemstoneNetheriteItem VAYUDA_TURQUOISE_GEMSTONE_NETHERITE_ITEM = register("vayuda_turquoise_gemstone_netherite", new VayudaTurquoiseGemstoneNetheriteItem()); public static final VayudaTurquoiseGemstoneIronSwordItem VAYUDA_TURQUOISE_GEMSTONE_IRON_SWORD_ITEM = register("vayuda_turquoise_gemstone_iron_sword", new VayudaTurquoiseGemstoneIronSwordItem()); public static final VayudaTurquoiseGemstoneDiamondSwordItem VAYUDA_TURQUOISE_GEMSTONE_DIAMOND_SWORD_ITEM = register("vayuda_turquoise_gemstone_diamond_sword", new VayudaTurquoiseGemstoneDiamondSwordItem()); public static final VayudaTurquoiseGemstoneNetheriteSwordItem VAYUDA_TURQUOISE_GEMSTONE_NETHERITE_SWORD_ITEM = register("vayuda_turquoise_gemstone_netherite_sword", new VayudaTurquoiseGemstoneNetheriteSwordItem()); public static final VayudaTurquoiseGemstoneNetheriteArmorItem.Helmet VAYUDA_TURQUOISE_GEMSTONE_NETHERITE_HELMET_ITEM = register("vayuda_turquoise_gemstone_netherite_helmet", new VayudaTurquoiseGemstoneNetheriteArmorItem.Helmet()); public static final VayudaTurquoiseGemstoneNetheriteArmorItem.Chestplate VAYUDA_TURQUOISE_GEMSTONE_NETHERITE_CHESTPLATE_ITEM = register("vayuda_turquoise_gemstone_netherite_chestplate", new VayudaTurquoiseGemstoneNetheriteArmorItem.Chestplate()); public static final VayudaTurquoiseGemstoneNetheriteArmorItem.Leggings VAYUDA_TURQUOISE_GEMSTONE_NETHERITE_LEGGINGS_ITEM = register("vayuda_turquoise_gemstone_netherite_leggings", new VayudaTurquoiseGemstoneNetheriteArmorItem.Leggings()); public static final VayudaTurquoiseGemstoneNetheriteArmorItem.Boots VAYUDA_TURQUOISE_GEMSTONE_NETHERITE_BOOTS_ITEM = register("vayuda_turquoise_gemstone_netherite_boots", new VayudaTurquoiseGemstoneNetheriteArmorItem.Boots()); public static final VayudaTurquoiseGemstoneDiamondArmorItem.Helmet VAYUDA_TURQUOISE_GEMSTONE_DIAMOND_HELMET_ITEM = register("vayuda_turquoise_gemstone_diamond_helmet", new VayudaTurquoiseGemstoneDiamondArmorItem.Helmet()); public static final VayudaTurquoiseGemstoneDiamondArmorItem.Chestplate VAYUDA_TURQUOISE_GEMSTONE_DIAMOND_CHESTPLATE_ITEM = register("vayuda_turquoise_gemstone_diamond_chestplate", new VayudaTurquoiseGemstoneDiamondArmorItem.Chestplate()); public static final VayudaTurquoiseGemstoneDiamondArmorItem.Leggings VAYUDA_TURQUOISE_GEMSTONE_DIAMOND_LEGGINGS_ITEM = register("vayuda_turquoise_gemstone_diamond_leggings", new VayudaTurquoiseGemstoneDiamondArmorItem.Leggings()); public static final VayudaTurquoiseGemstoneDiamondArmorItem.Boots VAYUDA_TURQUOISE_GEMSTONE_DIAMOND_BOOTS_ITEM = register("vayuda_turquoise_gemstone_diamond_boots", new VayudaTurquoiseGemstoneDiamondArmorItem.Boots()); public static final VayudaTurquoiseGemstoneIronArmorItem.Helmet VAYUDA_TURQUOISE_GEMSTONE_IRON_HELMET_ITEM = register("vayuda_turquoise_gemstone_iron_helmet", new VayudaTurquoiseGemstoneIronArmorItem.Helmet()); public static final VayudaTurquoiseGemstoneIronArmorItem.Chestplate VAYUDA_TURQUOISE_GEMSTONE_IRON_CHESTPLATE_ITEM = register("vayuda_turquoise_gemstone_iron_chestplate", new VayudaTurquoiseGemstoneIronArmorItem.Chestplate()); public static final VayudaTurquoiseGemstoneIronArmorItem.Leggings VAYUDA_TURQUOISE_GEMSTONE_IRON_LEGGINGS_ITEM = register("vayuda_turquoise_gemstone_iron_leggings", new VayudaTurquoiseGemstoneIronArmorItem.Leggings()); public static final VayudaTurquoiseGemstoneIronArmorItem.Boots VAYUDA_TURQUOISE_GEMSTONE_IRON_BOOTS_ITEM = register("vayuda_turquoise_gemstone_iron_boots", new VayudaTurquoiseGemstoneIronArmorItem.Boots()); public static final Item VAJRADA_AMETHYST_ITEM = register("vajrada_amethyst", new Item(new Item.Properties())); public static final Item VAJRADA_AMETHYST_SLIVER_ITEM = register("vajrada_amethyst_sliver", new Item(new Item.Properties())); public static final Item VAJRADA_AMETHYST_FRAGMENT_ITEM = register("vajrada_amethyst_fragment", new Item(new Item.Properties())); public static final Item VAJRADA_AMETHYST_PIECE_ITEM = register("vajrada_amethyst_piece", new Item(new Item.Properties())); public static final DendroCoreItem DENDRO_CORE_ITEM = register("dendro_core", new DendroCoreItem()); public static final VajradaAmethystHoeItem VAJRADA_AMETHYST_HOE_ITEM = register("vajrada_amethyst_hoe", new VajradaAmethystHoeItem()); public static final VajradaAmethystAxeItem VAJRADA_AMETHYST_AXE_ITEM = register("vajrada_amethyst_axe", new VajradaAmethystAxeItem()); public static final VajradaAmethystPickaxeItem VAJRADA_AMETHYST_PICKAXE_ITEM = register("vajrada_amethyst_pickaxe", new VajradaAmethystPickaxeItem()); public static final VajradaAmethystShovelItem VAJRADA_AMETHYST_SHOVEL_ITEM = register("vajrada_amethyst_shovel", new VajradaAmethystShovelItem()); public static final VajradaAmethystIronItem VAJRADA_AMETHYST_IRON_ITEM = register("vajrada_amethyst_iron", new VajradaAmethystIronItem()); public static final VajradaAmethystDiamondItem VAJRADA_AMETHYST_DIAMOND_ITEM = register("vajrada_amethyst_diamond", new VajradaAmethystDiamondItem()); public static final VajradaAmethystNetheriteItem VAJRADA_AMETHYST_NETHERITE_ITEM = register("vajrada_amethyst_netherite", new VajradaAmethystNetheriteItem()); public static final VajradaAmethystIronSwordItem VAJRADA_AMETHYST_IRON_SWORD_ITEM = register("vajrada_amethyst_iron_sword", new VajradaAmethystIronSwordItem()); public static final VajradaAmethystDiamondSwordItem VAJRADA_AMETHYST_DIAMOND_SWORD_ITEM = register("vajrada_amethyst_diamond_sword", new VajradaAmethystDiamondSwordItem()); public static final VajradaAmethystNetheriteSwordItem VAJRADA_AMETHYST_NETHERITE_SWORD_ITEM = register("vajrada_amethyst_netherite_sword", new VajradaAmethystNetheriteSwordItem()); public static final VajradaAmethystIronArmorItem.Helmet VAJRADA_AMETHYST_IRON_HELMET_ITEM = register("vajrada_amethyst_iron_helmet", new VajradaAmethystIronArmorItem.Helmet()); public static final VajradaAmethystIronArmorItem.Chestplate VAJRADA_AMETHYST_IRON_CHESTPLATE_ITEM = register("vajrada_amethyst_iron_chestplate", new VajradaAmethystIronArmorItem.Chestplate()); public static final VajradaAmethystIronArmorItem.Leggings VAJRADA_AMETHYST_IRON_LEGGINGS_ITEM = register("vajrada_amethyst_iron_leggings", new VajradaAmethystIronArmorItem.Leggings()); public static final VajradaAmethystIronArmorItem.Boots VAJRADA_AMETHYST_IRON_BOOTS_ITEM = register("vajrada_amethyst_iron_boots", new VajradaAmethystIronArmorItem.Boots()); public static final VajradaAmethystDiamondArmorItem.Helmet VAJRADA_AMETHYST_DIAMOND_HELMET_ITEM = register("vajrada_amethyst_diamond_helmet", new VajradaAmethystDiamondArmorItem.Helmet()); public static final VajradaAmethystDiamondArmorItem.Chestplate VAJRADA_AMETHYST_DIAMOND_CHESTPLATE_ITEM = register("vajrada_amethyst_diamond_chestplate", new VajradaAmethystDiamondArmorItem.Chestplate()); public static final VajradaAmethystDiamondArmorItem.Leggings VAJRADA_AMETHYST_DIAMOND_LEGGINGS_ITEM = register("vajrada_amethyst_diamond_leggings", new VajradaAmethystDiamondArmorItem.Leggings()); public static final VajradaAmethystDiamondArmorItem.Boots VAJRADA_AMETHYST_DIAMOND_BOOTS_ITEM = register("vajrada_amethyst_diamond_boots", new VajradaAmethystDiamondArmorItem.Boots()); public static final VajradaAmethystNetheriteArmorItem.Helmet VAJRADA_AMETHYST_NETHERITE_HELMET_ITEM = register("vajrada_amethyst_netherite_helmet", new VajradaAmethystNetheriteArmorItem.Helmet()); public static final VajradaAmethystNetheriteArmorItem.Chestplate VAJRADA_AMETHYST_NETHERITE_CHESTPLATE_ITEM = register("vajrada_amethyst_netherite_chestplate", new VajradaAmethystNetheriteArmorItem.Chestplate()); public static final VajradaAmethystNetheriteArmorItem.Leggings VAJRADA_AMETHYST_NETHERITE_LEGGINGS_ITEM = register("vajrada_amethyst_netherite_leggings", new VajradaAmethystNetheriteArmorItem.Leggings()); public static final VajradaAmethystNetheriteArmorItem.Boots VAJRADA_AMETHYST_NETHERITE_BOOTS_ITEM = register("vajrada_amethyst_netherite_boots", new VajradaAmethystNetheriteArmorItem.Boots()); public static final SmithingTemplateMoraItem SMITHING_TEMPLATE_MORA_ITEM = register("smithing_template_mora", new SmithingTemplateMoraItem()); public static final SmithingTemplateElement1Item SMITHING_TEMPLATE_ELEMENT_1_ITEM = register("smithing_template_element1", new SmithingTemplateElement1Item()); public static final SmithingTemplateElement2Item SMITHING_TEMPLATE_ELEMENT_2_ITEM = register("smithing_template_element2", new SmithingTemplateElement2Item()); public static final Item ELEMENT_CRYSTAL_ITEM = register("element_crystal", new Item(new Item.Properties().fireResistant().rarity(Rarity.EPIC))); public static final Item NAGADUS_EMERALD_ITEM = register("nagadus_emerald", new Item(new Item.Properties())); public static final Item NAGADUS_EMERALD_SLIVER_ITEM = register("nagadus_emerald_sliver", new Item(new Item.Properties())); public static final Item NAGADUS_EMERALD_FRAGMENT_ITEM = register("nagadus_emerald_fragment", new Item(new Item.Properties())); public static final Item NAGADUS_EMERALD_PIECE_ITEM = register("nagadus_emerald_piece", new Item(new Item.Properties())); public static final NagadusEmeraldHoeItem NAGADUS_EMERALD_HOE_ITEM = register("nagadus_emerald_hoe", new NagadusEmeraldHoeItem()); public static final NagadusEmeraldAxeItem NAGADUS_EMERALD_AXE_ITEM = register("nagadus_emerald_axe", new NagadusEmeraldAxeItem()); public static final Item NAGADUS_EMERALD_IRON_ITEM = register("nagadus_emerald_iron", new Item(new Item.Properties())); public static final Item NAGADUS_EMERALD_DIAMOND_ITEM = register("nagadus_emerald_diamond", new Item(new Item.Properties())); public static final Item NAGADUS_EMERALD_NETHERITE_ITEM = register("nagadus_emerald_netherite", new Item(new Item.Properties())); public static final NagadusEmeraldShovelItem NAGADUS_EMERALD_SHOVEL_ITEM = register("nagadus_emerald_shovel", new NagadusEmeraldShovelItem()); public static final NagadusEmeraldIronSwordItem NAGADUS_EMERALD_IRON_SWORD_ITEM = register("nagadus_emerald_iron_sword", new NagadusEmeraldIronSwordItem()); public static final NagadusEmeraldDiamondSwordItem NAGADUS_EMERALD_DIAMOND_SWORD_ITEM = register("nagadus_emerald_diamond_sword", new NagadusEmeraldDiamondSwordItem()); public static final NagadusEmeraldNetheriteSwordItem NAGADUS_EMERALD_NETHERITE_SWORD_ITEM = register("nagadus_emerald_netherite_sword", new NagadusEmeraldNetheriteSwordItem()); public static final NagadusEmeraldIronArmorItem.Helmet NAGADUS_EMERALD_IRON_HELMET_ITEM = register("nagadus_emerald_iron_helmet", new NagadusEmeraldIronArmorItem.Helmet()); public static final NagadusEmeraldIronArmorItem.Chestplate NAGADUS_EMERALD_IRON_CHESTPLATE_ITEM = register("nagadus_emerald_iron_chestplate", new NagadusEmeraldIronArmorItem.Chestplate()); public static final NagadusEmeraldIronArmorItem.Leggings NAGADUS_EMERALD_IRON_LEGGINGS_ITEM = register("nagadus_emerald_iron_leggings", new NagadusEmeraldIronArmorItem.Leggings()); public static final NagadusEmeraldIronArmorItem.Boots NAGADUS_EMERALD_IRON_BOOTS_ITEM = register("nagadus_emerald_iron_boots", new NagadusEmeraldIronArmorItem.Boots()); public static final NagadusEmeraldDiamondArmorItem.Helmet NAGADUS_EMERALD_DIAMOND_HELMET_ITEM = register("nagadus_emerald_diamond_helmet", new NagadusEmeraldDiamondArmorItem.Helmet()); public static final NagadusEmeraldDiamondArmorItem.Chestplate NAGADUS_EMERALD_DIAMOND_CHESTPLATE_ITEM = register("nagadus_emerald_diamond_chestplate", new NagadusEmeraldDiamondArmorItem.Chestplate()); public static final NagadusEmeraldDiamondArmorItem.Leggings NAGADUS_EMERALD_DIAMOND_LEGGINGS_ITEM = register("nagadus_emerald_diamond_leggings", new NagadusEmeraldDiamondArmorItem.Leggings()); public static final NagadusEmeraldDiamondArmorItem.Boots NAGADUS_EMERALD_DIAMOND_BOOTS_ITEM = register("nagadus_emerald_diamond_boots", new NagadusEmeraldDiamondArmorItem.Boots()); public static final NagadusEmeraldNetheriteArmorItem.Helmet NAGADUS_EMERALD_NETHERITE_HELMET_ITEM = register("nagadus_emerald_netherite_helmet", new NagadusEmeraldNetheriteArmorItem.Helmet()); public static final NagadusEmeraldNetheriteArmorItem.Chestplate NAGADUS_EMERALD_NETHERITE_CHESTPLATE_ITEM = register("nagadus_emerald_netherite_chestplate", new NagadusEmeraldNetheriteArmorItem.Chestplate()); public static final NagadusEmeraldNetheriteArmorItem.Leggings NAGADUS_EMERALD_NETHERITE_LEGGINGS_ITEM = register("nagadus_emerald_netherite_leggings", new NagadusEmeraldNetheriteArmorItem.Leggings()); public static final NagadusEmeraldNetheriteArmorItem.Boots NAGADUS_EMERALD_NETHERITE_BOOTS_ITEM = register("nagadus_emerald_netherite_boots", new NagadusEmeraldNetheriteArmorItem.Boots()); public static final Item AGNIDUS_AGATE_ITEM = register("agnidus_agate", new Item(new Item.Properties())); public static final Item AGNIDUS_AGATE_SLIVER_ITEM = register("agnidus_agate_sliver", new Item(new Item.Properties())); public static final Item AGNIDUS_AGATE_FRAGMENT_ITEM = register("agnidus_agate_fragment", new Item(new Item.Properties())); public static final Item AGNIDUS_AGATE_PIECE_ITEM = register("agnidus_agate_piece", new Item(new Item.Properties())); public static final AgnidusAgateIronItem AGNIDUS_AGATE_IRON_ITEM = register("agnidus_agate_iron", new AgnidusAgateIronItem()); public static final AgnidusAgateDiamondItem AGNIDUS_AGATE_DIAMOND_ITEM = register("agnidus_agate_diamond", new AgnidusAgateDiamondItem()); public static final AgnidusAgateNetheriteItem AGNIDUS_AGATE_NETHERITE_ITEM = register("agnidus_agate_netherite", new AgnidusAgateNetheriteItem()); public static final AgnidusAgateShovelItem AGNIDUS_AGATE_SHOVEL_ITEM = register("agnidus_agate_shovel", new AgnidusAgateShovelItem()); public static final AgnidusAgateHoeItem AGNIDUS_AGATE_HOE_ITEM = register("agnidus_agate_hoe", new AgnidusAgateHoeItem()); public static final ElementCrystalDustItem ELEMENT_CRYSTAL_DUST_ITEM = register("element_crystal_dust", new ElementCrystalDustItem()); public static final AgnidusAgateAxeItem AGNIDUS_AGATE_AXE_ITEM = register("agnidus_agate_axe", new AgnidusAgateAxeItem()); public static final AgnidusAgatePickaxeItem AGNIDUS_AGATE_PICKAXE_ITEM = register("agnidus_agate_pickaxe", new AgnidusAgatePickaxeItem()); public static final AgnidusAgateIronSwordItem AGNIDUS_AGATE_IRON_SWORD_ITEM = register("agnidus_agate_iron_sword", new AgnidusAgateIronSwordItem()); public static final AgnidusAgateDiamondSwordItem AGNIDUS_AGATE_DIAMOND_SWORD_ITEM = register("agnidus_agate_diamond_sword", new AgnidusAgateDiamondSwordItem()); public static final AgnidusAgateNetheriteSwordItem AGNIDUS_AGATE_NETHERITE_SWORD_ITEM = register("agnidus_agate_netherite_sword", new AgnidusAgateNetheriteSwordItem()); public static final AgnidusAgateIronArmorItem.Helmet AGNIDUS_AGATE_IRON_HELMET_ITEM = register("agnidus_agate_iron_helmet", new AgnidusAgateIronArmorItem.Helmet()); public static final AgnidusAgateIronArmorItem.Chestplate AGNIDUS_AGATE_IRON_CHESTPLATE_ITEM = register("agnidus_agate_iron_chestplate", new AgnidusAgateIronArmorItem.Chestplate()); public static final AgnidusAgateIronArmorItem.Leggings AGNIDUS_AGATE_IRON_LEGGINGS_ITEM = register("agnidus_agate_iron_leggings", new AgnidusAgateIronArmorItem.Leggings()); public static final AgnidusAgateIronArmorItem.Boots AGNIDUS_AGATE_IRON_BOOTS_ITEM = register("agnidus_agate_iron_boots", new AgnidusAgateIronArmorItem.Boots()); public static final AgnidusAgateDiamondArmorItem.Helmet AGNIDUS_AGATE_DIAMOND_HELMET_ITEM = register("agnidus_agate_diamond_helmet", new AgnidusAgateDiamondArmorItem.Helmet()); public static final AgnidusAgateDiamondArmorItem.Chestplate AGNIDUS_AGATE_DIAMOND_CHESTPLATE_ITEM = register("agnidus_agate_diamond_chestplate", new AgnidusAgateDiamondArmorItem.Chestplate()); public static final AgnidusAgateDiamondArmorItem.Leggings AGNIDUS_AGATE_DIAMOND_LEGGINGS_ITEM = register("agnidus_agate_diamond_leggings", new AgnidusAgateDiamondArmorItem.Leggings()); public static final AgnidusAgateDiamondArmorItem.Boots AGNIDUS_AGATE_DIAMOND_BOOTS_ITEM = register("agnidus_agate_diamond_boots", new AgnidusAgateDiamondArmorItem.Boots()); public static final AgnidusAgateNetheriteArmorItem.Boots AGNIDUS_AGATE_NETHERITE_BOOTS_ITEM = register("agnidus_agate_netherite_boots", new AgnidusAgateNetheriteArmorItem.Boots()); public static final AgnidusAgateNetheriteArmorItem.Helmet AGNIDUS_AGATE_NETHERITE_HELMET_ITEM = register("agnidus_agate_netherite_helmet", new AgnidusAgateNetheriteArmorItem.Helmet()); public static final AgnidusAgateNetheriteArmorItem.Chestplate AGNIDUS_AGATE_NETHERITE_CHESTPLATE_ITEM = register("agnidus_agate_netherite_chestplate", new AgnidusAgateNetheriteArmorItem.Chestplate()); public static final AgnidusAgateNetheriteArmorItem.Leggings AGNIDUS_AGATE_NETHERITE_LEGGINGS_ITEM = register("agnidus_agate_netherite_leggings", new AgnidusAgateNetheriteArmorItem.Leggings()); public static final Item PRITHVA_TOPAZ_ITEM = register("prithva_topaz", new Item(new Item.Properties())); public static final Item PRITHVA_TOPAZ_FRAGMENT_ITEM = register("prithva_topaz_fragment", new Item(new Item.Properties())); public static final Item PRITHVA_TOPAZ_SLIVER_ITEM = register("prithva_topaz_sliver", new Item(new Item.Properties())); public static final Item PRITHVA_TOPAZ_PIECE_ITEM = register("prithva_topaz_piece", new Item(new Item.Properties())); public static void init() { PrimogemCraftMobEffects.init(); } private static <T extends Item> T register(String id, T item) {
package com.primogemstudio.primogemcraft.items; public class PrimogemCraftItems { public static final TheAllBeginningItem THE_ALL_BEGINNING_ITEM = register("the_all_beginning", new TheAllBeginningItem()); public static final PrimogemItem PRIMOGEM_ITEM = register("primogem", new PrimogemItem()); public static final OldStoneItem OLD_STONE_ITEM = register("old_stone", new OldStoneItem()); public static final Item MASTER_LESS_STAR_DUST_ITEM = register("masterless_stardust", new Item(new Item.Properties().stacksTo(64).rarity(Rarity.COMMON))); public static final Item MASTER_LESS_STARG_LITTER_ITEM = register("masterless_starglitter", new Item(new Item.Properties().stacksTo(64).rarity(Rarity.COMMON))); public static final PrimogemBilletItem PRIMOGEM_BILLET_ITEM = register("primogem_billet", new PrimogemBilletItem()); public static final IntertwinedFateItem INTERTWINED_FATE_ITEM = register("intertwined_fate", new IntertwinedFateItem()); public static final AcquaintFateItem ACQUAINT_FATE_ITEM = register("acquaint_fate", new AcquaintFateItem()); public static final NagadusEmeraldPickaxeItem NAGADUS_EMERALD_PICKAXE_ITEM = register("nagadus_emerald_pickaxe", new NagadusEmeraldPickaxeItem()); public static final PrimogemPickaxeItem PRIMOGEM_PICKAXE_ITEM = register("primogem_pickaxe", new PrimogemPickaxeItem()); public static final PrimogemHoeItem PRIMOGEM_HOE_ITEM = register("primogem_hoe", new PrimogemHoeItem()); public static final PrimogemAxeItem PRIMOGEM_AXE_ITEM = register("primogem_axe", new PrimogemAxeItem()); public static final PrimogemShovelItem PRIMOGEM_SHOVEL_ITEM = register("primogem_shovel", new PrimogemShovelItem()); public static final PrimogemSwordItem PRIMOGEM_SWORD_ITEM = register("primogem_sword", new PrimogemSwordItem()); public static final DullBladeItem DULL_BLADE_ITEM = register("dull_blade", new DullBladeItem()); public static final ANewDayWithHopeRecordItem A_NEW_DAY_WITH_HOPE_RECORD_ITEM = register("music_disc_a_new_day_with_hope", new ANewDayWithHopeRecordItem()); public static final TheFadingStoriesRecordItem THE_FADING_STORIES_RECORD_ITEM = register("music_disc_the_fading_stories", new TheFadingStoriesRecordItem()); public static final HakushinLullabyRecordItem HAKUSHIN_LULLABY_RECORD_ITEM = register("music_disc_hakushin_lullaby", new HakushinLullabyRecordItem()); public static final VillageSurroundedByGreenRecordItem VILLAGE_SURROUNDED_BY_GREEN_RECORD_ITEM = register("music_disc_village_surrounded_by_green", new VillageSurroundedByGreenRecordItem()); public static final BalladofManyWatersRecordItem BALLAD_OF_MANY_WATERS_RECORD_ITEM = register("music_disc_ballad_of_many_waters", new BalladofManyWatersRecordItem()); public static final SpaceWalkRecordItem SPACE_WALK_RECORD_ITEM = register("music_disc_space_walk", new SpaceWalkRecordItem()); public static final SaltyMoonRecordItem SALTY_MOON_RECORD_ITEM = register("music_disc_salty_moon", new SaltyMoonRecordItem()); public static final TakeTheJourneyRecordItem TAKE_THE_JOURNEY_RECORD_ITEM = register("music_disc_take_the_journey", new TakeTheJourneyRecordItem()); public static final IntertwinedFateTenTimesItem INTERTWINED_FATE_TEN_ITEM = register("intertwined_fate_ten", new IntertwinedFateTenTimesItem()); public static final Item MORA_BILLET_ITEM = register("mora_billet", new Item(new Item.Properties().rarity(Rarity.UNCOMMON))); public static final Item MORA_ITEM = register("mora", new Item(new Item.Properties().rarity(Rarity.UNCOMMON))); public static final ExquisiteMoraItem EXQUISITE_MORA_ITEM = register("exquisite_mora", new ExquisiteMoraItem()); public static final ExquisiteMoraBagItem EXQUISITE_MORA_BAG_ITEM = register("exquisite_mora_bag", new ExquisiteMoraBagItem()); public static final MoraWalletItem MORA_WALLET_ITEM = register("mora_wallet", new MoraWalletItem()); public static final CosmicFragmentsItem COSMIC_FRAGMENTS_ITEM = register("cosmic_fragments", new CosmicFragmentsItem()); public static final SocietyTicketItem SOCIETY_TICKET_ITEM = register("society_ticket", new SocietyTicketItem()); public static final StrangePrimogemSwordItem STRANGE_PRIMOGEM_SWORD_ITEM = register("strange_primogem_sword", new StrangePrimogemSwordItem()); public static final MoraPickaxeItem MORA_PICKAXE_ITEM = register("mora_pickaxe", new MoraPickaxeItem()); public static final MoraSwordItem MORA_SWORD_ITEM = register("mora_sword", new MoraSwordItem()); public static final MoraShovelItem MORA_SHOVEL_ITEM = register("mora_shovel", new MoraShovelItem()); public static final MoraHoeItem MORA_HOE_ITEM = register("mora_hoe", new MoraHoeItem()); public static final MoraAxeItem MORA_AXE_ITEM = register("mora_axe", new MoraAxeItem()); public static final MoraArmorItem.MoraHelmet MORA_HELMET_ITEM = register("mora_helmet", new MoraArmorItem.MoraHelmet()); public static final MoraArmorItem.MoraChestplate MORA_CHESTPLATE_ITEM = register("mora_chestplate", new MoraArmorItem.MoraChestplate()); public static final MoraArmorItem.MoraLeggings MORA_LEGGINGS_ITEM = register("mora_leggings", new MoraArmorItem.MoraLeggings()); public static final MoraArmorItem.MoraBoots MORA_BOOTS_ITEM = register("mora_boots", new MoraArmorItem.MoraBoots()); public static final Item TEYVAT_STICK_ITEM = register("teyvat_stick", new Item(new Item.Properties())); public static final Item VAYUDA_TURQUOISE_GEMSTONE_ITEM = register("vayuda_turquoise_gemstone", new Item(new Item.Properties())); public static final Item VAYUDA_TURQUOISE_GEMSTONE_PIECE_ITEM = register("vayuda_turquoise_gemstone_piece", new Item(new Item.Properties())); public static final Item VAYUDA_TURQUOISE_GEMSTONE_FRAGMENT_ITEM = register("vayuda_turquoise_gemstone_fragment", new Item(new Item.Properties().rarity(Rarity.UNCOMMON))); public static final Item VAYUDA_TURQUOISE_GEMSTONE_SLIVER_ITEM = register("vayuda_turquoise_gemstone_sliver", new Item(new Item.Properties().rarity(Rarity.UNCOMMON))); public static final VayudaTurquoiseGemstoneHoeItem VAYUDA_TURQUOISE_GEMSTONE_HOE_ITEM = register("vayuda_turquoise_gemstone_hoe", new VayudaTurquoiseGemstoneHoeItem()); public static final VayudaTurquoiseGemstoneAxeItem VAYUDA_TURQUOISE_GEMSTONE_AXE_ITEM = register("vayuda_turquoise_gemstone_axe", new VayudaTurquoiseGemstoneAxeItem()); public static final VayudaTurquoiseGemstonePickaxeItem VAYUDA_TURQUOISE_GEMSTONE_PICKAXE_ITEM = register("vayuda_turquoise_gemstone_pickaxe", new VayudaTurquoiseGemstonePickaxeItem()); public static final VayudaTurquoiseGemstoneShovelItem VAYUDA_TURQUOISE_GEMSTONE_SHOVEL_ITEM = register("vayuda_turquoise_gemstone_shovel", new VayudaTurquoiseGemstoneShovelItem()); public static final VayudaTurquoiseGemstoneIronItem VAYUDA_TURQUOISE_GEMSTONE_IRON_ITEM = register("vayuda_turquoise_gemstone_iron", new VayudaTurquoiseGemstoneIronItem()); public static final VayudaTurquoiseGemstoneDiamondItem VAYUDA_TURQUOISE_GEMSTONE_DIAMOND_ITEM = register("vayuda_turquoise_gemstone_diamond", new VayudaTurquoiseGemstoneDiamondItem()); public static final VayudaTurquoiseGemstoneNetheriteItem VAYUDA_TURQUOISE_GEMSTONE_NETHERITE_ITEM = register("vayuda_turquoise_gemstone_netherite", new VayudaTurquoiseGemstoneNetheriteItem()); public static final VayudaTurquoiseGemstoneIronSwordItem VAYUDA_TURQUOISE_GEMSTONE_IRON_SWORD_ITEM = register("vayuda_turquoise_gemstone_iron_sword", new VayudaTurquoiseGemstoneIronSwordItem()); public static final VayudaTurquoiseGemstoneDiamondSwordItem VAYUDA_TURQUOISE_GEMSTONE_DIAMOND_SWORD_ITEM = register("vayuda_turquoise_gemstone_diamond_sword", new VayudaTurquoiseGemstoneDiamondSwordItem()); public static final VayudaTurquoiseGemstoneNetheriteSwordItem VAYUDA_TURQUOISE_GEMSTONE_NETHERITE_SWORD_ITEM = register("vayuda_turquoise_gemstone_netherite_sword", new VayudaTurquoiseGemstoneNetheriteSwordItem()); public static final VayudaTurquoiseGemstoneNetheriteArmorItem.Helmet VAYUDA_TURQUOISE_GEMSTONE_NETHERITE_HELMET_ITEM = register("vayuda_turquoise_gemstone_netherite_helmet", new VayudaTurquoiseGemstoneNetheriteArmorItem.Helmet()); public static final VayudaTurquoiseGemstoneNetheriteArmorItem.Chestplate VAYUDA_TURQUOISE_GEMSTONE_NETHERITE_CHESTPLATE_ITEM = register("vayuda_turquoise_gemstone_netherite_chestplate", new VayudaTurquoiseGemstoneNetheriteArmorItem.Chestplate()); public static final VayudaTurquoiseGemstoneNetheriteArmorItem.Leggings VAYUDA_TURQUOISE_GEMSTONE_NETHERITE_LEGGINGS_ITEM = register("vayuda_turquoise_gemstone_netherite_leggings", new VayudaTurquoiseGemstoneNetheriteArmorItem.Leggings()); public static final VayudaTurquoiseGemstoneNetheriteArmorItem.Boots VAYUDA_TURQUOISE_GEMSTONE_NETHERITE_BOOTS_ITEM = register("vayuda_turquoise_gemstone_netherite_boots", new VayudaTurquoiseGemstoneNetheriteArmorItem.Boots()); public static final VayudaTurquoiseGemstoneDiamondArmorItem.Helmet VAYUDA_TURQUOISE_GEMSTONE_DIAMOND_HELMET_ITEM = register("vayuda_turquoise_gemstone_diamond_helmet", new VayudaTurquoiseGemstoneDiamondArmorItem.Helmet()); public static final VayudaTurquoiseGemstoneDiamondArmorItem.Chestplate VAYUDA_TURQUOISE_GEMSTONE_DIAMOND_CHESTPLATE_ITEM = register("vayuda_turquoise_gemstone_diamond_chestplate", new VayudaTurquoiseGemstoneDiamondArmorItem.Chestplate()); public static final VayudaTurquoiseGemstoneDiamondArmorItem.Leggings VAYUDA_TURQUOISE_GEMSTONE_DIAMOND_LEGGINGS_ITEM = register("vayuda_turquoise_gemstone_diamond_leggings", new VayudaTurquoiseGemstoneDiamondArmorItem.Leggings()); public static final VayudaTurquoiseGemstoneDiamondArmorItem.Boots VAYUDA_TURQUOISE_GEMSTONE_DIAMOND_BOOTS_ITEM = register("vayuda_turquoise_gemstone_diamond_boots", new VayudaTurquoiseGemstoneDiamondArmorItem.Boots()); public static final VayudaTurquoiseGemstoneIronArmorItem.Helmet VAYUDA_TURQUOISE_GEMSTONE_IRON_HELMET_ITEM = register("vayuda_turquoise_gemstone_iron_helmet", new VayudaTurquoiseGemstoneIronArmorItem.Helmet()); public static final VayudaTurquoiseGemstoneIronArmorItem.Chestplate VAYUDA_TURQUOISE_GEMSTONE_IRON_CHESTPLATE_ITEM = register("vayuda_turquoise_gemstone_iron_chestplate", new VayudaTurquoiseGemstoneIronArmorItem.Chestplate()); public static final VayudaTurquoiseGemstoneIronArmorItem.Leggings VAYUDA_TURQUOISE_GEMSTONE_IRON_LEGGINGS_ITEM = register("vayuda_turquoise_gemstone_iron_leggings", new VayudaTurquoiseGemstoneIronArmorItem.Leggings()); public static final VayudaTurquoiseGemstoneIronArmorItem.Boots VAYUDA_TURQUOISE_GEMSTONE_IRON_BOOTS_ITEM = register("vayuda_turquoise_gemstone_iron_boots", new VayudaTurquoiseGemstoneIronArmorItem.Boots()); public static final Item VAJRADA_AMETHYST_ITEM = register("vajrada_amethyst", new Item(new Item.Properties())); public static final Item VAJRADA_AMETHYST_SLIVER_ITEM = register("vajrada_amethyst_sliver", new Item(new Item.Properties())); public static final Item VAJRADA_AMETHYST_FRAGMENT_ITEM = register("vajrada_amethyst_fragment", new Item(new Item.Properties())); public static final Item VAJRADA_AMETHYST_PIECE_ITEM = register("vajrada_amethyst_piece", new Item(new Item.Properties())); public static final DendroCoreItem DENDRO_CORE_ITEM = register("dendro_core", new DendroCoreItem()); public static final VajradaAmethystHoeItem VAJRADA_AMETHYST_HOE_ITEM = register("vajrada_amethyst_hoe", new VajradaAmethystHoeItem()); public static final VajradaAmethystAxeItem VAJRADA_AMETHYST_AXE_ITEM = register("vajrada_amethyst_axe", new VajradaAmethystAxeItem()); public static final VajradaAmethystPickaxeItem VAJRADA_AMETHYST_PICKAXE_ITEM = register("vajrada_amethyst_pickaxe", new VajradaAmethystPickaxeItem()); public static final VajradaAmethystShovelItem VAJRADA_AMETHYST_SHOVEL_ITEM = register("vajrada_amethyst_shovel", new VajradaAmethystShovelItem()); public static final VajradaAmethystIronItem VAJRADA_AMETHYST_IRON_ITEM = register("vajrada_amethyst_iron", new VajradaAmethystIronItem()); public static final VajradaAmethystDiamondItem VAJRADA_AMETHYST_DIAMOND_ITEM = register("vajrada_amethyst_diamond", new VajradaAmethystDiamondItem()); public static final VajradaAmethystNetheriteItem VAJRADA_AMETHYST_NETHERITE_ITEM = register("vajrada_amethyst_netherite", new VajradaAmethystNetheriteItem()); public static final VajradaAmethystIronSwordItem VAJRADA_AMETHYST_IRON_SWORD_ITEM = register("vajrada_amethyst_iron_sword", new VajradaAmethystIronSwordItem()); public static final VajradaAmethystDiamondSwordItem VAJRADA_AMETHYST_DIAMOND_SWORD_ITEM = register("vajrada_amethyst_diamond_sword", new VajradaAmethystDiamondSwordItem()); public static final VajradaAmethystNetheriteSwordItem VAJRADA_AMETHYST_NETHERITE_SWORD_ITEM = register("vajrada_amethyst_netherite_sword", new VajradaAmethystNetheriteSwordItem()); public static final VajradaAmethystIronArmorItem.Helmet VAJRADA_AMETHYST_IRON_HELMET_ITEM = register("vajrada_amethyst_iron_helmet", new VajradaAmethystIronArmorItem.Helmet()); public static final VajradaAmethystIronArmorItem.Chestplate VAJRADA_AMETHYST_IRON_CHESTPLATE_ITEM = register("vajrada_amethyst_iron_chestplate", new VajradaAmethystIronArmorItem.Chestplate()); public static final VajradaAmethystIronArmorItem.Leggings VAJRADA_AMETHYST_IRON_LEGGINGS_ITEM = register("vajrada_amethyst_iron_leggings", new VajradaAmethystIronArmorItem.Leggings()); public static final VajradaAmethystIronArmorItem.Boots VAJRADA_AMETHYST_IRON_BOOTS_ITEM = register("vajrada_amethyst_iron_boots", new VajradaAmethystIronArmorItem.Boots()); public static final VajradaAmethystDiamondArmorItem.Helmet VAJRADA_AMETHYST_DIAMOND_HELMET_ITEM = register("vajrada_amethyst_diamond_helmet", new VajradaAmethystDiamondArmorItem.Helmet()); public static final VajradaAmethystDiamondArmorItem.Chestplate VAJRADA_AMETHYST_DIAMOND_CHESTPLATE_ITEM = register("vajrada_amethyst_diamond_chestplate", new VajradaAmethystDiamondArmorItem.Chestplate()); public static final VajradaAmethystDiamondArmorItem.Leggings VAJRADA_AMETHYST_DIAMOND_LEGGINGS_ITEM = register("vajrada_amethyst_diamond_leggings", new VajradaAmethystDiamondArmorItem.Leggings()); public static final VajradaAmethystDiamondArmorItem.Boots VAJRADA_AMETHYST_DIAMOND_BOOTS_ITEM = register("vajrada_amethyst_diamond_boots", new VajradaAmethystDiamondArmorItem.Boots()); public static final VajradaAmethystNetheriteArmorItem.Helmet VAJRADA_AMETHYST_NETHERITE_HELMET_ITEM = register("vajrada_amethyst_netherite_helmet", new VajradaAmethystNetheriteArmorItem.Helmet()); public static final VajradaAmethystNetheriteArmorItem.Chestplate VAJRADA_AMETHYST_NETHERITE_CHESTPLATE_ITEM = register("vajrada_amethyst_netherite_chestplate", new VajradaAmethystNetheriteArmorItem.Chestplate()); public static final VajradaAmethystNetheriteArmorItem.Leggings VAJRADA_AMETHYST_NETHERITE_LEGGINGS_ITEM = register("vajrada_amethyst_netherite_leggings", new VajradaAmethystNetheriteArmorItem.Leggings()); public static final VajradaAmethystNetheriteArmorItem.Boots VAJRADA_AMETHYST_NETHERITE_BOOTS_ITEM = register("vajrada_amethyst_netherite_boots", new VajradaAmethystNetheriteArmorItem.Boots()); public static final SmithingTemplateMoraItem SMITHING_TEMPLATE_MORA_ITEM = register("smithing_template_mora", new SmithingTemplateMoraItem()); public static final SmithingTemplateElement1Item SMITHING_TEMPLATE_ELEMENT_1_ITEM = register("smithing_template_element1", new SmithingTemplateElement1Item()); public static final SmithingTemplateElement2Item SMITHING_TEMPLATE_ELEMENT_2_ITEM = register("smithing_template_element2", new SmithingTemplateElement2Item()); public static final Item ELEMENT_CRYSTAL_ITEM = register("element_crystal", new Item(new Item.Properties().fireResistant().rarity(Rarity.EPIC))); public static final Item NAGADUS_EMERALD_ITEM = register("nagadus_emerald", new Item(new Item.Properties())); public static final Item NAGADUS_EMERALD_SLIVER_ITEM = register("nagadus_emerald_sliver", new Item(new Item.Properties())); public static final Item NAGADUS_EMERALD_FRAGMENT_ITEM = register("nagadus_emerald_fragment", new Item(new Item.Properties())); public static final Item NAGADUS_EMERALD_PIECE_ITEM = register("nagadus_emerald_piece", new Item(new Item.Properties())); public static final NagadusEmeraldHoeItem NAGADUS_EMERALD_HOE_ITEM = register("nagadus_emerald_hoe", new NagadusEmeraldHoeItem()); public static final NagadusEmeraldAxeItem NAGADUS_EMERALD_AXE_ITEM = register("nagadus_emerald_axe", new NagadusEmeraldAxeItem()); public static final Item NAGADUS_EMERALD_IRON_ITEM = register("nagadus_emerald_iron", new Item(new Item.Properties())); public static final Item NAGADUS_EMERALD_DIAMOND_ITEM = register("nagadus_emerald_diamond", new Item(new Item.Properties())); public static final Item NAGADUS_EMERALD_NETHERITE_ITEM = register("nagadus_emerald_netherite", new Item(new Item.Properties())); public static final NagadusEmeraldShovelItem NAGADUS_EMERALD_SHOVEL_ITEM = register("nagadus_emerald_shovel", new NagadusEmeraldShovelItem()); public static final NagadusEmeraldIronSwordItem NAGADUS_EMERALD_IRON_SWORD_ITEM = register("nagadus_emerald_iron_sword", new NagadusEmeraldIronSwordItem()); public static final NagadusEmeraldDiamondSwordItem NAGADUS_EMERALD_DIAMOND_SWORD_ITEM = register("nagadus_emerald_diamond_sword", new NagadusEmeraldDiamondSwordItem()); public static final NagadusEmeraldNetheriteSwordItem NAGADUS_EMERALD_NETHERITE_SWORD_ITEM = register("nagadus_emerald_netherite_sword", new NagadusEmeraldNetheriteSwordItem()); public static final NagadusEmeraldIronArmorItem.Helmet NAGADUS_EMERALD_IRON_HELMET_ITEM = register("nagadus_emerald_iron_helmet", new NagadusEmeraldIronArmorItem.Helmet()); public static final NagadusEmeraldIronArmorItem.Chestplate NAGADUS_EMERALD_IRON_CHESTPLATE_ITEM = register("nagadus_emerald_iron_chestplate", new NagadusEmeraldIronArmorItem.Chestplate()); public static final NagadusEmeraldIronArmorItem.Leggings NAGADUS_EMERALD_IRON_LEGGINGS_ITEM = register("nagadus_emerald_iron_leggings", new NagadusEmeraldIronArmorItem.Leggings()); public static final NagadusEmeraldIronArmorItem.Boots NAGADUS_EMERALD_IRON_BOOTS_ITEM = register("nagadus_emerald_iron_boots", new NagadusEmeraldIronArmorItem.Boots()); public static final NagadusEmeraldDiamondArmorItem.Helmet NAGADUS_EMERALD_DIAMOND_HELMET_ITEM = register("nagadus_emerald_diamond_helmet", new NagadusEmeraldDiamondArmorItem.Helmet()); public static final NagadusEmeraldDiamondArmorItem.Chestplate NAGADUS_EMERALD_DIAMOND_CHESTPLATE_ITEM = register("nagadus_emerald_diamond_chestplate", new NagadusEmeraldDiamondArmorItem.Chestplate()); public static final NagadusEmeraldDiamondArmorItem.Leggings NAGADUS_EMERALD_DIAMOND_LEGGINGS_ITEM = register("nagadus_emerald_diamond_leggings", new NagadusEmeraldDiamondArmorItem.Leggings()); public static final NagadusEmeraldDiamondArmorItem.Boots NAGADUS_EMERALD_DIAMOND_BOOTS_ITEM = register("nagadus_emerald_diamond_boots", new NagadusEmeraldDiamondArmorItem.Boots()); public static final NagadusEmeraldNetheriteArmorItem.Helmet NAGADUS_EMERALD_NETHERITE_HELMET_ITEM = register("nagadus_emerald_netherite_helmet", new NagadusEmeraldNetheriteArmorItem.Helmet()); public static final NagadusEmeraldNetheriteArmorItem.Chestplate NAGADUS_EMERALD_NETHERITE_CHESTPLATE_ITEM = register("nagadus_emerald_netherite_chestplate", new NagadusEmeraldNetheriteArmorItem.Chestplate()); public static final NagadusEmeraldNetheriteArmorItem.Leggings NAGADUS_EMERALD_NETHERITE_LEGGINGS_ITEM = register("nagadus_emerald_netherite_leggings", new NagadusEmeraldNetheriteArmorItem.Leggings()); public static final NagadusEmeraldNetheriteArmorItem.Boots NAGADUS_EMERALD_NETHERITE_BOOTS_ITEM = register("nagadus_emerald_netherite_boots", new NagadusEmeraldNetheriteArmorItem.Boots()); public static final Item AGNIDUS_AGATE_ITEM = register("agnidus_agate", new Item(new Item.Properties())); public static final Item AGNIDUS_AGATE_SLIVER_ITEM = register("agnidus_agate_sliver", new Item(new Item.Properties())); public static final Item AGNIDUS_AGATE_FRAGMENT_ITEM = register("agnidus_agate_fragment", new Item(new Item.Properties())); public static final Item AGNIDUS_AGATE_PIECE_ITEM = register("agnidus_agate_piece", new Item(new Item.Properties())); public static final AgnidusAgateIronItem AGNIDUS_AGATE_IRON_ITEM = register("agnidus_agate_iron", new AgnidusAgateIronItem()); public static final AgnidusAgateDiamondItem AGNIDUS_AGATE_DIAMOND_ITEM = register("agnidus_agate_diamond", new AgnidusAgateDiamondItem()); public static final AgnidusAgateNetheriteItem AGNIDUS_AGATE_NETHERITE_ITEM = register("agnidus_agate_netherite", new AgnidusAgateNetheriteItem()); public static final AgnidusAgateShovelItem AGNIDUS_AGATE_SHOVEL_ITEM = register("agnidus_agate_shovel", new AgnidusAgateShovelItem()); public static final AgnidusAgateHoeItem AGNIDUS_AGATE_HOE_ITEM = register("agnidus_agate_hoe", new AgnidusAgateHoeItem()); public static final ElementCrystalDustItem ELEMENT_CRYSTAL_DUST_ITEM = register("element_crystal_dust", new ElementCrystalDustItem()); public static final AgnidusAgateAxeItem AGNIDUS_AGATE_AXE_ITEM = register("agnidus_agate_axe", new AgnidusAgateAxeItem()); public static final AgnidusAgatePickaxeItem AGNIDUS_AGATE_PICKAXE_ITEM = register("agnidus_agate_pickaxe", new AgnidusAgatePickaxeItem()); public static final AgnidusAgateIronSwordItem AGNIDUS_AGATE_IRON_SWORD_ITEM = register("agnidus_agate_iron_sword", new AgnidusAgateIronSwordItem()); public static final AgnidusAgateDiamondSwordItem AGNIDUS_AGATE_DIAMOND_SWORD_ITEM = register("agnidus_agate_diamond_sword", new AgnidusAgateDiamondSwordItem()); public static final AgnidusAgateNetheriteSwordItem AGNIDUS_AGATE_NETHERITE_SWORD_ITEM = register("agnidus_agate_netherite_sword", new AgnidusAgateNetheriteSwordItem()); public static final AgnidusAgateIronArmorItem.Helmet AGNIDUS_AGATE_IRON_HELMET_ITEM = register("agnidus_agate_iron_helmet", new AgnidusAgateIronArmorItem.Helmet()); public static final AgnidusAgateIronArmorItem.Chestplate AGNIDUS_AGATE_IRON_CHESTPLATE_ITEM = register("agnidus_agate_iron_chestplate", new AgnidusAgateIronArmorItem.Chestplate()); public static final AgnidusAgateIronArmorItem.Leggings AGNIDUS_AGATE_IRON_LEGGINGS_ITEM = register("agnidus_agate_iron_leggings", new AgnidusAgateIronArmorItem.Leggings()); public static final AgnidusAgateIronArmorItem.Boots AGNIDUS_AGATE_IRON_BOOTS_ITEM = register("agnidus_agate_iron_boots", new AgnidusAgateIronArmorItem.Boots()); public static final AgnidusAgateDiamondArmorItem.Helmet AGNIDUS_AGATE_DIAMOND_HELMET_ITEM = register("agnidus_agate_diamond_helmet", new AgnidusAgateDiamondArmorItem.Helmet()); public static final AgnidusAgateDiamondArmorItem.Chestplate AGNIDUS_AGATE_DIAMOND_CHESTPLATE_ITEM = register("agnidus_agate_diamond_chestplate", new AgnidusAgateDiamondArmorItem.Chestplate()); public static final AgnidusAgateDiamondArmorItem.Leggings AGNIDUS_AGATE_DIAMOND_LEGGINGS_ITEM = register("agnidus_agate_diamond_leggings", new AgnidusAgateDiamondArmorItem.Leggings()); public static final AgnidusAgateDiamondArmorItem.Boots AGNIDUS_AGATE_DIAMOND_BOOTS_ITEM = register("agnidus_agate_diamond_boots", new AgnidusAgateDiamondArmorItem.Boots()); public static final AgnidusAgateNetheriteArmorItem.Boots AGNIDUS_AGATE_NETHERITE_BOOTS_ITEM = register("agnidus_agate_netherite_boots", new AgnidusAgateNetheriteArmorItem.Boots()); public static final AgnidusAgateNetheriteArmorItem.Helmet AGNIDUS_AGATE_NETHERITE_HELMET_ITEM = register("agnidus_agate_netherite_helmet", new AgnidusAgateNetheriteArmorItem.Helmet()); public static final AgnidusAgateNetheriteArmorItem.Chestplate AGNIDUS_AGATE_NETHERITE_CHESTPLATE_ITEM = register("agnidus_agate_netherite_chestplate", new AgnidusAgateNetheriteArmorItem.Chestplate()); public static final AgnidusAgateNetheriteArmorItem.Leggings AGNIDUS_AGATE_NETHERITE_LEGGINGS_ITEM = register("agnidus_agate_netherite_leggings", new AgnidusAgateNetheriteArmorItem.Leggings()); public static final Item PRITHVA_TOPAZ_ITEM = register("prithva_topaz", new Item(new Item.Properties())); public static final Item PRITHVA_TOPAZ_FRAGMENT_ITEM = register("prithva_topaz_fragment", new Item(new Item.Properties())); public static final Item PRITHVA_TOPAZ_SLIVER_ITEM = register("prithva_topaz_sliver", new Item(new Item.Properties())); public static final Item PRITHVA_TOPAZ_PIECE_ITEM = register("prithva_topaz_piece", new Item(new Item.Properties())); public static void init() { PrimogemCraftMobEffects.init(); } private static <T extends Item> T register(String id, T item) {
return Registry.register(BuiltInRegistries.ITEM, new ResourceLocation(MOD_ID, id), item);
5
2023-10-15 08:07:06+00:00
12k
turtleisaac/PokEditor
src/main/java/io/github/turtleisaac/pokeditor/gui/sheets/tables/DefaultTable.java
[ { "identifier": "DataManager", "path": "src/main/java/io/github/turtleisaac/pokeditor/DataManager.java", "snippet": "public class DataManager\n{\n public static final String SHEET_STRINGS_PATH = \"pokeditor/sheet_strings\";\n\n public static DefaultSheetPanel<PersonalData, ?> createPersonalSheet(PokeditorManager manager, NintendoDsRom rom)\n {\n List<TextBankData> textData = DataManager.getData(rom, TextBankData.class);\n List<PersonalData> data = DataManager.getData(rom, PersonalData.class);\n return new DefaultSheetPanel<>(manager, new PersonalTable(data, textData));\n }\n\n public static DefaultSheetPanel<PersonalData, ?> createTmCompatibilitySheet(PokeditorManager manager, NintendoDsRom rom)\n {\n List<TextBankData> textData = DataManager.getData(rom, TextBankData.class);\n List<PersonalData> data = DataManager.getData(rom, PersonalData.class);\n DefaultSheetPanel<PersonalData, ?> sheetPanel = new DefaultSheetPanel<>(manager, new TmCompatibilityTable(data, textData));\n// String[] moveNames = textData.get(TextFiles.MOVE_NAMES.getValue()).getStringList().toArray(String[]::new);\n// sheetPanel.thing(new ComboBoxCellEditor(moveNames));\n return sheetPanel;\n }\n\n public static DefaultSheetPanel<EvolutionData, ?> createEvolutionSheet(PokeditorManager manager, NintendoDsRom rom)\n {\n List<TextBankData> textData = DataManager.getData(rom, TextBankData.class);\n List<EvolutionData> data = DataManager.getData(rom, EvolutionData.class);\n return new DefaultSheetPanel<>(manager, new EvolutionsTable(data, textData));\n }\n\n public static DefaultSheetPanel<LearnsetData, ?> createLearnsetSheet(PokeditorManager manager, NintendoDsRom rom)\n {\n List<TextBankData> textData = DataManager.getData(rom, TextBankData.class);\n List<LearnsetData> data = DataManager.getData(rom, LearnsetData.class);\n return new DefaultSheetPanel<>(manager, new LearnsetsTable(data, textData));\n }\n\n public static DefaultSheetPanel<MoveData, ?> createMoveSheet(PokeditorManager manager, NintendoDsRom rom)\n {\n List<TextBankData> textData = DataManager.getData(rom, TextBankData.class);\n List<MoveData> data = DataManager.getData(rom, MoveData.class);\n return new DefaultSheetPanel<>(manager, new MovesTable(data, textData));\n }\n\n public static DefaultDataEditorPanel<PokemonSpriteData, ?> createPokemonSpriteEditor(PokeditorManager manager, NintendoDsRom rom)\n {\n List<TextBankData> textData = DataManager.getData(rom, TextBankData.class);\n List<PokemonSpriteData> data = DataManager.getData(rom, PokemonSpriteData.class);\n return new DefaultDataEditorPanel<>(manager, new PokemonSpriteEditor(data, textData));\n }\n\n public static DefaultDataEditorPanel<GenericScriptData, ?> createFieldScriptEditor(PokeditorManager manager, NintendoDsRom rom)\n {\n List<TextBankData> textData = DataManager.getData(rom, TextBankData.class);\n List<GenericScriptData> data = DataManager.getData(rom, GenericScriptData.class);\n return new DefaultDataEditorPanel<>(manager, new FieldScriptEditor(data, textData));\n }\n\n private static final Injector injector = Guice.createInjector(\n new PersonalModule(),\n new LearnsetsModule(),\n new EvolutionsModule(),\n new TrainersModule(),\n new MovesModule(),\n new SinnohEncountersModule(),\n new JohtoEncountersModule(),\n new ItemsModule(),\n new TextBankModule(),\n new PokemonSpriteModule());\n\n @SuppressWarnings(\"unchecked\")\n public static <E extends GenericFileData> GenericParser<E> getParser(Class<E> eClass)\n {\n if (eClass != GenericScriptData.class) {\n ParameterizedType type = Types.newParameterizedType(GenericParser.class, eClass);\n return (GenericParser<E>) injector.getInstance(Key.get(TypeLiteral.get(type)));\n } else {\n return (GenericParser<E>) new ScriptParser();\n }\n }\n\n private static final Map<Class<? extends GenericFileData>, List<? extends GenericFileData>> dataMap = new HashMap<>();\n private static final Map<GameCodeBinaries, CodeBinary> codeBinaries = new HashMap<>();\n\n @SuppressWarnings(\"unchecked\")\n public static <E extends GenericFileData> List<E> getData(NintendoDsRom rom, Class<E> eClass)\n {\n if (dataMap.containsKey(eClass))\n return (List<E>) dataMap.get(eClass);\n\n GenericParser<E> parser = DataManager.getParser(eClass);\n Map<GameFiles, Narc> input = new HashMap<>();\n for (GameFiles gameFile : parser.getRequirements())\n {\n input.put(gameFile, new Narc(rom.getFileByName(gameFile.getPath())));\n }\n\n List<E> data = parser.generateDataList(input, codeBinaries);\n dataMap.put(eClass, data);\n\n return data;\n }\n\n public static <E extends GenericFileData> void saveData(NintendoDsRom rom, Class<E> eClass)\n {\n if (!dataMap.containsKey(eClass))\n return;\n\n GenericParser<E> parser = DataManager.getParser(eClass);\n Map<GameFiles, Narc> map = parser.processDataList(getData(rom, eClass), codeBinaries);\n for (GameFiles gameFile : map.keySet())\n {\n rom.setFileByName(gameFile.getPath(), map.get(gameFile).save());\n }\n }\n\n @SuppressWarnings(\"unchecked\")\n public static <E extends GenericFileData> void resetData(NintendoDsRom rom, Class<E> eClass)\n {\n if (!dataMap.containsKey(eClass))\n return;\n\n List<E> list = (List<E>) dataMap.get(eClass);\n list.clear();\n dataMap.remove(eClass);\n List<E> newList = getData(rom, eClass);\n dataMap.remove(newList);\n\n list.addAll(newList);\n dataMap.put(eClass, list);\n }\n\n public static void codeBinarySetup(NintendoDsRom rom)\n {\n MainCodeFile arm9 = rom.loadArm9();\n codeBinaries.put(GameCodeBinaries.ARM9, arm9);\n// codeBinaries.put(GameCodeBinaries.ARM7, rom.loadArm7());\n\n MemBuf.MemBufWriter writer = arm9.getPhysicalAddressBuffer().writer();\n int pos = writer.getPosition();\n writer.setPosition(0xBB4); //todo account for DP if I ever add back support\n writer.writeInt(0);\n writer.setPosition(pos);\n }\n\n public static void saveCodeBinaries(NintendoDsRom rom, List<GameCodeBinaries> codeBinaries)\n {\n for (GameCodeBinaries codeBinary : codeBinaries)\n {\n CodeBinary binary = DataManager.codeBinaries.get(codeBinary);\n binary.lock();\n try {\n if(codeBinary == GameCodeBinaries.ARM9)\n {\n rom.setArm9(binary.getData());\n }\n }\n finally {\n binary.unlock();\n }\n }\n }\n\n static class PersonalModule extends AbstractModule\n {\n @Override\n protected void configure()\n {\n bind(new TypeLiteral<GenericParser<PersonalData>>() {})\n .to(PersonalParser.class)\n .in(Scopes.SINGLETON);\n }\n }\n\n static class LearnsetsModule extends AbstractModule {\n @Override\n protected void configure()\n {\n bind(new TypeLiteral<GenericParser<LearnsetData>>() {})\n .to(LearnsetParser.class)\n .in(Scopes.SINGLETON);\n }\n }\n\n static class EvolutionsModule extends AbstractModule {\n @Override\n protected void configure()\n {\n bind(new TypeLiteral<GenericParser<EvolutionData>>() {})\n .to(EvolutionParser.class)\n .in(Scopes.SINGLETON);\n }\n }\n\n static class TrainersModule extends AbstractModule {\n @Override\n protected void configure()\n {\n bind(new TypeLiteral<GenericParser<TrainerData>>() {})\n .to(TrainerParser.class)\n .in(Scopes.SINGLETON);\n }\n }\n\n static class MovesModule extends AbstractModule {\n @Override\n protected void configure()\n {\n bind(new TypeLiteral<GenericParser<MoveData>>() {})\n .to(MoveParser.class)\n .in(Scopes.SINGLETON);\n }\n }\n\n static class SinnohEncountersModule extends AbstractModule {\n @Override\n protected void configure()\n {\n bind(new TypeLiteral<GenericParser<SinnohEncounterData>>() {})\n .to(SinnohEncounterParser.class)\n .in(Scopes.SINGLETON);\n }\n }\n\n static class JohtoEncountersModule extends AbstractModule {\n @Override\n protected void configure()\n {\n bind(new TypeLiteral<GenericParser<JohtoEncounterData>>() {})\n .to(JohtoEncounterParser.class)\n .in(Scopes.SINGLETON);\n }\n }\n\n static class ItemsModule extends AbstractModule {\n @Override\n protected void configure()\n {\n bind(new TypeLiteral<GenericParser<ItemData>>() {})\n .to(ItemParser.class)\n .in(Scopes.SINGLETON);\n }\n }\n\n static class TextBankModule extends AbstractModule {\n @Override\n protected void configure()\n {\n bind(new TypeLiteral<GenericParser<TextBankData>>() {})\n .to(TextBankParser.class)\n .in(Scopes.SINGLETON);\n }\n }\n\n static class PokemonSpriteModule extends AbstractModule {\n @Override\n protected void configure()\n {\n bind(new TypeLiteral<GenericParser<PokemonSpriteData>>() {})\n .to(PokemonSpriteParser.class)\n .in(Scopes.SINGLETON);\n }\n }\n}" }, { "identifier": "PokeditorManager", "path": "src/main/java/io/github/turtleisaac/pokeditor/gui/PokeditorManager.java", "snippet": "public class PokeditorManager extends PanelManager\n{\n private static final Dimension dimension = new Dimension(1200, 714);\n\n public static final FlatSVGIcon sheetExportIcon;\n public static final FlatSVGIcon sheetImportIcon;\n public static final FlatSVGIcon rowRemoveIcon;\n public static final FlatSVGIcon rowInsertIcon;\n public static final FlatSVGIcon searchIcon;\n public static final FlatSVGIcon clipboardIcon;\n public static final FlatSVGIcon copyIcon;\n\n public static final Color[] typeColors = new Color[]{new Color(201, 201, 201),\n new Color(173, 96, 94),\n new Color(165, 218, 218),\n new Color(184, 121, 240),\n new Color(200, 164, 117),\n new Color(184, 146, 48),\n new Color(157, 195, 132),\n new Color(139, 125, 190),\n new Color(153, 153, 153),\n new Color(230, 199, 255),\n new Color(189, 75, 49),\n new Color(88, 132, 225),\n new Color(120, 166, 90),\n new Color(249, 218, 120),\n new Color(223, 151, 143),\n new Color(70, 185, 185),\n new Color(98, 98, 246),\n new Color(102, 102, 102),\n };\n\n public static final Color[] darkModeTypeColors = new Color[]{new Color(116, 116, 116),\n new Color(130, 72, 71),\n new Color(101, 133, 133),\n new Color(86, 57, 112),\n new Color(157, 129, 92),\n new Color(99, 79, 26),\n new Color(123, 152, 103),\n new Color(77, 69, 105),\n new Color(68, 68, 68),\n new Color(192, 166, 212), //\n new Color(61, 24, 16), //\n new Color(55, 82, 140), //\n new Color(59, 81, 44),\n new Color(163, 144, 79),\n new Color(180, 122, 116),\n new Color(38, 100, 100),\n new Color(30, 30, 76),\n new Color(17, 17, 17),\n };\n\n static {\n try {\n sheetExportIcon = new FlatSVGIcon(PokeditorManager.class.getResourceAsStream(\"/pokeditor/icons/svg/table-export.svg\"));\n sheetImportIcon = new FlatSVGIcon(PokeditorManager.class.getResourceAsStream(\"/pokeditor/icons/svg/table-import.svg\"));\n rowRemoveIcon = new FlatSVGIcon(PokeditorManager.class.getResourceAsStream(\"/pokeditor/icons/svg/row-remove.svg\"));\n rowInsertIcon = new FlatSVGIcon(PokeditorManager.class.getResourceAsStream(\"/pokeditor/icons/svg/row-insert-bottom.svg\"));\n searchIcon = new FlatSVGIcon(PokeditorManager.class.getResourceAsStream(\"/pokeditor/icons/svg/list-search.svg\"));\n clipboardIcon = new FlatSVGIcon(PokeditorManager.class.getResourceAsStream(\"/pokeditor/icons/svg/clipboard-copy.svg\"));\n copyIcon = new FlatSVGIcon(PokeditorManager.class.getResourceAsStream(\"/pokeditor/icons/svg/copy.svg\"));\n\n sheetExportIcon.setColorFilter(ThemeUtils.iconColorFilter);\n sheetImportIcon.setColorFilter(ThemeUtils.iconColorFilter);\n rowRemoveIcon.setColorFilter(ThemeUtils.iconColorFilter);\n rowInsertIcon.setColorFilter(ThemeUtils.iconColorFilter);\n searchIcon.setColorFilter(ThemeUtils.iconColorFilter);\n clipboardIcon.setColorFilter(ThemeUtils.iconColorFilter);\n copyIcon.setColorFilter(ThemeUtils.iconColorFilter);\n\n /*\n this code determines if the label foreground color is closer to/further from black/white, then uses that\n to select which set of colors to use for the types on the sheets (lighter or darker)\n (the idea being a darker theme tends to have a lighter text foreground color)\n */\n Color c = UIManager.getColor(\"Label.foreground\");\n double diff = (double) (c.getRed() + c.getBlue() + c.getGreen()) / 3;\n if (Math.max(diff, 255 - diff) == diff)\n {\n System.arraycopy(darkModeTypeColors, 0, typeColors, 0, typeColors.length);\n }\n }\n catch(IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n private List<JPanel> panels;\n\n private NintendoDsRom rom;\n private Game baseRom;\n private boolean gitEnabled;\n\n public PokeditorManager(Tool tool)\n {\n super(tool, \"PokEditor\");\n\n rom = tool.getRom();\n baseRom = Game.parseBaseRom(rom.getGameCode());\n gitEnabled = tool.isGitEnabled();\n GameFiles.initialize(baseRom);\n TextFiles.initialize(baseRom);\n GameCodeBinaries.initialize(baseRom);\n Tables.initialize(baseRom);\n\n DataManager.codeBinarySetup(rom);\n\n// sheetPanels = new HashMap<>();\n panels = new ArrayList<>();\n// JPanel placeholder = new JPanel();\n// placeholder.setName(\"Test panel\");\n//\n// placeholder.setPreferredSize(dimension);\n// placeholder.setMinimumSize(dimension);\n\n DefaultDataEditorPanel<PokemonSpriteData, ?> battleSpriteEditor = DataManager.createPokemonSpriteEditor(this, rom);\n battleSpriteEditor.setName(\"Pokemon Sprites\");\n battleSpriteEditor.setPreferredSize(battleSpriteEditor.getPreferredSize());\n\n DefaultSheetPanel<PersonalData, ?> personalPanel = DataManager.createPersonalSheet(this, rom);\n personalPanel.setName(\"Personal Sheet\");\n\n DefaultSheetPanel<PersonalData, ?> tmCompatibilityPanel = DataManager.createTmCompatibilitySheet(this, rom);\n tmCompatibilityPanel.setName(\"TMs Sheet\");\n// panels.add(personalPanel);\n\n DefaultSheetPanel<EvolutionData, ?> evolutionsPanel = DataManager.createEvolutionSheet(this, rom);\n evolutionsPanel.setName(\"Evolutions Sheet\");\n// panels.add(evolutionsPanel);\n\n DefaultSheetPanel<LearnsetData, ?> learnsetsPanel = DataManager.createLearnsetSheet(this, rom);\n learnsetsPanel.setName(\"Learnsets Sheet\");\n// panels.add(evolutionsPanel);\n\n DefaultSheetPanel<MoveData, ?> movesPanel = DataManager.createMoveSheet(this, rom);\n movesPanel.setName(\"Moves Sheet\");\n\n DefaultDataEditorPanel<GenericScriptData, ?> fieldScriptEditor = DataManager.createFieldScriptEditor(this, rom);\n fieldScriptEditor.setName(\"Field Scripts\");\n fieldScriptEditor.setPreferredSize(fieldScriptEditor.getPreferredSize());\n\n\n// JPanel fieldPanel = new JPanel();\n// fieldPanel.setName(\"Field\");\n// JPanel waterPanel = new JPanel();\n// waterPanel.setName(\"Water\");\n// PanelGroup encounters = new PanelGroup(\"Encounters\", fieldPanel, waterPanel);\n\n PanelGroup pokemonGroup = new PanelGroup(\"Pokémon Editing\", personalPanel, tmCompatibilityPanel, learnsetsPanel, evolutionsPanel, battleSpriteEditor);\n panels.add(pokemonGroup);\n// panels.add(battleSpriteEditor);\n panels.add(movesPanel);\n// panels.add(encounters);\n panels.add(fieldScriptEditor);\n// panels.add(placeholder);\n }\n\n public <E extends GenericFileData> void saveData(Class<E> dataClass)\n {\n DataManager.saveData(rom, dataClass);\n DataManager.saveData(rom, TextBankData.class);\n// DataManager.saveCodeBinaries(rom, List.of(GameCodeBinaries.ARM9));\n\n// if (!wipeAndWriteUnpacked())\n// throw new RuntimeException(\"An error occurred while deleting or writing a file, please check write permissions\");\n String message = null;\n if (gitEnabled)\n {\n message = JOptionPane.showInputDialog(null, \"Enter commit message:\", \"Save & Commit Changes\", JOptionPane.INFORMATION_MESSAGE);\n if (message == null)\n {\n JOptionPane.showMessageDialog(null, \"Save aborted\", \"Abort\", JOptionPane.ERROR_MESSAGE);\n return;\n }\n else if (message.isEmpty())\n {\n message = null;\n }\n }\n\n wipeAndWriteUnpacked(message);\n }\n\n public <E extends GenericFileData> void resetData(Class<E> dataClass)\n {\n DataManager.resetData(rom, dataClass);\n }\n\n public void resetAllIndexedCellRendererText()\n {\n for (JPanel panel : panels)\n {\n if (panel instanceof DefaultSheetPanel<?,?> sheetPanel)\n {\n sheetPanel.getTable().resetIndexedCellRendererText();\n }\n else if (panel instanceof PanelGroup panelGroup)\n {\n for (JPanel groupPanel : panelGroup.getPanels())\n {\n if (groupPanel instanceof DefaultSheetPanel<?,?> sheetPanel)\n {\n sheetPanel.getTable().resetIndexedCellRendererText();\n }\n }\n }\n }\n }\n\n public void writeSheet(String[][] data)\n {\n JFileChooser fc = new JFileChooser(System.getProperty(\"user.dir\"));\n fc.setDialogTitle(\"Export Sheet\");\n fc.setAcceptAllFileFilterUsed(false);\n\n fc.setFileSelectionMode(JFileChooser.FILES_ONLY);\n fc.addChoosableFileFilter(new FileFilter()\n {\n @Override\n public boolean accept(File f)\n {\n return f.isDirectory() || f.getName().endsWith(\".csv\");\n }\n\n @Override\n public String getDescription()\n {\n return \"CSV file (*.csv)\";\n }\n });\n\n int returnVal = fc.showSaveDialog(null);\n\n if (returnVal == JFileChooser.APPROVE_OPTION) {\n File selected = fc.getSelectedFile();\n String path = selected.getAbsolutePath();\n if (!path.endsWith(\".csv\"))\n path = path + \".csv\";\n try\n {\n BufferedWriter writer = new BufferedWriter(new FileWriter(path));\n for (String[] row : data) {\n for (String s : row)\n writer.write(s + \",\");\n writer.write(\"\\n\");\n }\n\n writer.close();\n }\n catch(IOException e) {\n throw new RuntimeException(e);\n }\n\n }\n }\n\n private static JFileChooser prepareImageChooser(String title, boolean allowPalette)\n {\n String lastPath = Tool.preferences.get(\"pokeditor.imagePath\", null);\n if (lastPath == null) {\n lastPath = System.getProperty(\"user.dir\");\n }\n\n JFileChooser fc = new JFileChooser(lastPath);\n fc.setDialogTitle(title);\n fc.setAcceptAllFileFilterUsed(false);\n\n fc.setFileSelectionMode(JFileChooser.FILES_ONLY);\n\n fc.addChoosableFileFilter(pngFilter);\n fc.addChoosableFileFilter(ncgrFilter);\n if (allowPalette)\n fc.addChoosableFileFilter(nclrFilter);\n return fc;\n }\n\n public static void writeIndexedImage(IndexedImage image)\n {\n JFileChooser fc = prepareImageChooser(\"Export Sprite\", true);\n int returnVal = fc.showSaveDialog(null);\n\n if (returnVal == JFileChooser.APPROVE_OPTION) {\n File selected = fc.getSelectedFile();\n\n String extension;\n if (fc.getFileFilter().equals(pngFilter))\n extension = \"png\";\n else if (fc.getFileFilter().equals(ncgrFilter))\n extension = \"NCGR\";\n else\n extension = \"NCLR\";\n\n String path = selected.getAbsolutePath();\n if (!path.endsWith(\".\" + extension))\n path = path + \".\" + extension;\n\n Tool.preferences.put(\"pokeditor.imagePath\", selected.getParentFile().getAbsolutePath());\n\n try\n {\n if (extension.equals(\"png\"))\n image.saveToIndexedPngFile(path);\n else if (extension.equals(\"NCGR\"))\n image.saveToFile(path);\n else\n image.getPalette().saveToFile(path);\n }\n catch(IOException e) {\n JOptionPane.showMessageDialog(null, \"A fatal error occurred while writing an indexed PNG to disk. See command-line for details.\", \"Error\", JOptionPane.ERROR_MESSAGE);\n throw new RuntimeException(e);\n }\n\n }\n }\n\n public static GenericNtrFile readIndexedImage(boolean allowPalette)\n {\n JFileChooser fc = prepareImageChooser(\"Import Sprite\", allowPalette);\n int returnVal = fc.showOpenDialog(null);\n\n if (returnVal == JFileChooser.APPROVE_OPTION) {\n File selected = fc.getSelectedFile();\n\n String path = selected.getAbsolutePath();\n\n Tool.preferences.put(\"pokeditor.imagePath\", selected.getParentFile().getAbsolutePath());\n\n try\n {\n if (fc.getFileFilter().equals(pngFilter))\n return IndexedImage.fromIndexedPngFile(path);\n else if (fc.getFileFilter().equals(ncgrFilter))\n return IndexedImage.fromFile(path, 0, 0, 1, 1, true); //todo revisit if implementing DP support\n else\n return Palette.fromFile(path, 4);\n }\n catch(IOException e) {\n JOptionPane.showMessageDialog(null, \"A fatal error occurred while writing an indexed PNG to disk. See command-line for details.\", \"Error\", JOptionPane.ERROR_MESSAGE);\n throw new RuntimeException(e);\n }\n }\n\n return new GenericNtrFile();\n }\n\n @Override\n public List<JPanel> getPanels()\n {\n return panels;\n }\n\n @Override\n public boolean hasUnsavedChanges()\n {\n //todo\n return false;\n }\n\n @Override\n public void doInfoButtonAction(ActionEvent actionEvent)\n {\n //todo\n JOptionPane.showMessageDialog(null, \"Not yet implemented\", \"Sorry\", JOptionPane.ERROR_MESSAGE);\n }\n\n private static final FileFilter pngFilter = new FileFilter() {\n @Override\n public boolean accept(File f)\n {\n return f.isDirectory() || f.getName().endsWith(\".png\");\n }\n\n @Override\n public String getDescription()\n {\n return \"Portable Network Graphics file (*.png)\";\n }\n };\n\n private static final FileFilter ncgrFilter = new FileFilter()\n {\n @Override\n public boolean accept(File f)\n {\n return f.isDirectory() || f.getName().endsWith(\".NCGR\");\n }\n\n @Override\n public String getDescription()\n {\n return \"Nitro Character Graphics Resource (*.NCGR)\";\n }\n };\n\n private static final FileFilter nclrFilter = new FileFilter()\n {\n @Override\n public boolean accept(File f)\n {\n return f.isDirectory() || f.getName().endsWith(\".NCLR\");\n }\n\n @Override\n public String getDescription()\n {\n return \"Nitro Color Resource (*.NCLR)\";\n }\n };\n}" }, { "identifier": "CellTypes", "path": "src/main/java/io/github/turtleisaac/pokeditor/gui/sheets/tables/cells/CellTypes.java", "snippet": "public enum CellTypes\n{\n INTEGER,\n STRING,\n COMBO_BOX,\n COLORED_COMBO_BOX,\n BITFIELD_COMBO_BOX,\n CHECKBOX,\n CUSTOM;\n\n\n public interface CustomCellFunctionSupplier {\n\n TableCellEditor getEditor(String[]... strings);\n TableCellRenderer getRenderer(String[]... strings);\n }\n}" }, { "identifier": "BitfieldComboBoxEditor", "path": "src/main/java/io/github/turtleisaac/pokeditor/gui/sheets/tables/cells/editors/BitfieldComboBoxEditor.java", "snippet": "public class BitfieldComboBoxEditor extends ComboBoxCellEditor\n{\n public BitfieldComboBoxEditor(String[] items)\n {\n super(items);\n }\n\n @Override\n public Object getCellEditorValue()\n {\n int val = comboBox.getSelectedIndex();\n if (val == 0)\n return 0;\n\n return (1 << val - 1);\n }\n\n @Override\n public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column)\n {\n int val = (Integer) value;\n if (val == 0)\n comboBox.setSelectedIndex(0);\n else {\n val = (int) (Math.log(val) / Math.log(2)) + 1;\n comboBox.setSelectedIndex(val);\n }\n\n return comboBox;\n }\n}" }, { "identifier": "CheckBoxEditor", "path": "src/main/java/io/github/turtleisaac/pokeditor/gui/sheets/tables/cells/editors/CheckBoxEditor.java", "snippet": "public class CheckBoxEditor extends AbstractCellEditor implements TableCellEditor\n{\n JPanel panel = new JPanel();\n JCheckBox checkBox;\n\n public CheckBoxEditor()\n {\n super();\n checkBox = new JCheckBox();\n panel.add(checkBox);\n }\n\n @Override\n public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column)\n {\n checkBox.setSelected((Boolean) value);\n return panel;\n }\n\n @Override\n public Object getCellEditorValue()\n {\n return checkBox.isSelected();\n }\n}" }, { "identifier": "ComboBoxCellEditor", "path": "src/main/java/io/github/turtleisaac/pokeditor/gui/sheets/tables/cells/editors/ComboBoxCellEditor.java", "snippet": "public class ComboBoxCellEditor extends AbstractCellEditor implements TableCellEditor\n{\n\n EditorComboBox comboBox;\n\n public ComboBoxCellEditor(String[] items)\n {\n comboBox = new EditorComboBox(items);\n }\n\n public void setItems(String[] items)\n {\n comboBox = new EditorComboBox(items);\n }\n\n @Override\n public Object getCellEditorValue()\n {\n return comboBox.getSelectedIndex();\n }\n\n @Override\n public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column)\n {\n comboBox.setSelectedIndex((Integer) value);\n return comboBox;\n }\n}" }, { "identifier": "NumberOnlyCellEditor", "path": "src/main/java/io/github/turtleisaac/pokeditor/gui/sheets/tables/cells/editors/NumberOnlyCellEditor.java", "snippet": "public class NumberOnlyCellEditor extends AbstractCellEditor implements TableCellEditor\n{\n private final JTextField textField;\n private Object lastValue;\n\n public NumberOnlyCellEditor()\n {\n textField = new JTextField();\n ((AbstractDocument) textField.getDocument()).setDocumentFilter(new DocumentFilter() {\n @Override\n public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException\n {\n fb.insertString(offset, string.replaceAll(\"\\\\D++\", \"\"), attr);\n }\n\n @Override\n public void replace(FilterBypass fb, int off, int len, String str, AttributeSet attr)\n throws BadLocationException {\n fb.replace(off, len, str.replaceAll(\"\\\\D++\", \"\"), attr);\n }\n });\n }\n\n @Override\n public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column)\n {\n lastValue = String.valueOf(value);\n if (value instanceof String)\n textField.setText((String) value);\n else if (value instanceof Integer)\n textField.setText(((Integer) value).toString());\n return textField;\n }\n\n @Override\n public Object getCellEditorValue()\n {\n int val = Integer.parseInt((String) lastValue);\n if (val >= 0 || val <= 255)\n return textField.getText();\n return lastValue;\n }\n}" } ]
import com.formdev.flatlaf.util.SystemInfo; import io.github.turtleisaac.pokeditor.DataManager; import io.github.turtleisaac.pokeditor.formats.GenericFileData; import io.github.turtleisaac.pokeditor.formats.text.TextBankData; import io.github.turtleisaac.pokeditor.gui.PokeditorManager; import io.github.turtleisaac.pokeditor.gui.sheets.tables.cells.CellTypes; import io.github.turtleisaac.pokeditor.gui.sheets.tables.cells.editors.BitfieldComboBoxEditor; import io.github.turtleisaac.pokeditor.gui.sheets.tables.cells.editors.CheckBoxEditor; import io.github.turtleisaac.pokeditor.gui.sheets.tables.cells.editors.ComboBoxCellEditor; import io.github.turtleisaac.pokeditor.gui.sheets.tables.cells.editors.NumberOnlyCellEditor; import io.github.turtleisaac.pokeditor.gui.sheets.tables.cells.renderers.*; import javax.swing.*; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.TableCellEditor; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableColumn; import java.awt.*; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.UnsupportedFlavorException; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.io.IOException; import java.util.*; import java.util.List;
8,292
package io.github.turtleisaac.pokeditor.gui.sheets.tables; public abstract class DefaultTable<G extends GenericFileData, E extends Enum<E>> extends JTable { final CellTypes[] cellTypes; private final int[] widths; private final List<TextBankData> textData; private final FormatModel<G, E> formatModel; private final CellTypes.CustomCellFunctionSupplier customCellSupplier; public DefaultTable(FormatModel<G, E> model, List<TextBankData> textData, int[] widths, CellTypes.CustomCellFunctionSupplier customCellSupplier) { super(model); this.formatModel = model; cellTypes = new CellTypes[getColumnCount()]; for (int i = 0; i < cellTypes.length; i++) { cellTypes[i] = model.getCellType(i); } // cellTypes = Arrays.copyOfRange(cellTypes, getNumFrozenColumns(), cellTypes.length); widths = Arrays.copyOfRange(widths, model.getNumFrozenColumns(), widths.length); // this.cellTypes = cellTypes; this.widths = widths; this.textData = textData; this.customCellSupplier = customCellSupplier; setAutoResizeMode(JTable.AUTO_RESIZE_OFF); setRowMargin(1); getColumnModel().setColumnMargin(1); setShowGrid(true); setGridColor(Color.black); setShowHorizontalLines(true); setShowVerticalLines(true); // setBackground(Color.WHITE); // setForeground(Color.black); loadCellRenderers(obtainTextSources(textData)); MultiLineTableHeaderRenderer renderer = new MultiLineTableHeaderRenderer(); Enumeration<TableColumn> columns = getColumnModel().getColumns(); while (columns.hasMoreElements()) { columns.nextElement().setHeaderRenderer(renderer); } setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); getTableHeader().setReorderingAllowed(false); setDragEnabled(false); setRowSelectionAllowed(true); setColumnSelectionAllowed(true); setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION); InputMap inputMap = getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); PasteAction action = new PasteAction(this); KeyStroke stroke; if (!SystemInfo.isMacOS) { stroke = KeyStroke.getKeyStroke(KeyEvent.VK_V, ActionEvent.CTRL_MASK, false); } else { stroke = KeyStroke.getKeyStroke(KeyEvent.VK_V, ActionEvent.META_MASK, false); } inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_PASTE, 0), action); registerKeyboardAction(action, "Paste", stroke, JComponent.WHEN_FOCUSED); // inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), new AbstractAction() // { // @Override // public void actionPerformed(ActionEvent e) // { // System.out.println("moo"); // editingCanceled(null); // } // }); // inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "cancel"); // addKeyListener(new KeyAdapter() // { // @Override // public void keyPressed(KeyEvent e) // { //// super.keyPressed(e); // if (e.getKeyCode() == KeyEvent.VK_ESCAPE) // clearSelection(); // } // }); setDefaultRenderer(Object.class, new DefaultSheetCellRenderer()); } public abstract Queue<String[]> obtainTextSources(List<TextBankData> textData); public FormatModel<G, E> getFormatModel() { return formatModel; } public abstract Class<G> getDataClass(); // public abstract int getNumFrozenColumns(); public void loadCellRenderers(Queue<String[]> textSources) { TableCellEditor customEditor = null; TableCellRenderer customRenderer = null; for (int i = 0; i < getColumnCount(); i++) { CellTypes c = cellTypes[i]; TableColumn col = getColumnModel().getColumn(i); col.setWidth(widths[i]); col.setPreferredWidth(widths[i]); if (c == CellTypes.CHECKBOX) { col.setCellRenderer(new CheckBoxRenderer()); col.setCellEditor(new CheckBoxEditor()); } else if (c == CellTypes.COMBO_BOX || c == CellTypes.COLORED_COMBO_BOX || c == CellTypes.BITFIELD_COMBO_BOX) { String[] text = getTextFromSource(textSources); if (c != CellTypes.BITFIELD_COMBO_BOX) //normal and colored col.setCellEditor(new ComboBoxCellEditor(text)); else // bitfield combo box
package io.github.turtleisaac.pokeditor.gui.sheets.tables; public abstract class DefaultTable<G extends GenericFileData, E extends Enum<E>> extends JTable { final CellTypes[] cellTypes; private final int[] widths; private final List<TextBankData> textData; private final FormatModel<G, E> formatModel; private final CellTypes.CustomCellFunctionSupplier customCellSupplier; public DefaultTable(FormatModel<G, E> model, List<TextBankData> textData, int[] widths, CellTypes.CustomCellFunctionSupplier customCellSupplier) { super(model); this.formatModel = model; cellTypes = new CellTypes[getColumnCount()]; for (int i = 0; i < cellTypes.length; i++) { cellTypes[i] = model.getCellType(i); } // cellTypes = Arrays.copyOfRange(cellTypes, getNumFrozenColumns(), cellTypes.length); widths = Arrays.copyOfRange(widths, model.getNumFrozenColumns(), widths.length); // this.cellTypes = cellTypes; this.widths = widths; this.textData = textData; this.customCellSupplier = customCellSupplier; setAutoResizeMode(JTable.AUTO_RESIZE_OFF); setRowMargin(1); getColumnModel().setColumnMargin(1); setShowGrid(true); setGridColor(Color.black); setShowHorizontalLines(true); setShowVerticalLines(true); // setBackground(Color.WHITE); // setForeground(Color.black); loadCellRenderers(obtainTextSources(textData)); MultiLineTableHeaderRenderer renderer = new MultiLineTableHeaderRenderer(); Enumeration<TableColumn> columns = getColumnModel().getColumns(); while (columns.hasMoreElements()) { columns.nextElement().setHeaderRenderer(renderer); } setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); getTableHeader().setReorderingAllowed(false); setDragEnabled(false); setRowSelectionAllowed(true); setColumnSelectionAllowed(true); setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION); InputMap inputMap = getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); PasteAction action = new PasteAction(this); KeyStroke stroke; if (!SystemInfo.isMacOS) { stroke = KeyStroke.getKeyStroke(KeyEvent.VK_V, ActionEvent.CTRL_MASK, false); } else { stroke = KeyStroke.getKeyStroke(KeyEvent.VK_V, ActionEvent.META_MASK, false); } inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_PASTE, 0), action); registerKeyboardAction(action, "Paste", stroke, JComponent.WHEN_FOCUSED); // inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), new AbstractAction() // { // @Override // public void actionPerformed(ActionEvent e) // { // System.out.println("moo"); // editingCanceled(null); // } // }); // inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "cancel"); // addKeyListener(new KeyAdapter() // { // @Override // public void keyPressed(KeyEvent e) // { //// super.keyPressed(e); // if (e.getKeyCode() == KeyEvent.VK_ESCAPE) // clearSelection(); // } // }); setDefaultRenderer(Object.class, new DefaultSheetCellRenderer()); } public abstract Queue<String[]> obtainTextSources(List<TextBankData> textData); public FormatModel<G, E> getFormatModel() { return formatModel; } public abstract Class<G> getDataClass(); // public abstract int getNumFrozenColumns(); public void loadCellRenderers(Queue<String[]> textSources) { TableCellEditor customEditor = null; TableCellRenderer customRenderer = null; for (int i = 0; i < getColumnCount(); i++) { CellTypes c = cellTypes[i]; TableColumn col = getColumnModel().getColumn(i); col.setWidth(widths[i]); col.setPreferredWidth(widths[i]); if (c == CellTypes.CHECKBOX) { col.setCellRenderer(new CheckBoxRenderer()); col.setCellEditor(new CheckBoxEditor()); } else if (c == CellTypes.COMBO_BOX || c == CellTypes.COLORED_COMBO_BOX || c == CellTypes.BITFIELD_COMBO_BOX) { String[] text = getTextFromSource(textSources); if (c != CellTypes.BITFIELD_COMBO_BOX) //normal and colored col.setCellEditor(new ComboBoxCellEditor(text)); else // bitfield combo box
col.setCellEditor(new BitfieldComboBoxEditor(text));
3
2023-10-15 05:00:57+00:00
12k
eclipse-egit/egit
org.eclipse.egit.ui.test/src/org/eclipse/egit/ui/internal/synchronize/model/GitModelCacheTest.java
[ { "identifier": "RepositoryUtil", "path": "org.eclipse.egit.core/src/org/eclipse/egit/core/RepositoryUtil.java", "snippet": "public enum RepositoryUtil {\n\n\t/**\n\t * The singleton {@link RepositoryUtil} instance.\n\t */\n\tINSTANCE;\n\n\t/**\n\t * The preferences to store the absolute paths of all repositories shown in\n\t * the Git Repositories view\n\t *\n\t * @deprecated maintained to ensure compatibility for old EGit versions\n\t */\n\t@Deprecated\n\tpublic static final String PREFS_DIRECTORIES = \"GitRepositoriesView.GitDirectories\"; //$NON-NLS-1$\n\n\t/**\n\t * The preferences to store paths of all repositories shown in the Git\n\t * Repositories view. For repositories located in the Eclipse workspace\n\t * store the relative path to the workspace root to enable moving and\n\t * copying the workspace. For repositories outside the Eclipse workspace\n\t * store their absolute path.\n\t */\n\tpublic static final String PREFS_DIRECTORIES_REL = \"GitRepositoriesView.GitDirectories.relative\"; //$NON-NLS-1$\n\n\tprivate final Map<String, Map<String, String>> commitMappingCache = new HashMap<>();\n\n\tprivate final Map<String, String> repositoryNameCache = new HashMap<>();\n\n\tprivate final IEclipsePreferences prefs = InstanceScope.INSTANCE\n\t\t\t.getNode(Activator.PLUGIN_ID);\n\n\tprivate final java.nio.file.Path workspacePath;\n\n\tprivate RepositoryUtil() {\n\t\tworkspacePath = ResourcesPlugin.getWorkspace().getRoot().getLocation()\n\t\t\t\t.toFile().toPath();\n\t}\n\n\tvoid clear() {\n\t\tcommitMappingCache.clear();\n\t\trepositoryNameCache.clear();\n\t}\n\n\t/**\n\t * @return The default repository directory as configured in the\n\t * preferences, with variables substituted. Returns workspace\n\t * location if there was an error during substitution.\n\t */\n\t@NonNull\n\tpublic static String getDefaultRepositoryDir() {\n\t\tString key = GitCorePreferences.core_defaultRepositoryDir;\n\t\tString dir = migrateRepoRootPreference();\n\t\tIEclipsePreferences p = InstanceScope.INSTANCE\n\t\t\t\t.getNode(Activator.PLUGIN_ID);\n\t\tif (dir == null) {\n\t\t\tdir = Platform.getPreferencesService().getString(\n\t\t\t\t\tActivator.PLUGIN_ID, key, getDefaultDefaultRepositoryDir(),\n\t\t\t\t\tnull);\n\t\t} else {\n\t\t\tp.put(key, dir);\n\t\t}\n\t\tIStringVariableManager manager = VariablesPlugin.getDefault()\n\t\t\t\t.getStringVariableManager();\n\t\tString result;\n\t\ttry {\n\t\t\tresult = manager.performStringSubstitution(dir);\n\t\t} catch (CoreException e) {\n\t\t\tresult = \"\"; //$NON-NLS-1$\n\t\t}\n\t\tif (result == null || result.isEmpty()) {\n\t\t\tresult = ResourcesPlugin.getWorkspace().getRoot().getRawLocation()\n\t\t\t\t\t.toOSString();\n\t\t}\n\t\treturn FileUtils.canonicalize(new File(result)).toString();\n\t}\n\n\t@NonNull\n\tstatic String getDefaultDefaultRepositoryDir() {\n\t\treturn new File(FS.DETECTED.userHome(), \"git\").getPath(); //$NON-NLS-1$\n\t}\n\n\t/**\n\t * Prior to 4.1 the preference was hosted in the UI plugin. So if this one\n\t * exists, we remove it from there and return. Otherwise null is returned.\n\t *\n\t * @return previously existing UI preference or null\n\t */\n\t@Nullable\n\tprivate static String migrateRepoRootPreference() {\n\t\tIEclipsePreferences p = InstanceScope.INSTANCE\n\t\t\t\t.getNode(\"org.eclipse.egit.ui\"); //$NON-NLS-1$\n\t\tString deprecatedUiKey = \"default_repository_dir\"; //$NON-NLS-1$\n\t\tString value = p.get(deprecatedUiKey, null);\n\t\tif (value != null && value.isEmpty()) {\n\t\t\tvalue = null;\n\t\t}\n\t\tif (value != null) {\n\t\t\tp.remove(deprecatedUiKey);\n\t\t}\n\t\treturn value;\n\t}\n\n\t/**\n\t * Get the configured default branch name configured with git option\n\t * init.defaultBranch. Default is {@code master}.\n\t *\n\t * @return the configured default branch name configured with git option\n\t * init.defaultBranch\n\t * @throws ConfigInvalidException\n\t * if global or system wide configuration is invalid\n\t * @throws IOException\n\t * if an IO error occurred when reading git configurations\n\t */\n\tpublic static String getDefaultBranchName()\n\t\t\tthrows ConfigInvalidException, IOException {\n\t\treturn SystemReader.getInstance().getUserConfig().getString(\n\t\t\t\tConfigConstants.CONFIG_INIT_SECTION, null,\n\t\t\t\tConfigConstants.CONFIG_KEY_DEFAULT_BRANCH);\n\t}\n\n\t/**\n\t * Reads a reflog (in reverse), returning an empty list and logging\n\t * exceptions if the reflog cannot be parsed.\n\t *\n\t * @param repository\n\t * to read a reflog from\n\t * @param refName\n\t * identifying the reflog\n\t * @return the entries of the reflog\n\t * @throws IOException\n\t * if the reflog file itself cannot be read\n\t */\n\tpublic static List<ReflogEntry> safeReadReflog(Repository repository,\n\t\t\tString refName) throws IOException {\n\t\tReflogReader reflogReader = repository.getReflogReader(refName);\n\t\tif (reflogReader != null) {\n\t\t\ttry {\n\t\t\t\treturn reflogReader.getReverseEntries();\n\t\t\t} catch (RuntimeException e) {\n\t\t\t\tActivator.logError(MessageFormat.format(\n\t\t\t\t\t\tCoreText.RepositoryUtil_ReflogCorrupted, refName,\n\t\t\t\t\t\trepository.getDirectory()), e);\n\t\t\t}\n\t\t}\n\t\treturn Collections.emptyList();\n\t}\n\n\t/**\n\t * Tries to map a commit to a symbolic reference.\n\t * <p>\n\t * This value will be cached for the given commit ID unless refresh is\n\t * specified. The return value will be the full name, e.g.\n\t * \"refs/remotes/someBranch\", \"refs/tags/v.1.0\"\n\t * <p>\n\t * Since this mapping is not unique, the following precedence rules are\n\t * used:\n\t * <ul>\n\t * <li>Tags take precedence over branches</li>\n\t * <li>Local branches take preference over remote branches</li>\n\t * <li>Newer references take precedence over older ones where time stamps\n\t * are available. Use committer time stamp from commit if no stamp can be\n\t * found on the tag</li>\n\t * <li>If there are still ambiguities, the reference name with the highest\n\t * lexicographic value will be returned</li>\n\t * </ul>\n\t *\n\t * @param repository\n\t * the {@link Repository}\n\t * @param commitId\n\t * a commit\n\t * @param refresh\n\t * if true, the cache will be invalidated\n\t * @return the symbolic reference, or <code>null</code> if no such reference\n\t * can be found\n\t */\n\tpublic String mapCommitToRef(Repository repository, String commitId,\n\t\t\tboolean refresh) {\n\t\tsynchronized (commitMappingCache) {\n\n\t\t\tif (!ObjectId.isId(commitId)) {\n\t\t\t\treturn null;\n\t\t\t}\n\n\t\t\ttry {\n\t\t\t\tList<ReflogEntry> lastEntry = safeReadReflog(repository,\n\t\t\t\t\t\tConstants.HEAD);\n\t\t\t\tfor (ReflogEntry entry : lastEntry) {\n\t\t\t\t\tif (entry.getNewId().name().equals(commitId)) {\n\t\t\t\t\t\tCheckoutEntry checkoutEntry = entry.parseCheckout();\n\t\t\t\t\t\tif (checkoutEntry != null) {\n\t\t\t\t\t\t\tRef ref = repository\n\t\t\t\t\t\t\t\t\t.findRef(checkoutEntry.getToBranch());\n\t\t\t\t\t\t\tif (ref != null) {\n\t\t\t\t\t\t\t\tObjectId objectId = ref.getObjectId();\n\t\t\t\t\t\t\t\tif (objectId != null && objectId.getName()\n\t\t\t\t\t\t\t\t\t\t.equals(commitId)) {\n\t\t\t\t\t\t\t\t\treturn checkoutEntry.getToBranch();\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tref = repository.getRefDatabase().peel(ref);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif (ref != null) {\n\t\t\t\t\t\t\t\tObjectId id = ref.getPeeledObjectId();\n\t\t\t\t\t\t\t\tif (id != null\n\t\t\t\t\t\t\t\t\t\t&& id.getName().equals(commitId)) {\n\t\t\t\t\t\t\t\t\treturn checkoutEntry.getToBranch();\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} catch (IOException e) {\n\t\t\t\t// ignore here\n\t\t\t}\n\n\t\t\tMap<String, String> cacheEntry = commitMappingCache.get(repository\n\t\t\t\t\t.getDirectory().toString());\n\t\t\tif (!refresh && cacheEntry != null\n\t\t\t\t\t&& cacheEntry.containsKey(commitId)) {\n\t\t\t\t// this may be null in fact\n\t\t\t\treturn cacheEntry.get(commitId);\n\t\t\t}\n\t\t\tif (cacheEntry == null) {\n\t\t\t\tcacheEntry = new HashMap<>();\n\t\t\t\tcommitMappingCache.put(repository.getDirectory().getPath(),\n\t\t\t\t\t\tcacheEntry);\n\t\t\t} else {\n\t\t\t\tcacheEntry.clear();\n\t\t\t}\n\n\t\t\tMap<String, Date> tagMap = new HashMap<>();\n\t\t\ttry (RevWalk rw = new RevWalk(repository)) {\n\t\t\t\tList<Ref> tags = repository.getRefDatabase().getRefsByPrefix(\n\t\t\t\t\t\tConstants.R_TAGS);\n\t\t\t\tfor (Ref tagRef : tags) {\n\t\t\t\t\tObjectId id = tagRef.getLeaf().getObjectId();\n\t\t\t\t\tif (id == null) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tRevObject any = rw.parseAny(id);\n\t\t\t\t\tif (any instanceof RevTag) {\n\t\t\t\t\t\tRevTag tag = (RevTag) any;\n\t\t\t\t\t\tif (tag.getObject().name().equals(commitId)) {\n\t\t\t\t\t\t\tDate timestamp;\n\t\t\t\t\t\t\tif (tag.getTaggerIdent() != null) {\n\t\t\t\t\t\t\t\ttimestamp = tag.getTaggerIdent().getWhen();\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\tRevCommit commit = rw.parseCommit(tag.getObject());\n\t\t\t\t\t\t\t\t\ttimestamp = commit.getCommitterIdent().getWhen();\n\t\t\t\t\t\t\t\t} catch (IncorrectObjectTypeException e) {\n\t\t\t\t\t\t\t\t\t// not referencing a commit\n\t\t\t\t\t\t\t\t\ttimestamp = null;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\ttagMap.put(tagRef.getName(), timestamp);\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (any instanceof RevCommit) {\n\t\t\t\t\t\tRevCommit commit = ((RevCommit)any);\n\t\t\t\t\t\tif (commit.name().equals(commitId))\n\t\t\t\t\t\t\ttagMap.put(tagRef.getName(), commit.getCommitterIdent().getWhen());\n\t\t\t\t\t} // else ignore here\n\t\t\t\t}\n\t\t\t} catch (IOException e) {\n\t\t\t\t// ignore here\n\t\t\t}\n\n\t\t\tString cacheValue = null;\n\n\t\t\tif (!tagMap.isEmpty()) {\n\t\t\t\t// we try to obtain the \"latest\" tag\n\t\t\t\tDate compareDate = new Date(0);\n\t\t\t\tfor (Map.Entry<String, Date> tagEntry : tagMap.entrySet()) {\n\t\t\t\t\tif (tagEntry.getValue() != null\n\t\t\t\t\t\t\t&& tagEntry.getValue().after(compareDate)) {\n\t\t\t\t\t\tcompareDate = tagEntry.getValue();\n\t\t\t\t\t\tcacheValue = tagEntry.getKey();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// if we don't have time stamps, we sort\n\t\t\t\tif (cacheValue == null) {\n\t\t\t\t\tfor (String tagName : tagMap.keySet()) {\n\t\t\t\t\t\tif (cacheValue == null\n\t\t\t\t\t\t\t\t|| cacheValue.compareTo(tagName) < 0) {\n\t\t\t\t\t\t\tcacheValue = tagName;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (cacheValue == null) {\n\t\t\t\t// we didnt't find a tag, so let's look for local branches\n\t\t\t\ttry {\n\t\t\t\t\tcacheValue = lastRefNameForCommitId(repository,\n\t\t\t\t\t\t\tConstants.R_HEADS, commitId);\n\t\t\t\t} catch (IOException e) {\n\t\t\t\t\t// ignore here\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (cacheValue == null) {\n\t\t\t\t// last try: remote branches\n\t\t\t\ttry {\n\t\t\t\t\tcacheValue = lastRefNameForCommitId(repository,\n\t\t\t\t\t\t\tConstants.R_REMOTES, commitId);\n\t\t\t\t} catch (IOException e) {\n\t\t\t\t\t// ignore here\n\t\t\t\t}\n\t\t\t}\n\t\t\tcacheEntry.put(commitId, cacheValue);\n\t\t\treturn cacheValue;\n\t\t}\n\t}\n\n\tprivate String lastRefNameForCommitId(Repository repository,\n\t\t\tString refPrefix, String commitId) throws IOException {\n\t\tString result = null;\n\t\tfor (Ref ref : repository.getRefDatabase().getRefsByPrefix(refPrefix)) {\n\t\t\tObjectId objectId = ref.getObjectId();\n\t\t\tif (objectId != null && objectId.name().equals(commitId)) {\n\t\t\t\tif (result == null || result.compareTo(ref.getName()) < 0) {\n\t\t\t\t\tresult = ref.getName();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\n\t/**\n\t * Return a cached UI \"name\" for a Repository\n\t * <p>\n\t * This uses the name of the working directory. In case of a bare\n\t * repository, the repository directory name is used.\n\t *\n\t * @param repository\n\t * @return the name\n\t */\n\tpublic String getRepositoryName(final Repository repository) {\n\t\tFile dir;\n\t\t// Use working directory name for non-bare repositories\n\t\tif (!repository.isBare())\n\t\t\tdir = repository.getWorkTree();\n\t\telse\n\t\t\tdir = repository.getDirectory();\n\n\t\tif (dir == null)\n\t\t\treturn \"\"; //$NON-NLS-1$\n\n\t\tsynchronized (repositoryNameCache) {\n\t\t\tfinal String path = dir.getPath();\n\t\t\tString name = repositoryNameCache.get(path);\n\t\t\tif (name != null)\n\t\t\t\treturn name;\n\t\t\tname = dir.getName();\n\t\t\trepositoryNameCache.put(path, name);\n\t\t\treturn name;\n\t\t}\n\t}\n\n\t/**\n\t * Get the repository specific preference key for the given preference key\n\t * and repository.\n\t *\n\t * @param repositoryId\n\t * The id of the repository to get the key for\n\t * @param preferenceKey\n\t * The preference key to get the repository specific one for\n\t * @return The repository specific key\n\t */\n\tpublic String getRepositorySpecificPreferenceKey(String repositoryId,\n\t\t\tString preferenceKey) {\n\t\treturn preferenceKey + \"_\" + repositoryId; //$NON-NLS-1$\n\t}\n\n\t/**\n\t * Get the repository specific preference key for the given preference key\n\t * and repository.\n\t *\n\t * @param repository\n\t * The repository to get the key for\n\t * @param preferenceKey\n\t * The preference key to get the repository specific one for\n\t * @return The repository specific key\n\t */\n\tpublic String getRepositorySpecificPreferenceKey(\n\t\t\t@NonNull Repository repository, String preferenceKey) {\n\t\tString pathString = getRelativizedRepositoryPath(repository);\n\n\t\tif (pathString == null) {\n\t\t\treturn getRepositorySpecificPreferenceKey(repository.toString(),\n\t\t\t\t\tpreferenceKey);\n\t\t}\n\n\t\treturn getRepositorySpecificPreferenceKey(pathString, preferenceKey);\n\t}\n\n\t/**\n\t * @return the underlying preferences\n\t */\n\tpublic IEclipsePreferences getPreferences() {\n\t\treturn prefs;\n\t}\n\n\t/**\n\t * Get the set of absolute path strings of all configured repositories.\n\t *\n\t * @return set of absolute paths of all configured repositories' .git\n\t * directories\n\t *\n\t * @since 4.2\n\t */\n\t@NonNull\n\tpublic Set<String> getRepositories() {\n\t\tString dirString;\n\t\tSet<String> dirs;\n\t\tsynchronized (prefs) {\n\t\t\tdirString = prefs.get(PREFS_DIRECTORIES_REL, \"\"); //$NON-NLS-1$\n\t\t\tif (dirString.isEmpty()) {\n\t\t\t\tdirs = migrateAbsolutePaths();\n\t\t\t} else {\n\t\t\t\tdirs = toDirSet(dirString);\n\t\t\t}\n\t\t}\n\t\treturn dirs;\n\t}\n\n\t/**\n\t * Migrate set of absolute paths created by an older version of EGit to the\n\t * new format using relative paths for repositories located under the\n\t * Eclipse workspace\n\t *\n\t * @return set of absolute paths of all configured git repositories\n\t */\n\tprivate Set<String> migrateAbsolutePaths() {\n\t\tString dirString;\n\t\tSet<String> dirs;\n\t\tdirString = prefs.get(PREFS_DIRECTORIES, \"\"); //$NON-NLS-1$\n\t\tdirs = toDirSet(dirString);\n\t\t// save migrated list\n\t\tsaveDirs(dirs);\n\t\treturn dirs;\n\t}\n\n\t/**\n\t * @param dirs\n\t * String with repository directories separated by path separator\n\t * @return set of absolute paths of repository directories, relative paths\n\t * are resolved against the workspace root\n\t */\n\tprivate Set<String> toDirSet(String dirs) {\n\t\tif (dirs == null || dirs.isEmpty()) {\n\t\t\treturn Collections.emptySet();\n\t\t}\n\t\tSet<String> configuredStrings = new HashSet<>();\n\t\tStringTokenizer tok = new StringTokenizer(dirs, File.pathSeparator);\n\t\twhile (tok.hasMoreTokens()) {\n\t\t\tconfiguredStrings.add(getAbsoluteRepositoryPath(tok.nextToken()));\n\t\t}\n\t\treturn configuredStrings;\n\t}\n\n\t/**\n\t *\n\t * @return the list of configured Repository paths; will be sorted\n\t */\n\tpublic List<String> getConfiguredRepositories() {\n\t\tfinal List<String> repos = new ArrayList<>(getRepositories());\n\t\tCollections.sort(repos);\n\t\treturn repos;\n\t}\n\n\t/**\n\t *\n\t * @param repositoryDir\n\t * the Repository path\n\t * @return <code>true</code> if the repository path was not yet configured\n\t * @throws IllegalArgumentException\n\t * if the path does not \"look\" like a Repository\n\t */\n\tpublic boolean addConfiguredRepository(File repositoryDir)\n\t\t\tthrows IllegalArgumentException {\n\t\tsynchronized (prefs) {\n\n\t\t\tif (!FileKey.isGitRepository(repositoryDir, FS.DETECTED))\n\t\t\t\tthrow new IllegalArgumentException(MessageFormat.format(\n\t\t\t\t\t\tCoreText.RepositoryUtil_DirectoryIsNotGitDirectory,\n\t\t\t\t\t\trepositoryDir));\n\n\t\t\tString dirString = repositoryDir.getAbsolutePath();\n\n\t\t\tList<String> dirStrings = getConfiguredRepositories();\n\t\t\tif (dirStrings.contains(dirString)) {\n\t\t\t\treturn false;\n\t\t\t} else {\n\t\t\t\tSet<String> dirs = new HashSet<>();\n\t\t\t\tdirs.addAll(dirStrings);\n\t\t\t\tdirs.add(dirString);\n\t\t\t\tsaveDirs(dirs);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * @param file\n\t * @return <code>true</code> if the configuration was changed by the remove\n\t */\n\tpublic boolean removeDir(File file) {\n\t\tsynchronized (prefs) {\n\t\t\tString dirString = file.getAbsolutePath();\n\t\t\tSet<String> dirStrings = new HashSet<>();\n\t\t\tdirStrings.addAll(getConfiguredRepositories());\n\t\t\tif (dirStrings.remove(dirString)) {\n\t\t\t\tsaveDirs(dirStrings);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tprivate void saveDirs(Set<String> gitDirStrings) {\n\t\tStringBuilder sbRelative = new StringBuilder();\n\t\tStringBuilder sbAbsolute = new StringBuilder();\n\t\tfor (String gitDirString : gitDirStrings) {\n\t\t\tsbRelative.append(relativizeToWorkspace(gitDirString));\n\t\t\tsbRelative.append(File.pathSeparatorChar);\n\t\t\tsbAbsolute.append(gitDirString);\n\t\t\tsbAbsolute.append(File.pathSeparatorChar);\n\t\t}\n\n\t\t// redundantly store absolute paths to ensure compatibility with older\n\t\t// EGit versions\n\t\tprefs.put(PREFS_DIRECTORIES, sbAbsolute.toString());\n\t\tprefs.put(PREFS_DIRECTORIES_REL, sbRelative.toString());\n\t\ttry {\n\t\t\tprefs.flush();\n\t\t} catch (BackingStoreException e) {\n\t\t\tActivator.logError(e.getMessage(), e);\n\t\t}\n\t}\n\n\t/**\n\t * Relativize the given absolute path.\n\t * <p>\n\t * The result is the path of {@code pathString} relative to the workspace\n\t * root if the given {@code pathString} is under the workspace root,\n\t * otherwise the absolute path {@code pathString}.\n\t * </p>\n\t * <p>\n\t * This enables moving or copying the workspace, when saving this path and\n\t * later resolving it relative to the workspace path\n\t * ({@link #getAbsoluteRepositoryPath}).\n\t * </p>\n\t * <p>\n\t * It is required, that the given pathString is absolute\n\t * </p>\n\t *\n\t * @param pathString\n\t * an absolute path String. Must be absolute.\n\t * @return the relativized path String\n\t * @throws java.nio.file.InvalidPathException\n\t * if the path string cannot be converted to a Path\n\t */\n\tpublic @NonNull String relativizeToWorkspace(@NonNull String pathString) {\n\t\tjava.nio.file.Path p = java.nio.file.Paths.get(pathString);\n\t\tif (p.startsWith(workspacePath)) {\n\t\t\treturn workspacePath.relativize(p).toString();\n\t\t} else {\n\t\t\treturn pathString;\n\t\t}\n\t}\n\n\t/**\n\t * Get the relativized path of the given repository.\n\t * <p>\n\t * If the repository is not local this method will return null.\n\t * </p>\n\t *\n\t * @param repository\n\t * The repository to get the path String of\n\t * @return the relativized path String\n\t * @see #relativizeToWorkspace(String)\n\t */\n\t@Nullable\n\tpublic String getRelativizedRepositoryPath(\n\t\t\tfinal @NonNull Repository repository) {\n\t\tFile dir = repository.getDirectory();\n\t\tif (dir == null) {\n\t\t\treturn null;\n\t\t}\n\t\treturn relativizeToWorkspace(dir.getAbsolutePath());\n\t}\n\n\t/**\n\t * Make a potentially relative path absolute.\n\t * <p>\n\t * The result is the absolute path of {@code pathString} resolved against\n\t * the workspace root.\n\t * This allows retrieving a path saved using {@link #relativizeToWorkspace}.\n\t * </p>\n\t *\n\t * @param pathString\n\t * a potentially workspace relative path String.\n\t * @return the absolute path String\n\t * @throws java.nio.file.InvalidPathException\n\t * if the path string cannot be converted to a Path\n\t */\n\tpublic @NonNull String getAbsoluteRepositoryPath(\n\t\t\t@NonNull String pathString) {\n\t\treturn workspacePath.resolve(pathString).toString();\n\t}\n\n\t/**\n\t * Does the collection of repository returned by\n\t * {@link #getConfiguredRepositories()} contain the given repository?\n\t *\n\t * @param repository\n\t * @return true if contains repository, false otherwise\n\t */\n\tpublic boolean contains(final Repository repository) {\n\t\treturn contains(repository.getDirectory().getAbsolutePath());\n\t}\n\n\t/**\n\t * Does the collection of repository returned by\n\t * {@link #getConfiguredRepositories()} contain the given repository\n\t * directory?\n\t *\n\t * @param repositoryDir\n\t * @return true if contains repository directory, false otherwise\n\t */\n\tpublic boolean contains(final String repositoryDir) {\n\t\treturn getRepositories().contains(repositoryDir);\n\t}\n\n\t/**\n\t * Get short branch text for given repository\n\t *\n\t * @param repository\n\t * @return short branch text\n\t * @throws IOException\n\t */\n\tpublic String getShortBranch(Repository repository) throws IOException {\n\t\tRef head = repository.exactRef(Constants.HEAD);\n\t\tif (head == null) {\n\t\t\treturn CoreText.RepositoryUtil_noHead;\n\t\t}\n\t\tif (head.isSymbolic()) {\n\t\t\treturn repository.getBranch();\n\t\t}\n\t\tObjectId objectId = head.getObjectId();\n\t\tif (objectId == null) {\n\t\t\treturn CoreText.RepositoryUtil_noHead;\n\t\t}\n\t\tString id = objectId.name();\n\t\tString ref = mapCommitToRef(repository, id, false);\n\t\tif (ref != null) {\n\t\t\treturn Repository.shortenRefName(ref) + ' ' + id.substring(0, 7);\n\t\t} else {\n\t\t\treturn id.substring(0, 7);\n\t\t}\n\t}\n\n\t/**\n\t * Resolve HEAD and parse the commit. Returns null if HEAD does not exist or\n\t * could not be parsed.\n\t * <p>\n\t * Only use this if you don't already have to work with a RevWalk.\n\t *\n\t * @param repository\n\t * @return the commit or null if HEAD does not exist or could not be parsed.\n\t * @since 2.2\n\t */\n\tpublic RevCommit parseHeadCommit(Repository repository) {\n\t\ttry (RevWalk walk = new RevWalk(repository)) {\n\t\t\tRef head = repository.exactRef(Constants.HEAD);\n\t\t\tif (head == null || head.getObjectId() == null)\n\t\t\t\treturn null;\n\n\t\t\tRevCommit commit = walk.parseCommit(head.getObjectId());\n\t\t\treturn commit;\n\t\t} catch (IOException e) {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\t/**\n\t * Checks if existing resource with given path is to be ignored.\n\t * <p>\n\t * <b>Note:</b>The check makes sense only for files which exists in the\n\t * working directory. This method returns false for paths to not existing\n\t * files or directories.\n\t *\n\t * @param path\n\t * Path to be checked, file or directory must exist on the disk\n\t * @return true if the path is either not inside git repository or exists\n\t * and matches an ignore rule\n\t * @throws IOException\n\t * @since 2.3\n\t */\n\tpublic static boolean isIgnored(IPath path) throws IOException {\n\t\tRepositoryMapping mapping = RepositoryMapping.getMapping(path);\n\t\tif (mapping == null) {\n\t\t\treturn true; // Linked resources may not be mapped\n\t\t}\n\t\tRepository repository = mapping.getRepository();\n\t\tWorkingTreeIterator treeIterator = IteratorService\n\t\t\t\t.createInitialIterator(repository);\n\t\tif (treeIterator == null) {\n\t\t\treturn true;\n\t\t}\n\t\tString repoRelativePath = mapping.getRepoRelativePath(path);\n\t\tif (repoRelativePath == null || repoRelativePath.isEmpty()) {\n\t\t\treturn true;\n\t\t}\n\t\ttry (TreeWalk walk = new TreeWalk(repository)) {\n\t\t\twalk.addTree(treeIterator);\n\t\t\twalk.setFilter(PathFilterGroup.createFromStrings(repoRelativePath));\n\t\t\twhile (walk.next()) {\n\t\t\t\tWorkingTreeIterator workingTreeIterator = walk.getTree(0,\n\t\t\t\t\t\tWorkingTreeIterator.class);\n\t\t\t\tif (walk.getPathString().equals(repoRelativePath)) {\n\t\t\t\t\treturn workingTreeIterator.isEntryIgnored();\n\t\t\t\t}\n\t\t\t\tif (workingTreeIterator.getEntryFileMode()\n\t\t\t\t\t\t.equals(FileMode.TREE)) {\n\t\t\t\t\twalk.enterSubtree();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\n\t/**\n\t * Checks if the existing resource with given path can be automatically\n\t * added to the .gitignore file.\n\t *\n\t * @param path\n\t * Path to be checked, file or directory must exist on the disk\n\t * @return true if the file or directory at given path exists, is inside\n\t * known git repository and does not match any existing ignore rule,\n\t * false otherwise\n\t * @throws IOException\n\t * @since 4.1.0\n\t */\n\tpublic static boolean canBeAutoIgnored(IPath path) throws IOException {\n\t\tRepository repository = RepositoryCache.INSTANCE.getRepository(path);\n\t\tif (repository == null || repository.isBare()) {\n\t\t\treturn false;\n\t\t}\n\t\tWorkingTreeIterator treeIterator = IteratorService\n\t\t\t\t.createInitialIterator(repository);\n\t\tif (treeIterator == null) {\n\t\t\treturn false;\n\t\t}\n\t\tString repoRelativePath = path\n\t\t\t\t.makeRelativeTo(\n\t\t\t\t\t\tnew Path(repository.getWorkTree().getAbsolutePath()))\n\t\t\t\t.toString();\n\t\tif (repoRelativePath.length() == 0\n\t\t\t\t|| repoRelativePath.equals(path.toString())) {\n\t\t\treturn false;\n\t\t}\n\t\ttry (TreeWalk walk = new TreeWalk(repository)) {\n\t\t\twalk.addTree(treeIterator);\n\t\t\twalk.setFilter(PathFilterGroup.createFromStrings(repoRelativePath));\n\t\t\twhile (walk.next()) {\n\t\t\t\tWorkingTreeIterator workingTreeIterator = walk.getTree(0,\n\t\t\t\t\t\tWorkingTreeIterator.class);\n\t\t\t\tif (walk.getPathString().equals(repoRelativePath)) {\n\t\t\t\t\treturn !workingTreeIterator.isEntryIgnored();\n\t\t\t\t}\n\t\t\t\tif (workingTreeIterator.getEntryFileMode()\n\t\t\t\t\t\t.equals(FileMode.TREE)) {\n\t\t\t\t\twalk.enterSubtree();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t// path not found in tree, we should not automatically ignore it\n\t\treturn false;\n\t}\n\n\t/**\n\t * Checks if given repository is in the 'detached HEAD' state.\n\t *\n\t * @param repository\n\t * the repository to check\n\t * @return <code>true</code> if the repository is in the 'detached HEAD'\n\t * state, <code>false</code> if it's not or an error occurred\n\t * @since 3.2\n\t */\n\tpublic static boolean isDetachedHead(Repository repository) {\n\t\ttry {\n\t\t\treturn ObjectId.isId(repository.getFullBranch());\n\t\t} catch (IOException e) {\n\t\t\tActivator.logError(e.getMessage(), e);\n\t\t}\n\t\treturn false;\n\t}\n\n\t/**\n\t * Determines whether the given {@link Repository} has any changes by\n\t * checking the {@link IndexDiffCacheEntry} of the repository.\n\t *\n\t * @param repository\n\t * to check\n\t * @return {@code true} if the repository has any changes, {@code false}\n\t * otherwise\n\t */\n\tpublic static boolean hasChanges(@NonNull Repository repository) {\n\t\tIndexDiffCacheEntry entry = IndexDiffCache.INSTANCE\n\t\t\t\t.getIndexDiffCacheEntry(repository);\n\t\tIndexDiffData data = entry != null ? entry.getIndexDiff() : null;\n\t\treturn data != null && data.hasChanges();\n\t}\n\n\t/**\n\t * Obtains a {@link GarbageCollectCommand} for the given repository.\n\t *\n\t * @param repository\n\t * to garbage collect\n\t * @return the {@link GarbageCollectCommand}\n\t * @throws IllegalStateException\n\t * if the repository cannot be garbage collected\n\t */\n\tpublic static GarbageCollectCommand getGarbageCollectCommand(\n\t\t\t@NonNull Repository repository) {\n\t\ttry (Git git = new Git(toFileRepository(repository))) {\n\t\t\treturn git.gc();\n\t\t}\n\t}\n\n\t@SuppressWarnings(\"restriction\")\n\tprivate static @NonNull Repository toFileRepository(\n\t\t\t@NonNull Repository repository) {\n\t\tRepository toConvert = repository;\n\t\tif (toConvert instanceof RepositoryHandle) {\n\t\t\ttoConvert = ((RepositoryHandle) toConvert).getDelegate();\n\t\t}\n\t\tif (toConvert instanceof org.eclipse.jgit.internal.storage.file.FileRepository) {\n\t\t\treturn toConvert;\n\t\t}\n\t\tthrow new IllegalStateException(\n\t\t\t\t\"Repository is not a FileRepository: \" + repository); //$NON-NLS-1$\n\t}\n}" }, { "identifier": "Change", "path": "org.eclipse.egit.core/src/org/eclipse/egit/core/synchronize/GitCommitsModelCache.java", "snippet": "public static class Change {\n\tint kind;\n\n\tString name;\n\n\tAbbreviatedObjectId objectId;\n\n\tAbbreviatedObjectId commitId;\n\n\tAbbreviatedObjectId remoteCommitId;\n\n\tAbbreviatedObjectId remoteObjectId;\n\n\tChange() {\n\t\t// reduce the visibility of the default constructor\n\t}\n\n\t/**\n\t * Describes if this change is incoming/outgoing addition, deletion or\n\t * change.\n\t *\n\t * It uses static values of LEFT, RIGHT, ADDITION, DELETION, CHANGE from\n\t * org.eclipse.compare.structuremergeviewer.Differencer class.\n\t *\n\t * @return kind\n\t */\n\tpublic int getKind() {\n\t\treturn kind;\n\t}\n\n\t/**\n\t * @return object name\n\t */\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\n\t/**\n\t * @return id of commit containing this change\n\t */\n\tpublic AbbreviatedObjectId getCommitId() {\n\t\treturn commitId;\n\t}\n\n\t/**\n\t * @return id of parent commit\n\t */\n\tpublic AbbreviatedObjectId getRemoteCommitId() {\n\t\treturn remoteCommitId;\n\t}\n\n\t/**\n\t * @return object id\n\t */\n\tpublic AbbreviatedObjectId getObjectId() {\n\t\treturn objectId;\n\t}\n\n\t/**\n\t * @return remote object id\n\t */\n\tpublic AbbreviatedObjectId getRemoteObjectId() {\n\t\treturn remoteObjectId;\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\tfinal int prime = 31;\n\t\tint result = 1;\n\t\tresult = prime * result\n\t\t\t\t+ ((objectId == null) ? 0 : objectId.hashCode());\n\t\tresult = prime\n\t\t\t\t* result\n\t\t\t\t+ ((remoteObjectId == null) ? 0 : remoteObjectId.hashCode());\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\tif (this == obj)\n\t\t\treturn true;\n\t\tif (obj == null)\n\t\t\treturn false;\n\t\tif (getClass() != obj.getClass())\n\t\t\treturn false;\n\t\tChange other = (Change) obj;\n\t\tif (objectId == null) {\n\t\t\tif (other.objectId != null)\n\t\t\t\treturn false;\n\t\t} else if (!objectId.equals(other.objectId))\n\t\t\treturn false;\n\t\tif (remoteObjectId == null) {\n\t\t\tif (other.remoteObjectId != null)\n\t\t\t\treturn false;\n\t\t} else if (!remoteObjectId.equals(other.remoteObjectId))\n\t\t\treturn false;\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\tStringBuilder change = new StringBuilder(\"Change(\"); //$NON-NLS-1$\n\t\tif ((kind & LEFT) != 0)\n\t\t\tchange.append(\"INCOMING \"); //$NON-NLS-1$\n\t\telse\n\t\t\t// should be RIGHT\n\t\t\tchange.append(\"OUTGOING \"); //$NON-NLS-1$\n\t\tint changeType = kind & CHANGE_TYPE_MASK;\n\t\tif (changeType == CHANGE)\n\t\t\tchange.append(\"CHANGE \"); //$NON-NLS-1$\n\t\telse if (changeType == ADDITION)\n\t\t\tchange.append(\"ADDITION \"); //$NON-NLS-1$\n\t\telse if (changeType == DELETION)\n\t\t\tchange.append(\"DELETION \"); //$NON-NLS-1$\n\n\t\tchange.append(name);\n\t\tchange.append(\";\\n\\tcurrent objectId: \"); //$NON-NLS-1$\n\t\tchange.append(getObjectId(objectId));\n\t\tchange.append(\";\\n\\tparent objectId: \"); //$NON-NLS-1$\n\t\tchange.append(getObjectId(remoteObjectId));\n\t\tchange.append(\";\\n\\tcurrent commit: \"); //$NON-NLS-1$\n\t\tchange.append(getObjectId(commitId));\n\t\tchange.append(\";\\n\\tparent commit: \"); //$NON-NLS-1$\n\t\tchange.append(getObjectId(remoteCommitId));\n\t\tchange.append(\"\\n)\"); //$NON-NLS-1$\n\n\t\treturn change.toString();\n\t}\n\n\tprivate String getObjectId(AbbreviatedObjectId object) {\n\t\tif (object != null)\n\t\t\treturn object.toObjectId().getName();\n\t\telse\n\t\t\treturn ObjectId.zeroId().getName();\n\t}\n\n}" }, { "identifier": "StagedChangeCache", "path": "org.eclipse.egit.core/src/org/eclipse/egit/core/synchronize/StagedChangeCache.java", "snippet": "public class StagedChangeCache {\n\n\t/**\n\t * @param repo\n\t * repository which should be scanned\n\t * @return list of changes in git staging area\n\t */\n\tpublic static Map<String, Change> build(Repository repo) {\n\t\ttry (TreeWalk tw = new TreeWalk(repo)) {\n\t\t\ttw.addTree(new DirCacheIterator(repo.readDirCache()));\n\t\t\tObjectId headId = repo.resolve(HEAD);\n\t\t\tRevCommit headCommit = null;\n\t\t\tif (headId != null) {\n\t\t\t\ttry (RevWalk rw = new RevWalk(repo)) {\n\t\t\t\t\theadCommit = rw.parseCommit(headId);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tAbbreviatedObjectId commitId;\n\t\t\tif (headCommit != null) {\n\t\t\t\ttw.addTree(headCommit.getTree());\n\t\t\t\tcommitId = AbbreviatedObjectId.fromObjectId(headCommit);\n\t\t\t} else {\n\t\t\t\ttw.addTree(new EmptyTreeIterator());\n\t\t\t\tcommitId =AbbreviatedObjectId.fromObjectId(zeroId());\n\t\t\t}\n\n\t\t\ttw.setRecursive(true);\n\t\t\theadCommit = null;\n\n\t\t\tMutableObjectId idBuf = new MutableObjectId();\n\t\t\tMap<String, Change> result = new HashMap<>();\n\t\t\twhile(tw.next()) {\n\t\t\t\tif (!shouldIncludeEntry(tw))\n\t\t\t\t\tcontinue;\n\n\t\t\t\tChange change = new Change();\n\t\t\t\tchange.name = tw.getNameString();\n\t\t\t\tchange.remoteCommitId = commitId;\n\n\t\t\t\ttw.getObjectId(idBuf, 0);\n\t\t\t\tchange.objectId = AbbreviatedObjectId.fromObjectId(idBuf);\n\t\t\t\ttw.getObjectId(idBuf, 1);\n\t\t\t\tchange.remoteObjectId = AbbreviatedObjectId.fromObjectId(idBuf);\n\n\t\t\t\tcalculateAndSetChangeKind(RIGHT, change);\n\n\t\t\t\tresult.put(tw.getPathString(), change);\n\t\t\t}\n\n\t\t\treturn result;\n\t\t} catch (IOException e) {\n\t\t\tActivator.logError(e.getMessage(), e);\n\t\t\treturn new HashMap<>(0);\n\t\t}\n\t}\n\n\tprivate static boolean shouldIncludeEntry(TreeWalk tw) {\n\t\tfinal int mHead = tw.getRawMode(1);\n\t\tfinal int mCache = tw.getRawMode(0);\n\n\t\treturn mHead == MISSING.getBits() // initial add to cache\n\t\t\t\t|| mCache == MISSING.getBits() // removed from cache\n\t\t\t\t|| (mHead != mCache || (mCache != TREE.getBits() && !tw\n\t\t\t\t\t\t.idEqual(1, 0))); // modified\n\t}\n\n}" } ]
import static org.eclipse.jgit.junit.JGitTestUtil.writeTrashFile; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import java.io.File; import java.util.Map; import org.eclipse.egit.core.RepositoryUtil; import org.eclipse.egit.core.synchronize.GitCommitsModelCache.Change; import org.eclipse.egit.core.synchronize.StagedChangeCache; import org.eclipse.jgit.api.Git; import org.eclipse.jgit.lib.Repository; import org.junit.Before; import org.junit.Test;
9,973
/******************************************************************************* * Copyright (C) 2011, 2013 Dariusz Luksza <[email protected]> and others. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 * which accompanies this distribution, and is available at * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 *******************************************************************************/ package org.eclipse.egit.ui.internal.synchronize.model; public class GitModelCacheTest extends GitModelTestCase { @Test public void shouldReturnEqualForSameInstance() throws Exception { // given GitModelCache left = new GitModelCache(createModelRepository(), lookupRepository(leftRepoFile), null); // when boolean actual = left.equals(left); // then assertTrue(actual); } @Test public void shouldReturnNotEqualForDifferentRepositories() throws Exception { // given File localRightRepoFile = createProjectAndCommitToRepository(REPO2); GitModelRepository rightGsd = new GitModelRepository( getGSD(lookupRepository(localRightRepoFile))); GitModelCache left = new GitModelCache(createModelRepository(), lookupRepository(leftRepoFile), null); GitModelCache right = new GitModelCache(rightGsd, lookupRepository(leftRepoFile), null); // when boolean actual = left.equals(right); // then assertFalse(actual); } @Test public void shouldReturnEqualForSameCommits() throws Exception { // given GitModelCache left = new GitModelCache(createModelRepository(), lookupRepository(leftRepoFile), null); GitModelCache right = new GitModelCache(createModelRepository(), lookupRepository(leftRepoFile), null); // when boolean actual = left.equals(right); // then assertTrue(actual); } @Test public void shouldReturnNotEqualWhenComparingCacheAndWorkingTree() throws Exception { // given GitModelCache left = new GitModelCache(createModelRepository(), lookupRepository(leftRepoFile), null); GitModelCache right = mock(GitModelWorkingTree.class); // when boolean actual = left.equals(right); // then assertFalse(actual); } @Test public void shouldReturnNotEqualWhenCacheTreeAndCommit() throws Exception { // given GitModelObject left = new GitModelCache(createModelRepository(), lookupRepository(leftRepoFile), null); GitModelObject right = mock(GitModelCommit.class); // when boolean actual = left.equals(right); // then assertFalse(actual); } @Test public void shouldReturnChildren() throws Exception { Repository repo = lookupRepository(leftRepoFile); writeTrashFile(repo, "dir/a.txt", "trash"); writeTrashFile(repo, "dir/b.txt", "trash"); writeTrashFile(repo, "dir/c.txt", "trash"); writeTrashFile(repo, "dir/d.txt", "trash"); try (Git git = new Git(repo)) { git.add().addFilepattern("dir").call(); } Map<String, Change> changes = StagedChangeCache.build(repo); assertEquals(4, changes.size()); GitModelCache cache = new GitModelCache(createModelRepository(), repo, changes); GitModelObject[] cacheChildren = cache.getChildren(); assertEquals(1, cacheChildren.length); GitModelObject dir = cacheChildren[0]; assertEquals("dir", dir.getName()); GitModelObject[] dirChildren = dir.getChildren(); assertEquals(4, dirChildren.length); } @Before public void setupEnvironment() throws Exception { leftRepoFile = createProjectAndCommitToRepository();
/******************************************************************************* * Copyright (C) 2011, 2013 Dariusz Luksza <[email protected]> and others. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License 2.0 * which accompanies this distribution, and is available at * https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 *******************************************************************************/ package org.eclipse.egit.ui.internal.synchronize.model; public class GitModelCacheTest extends GitModelTestCase { @Test public void shouldReturnEqualForSameInstance() throws Exception { // given GitModelCache left = new GitModelCache(createModelRepository(), lookupRepository(leftRepoFile), null); // when boolean actual = left.equals(left); // then assertTrue(actual); } @Test public void shouldReturnNotEqualForDifferentRepositories() throws Exception { // given File localRightRepoFile = createProjectAndCommitToRepository(REPO2); GitModelRepository rightGsd = new GitModelRepository( getGSD(lookupRepository(localRightRepoFile))); GitModelCache left = new GitModelCache(createModelRepository(), lookupRepository(leftRepoFile), null); GitModelCache right = new GitModelCache(rightGsd, lookupRepository(leftRepoFile), null); // when boolean actual = left.equals(right); // then assertFalse(actual); } @Test public void shouldReturnEqualForSameCommits() throws Exception { // given GitModelCache left = new GitModelCache(createModelRepository(), lookupRepository(leftRepoFile), null); GitModelCache right = new GitModelCache(createModelRepository(), lookupRepository(leftRepoFile), null); // when boolean actual = left.equals(right); // then assertTrue(actual); } @Test public void shouldReturnNotEqualWhenComparingCacheAndWorkingTree() throws Exception { // given GitModelCache left = new GitModelCache(createModelRepository(), lookupRepository(leftRepoFile), null); GitModelCache right = mock(GitModelWorkingTree.class); // when boolean actual = left.equals(right); // then assertFalse(actual); } @Test public void shouldReturnNotEqualWhenCacheTreeAndCommit() throws Exception { // given GitModelObject left = new GitModelCache(createModelRepository(), lookupRepository(leftRepoFile), null); GitModelObject right = mock(GitModelCommit.class); // when boolean actual = left.equals(right); // then assertFalse(actual); } @Test public void shouldReturnChildren() throws Exception { Repository repo = lookupRepository(leftRepoFile); writeTrashFile(repo, "dir/a.txt", "trash"); writeTrashFile(repo, "dir/b.txt", "trash"); writeTrashFile(repo, "dir/c.txt", "trash"); writeTrashFile(repo, "dir/d.txt", "trash"); try (Git git = new Git(repo)) { git.add().addFilepattern("dir").call(); } Map<String, Change> changes = StagedChangeCache.build(repo); assertEquals(4, changes.size()); GitModelCache cache = new GitModelCache(createModelRepository(), repo, changes); GitModelObject[] cacheChildren = cache.getChildren(); assertEquals(1, cacheChildren.length); GitModelObject dir = cacheChildren[0]; assertEquals("dir", dir.getName()); GitModelObject[] dirChildren = dir.getChildren(); assertEquals(4, dirChildren.length); } @Before public void setupEnvironment() throws Exception { leftRepoFile = createProjectAndCommitToRepository();
RepositoryUtil.INSTANCE.addConfiguredRepository(leftRepoFile);
0
2023-10-20 15:17:51+00:00
12k
leforero4-ui/unico_proyecto_con_todos_los_patrones_de_diseno_en_java
src/main/application/driver/adapter/usecase/Game.java
[ { "identifier": "BigBoard", "path": "src/main/application/driver/adapter/usecase/board/BigBoard.java", "snippet": "public class BigBoard implements BoardCollection<Enemy> {\n private final Enemy[][] squares;\n private final PatternsIterator<Enemy> iterator;\n private static final int ROWS = 8;\n private static final int COLUMNS = 8;\n\n public BigBoard(final List<Enemy> enemies) {\n squares = new Enemy[ROWS][COLUMNS];\n int indexEnemy = 0;\n SQUARE_LOOP: for (int row = 0; row < ROWS; row++) {\n for (int column = 0; column < COLUMNS; column++) {\n if (indexEnemy < enemies.size()) {\n \tsquares[row][column] = enemies.get(indexEnemy);\n indexEnemy++;\n } else {\n break SQUARE_LOOP;\n }\n }\n }\n this.iterator = new BoardIterator(this);\n }\n\n\t@Override\n public int getRows() {\n return ROWS;\n }\n\n\t@Override\n public int getColumns() {\n return COLUMNS;\n }\n\n\t@Override\n public Enemy getEnemy(final int row, final int column) {\n return squares[row][column];\n }\n\n\t@Override\n\tpublic void deleteEnemy(final int row, final int column) {\n SQUARE_LOOP: for (int rowCurrent = row; rowCurrent < ROWS; rowCurrent++) {\n for (int columnCurrent = column; columnCurrent < COLUMNS; columnCurrent++) {\n \tif ((rowCurrent != ROWS - 1) || (columnCurrent != COLUMNS - 1)) {\n \t\tfinal int rowNext;\n \t\tfinal int columnNext = columnCurrent < COLUMNS - 1 ? columnCurrent + 1 : 0;\n \t\tif (columnCurrent == COLUMNS - 1) {\n \t\trowNext = rowCurrent < ROWS - 1 ? rowCurrent + 1 : 0;\n \t\t} else {\n \t\t\trowNext = rowCurrent;\n \t\t}\n \tfinal Enemy enemyNext = squares[rowNext][columnNext];\n \tif (enemyNext == null) {\n \tsquares[rowCurrent][columnCurrent] = null;\n \t\tbreak SQUARE_LOOP;\n \t}\n \tsquares[rowCurrent][columnCurrent] = enemyNext;\n \t} else {\n \tsquares[rowCurrent][columnCurrent] = null;\n break SQUARE_LOOP;\n \t}\n }\n }\n }\n\n\t@Override\n\tpublic String getAvatarSquare(final int row, final int column) {\n\t\tfinal Enemy enemy = squares[row][column];\n\t\tfinal StringBuilder avatarSquare = new StringBuilder();\n\t\tif (enemy != null) {\n\t\t\tavatarSquare.append(\"{\");\n\t\t\tavatarSquare.append(row);\n\t\t\tavatarSquare.append(\"-\");\n\t\t\tavatarSquare.append(column);\n\t\t\tavatarSquare.append(\":\");\n\t\t\tfinal String avatar = enemy.getAvatar(\"\");\n\t\t\tavatarSquare.append(!avatar.isEmpty() ? avatar.substring(0, avatar.length() - 1) : \"\");\n\t\t\tavatarSquare.append(\":\");\n\t\t\tavatarSquare.append(enemy.getLife());\n\t\t\tavatarSquare.append(\":\");\n\t\t\tavatarSquare.append(enemy.getAttackLevel(false));\n\t\t\tavatarSquare.append(\"}\");\n\t\t\tif (column == COLUMNS - 1) {\n\t\t\t\tavatarSquare.append(\"\\n\");\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn avatarSquare.toString();\n\t}\n\n\t@Override\n\tpublic PatternsIterator<Enemy> getIterator() {\n\t\treturn this.iterator;\n\t}\n\n}" }, { "identifier": "ConjunctionExpression", "path": "src/main/application/driver/adapter/usecase/expression/ConjunctionExpression.java", "snippet": "public class ConjunctionExpression implements Expression {\n\tprivate final Expression leftExpression;\n\tprivate final Expression rightExpression;\n\t\n\tpublic ConjunctionExpression(final Expression leftExpression, final Expression rightExpression) {\n\t\tthis.leftExpression = leftExpression;\n\t\tthis.rightExpression = rightExpression;\n\t}\n\n\t@Override\n\tpublic List<String> interpret(Context context) {\n\t\tList<String> leftAvatarSquares = leftExpression.interpret(context);\n\t\tList<String> rightAvatarSquares = rightExpression.interpret(context);\n\t\tList<String> avatarSquares = new ArrayList<>(leftAvatarSquares);\n\t\tavatarSquares.retainAll(rightAvatarSquares);\n return avatarSquares;\n\t}\n\n}" }, { "identifier": "Context", "path": "src/main/application/driver/adapter/usecase/expression/Context.java", "snippet": "public class Context {\n\tprivate final List<String> avatarSquares;\n\t\n\tpublic Context(final List<String> avatarSquares) {\n\t\tthis.avatarSquares = avatarSquares;\n\t}\n\t\n\tpublic List<String> getAvatarSquares() {\n\t\treturn this.avatarSquares;\n\t}\n}" }, { "identifier": "AlternativeExpression", "path": "src/main/application/driver/adapter/usecase/expression/AlternativeExpression.java", "snippet": "public class AlternativeExpression implements Expression {\n\tprivate final Expression leftExpression;\n\tprivate final Expression rightExpression;\n\t\n\tpublic AlternativeExpression(final Expression leftExpression, final Expression rightExpression) {\n\t\tthis.leftExpression = leftExpression;\n\t\tthis.rightExpression = rightExpression;\n\t}\n\n\t@Override\n\tpublic List<String> interpret(Context context) {\n\t\tList<String> leftAvatarSquares = leftExpression.interpret(context);\n\t\tList<String> rightAvatarSquares = rightExpression.interpret(context);\n\t\tSet<String> avatarSquares = new LinkedHashSet<>(leftAvatarSquares);\n\t\tavatarSquares.addAll(rightAvatarSquares);\n return new ArrayList<>(avatarSquares);\n\t}\n\n}" }, { "identifier": "EnemyExpression", "path": "src/main/application/driver/adapter/usecase/expression/EnemyExpression.java", "snippet": "public class EnemyExpression implements Expression {\n\tprivate final String word;\n\n\tpublic EnemyExpression(String word) {\n\t\tthis.word = switch(word.toLowerCase()) {\n\t\tcase \"soldado\" -> \"S\";\n\t\tcase \"aire\" -> \"A\";\n\t\tcase \"naval\" -> \"N\";\n\t\tcase \"fortaleza\" -> \"F\";\n\t\tcase \"escuadron\", \"escuadrón\" -> \"E\";\n\t\tcase \"supremo\", \"maestro\", \"jefe\" -> \"J\";\n\t\tdefault -> word.toUpperCase();\n\t\t};\n\t}\n\n\t@Override\n\tpublic List<String> interpret(Context context) {\n return context.getAvatarSquares().stream()\n .filter(avatarSquare -> avatarSquare.contains(this.word))\n .toList();\n\t}\n\n}" }, { "identifier": "EnemyBasicMethod", "path": "src/main/application/driver/adapter/usecase/factory_enemies/EnemyBasicMethod.java", "snippet": "public class EnemyBasicMethod implements EnemyMethod {\n\tprivate final ArmyFactory armyFactory;\n\n\tpublic EnemyBasicMethod(final ArmyFactory armyFactory) {\n\t\tthis.armyFactory = armyFactory;\n\t}\n\n\n\t@Override\n\tpublic List<Enemy> createEnemies() {\n\t\tfinal List<Enemy> enemies = new ArrayList<Enemy>();\n\t\t\n final int lifeSoldier = 25;\n final int attackLevelSoldier = 5;\n final Soldier soldierEnemyBase = armyFactory.createSoldier(lifeSoldier, attackLevelSoldier, new Poison());\n\t\t\n\t\t// supreme\n\t\tSupreme supreme = armyFactory.getSupreme();\n\t\tenemies.add(supreme);\n\n\t\t// soldiers\n final int quantitySoldiers = 8;\n\t\tfor (int created = 1; created <= quantitySoldiers; created++) {\n\t\t\tfinal Soldier soldierEnemy = soldierEnemyBase.clone();\n\t\t\tenemies.add(soldierEnemy);\n\t\t\tif (created <= Math.round(enemies.size() / 3)){\n\t\t\t\tsupreme.addProtector(soldierEnemy);\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn enemies;\n\t}\n\n\n\t@Override\n\tpublic FavorableEnvironment createFavorableEnvironments() {\n\t\tfinal FavorableEnvironment favorableEnvironmentFirst = new Cold();\n\t\tfinal FavorableEnvironment favorableEnvironmentSecond = new Heat();\n\t\t\n\t\tfavorableEnvironmentFirst.setNextFavorableEnvironment(favorableEnvironmentSecond);\n\t\t\n\t\treturn favorableEnvironmentFirst;\n\t}\n\n}" }, { "identifier": "EnemyHighMethod", "path": "src/main/application/driver/adapter/usecase/factory_enemies/EnemyHighMethod.java", "snippet": "public class EnemyHighMethod implements EnemyMethod {\n\tprivate final ArmyFactory armyFactory;\n\n\tpublic EnemyHighMethod(final ArmyFactory armyFactory) {\n\t\tthis.armyFactory = armyFactory;\n\t}\n\n\n\t@Override\n\tpublic List<Enemy> createEnemies() {\n\t\tfinal List<Enemy> enemies = new ArrayList<>();\n\t\t\n final int lifeSoldier = 25;\n final int attackLevelSoldier = 5;\n final Soldier soldierEnemyBase = armyFactory.createSoldier(lifeSoldier, attackLevelSoldier, new Bang(3));\n\t\t\n\t\t// supreme\n\t\tSupreme supreme = armyFactory.getSupreme();\n\t\tenemies.add(supreme);\n\n\t\t// soldiers\n final int quantitySoldiers = 5;\n\t\tfor (int created = 1; created <= quantitySoldiers; created++) {\n\t\t\tfinal Soldier soldierEnemy = soldierEnemyBase.clone();\n\t\t\tenemies.add(soldierEnemy);\n\t\t\tsupreme.addProtector(soldierEnemy);\n\t\t}\n\n\t\t// soldiers with fort\n final int quantitySoldiersWithFork = 2;\n\t\tfor (int created = 1; created <= quantitySoldiersWithFork; created++) {\n\t\t\tenemies.add(new Fort(soldierEnemyBase.clone()));\n\t\t}\n\t\t\n\t\t// infantry\n final int quantitySquadron = 2;\n final int quantitySoldiersForSquadron = 3;\n\t\tfinal List<Enemy> squadronsAndSoldiers = new ArrayList<>();\n\t\tfor (int createdSquadron = 1; createdSquadron <= quantitySquadron; createdSquadron++) {\n\t\t\tfinal List<Enemy> soldiers = new ArrayList<>();\n\t\t\tfor (int created = 1; created <= quantitySoldiersForSquadron; created++) {\n\t\t\t\tsoldiers.add(soldierEnemyBase.clone());\n\t\t\t}\n\t\t\tEnemy squadron = armyFactory.createSquadron(soldiers, new MultipleShots(2));\n\t\t\tif (createdSquadron == 1) {\n\t\t\t\tsquadron = new Fort(squadron);\n\t\t\t}\n\t\t\tsquadronsAndSoldiers.add(squadron);\n\t\t}\n final int quantitySoldiersInSquadron = 4;\n\t\tfor (int created = 1; created <= quantitySoldiersInSquadron; created++) {\n\t\t\tsquadronsAndSoldiers.add(soldierEnemyBase.clone());\n\t\t}\n\t\tfinal Enemy infantry = armyFactory.createSquadron(squadronsAndSoldiers, new Poison());\n\t\tenemies.add(infantry);\n\t\t\n\t\treturn enemies;\n\t}\n\n\n\t@Override\n\tpublic FavorableEnvironment createFavorableEnvironments() {\n\t\tfinal FavorableEnvironment favorableEnvironmentFirst = new Heat();\n\t\tfinal FavorableEnvironment favorableEnvironmentSecond = new Cold();\n\t\tfinal FavorableEnvironment favorableEnvironmentThird = new Rainy();\n\t\tfinal FavorableEnvironment favorableEnvironmentFourth = new Jungle(12);\n\t\tfinal FavorableEnvironment favorableEnvironmentFifth = new City(83);\n\n\t\tfavorableEnvironmentFirst.setNextFavorableEnvironment(favorableEnvironmentSecond);\n\t\tfavorableEnvironmentSecond.setNextFavorableEnvironment(favorableEnvironmentThird);\n\t\tfavorableEnvironmentThird.setNextFavorableEnvironment(favorableEnvironmentFourth);\n\t\tfavorableEnvironmentFourth.setNextFavorableEnvironment(favorableEnvironmentFifth);\n\t\t\n\t\treturn favorableEnvironmentFirst;\n\t}\n\n}" }, { "identifier": "EnemyMiddleMethod", "path": "src/main/application/driver/adapter/usecase/factory_enemies/EnemyMiddleMethod.java", "snippet": "public class EnemyMiddleMethod implements EnemyMethod {\n\tprivate final ArmyFactory armyFactory;\n\n\tpublic EnemyMiddleMethod(final ArmyFactory armyFactory) {\n\t\tthis.armyFactory = armyFactory;\n\t}\n\n\n\t@Override\n\tpublic List<Enemy> createEnemies() {\n\t\tfinal List<Enemy> enemies = new ArrayList<>();\n\t\t\n final int lifeSoldier = 25;\n final int attackLevelSoldier = 5;\n final Soldier soldierEnemyBase = armyFactory.createSoldier(lifeSoldier, attackLevelSoldier, new Bang(2));\n\t\t\n\t\t// supreme\n\t\tSupreme supreme = armyFactory.getSupreme();\n\t\tenemies.add(supreme);\n\n\t\t// soldiers\n final int quantitySoldiers = 6;\n\t\tfor (int created = 1; created <= quantitySoldiers; created++) {\n\t\t\tfinal Soldier soldierEnemy = soldierEnemyBase.clone();\n\t\t\tenemies.add(soldierEnemy);\n\t\t\tif (created <= Math.round(enemies.size() / 2)){\n\t\t\t\tsupreme.addProtector(soldierEnemy);\n\t\t\t}\n\t\t}\n\t\t\n\t\t// infantry\n final int quantitySquadron = 2;\n final int quantitySoldiersForSquadron = 3;\n\t\tfinal List<Enemy> squadronsAndSoldiers = new ArrayList<>();\n\t\tfor (int createdSquadron = 1; createdSquadron <= quantitySquadron; createdSquadron++) {\n\t\t\tfinal List<Enemy> soldiers = new ArrayList<>();\n\t\t\tfor (int created = 1; created <= quantitySoldiersForSquadron; created++) {\n\t\t\t\tsoldiers.add(soldierEnemyBase.clone());\n\t\t\t}\n\t\t\tfinal Enemy squadron = armyFactory.createSquadron(soldiers, new Poison());\n\t\t\tsquadronsAndSoldiers.add(squadron);\n\t\t}\n final int quantitySoldiersInSquadron = 3;\n\t\tfor (int created = 1; created <= quantitySoldiersInSquadron; created++) {\n\t\t\tsquadronsAndSoldiers.add(soldierEnemyBase.clone());\n\t\t}\n\t\tfinal Enemy infantry = armyFactory.createSquadron(squadronsAndSoldiers, new MultipleShots(2));\n\t\tenemies.add(infantry);\n\t\t\n\t\treturn enemies;\n\t}\n\n\n\t@Override\n\tpublic FavorableEnvironment createFavorableEnvironments() {\n\t\tfinal FavorableEnvironment favorableEnvironmentFirst = new Cold();\n\t\tfinal FavorableEnvironment favorableEnvironmentSecond = new Jungle(12);\n\t\tfinal FavorableEnvironment favorableEnvironmentThird = new City(83);\n\t\tfinal FavorableEnvironment favorableEnvironmentFourth = new Heat();\n\n\t\tfavorableEnvironmentFirst.setNextFavorableEnvironment(favorableEnvironmentSecond);\n\t\tfavorableEnvironmentSecond.setNextFavorableEnvironment(favorableEnvironmentThird);\n\t\tfavorableEnvironmentThird.setNextFavorableEnvironment(favorableEnvironmentFourth);\n\t\t\n\t\treturn favorableEnvironmentFirst;\n\t}\n\n}" }, { "identifier": "BasicMission", "path": "src/main/application/driver/adapter/usecase/mission/BasicMission.java", "snippet": "public class BasicMission extends Mission {\n\n\tpublic BasicMission(BoardCollection<Enemy> board) {\n\t\tsuper(board);\n\t}\n\n\t@Override\n\tprotected boolean isMainObjectiveComplete() {\n\t\tboolean isWeakened = true;\n\t\t\n\t\twhile (this.enemyIterator.hasNext()) {\n\t\t\tfinal Enemy enemy = this.enemyIterator.getNext();\n\t\t\tif(enemy instanceof SupremeAir || enemy instanceof SupremeNaval) {\n\t\t\t\tisWeakened = enemy.getLife() < 150;\n\t\t\t\tbreak;\n\t\t\t}\n }\n\t\tthis.enemyIterator.reset();\n\t\t\n\t\treturn isWeakened;\n\t}\n\n\t@Override\n\tprotected boolean isSecondaryObjectiveComplete() {\n\t\treturn true;\n\t}\n\n\t@Override\n\tprotected boolean isTertiaryObjectiveComplete() {\n\t\treturn true;\n\t}\n\n}" }, { "identifier": "HighMission", "path": "src/main/application/driver/adapter/usecase/mission/HighMission.java", "snippet": "public class HighMission extends Mission {\n\n\tpublic HighMission(BoardCollection<Enemy> board) {\n\t\tsuper(board);\n\t}\n\n\t@Override\n\tprotected boolean isMainObjectiveComplete() {\n\t\tboolean isSupremeDead = true;\n\t\t\n\t\twhile (this.enemyIterator.hasNext()) {\n\t\t\tfinal Enemy enemy = this.enemyIterator.getNext();\n\t\t\tif(enemy instanceof SupremeAir || enemy instanceof SupremeNaval) {\n\t\t\t\tisSupremeDead = enemy.getLife() <= 0;\n\t\t\t\tbreak;\n\t\t\t}\n }\n\t\tthis.enemyIterator.reset();\n\t\t\n\t\treturn isSupremeDead;\n\t}\n\n\t@Override\n\tprotected boolean isSecondaryObjectiveComplete() {\n\t\tboolean isFortAlive = true;\n\t\t\n\t\twhile (this.enemyIterator.hasNext()) {\n\t\t\tif(this.enemyIterator.getNext() instanceof Fort) {\n\t\t\t\tisFortAlive = false;\n\t\t\t\tbreak;\n\t\t\t}\n }\n\t\tthis.enemyIterator.reset();\n\t\t\n\t\treturn isFortAlive;\n\t}\n\n}" }, { "identifier": "MiddleMission", "path": "src/main/application/driver/adapter/usecase/mission/MiddleMission.java", "snippet": "public class MiddleMission extends Mission {\n\n\tpublic MiddleMission(BoardCollection<Enemy> board) {\n\t\tsuper(board);\n\t}\n\n\t@Override\n\tprotected boolean isMainObjectiveComplete() {\n\t\tboolean isWeakened = true;\n\t\t\n\t\twhile (this.enemyIterator.hasNext()) {\n\t\t\tfinal Enemy enemy = this.enemyIterator.getNext();\n\t\t\tif(enemy instanceof SupremeAir || enemy instanceof SupremeNaval) {\n\t\t\t\tisWeakened = enemy.getLife() < 80;\n\t\t\t\tbreak;\n\t\t\t}\n }\n\t\tthis.enemyIterator.reset();\n\t\t\n\t\treturn isWeakened;\n\t}\n\n\t@Override\n\tprotected boolean isSecondaryObjectiveComplete() {\n\t\tint squadronsAlive = 0;\n\t\t\n\t\twhile (this.enemyIterator.hasNext()) {\n\t\t\tfinal Enemy enemy = this.enemyIterator.getNext();\n\t\t\tif(enemy instanceof SquadronAir || enemy instanceof SquadronNaval) {\n\t\t\t\t++squadronsAlive;\n\t\t\t\tbreak;\n\t\t\t}\n }\n\t\tthis.enemyIterator.reset();\n\t\t\n\t\treturn squadronsAlive <= 1;\n\t}\n\n}" }, { "identifier": "EnemyMethod", "path": "src/main/application/driver/port/usecase/EnemyMethod.java", "snippet": "public interface EnemyMethod {\n\tList<Enemy> createEnemies();\n\tFavorableEnvironment createFavorableEnvironments();\n}" }, { "identifier": "Expression", "path": "src/main/application/driver/port/usecase/Expression.java", "snippet": "public interface Expression {\n\tList<String> interpret(Context context);\n}" }, { "identifier": "GameableUseCase", "path": "src/main/application/driver/port/usecase/GameableUseCase.java", "snippet": "public interface GameableUseCase {\n\tvoid startGame();\n\tBoolean[] attackAndCounterAttack(int row, int column);\n\tBoolean[] attackWithComboAndCounterAttack(int row, int column);\n\tvoid calculateFreezing();\n\tboolean isFrozen();\n\tint getTurnsForDefrost();\n\tvoid plusTurnFrozen();\n\tString getStringAvatarSquares();\n\tString getStringAvatarPlayer();\n\tvoid removeDeadEnemies();\n\tString getEnemies(String stringExpression);\n\tvoid healing();\n\tboolean doOrRestoreBackup(String inputString);\n\tboolean isGameCompleted();\n\tboolean verifyAnUpLevel();\n}" }, { "identifier": "BoardCollection", "path": "src/main/application/driver/port/usecase/iterator/BoardCollection.java", "snippet": "public interface BoardCollection<T> {\n int getRows();\n int getColumns();\n Enemy getEnemy(int row, int column);\n\tvoid deleteEnemy(int row, int column);\n\tString getAvatarSquare(int row, int column);\n\tPatternsIterator<T> getIterator();\n}" }, { "identifier": "PatternsIterator", "path": "src/main/application/driver/port/usecase/iterator/PatternsIterator.java", "snippet": "public interface PatternsIterator<T> {\n\tboolean hasNext();\n T getNext();\n\tvoid remove();\n String getAvatarSquareNext();\n void reset();\n}" }, { "identifier": "ArmyFactory", "path": "src/main/domain/model/ArmyFactory.java", "snippet": "public interface ArmyFactory {\n\tPlayer createPlayer(PlayerBuilder playerBuilder);\n\tSoldier createSoldier(int life, int attackLevel, Skillfull skill);\n\tEnemy createSquadron(List<Enemy> squadron, Skillfull skill);\n\tSupreme getSupreme();\n}" }, { "identifier": "CaretakerPlayer", "path": "src/main/domain/model/CaretakerPlayer.java", "snippet": "public class CaretakerPlayer {\n private final Map<String, MementoPlayer> mementosPlayerByKey;\n \n public CaretakerPlayer() {\n \tthis.mementosPlayerByKey = new HashMap<>();\n }\n\n public void addMementoPlayerByKey(final String key, final MementoPlayer mementoPlayer) {\n \tthis.mementosPlayerByKey.put(key, mementoPlayer);\n }\n\n public MementoPlayer getMementoPlayerByKey(final String key) {\n return this.mementosPlayerByKey.get(key);\n }\n}" }, { "identifier": "Command", "path": "src/main/domain/model/Command.java", "snippet": "public interface Command {\n\tvoid execute();\n}" }, { "identifier": "Enemy", "path": "src/main/domain/model/Enemy.java", "snippet": "public abstract class Enemy implements Protective {\n\tprotected int life;\n\tprotected int attackLevel;\n\tprotected final Skillfull skill;\n\tprotected Status status;\n\t\n\tpublic Enemy(int life, int attackLevel, Skillfull skill) {\n\t\tthis.life = life;\n\t\tthis.attackLevel = attackLevel;\n\t\tthis.skill = skill;\n\t\tthis.status = new Asleep();\n\t}\n\n\tpublic int getLife() {\n\t\treturn this.life;\n\t}\n\t\n\tpublic int getAttackLevel(boolean isAttacking) {\n\t\treturn this.skill.getEnhancedAttackLevel(this.attackLevel, isAttacking);\n\t}\n\t\n\tpublic int getCounterAttackLevel(final int attackLevelReceived) {\n\t\treturn this.status.getAttackLevel(attackLevelReceived, this);\n\t}\n\t\n\tpublic void setStatus(final Status status) {\n\t\tthis.status = status;\n\t}\n\t\n\t@Override\n\tpublic void protect(final Supreme theProtected) {\n\t\tthis.receiveAttack(1);\n\t\tif (this.getLife() <= 0) {\n\t\t\ttheProtected.removeProtector(this);\n\t\t}\n\t}\n\n\tpublic abstract void receiveAttack(final int attack);\n\t\n\tpublic abstract String getAvatar(final String prefix);\n\t\n\tpublic abstract void acceptVisit(Visitor visitor);\n}" }, { "identifier": "FavorableEnvironment", "path": "src/main/domain/model/FavorableEnvironment.java", "snippet": "public interface FavorableEnvironment {\n\tvoid setNextFavorableEnvironment(FavorableEnvironment favorableEnvironment);\n\tboolean canAttack(Enemy enemy);\n\tboolean canHandleAttack(Enemy enemy);\n}" }, { "identifier": "Healable", "path": "src/main/domain/model/Healable.java", "snippet": "public class Healable implements Visitor {\n\n\t@Override\n\tpublic void visitSoldier(Soldier soldier) {\n\t\tif (soldier.getTypeHair().equalsIgnoreCase(\"corto\")) {\n\t\t\tsoldier.life += 1;\n\t\t}\n\t}\n\n\t@Override\n\tpublic void visitSquadron(Squadron squadron) {\n\t\tfor (Enemy enemy : squadron.squadronList) {\n\t\t\tenemy.acceptVisit(this);\n\t\t}\n\t\tsquadron.calculateLife();\n\t}\n\n\t@Override\n\tpublic void visitSupreme(Supreme supreme) {\n\t\tsupreme.life += 1;\n\t}\n\n\t@Override\n\tpublic void visitPlayer(Player player) {\n\t\tplayer.life += 50;\n\t}\n\n}" }, { "identifier": "Mission", "path": "src/main/domain/model/Mission.java", "snippet": "public abstract class Mission {\n\tprotected final BoardCollection<Enemy> board;\n\tprotected final PatternsIterator<Enemy> enemyIterator;\n\t\n\tpublic Mission(BoardCollection<Enemy> board) {\n\t\tthis.board = board;\n\t\tthis.enemyIterator = this.board.getIterator();\n\t}\n\t\n\tpublic boolean isMissionComplete() {\n\t\treturn this.isMainObjectiveComplete()\n\t\t\t\t&& this.isSecondaryObjectiveComplete()\n\t\t\t\t&& this.isTertiaryObjectiveComplete();\n\t}\n\n\tprotected abstract boolean isMainObjectiveComplete();\n\tprotected abstract boolean isSecondaryObjectiveComplete();\n\t\n\tprotected boolean isTertiaryObjectiveComplete() {\n\t\tboolean isSoldierAlive = false;\n\t\t\n\t\twhile (this.enemyIterator.hasNext()) {\n\t\t\tfinal Enemy enemy = this.enemyIterator.getNext();\n\t\t\tif(enemy instanceof SoldierAir || enemy instanceof SoldierNaval) {\n\t\t\t\tisSoldierAlive = true;\n\t\t\t\tbreak;\n\t\t\t}\n }\n\t\tthis.enemyIterator.reset();\n\t\t\n\t\treturn isSoldierAlive;\n\t}\n\n}" }, { "identifier": "Player", "path": "src/main/domain/model/Player.java", "snippet": "public abstract class Player {\n\tprotected int life;\n\tprotected int attackLevel;\n\tprotected final String name;\n\tprotected final Type type;\n\tprotected final String typeEye;\n\tprotected final String typeHair;\n\tprotected final String typeShirt;\n\tprotected final String typePant;\n\tprotected final String typeShoes;\n\t\n\tpublic Player(final PlayerBuilder builder) {\n\t\tthis.life = 250;\n\t\tthis.attackLevel = 10;\n\t\tthis.name = builder.name() != null && builder.name() != \"\" ? builder.name() : \"NN\";\n\t\tthis.type = builder.type() != null ? builder.type() : new WarriorType();\n\t\tthis.typeEye = builder.typeEye() != null && builder.typeEye() != \"\" ? builder.typeEye() : \"lentes\";\n\t\tthis.typeHair = builder.typeHair() != null && builder.typeHair() != \"\" ? builder.typeHair() : \"corto\";\n\t\tthis.typeShirt = builder.typeShirt() != null && builder.typeShirt() != \"\" ? builder.typeShirt() : \"franela\";\n\t\tthis.typePant = builder.typePant() != null && builder.typePant() != \"\" ? builder.typePant() : \"largos\";\n\t\tthis.typeShoes = builder.typeShoes() != null && builder.typeShoes() != \"\" ? builder.typeShoes() : \"tennis\";\n\t}\n\t\n\tpublic abstract String getAvatar();\n\t\n\tpublic void acceptVisit(Visitor visitor) {\n\t\tvisitor.visitPlayer(this);\n\t}\n\n\tpublic int getLife() {\n\t\treturn this.life;\n\t}\n\t\n\tpublic int getAttackLevel() {\n\t\treturn this.attackLevel;\n\t}\n\t\n\tpublic void receiveAttack(final int attack) {\n\t\tthis.life -= attack;\n\t}\n\t\n\tpublic MementoPlayer doBackup() {\n\t\treturn new MementoPlayer(this);\n\t}\n\t\n\tpublic void restoreMemento(final MementoPlayer memento) {\n\t\tthis.life = memento.life;\n\t\tthis.attackLevel = memento.attackLevel;\n\t}\n\t\n\tpublic class MementoPlayer { //anidada para obtener todas las propiedades mutables sin problemas de visibilidad\n\t\tprivate final int life;\n\t\tprivate final int attackLevel;\n\t\t\n\t\t//las propiedades del memento deben ser inmutables y son las propiedades mutables de la clase originadora(en este caso la clase Player)\n\t\tpublic MementoPlayer(Player player) {\n\t\t\tthis.life = player.life;\n\t\t\tthis.attackLevel = player.attackLevel;\n\t\t}\n\t\t\n\t}\n}" }, { "identifier": "MementoPlayer", "path": "src/main/domain/model/Player.java", "snippet": "public class MementoPlayer { //anidada para obtener todas las propiedades mutables sin problemas de visibilidad\n\tprivate final int life;\n\tprivate final int attackLevel;\n\t\t\n\t//las propiedades del memento deben ser inmutables y son las propiedades mutables de la clase originadora(en este caso la clase Player)\n\tpublic MementoPlayer(Player player) {\n\t\tthis.life = player.life;\n\t\tthis.attackLevel = player.attackLevel;\n\t}\n\t\t\n}" }, { "identifier": "Attack", "path": "src/main/domain/model/command/Attack.java", "snippet": "public class Attack implements Command {\n\tprivate final FavorableEnvironment favorableEnvironments;\n\tprivate final int playerAttackLevel;\n\tprivate final Enemy enemy;\n\n\t//sus propiedades deben ser inmutables ya que se podría ejecutar en cualquier momento y no deben haber cambiado\n\t//por lo tanto tener cuidado con los objetos pasados por parámetros y sus propiedades que no cambien hasta ser ejecutado el comando\n\tpublic Attack(final FavorableEnvironment favorableEnvironments, final int playerAttackLevel, final Enemy enemy) {\n\t\tthis.favorableEnvironments = favorableEnvironments;\n\t\tthis.playerAttackLevel = playerAttackLevel;\n\t\tthis.enemy = enemy;\n\t}\n\n\t@Override\n\tpublic void execute() {\n\t\tif (this.enemy.getLife() > 0) { //esta propiedad como excepción a la regla se permite ser mutable ya que cuando se ejecute el comando el enemigo ya podría estar muerto\n\t\t\tfinal boolean isSuccessfulAttack = this.favorableEnvironments.canAttack(this.enemy);\n\t\t\tif (isSuccessfulAttack) {\n\t\t\t\tthis.enemy.receiveAttack(this.playerAttackLevel);\n\t\t\t}\n\t\t}\n\t}\n\n}" }, { "identifier": "HealingPlayer", "path": "src/main/domain/model/command/HealingPlayer.java", "snippet": "public class HealingPlayer implements Command {\n\tprivate final Player player;\n\tprivate final Visitor healable;\n\n\t//sus propiedades deben ser inmutables ya que se podría ejecutar en cualquier momento y no deben haber cambiado\n\t//por lo tanto tener cuidado con los objetos pasados por parámetros y sus propiedades que no cambien hasta ser ejecutado el comando\n\tpublic HealingPlayer(Player player) {\n\t\tthis.player = player;\n\t\tthis.healable = new Healable();\n\t}\n\n\t@Override\n\tpublic void execute() {\n\t\tthis.player.acceptVisit(this.healable);\n\t}\n\n}" }, { "identifier": "Visitor", "path": "src/main/domain/model/Visitor.java", "snippet": "public interface Visitor {\n\tvoid visitSoldier(Soldier soldier);\n\tvoid visitSquadron(Squadron squadron);\n\tvoid visitSupreme(Supreme supreme);\n\tvoid visitPlayer(Player player);\n}" } ]
import java.util.ArrayList; import java.util.List; import main.application.driver.adapter.usecase.board.BigBoard; import main.application.driver.adapter.usecase.expression.ConjunctionExpression; import main.application.driver.adapter.usecase.expression.Context; import main.application.driver.adapter.usecase.expression.AlternativeExpression; import main.application.driver.adapter.usecase.expression.EnemyExpression; import main.application.driver.adapter.usecase.factory_enemies.EnemyBasicMethod; import main.application.driver.adapter.usecase.factory_enemies.EnemyHighMethod; import main.application.driver.adapter.usecase.factory_enemies.EnemyMiddleMethod; import main.application.driver.adapter.usecase.mission.BasicMission; import main.application.driver.adapter.usecase.mission.HighMission; import main.application.driver.adapter.usecase.mission.MiddleMission; import main.application.driver.port.usecase.EnemyMethod; import main.application.driver.port.usecase.Expression; import main.application.driver.port.usecase.GameableUseCase; import main.application.driver.port.usecase.iterator.BoardCollection; import main.application.driver.port.usecase.iterator.PatternsIterator; import main.domain.model.ArmyFactory; import main.domain.model.CaretakerPlayer; import main.domain.model.Command; import main.domain.model.Enemy; import main.domain.model.FavorableEnvironment; import main.domain.model.Healable; import main.domain.model.Mission; import main.domain.model.Player; import main.domain.model.Player.MementoPlayer; import main.domain.model.command.Attack; import main.domain.model.command.HealingPlayer; import main.domain.model.Visitor;
8,490
@Override public Boolean[] attackWithComboAndCounterAttack(final int row, final int column) { final Enemy enemy = board.getEnemy(row, column); return new Boolean[] {this.combo(enemy), this.eliminedEnemyFallBackCounterAttack(enemy)}; } private boolean eliminedEnemyFallBackCounterAttack(final Enemy enemy) { final boolean isEnemyEliminated = enemy.getLife() <= 0; if (isEnemyEliminated) { this.deleteEnemy(enemy); } else { this.counterAttack(enemy); } return isEnemyEliminated; } private void counterAttack(final Enemy enemy) { this.player.receiveAttack(enemy.getCounterAttackLevel(this.player.getAttackLevel())); } private boolean combo(final Enemy enemy) { final int lifeBeforeAttack = enemy.getLife(); final List<Command> comboCommands = new ArrayList<>(); comboCommands.add(new Attack(this.favorableEnvironments, this.player.getAttackLevel(), enemy)); comboCommands.add(new HealingPlayer(this.player)); comboCommands.add(new Attack(this.favorableEnvironments, this.player.getAttackLevel(), enemy)); comboCommands.add(new HealingPlayer(this.player)); comboCommands.add(new Attack(this.favorableEnvironments, this.player.getAttackLevel(), enemy)); if (this.frostbite.isFrozen()) { this.frostbite.addCommands(comboCommands); return false; } comboCommands.forEach(Command::execute); return lifeBeforeAttack != enemy.getLife(); } private boolean attack(final Enemy enemy) { final int lifeBeforeAttack = enemy.getLife(); final Command attackCommand = new Attack(this.favorableEnvironments, this.player.getAttackLevel(), enemy); if (this.frostbite.isFrozen()) { this.frostbite.addCommand(attackCommand); return false; } attackCommand.execute(); return lifeBeforeAttack != enemy.getLife(); } @Override public void calculateFreezing() { this.frostbite.calculateFreezing(); } @Override public boolean isFrozen() { return this.frostbite.isFrozen(); } @Override public int getTurnsForDefrost() { return this.frostbite.getTurnsForDefrost(); } @Override public void plusTurnFrozen() { this.frostbite.plusTurnFrozen(); } private void deleteEnemy(final Enemy enemy) { while (this.enemyIterator.hasNext()) { if(this.enemyIterator.getNext().equals(enemy)) { this.enemyIterator.remove(); break; } } this.enemyIterator.reset(); } @Override public String getStringAvatarSquares() { final StringBuilder squares = new StringBuilder(); while (this.enemyIterator.hasNext()) { squares.append(this.enemyIterator.getAvatarSquareNext()); } this.enemyIterator.reset(); return "B=bomba,M=multiples disparos,F=fortaleza,V=veneno,A=aire,N=naval,S=soldado,E=escuadrón,J=Jefe\r\n" + "\r\n" + "tablero:{fila-columna:avatar:vida:ataque}\r\n" + "\r\n" + "enemigos: " + squares.toString() + "\r\n" + "\r\n" + "jugador: {X-X:" + this.player.getAvatar() + ":" + this.player.getLife() + ":" + this.player.getAttackLevel() + "}\r\n"; } @Override public String getStringAvatarPlayer() { return "jugador: {X-X:" + this.player.getAvatar() + ":" + this.player.getLife() + ":" + this.player.getAttackLevel() + "}\r\n"; } @Override public void removeDeadEnemies() { while (this.enemyIterator.hasNext()) { final Enemy enemy = this.enemyIterator.getNext(); if (enemy.getLife() <= 0) { this.enemyIterator.remove(); } } this.enemyIterator.reset(); } @Override public void healing() {
package main.application.driver.adapter.usecase; public class Game implements GameableUseCase { private final ArmyFactory armyFactory; private EnemyMethod enemyMethod; private final Player player; private BoardCollection<Enemy> board; private PatternsIterator<Enemy> enemyIterator; private FavorableEnvironment favorableEnvironments; private final Frostbite frostbite; private final CaretakerPlayer caretakerPlayer; private Mission mission; private int level; public Game(final ArmyFactory armyFactory, final Player player) { this.armyFactory = armyFactory; this.player = player; this.frostbite = new Frostbite(); this.caretakerPlayer = new CaretakerPlayer(); } @Override public void startGame() { this.enemyMethod = new EnemyBasicMethod(armyFactory); this.board = new BigBoard(this.enemyMethod.createEnemies()); this.enemyIterator = this.board.getIterator(); this.mission = new BasicMission(this.board); this.favorableEnvironments = this.enemyMethod.createFavorableEnvironments(); this.level = 1; } @Override public boolean verifyAnUpLevel() { if (this.mission.isMissionComplete()) { if (this.level == 1) { this.enemyMethod = new EnemyMiddleMethod(armyFactory); this.board = new BigBoard(this.enemyMethod.createEnemies()); this.enemyIterator = this.board.getIterator(); this.mission = new MiddleMission(this.board); this.favorableEnvironments = this.enemyMethod.createFavorableEnvironments(); } else { this.enemyMethod = new EnemyHighMethod(armyFactory); this.board = new BigBoard(this.enemyMethod.createEnemies()); this.enemyIterator = this.board.getIterator(); this.mission = new HighMission(this.board); this.favorableEnvironments = this.enemyMethod.createFavorableEnvironments(); } ++this.level; return true; } return false; } @Override public boolean isGameCompleted() { return this.level > 3; } @Override public Boolean[] attackAndCounterAttack(final int row, final int column) { final Enemy enemy = board.getEnemy(row, column); return new Boolean[] {this.attack(enemy), this.eliminedEnemyFallBackCounterAttack(enemy)}; } @Override public Boolean[] attackWithComboAndCounterAttack(final int row, final int column) { final Enemy enemy = board.getEnemy(row, column); return new Boolean[] {this.combo(enemy), this.eliminedEnemyFallBackCounterAttack(enemy)}; } private boolean eliminedEnemyFallBackCounterAttack(final Enemy enemy) { final boolean isEnemyEliminated = enemy.getLife() <= 0; if (isEnemyEliminated) { this.deleteEnemy(enemy); } else { this.counterAttack(enemy); } return isEnemyEliminated; } private void counterAttack(final Enemy enemy) { this.player.receiveAttack(enemy.getCounterAttackLevel(this.player.getAttackLevel())); } private boolean combo(final Enemy enemy) { final int lifeBeforeAttack = enemy.getLife(); final List<Command> comboCommands = new ArrayList<>(); comboCommands.add(new Attack(this.favorableEnvironments, this.player.getAttackLevel(), enemy)); comboCommands.add(new HealingPlayer(this.player)); comboCommands.add(new Attack(this.favorableEnvironments, this.player.getAttackLevel(), enemy)); comboCommands.add(new HealingPlayer(this.player)); comboCommands.add(new Attack(this.favorableEnvironments, this.player.getAttackLevel(), enemy)); if (this.frostbite.isFrozen()) { this.frostbite.addCommands(comboCommands); return false; } comboCommands.forEach(Command::execute); return lifeBeforeAttack != enemy.getLife(); } private boolean attack(final Enemy enemy) { final int lifeBeforeAttack = enemy.getLife(); final Command attackCommand = new Attack(this.favorableEnvironments, this.player.getAttackLevel(), enemy); if (this.frostbite.isFrozen()) { this.frostbite.addCommand(attackCommand); return false; } attackCommand.execute(); return lifeBeforeAttack != enemy.getLife(); } @Override public void calculateFreezing() { this.frostbite.calculateFreezing(); } @Override public boolean isFrozen() { return this.frostbite.isFrozen(); } @Override public int getTurnsForDefrost() { return this.frostbite.getTurnsForDefrost(); } @Override public void plusTurnFrozen() { this.frostbite.plusTurnFrozen(); } private void deleteEnemy(final Enemy enemy) { while (this.enemyIterator.hasNext()) { if(this.enemyIterator.getNext().equals(enemy)) { this.enemyIterator.remove(); break; } } this.enemyIterator.reset(); } @Override public String getStringAvatarSquares() { final StringBuilder squares = new StringBuilder(); while (this.enemyIterator.hasNext()) { squares.append(this.enemyIterator.getAvatarSquareNext()); } this.enemyIterator.reset(); return "B=bomba,M=multiples disparos,F=fortaleza,V=veneno,A=aire,N=naval,S=soldado,E=escuadrón,J=Jefe\r\n" + "\r\n" + "tablero:{fila-columna:avatar:vida:ataque}\r\n" + "\r\n" + "enemigos: " + squares.toString() + "\r\n" + "\r\n" + "jugador: {X-X:" + this.player.getAvatar() + ":" + this.player.getLife() + ":" + this.player.getAttackLevel() + "}\r\n"; } @Override public String getStringAvatarPlayer() { return "jugador: {X-X:" + this.player.getAvatar() + ":" + this.player.getLife() + ":" + this.player.getAttackLevel() + "}\r\n"; } @Override public void removeDeadEnemies() { while (this.enemyIterator.hasNext()) { final Enemy enemy = this.enemyIterator.getNext(); if (enemy.getLife() <= 0) { this.enemyIterator.remove(); } } this.enemyIterator.reset(); } @Override public void healing() {
final Visitor healable = new Healable();
27
2023-10-20 18:36:47+00:00
12k
Squawkykaka/when_pigs_fly
src/main/java/com/squawkykaka/when_pigs_fly/WhenPigsFly.java
[ { "identifier": "Heal_Feed", "path": "src/main/java/com/squawkykaka/when_pigs_fly/commands/Heal_Feed.java", "snippet": "public class Heal_Feed {\n public Heal_Feed() {\n new CommandBase(\"heal\", true) {\n @Override\n public boolean onCommand(CommandSender sender, String [] arguments) {\n Player player = (Player) sender;\n player.setHealth(Objects.requireNonNull(player.getAttribute(Attribute.GENERIC_MAX_HEALTH)).getBaseValue());\n return true;\n }\n\n @Override\n public @NotNull String getUsage() {\n return \"/heal\";\n }\n }.enableDelay(5);\n\n new CommandBase(\"feed\", true) {\n @Override\n public boolean onCommand(CommandSender sender, String [] arguments) {\n Player player = (Player) sender;\n player.setFoodLevel(20);\n return true;\n }\n\n @Override\n public @NotNull String getUsage() {\n return \"/feed\";\n }\n }.enableDelay(5);\n }\n}" }, { "identifier": "Menu", "path": "src/main/java/com/squawkykaka/when_pigs_fly/commands/Menu.java", "snippet": "public class Menu implements Listener {\n private final String invName = \"When pigs fly! Menu\";\n\n\n public Menu(WhenPigsFly plugin) {\n new CommandBase(\"menu\", true) {\n @Override\n public boolean onCommand(CommandSender sender, String[] arguments) {\n Player player = (Player) sender;\n\n Inventory inv = Bukkit.createInventory(player, 9 * 3, invName);\n\n inv.setItem(11, getItem(new ItemStack(Material.FEATHER), \"&2&oToggle &3&lFly\", \"&a&lClick&r&8 to toggle\"));\n inv.setItem(13, getItem(new ItemStack(Material.BLAZE_ROD), \"&aGive Yourself &d&lAxolotl Shooter\", \"&a&lClick&r&8 to give\"));\n inv.setItem(15, getItem(new ItemStack(Material.ENDER_PEARL), \"&6Go to Spawn\", \"&a&lClick&r&8 to tp\", \"&3Teleports&r you to the servers spawn\"));\n\n player.openInventory(inv);\n return true;\n }\n\n @Override\n public String getUsage() {\n return \"/menu\";\n }\n };\n\n Bukkit.getPluginManager().registerEvents(this, plugin);\n }\n\n @EventHandler\n public void onInventoryClick(InventoryClickEvent event) {\n WhenPigsFly plugin = WhenPigsFly.getPlugin(WhenPigsFly.class);\n FileConfiguration config = plugin.getConfig();\n\n if (!event.getView().getTitle().equals(invName)) {\n return;\n }\n event.setCancelled(true);\n Player player = (Player) event.getWhoClicked();\n int slot = event.getSlot();\n\n // Declare isFlying outside of the if statement\n boolean isFlying = player.getAllowFlight();\n\n // if the feather is clicked it toggles the flying state\n if (slot == 11) {\n // Toggle the flight state\n isFlying = !isFlying;\n player.setAllowFlight(isFlying);\n player.closeInventory();\n }\n\n if (slot == 13) {\n ItemStack gun = getItem(new ItemStack(Material.BLAZE_ROD), \"Gun\", \"Shoots axolotls\");\n ItemMeta meta = gun.getItemMeta();\n List<String> lores = new ArrayList<>();\n\n meta.setDisplayName(\"Gun\");\n lores.add(\"Shoots axolotls\");\n meta.setLore(lores);\n\n gun.setItemMeta(meta);\n player.getInventory().addItem(gun);\n }\n\n // TODO: slot 13 + 15. 13 is give a blaze rod named gun, 15 is run /spawn\n\n if (slot == 15) {\n\n String worldName = config.getString(\"spawn.world\");\n if (worldName == null) {\n Bukkit.getLogger().warning(\"spawn.world does not exist within config.yml\");\n return;\n }\n\n World world = Bukkit.getWorld(worldName);\n if (world == null) {\n Bukkit.getLogger().severe(\"World \\\"\" + worldName + \"\\\" does not exist.\");\n return;\n }\n\n int x = config.getInt(\"spawn.x\");\n int y = config.getInt(\"spawn.y\");\n int z = config.getInt(\"spawn.z\");\n float yaw = (float) config.getDouble(\"spawn.yaw\");\n float pitch = (float) config.getDouble(\"spawn.pitch\");\n Location spawn = new Location(world, x, y, z, yaw, pitch);\n\n player.teleport(spawn);\n Msg.send(player, \"Teleported to spawn.\");\n }\n }\n\n private ItemStack getItem(ItemStack item, String name, String... lore) {\n ItemMeta meta = item.getItemMeta();\n\n meta.setDisplayName(ChatColor.translateAlternateColorCodes('&', name));\n List<String> lores = new ArrayList<>();\n for (String s : lore) {\n lores.add(ChatColor.translateAlternateColorCodes('&', s));\n }\n meta.setLore(lores);\n\n item.setItemMeta(meta);\n return item;\n }\n}" }, { "identifier": "Spawn", "path": "src/main/java/com/squawkykaka/when_pigs_fly/commands/Spawn.java", "snippet": "public class Spawn {\n private Location spawn = null;\n\n public Spawn(WhenPigsFly plugin) {\n FileConfiguration config = plugin.getConfig();\n String worldName = config.getString(\"spawn.world\");\n if (worldName == null) {\n Bukkit.getLogger().warning(\"spawn.world does not exist within config.yml\");\n return;\n }\n\n World world = Bukkit.getWorld(worldName);\n if (world == null) {\n Bukkit.getLogger().severe(\"World \\\"\" + worldName + \"\\\" does not exist.\");\n return;\n }\n\n int x = config.getInt(\"spawn.x\");\n int y = config.getInt(\"spawn.y\");\n int z = config.getInt(\"spawn.z\");\n float yaw = (float) config.getDouble(\"spawn.yaw\");\n float pitch = (float) config.getDouble(\"spawn.pitch\");\n\n spawn = new Location(world, x, y, z, yaw, pitch);\n\n new CommandBase(\"setspawn\", true) {\n @Override\n public boolean onCommand(CommandSender sender, String[] arguments) {\n Player player = (Player) sender;\n Location location = player.getLocation();\n\n config.set(\"spawn.world\", location.getWorld().getName());\n config.set(\"spawn.x\", location.getBlockX());\n config.set(\"spawn.y\", location.getBlockY());\n config.set(\"spawn.z\", location.getBlockZ());\n config.set(\"spawn.yaw\", location.getYaw());\n config.set(\"spawn.pitch\", location.getPitch());\n\n plugin.saveConfig();\n Msg.send(player, \"New spawn point saved.\");\n\n spawn = location;\n return true;\n }\n\n @Override\n public String getUsage() {\n return \"/setspawn\";\n }\n }.enableDelay(2).setPermission(\"spawn.set\");\n\n new CommandBase(\"spawn\", true) {\n @Override\n public boolean onCommand(CommandSender sender, String[] arguments) {\n Player player = (Player) sender;\n\n player.teleport(spawn);\n Msg.send(player, \"Teleported to spawn.\");\n return true;\n }\n\n @Override\n public String getUsage() {\n return \"/spawn\";\n }\n };\n }\n}" }, { "identifier": "EventUtil", "path": "src/main/java/com/squawkykaka/when_pigs_fly/util/EventUtil.java", "snippet": "public class EventUtil {\n public static void register(Listener listener) {\n Bukkit.getServer().getPluginManager().registerEvents(listener, WhenPigsFly.getInstance());\n }\n}" }, { "identifier": "Metrics", "path": "src/main/java/com/squawkykaka/when_pigs_fly/util/Metrics.java", "snippet": "public class Metrics {\n\n private final Plugin plugin;\n\n private final MetricsBase metricsBase;\n\n /**\n * Creates a new Metrics instance.\n *\n * @param plugin Your plugin instance.\n * @param serviceId The id of the service. It can be found at <a\n * href=\"https://bstats.org/what-is-my-plugin-id\">What is my plugin id?</a>\n */\n public Metrics(JavaPlugin plugin, int serviceId) {\n this.plugin = plugin;\n // Get the config file\n File bStatsFolder = new File(plugin.getDataFolder().getParentFile(), \"bStats\");\n File configFile = new File(bStatsFolder, \"config.yml\");\n YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile);\n if (!config.isSet(\"serverUuid\")) {\n config.addDefault(\"enabled\", true);\n config.addDefault(\"serverUuid\", UUID.randomUUID().toString());\n config.addDefault(\"logFailedRequests\", false);\n config.addDefault(\"logSentData\", false);\n config.addDefault(\"logResponseStatusText\", false);\n // Inform the server owners about bStats\n config\n .options()\n .header(\n \"bStats (https://bStats.org) collects some basic information for plugin authors, like how\\n\"\n + \"many people use their plugin and their total player count. It's recommended to keep bStats\\n\"\n + \"enabled, but if you're not comfortable with this, you can turn this setting off. There is no\\n\"\n + \"performance penalty associated with having metrics enabled, and data sent to bStats is fully\\n\"\n + \"anonymous.\")\n .copyDefaults(true);\n try {\n config.save(configFile);\n } catch (IOException ignored) {\n }\n }\n // Load the data\n boolean enabled = config.getBoolean(\"enabled\", true);\n String serverUUID = config.getString(\"serverUuid\");\n boolean logErrors = config.getBoolean(\"logFailedRequests\", false);\n boolean logSentData = config.getBoolean(\"logSentData\", false);\n boolean logResponseStatusText = config.getBoolean(\"logResponseStatusText\", false);\n metricsBase =\n new MetricsBase(\n \"bukkit\",\n serverUUID,\n serviceId,\n enabled,\n this::appendPlatformData,\n this::appendServiceData,\n submitDataTask -> Bukkit.getScheduler().runTask(plugin, submitDataTask),\n plugin::isEnabled,\n (message, error) -> this.plugin.getLogger().log(Level.WARNING, message, error),\n (message) -> this.plugin.getLogger().log(Level.INFO, message),\n logErrors,\n logSentData,\n logResponseStatusText);\n }\n\n /** Shuts down the underlying scheduler service. */\n public void shutdown() {\n metricsBase.shutdown();\n }\n\n /**\n * Adds a custom chart.\n *\n * @param chart The chart to add.\n */\n public void addCustomChart(CustomChart chart) {\n metricsBase.addCustomChart(chart);\n }\n\n private void appendPlatformData(JsonObjectBuilder builder) {\n builder.appendField(\"playerAmount\", getPlayerAmount());\n builder.appendField(\"onlineMode\", Bukkit.getOnlineMode() ? 1 : 0);\n builder.appendField(\"bukkitVersion\", Bukkit.getVersion());\n builder.appendField(\"bukkitName\", Bukkit.getName());\n builder.appendField(\"javaVersion\", System.getProperty(\"java.version\"));\n builder.appendField(\"osName\", System.getProperty(\"os.name\"));\n builder.appendField(\"osArch\", System.getProperty(\"os.arch\"));\n builder.appendField(\"osVersion\", System.getProperty(\"os.version\"));\n builder.appendField(\"coreCount\", Runtime.getRuntime().availableProcessors());\n }\n\n private void appendServiceData(JsonObjectBuilder builder) {\n builder.appendField(\"pluginVersion\", plugin.getDescription().getVersion());\n }\n\n private int getPlayerAmount() {\n try {\n // Around MC 1.8 the return type was changed from an array to a collection,\n // This fixes java.lang.NoSuchMethodError:\n // org.bukkit.Bukkit.getOnlinePlayers()Ljava/util/Collection;\n Method onlinePlayersMethod = Class.forName(\"org.bukkit.Server\").getMethod(\"getOnlinePlayers\");\n return onlinePlayersMethod.getReturnType().equals(Collection.class)\n ? ((Collection<?>) onlinePlayersMethod.invoke(Bukkit.getServer())).size()\n : ((Player[]) onlinePlayersMethod.invoke(Bukkit.getServer())).length;\n } catch (Exception e) {\n // Just use the new method if the reflection failed\n return Bukkit.getOnlinePlayers().size();\n }\n }\n\n public static class MetricsBase {\n\n /** The version of the Metrics class. */\n public static final String METRICS_VERSION = \"3.0.2\";\n\n private static final String REPORT_URL = \"https://bStats.org/api/v2/data/%s\";\n\n private final ScheduledExecutorService scheduler;\n\n private final String platform;\n\n private final String serverUuid;\n\n private final int serviceId;\n\n private final Consumer<JsonObjectBuilder> appendPlatformDataConsumer;\n\n private final Consumer<JsonObjectBuilder> appendServiceDataConsumer;\n\n private final Consumer<Runnable> submitTaskConsumer;\n\n private final Supplier<Boolean> checkServiceEnabledSupplier;\n\n private final BiConsumer<String, Throwable> errorLogger;\n\n private final Consumer<String> infoLogger;\n\n private final boolean logErrors;\n\n private final boolean logSentData;\n\n private final boolean logResponseStatusText;\n\n private final Set<CustomChart> customCharts = new HashSet<>();\n\n private final boolean enabled;\n\n /**\n * Creates a new MetricsBase class instance.\n *\n * @param platform The platform of the service.\n * @param serviceId The id of the service.\n * @param serverUuid The server uuid.\n * @param enabled Whether or not data sending is enabled.\n * @param appendPlatformDataConsumer A consumer that receives a {@code JsonObjectBuilder} and\n * appends all platform-specific data.\n * @param appendServiceDataConsumer A consumer that receives a {@code JsonObjectBuilder} and\n * appends all service-specific data.\n * @param submitTaskConsumer A consumer that takes a runnable with the submit task. This can be\n * used to delegate the data collection to a another thread to prevent errors caused by\n * concurrency. Can be {@code null}.\n * @param checkServiceEnabledSupplier A supplier to check if the service is still enabled.\n * @param errorLogger A consumer that accepts log message and an error.\n * @param infoLogger A consumer that accepts info log messages.\n * @param logErrors Whether or not errors should be logged.\n * @param logSentData Whether or not the sent data should be logged.\n * @param logResponseStatusText Whether or not the response status text should be logged.\n */\n public MetricsBase(\n String platform,\n String serverUuid,\n int serviceId,\n boolean enabled,\n Consumer<JsonObjectBuilder> appendPlatformDataConsumer,\n Consumer<JsonObjectBuilder> appendServiceDataConsumer,\n Consumer<Runnable> submitTaskConsumer,\n Supplier<Boolean> checkServiceEnabledSupplier,\n BiConsumer<String, Throwable> errorLogger,\n Consumer<String> infoLogger,\n boolean logErrors,\n boolean logSentData,\n boolean logResponseStatusText) {\n ScheduledThreadPoolExecutor scheduler =\n new ScheduledThreadPoolExecutor(1, task -> new Thread(task, \"bStats-Metrics\"));\n // We want delayed tasks (non-periodic) that will execute in the future to be\n // cancelled when the scheduler is shutdown.\n // Otherwise, we risk preventing the server from shutting down even when\n // MetricsBase#shutdown() is called\n scheduler.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);\n this.scheduler = scheduler;\n this.platform = platform;\n this.serverUuid = serverUuid;\n this.serviceId = serviceId;\n this.enabled = enabled;\n this.appendPlatformDataConsumer = appendPlatformDataConsumer;\n this.appendServiceDataConsumer = appendServiceDataConsumer;\n this.submitTaskConsumer = submitTaskConsumer;\n this.checkServiceEnabledSupplier = checkServiceEnabledSupplier;\n this.errorLogger = errorLogger;\n this.infoLogger = infoLogger;\n this.logErrors = logErrors;\n this.logSentData = logSentData;\n this.logResponseStatusText = logResponseStatusText;\n checkRelocation();\n if (enabled) {\n // WARNING: Removing the option to opt-out will get your plugin banned from\n // bStats\n startSubmitting();\n }\n }\n\n public void addCustomChart(CustomChart chart) {\n this.customCharts.add(chart);\n }\n\n public void shutdown() {\n scheduler.shutdown();\n }\n\n private void startSubmitting() {\n final Runnable submitTask =\n () -> {\n if (!enabled || !checkServiceEnabledSupplier.get()) {\n // Submitting data or service is disabled\n scheduler.shutdown();\n return;\n }\n if (submitTaskConsumer != null) {\n submitTaskConsumer.accept(this::submitData);\n } else {\n this.submitData();\n }\n };\n // Many servers tend to restart at a fixed time at xx:00 which causes an uneven\n // distribution of requests on the\n // bStats backend. To circumvent this problem, we introduce some randomness into\n // the initial and second delay.\n // WARNING: You must not modify and part of this Metrics class, including the\n // submit delay or frequency!\n // WARNING: Modifying this code will get your plugin banned on bStats. Just\n // don't do it!\n long initialDelay = (long) (1000 * 60 * (3 + Math.random() * 3));\n long secondDelay = (long) (1000 * 60 * (Math.random() * 30));\n scheduler.schedule(submitTask, initialDelay, TimeUnit.MILLISECONDS);\n scheduler.scheduleAtFixedRate(\n submitTask, initialDelay + secondDelay, 1000 * 60 * 30, TimeUnit.MILLISECONDS);\n }\n\n private void submitData() {\n final JsonObjectBuilder baseJsonBuilder = new JsonObjectBuilder();\n appendPlatformDataConsumer.accept(baseJsonBuilder);\n final JsonObjectBuilder serviceJsonBuilder = new JsonObjectBuilder();\n appendServiceDataConsumer.accept(serviceJsonBuilder);\n JsonObjectBuilder.JsonObject[] chartData =\n customCharts.stream()\n .map(customChart -> customChart.getRequestJsonObject(errorLogger, logErrors))\n .filter(Objects::nonNull)\n .toArray(JsonObjectBuilder.JsonObject[]::new);\n serviceJsonBuilder.appendField(\"id\", serviceId);\n serviceJsonBuilder.appendField(\"customCharts\", chartData);\n baseJsonBuilder.appendField(\"service\", serviceJsonBuilder.build());\n baseJsonBuilder.appendField(\"serverUUID\", serverUuid);\n baseJsonBuilder.appendField(\"metricsVersion\", METRICS_VERSION);\n JsonObjectBuilder.JsonObject data = baseJsonBuilder.build();\n scheduler.execute(\n () -> {\n try {\n // Send the data\n sendData(data);\n } catch (Exception e) {\n // Something went wrong! :(\n if (logErrors) {\n errorLogger.accept(\"Could not submit bStats metrics data\", e);\n }\n }\n });\n }\n\n private void sendData(JsonObjectBuilder.JsonObject data) throws Exception {\n if (logSentData) {\n infoLogger.accept(\"Sent bStats metrics data: \" + data.toString());\n }\n String url = String.format(REPORT_URL, platform);\n HttpsURLConnection connection = (HttpsURLConnection) new URL(url).openConnection();\n // Compress the data to save bandwidth\n byte[] compressedData = compress(data.toString());\n connection.setRequestMethod(\"POST\");\n connection.addRequestProperty(\"Accept\", \"application/json\");\n connection.addRequestProperty(\"Connection\", \"close\");\n connection.addRequestProperty(\"Content-Encoding\", \"gzip\");\n connection.addRequestProperty(\"Content-Length\", String.valueOf(compressedData.length));\n connection.setRequestProperty(\"Content-Type\", \"application/json\");\n connection.setRequestProperty(\"User-Agent\", \"Metrics-Service/1\");\n connection.setDoOutput(true);\n try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) {\n outputStream.write(compressedData);\n }\n StringBuilder builder = new StringBuilder();\n try (BufferedReader bufferedReader =\n new BufferedReader(new InputStreamReader(connection.getInputStream()))) {\n String line;\n while ((line = bufferedReader.readLine()) != null) {\n builder.append(line);\n }\n }\n if (logResponseStatusText) {\n infoLogger.accept(\"Sent data to bStats and received response: \" + builder);\n }\n }\n\n /** Checks that the class was properly relocated. */\n private void checkRelocation() {\n // You can use the property to disable the check in your test environment\n if (System.getProperty(\"bstats.relocatecheck\") == null\n || !System.getProperty(\"bstats.relocatecheck\").equals(\"false\")) {\n // Maven's Relocate is clever and changes strings, too. So we have to use this\n // little \"trick\" ... :D\n final String defaultPackage =\n new String(new byte[] {'o', 'r', 'g', '.', 'b', 's', 't', 'a', 't', 's'});\n final String examplePackage =\n new String(new byte[] {'y', 'o', 'u', 'r', '.', 'p', 'a', 'c', 'k', 'a', 'g', 'e'});\n // We want to make sure no one just copy & pastes the example and uses the wrong\n // package names\n if (MetricsBase.class.getPackage().getName().startsWith(defaultPackage)\n || MetricsBase.class.getPackage().getName().startsWith(examplePackage)) {\n throw new IllegalStateException(\"bStats Metrics class has not been relocated correctly!\");\n }\n }\n }\n\n /**\n * Gzips the given string.\n *\n * @param str The string to gzip.\n * @return The gzipped string.\n */\n private static byte[] compress(final String str) throws IOException {\n if (str == null) {\n return null;\n }\n ByteArrayOutputStream outputStream = new ByteArrayOutputStream();\n try (GZIPOutputStream gzip = new GZIPOutputStream(outputStream)) {\n gzip.write(str.getBytes(StandardCharsets.UTF_8));\n }\n return outputStream.toByteArray();\n }\n }\n\n public static class SimplePie extends CustomChart {\n\n private final Callable<String> callable;\n\n /**\n * Class constructor.\n *\n * @param chartId The id of the chart.\n * @param callable The callable which is used to request the chart data.\n */\n public SimplePie(String chartId, Callable<String> callable) {\n super(chartId);\n this.callable = callable;\n }\n\n @Override\n protected JsonObjectBuilder.JsonObject getChartData() throws Exception {\n String value = callable.call();\n if (value == null || value.isEmpty()) {\n // Null = skip the chart\n return null;\n }\n return new JsonObjectBuilder().appendField(\"value\", value).build();\n }\n }\n\n public static class MultiLineChart extends CustomChart {\n\n private final Callable<Map<String, Integer>> callable;\n\n /**\n * Class constructor.\n *\n * @param chartId The id of the chart.\n * @param callable The callable which is used to request the chart data.\n */\n public MultiLineChart(String chartId, Callable<Map<String, Integer>> callable) {\n super(chartId);\n this.callable = callable;\n }\n\n @Override\n protected JsonObjectBuilder.JsonObject getChartData() throws Exception {\n JsonObjectBuilder valuesBuilder = new JsonObjectBuilder();\n Map<String, Integer> map = callable.call();\n if (map == null || map.isEmpty()) {\n // Null = skip the chart\n return null;\n }\n boolean allSkipped = true;\n for (Map.Entry<String, Integer> entry : map.entrySet()) {\n if (entry.getValue() == 0) {\n // Skip this invalid\n continue;\n }\n allSkipped = false;\n valuesBuilder.appendField(entry.getKey(), entry.getValue());\n }\n if (allSkipped) {\n // Null = skip the chart\n return null;\n }\n return new JsonObjectBuilder().appendField(\"values\", valuesBuilder.build()).build();\n }\n }\n\n public static class AdvancedPie extends CustomChart {\n\n private final Callable<Map<String, Integer>> callable;\n\n /**\n * Class constructor.\n *\n * @param chartId The id of the chart.\n * @param callable The callable which is used to request the chart data.\n */\n public AdvancedPie(String chartId, Callable<Map<String, Integer>> callable) {\n super(chartId);\n this.callable = callable;\n }\n\n @Override\n protected JsonObjectBuilder.JsonObject getChartData() throws Exception {\n JsonObjectBuilder valuesBuilder = new JsonObjectBuilder();\n Map<String, Integer> map = callable.call();\n if (map == null || map.isEmpty()) {\n // Null = skip the chart\n return null;\n }\n boolean allSkipped = true;\n for (Map.Entry<String, Integer> entry : map.entrySet()) {\n if (entry.getValue() == 0) {\n // Skip this invalid\n continue;\n }\n allSkipped = false;\n valuesBuilder.appendField(entry.getKey(), entry.getValue());\n }\n if (allSkipped) {\n // Null = skip the chart\n return null;\n }\n return new JsonObjectBuilder().appendField(\"values\", valuesBuilder.build()).build();\n }\n }\n\n public static class SimpleBarChart extends CustomChart {\n\n private final Callable<Map<String, Integer>> callable;\n\n /**\n * Class constructor.\n *\n * @param chartId The id of the chart.\n * @param callable The callable which is used to request the chart data.\n */\n public SimpleBarChart(String chartId, Callable<Map<String, Integer>> callable) {\n super(chartId);\n this.callable = callable;\n }\n\n @Override\n protected JsonObjectBuilder.JsonObject getChartData() throws Exception {\n JsonObjectBuilder valuesBuilder = new JsonObjectBuilder();\n Map<String, Integer> map = callable.call();\n if (map == null || map.isEmpty()) {\n // Null = skip the chart\n return null;\n }\n for (Map.Entry<String, Integer> entry : map.entrySet()) {\n valuesBuilder.appendField(entry.getKey(), new int[] {entry.getValue()});\n }\n return new JsonObjectBuilder().appendField(\"values\", valuesBuilder.build()).build();\n }\n }\n\n public static class AdvancedBarChart extends CustomChart {\n\n private final Callable<Map<String, int[]>> callable;\n\n /**\n * Class constructor.\n *\n * @param chartId The id of the chart.\n * @param callable The callable which is used to request the chart data.\n */\n public AdvancedBarChart(String chartId, Callable<Map<String, int[]>> callable) {\n super(chartId);\n this.callable = callable;\n }\n\n @Override\n protected JsonObjectBuilder.JsonObject getChartData() throws Exception {\n JsonObjectBuilder valuesBuilder = new JsonObjectBuilder();\n Map<String, int[]> map = callable.call();\n if (map == null || map.isEmpty()) {\n // Null = skip the chart\n return null;\n }\n boolean allSkipped = true;\n for (Map.Entry<String, int[]> entry : map.entrySet()) {\n if (entry.getValue().length == 0) {\n // Skip this invalid\n continue;\n }\n allSkipped = false;\n valuesBuilder.appendField(entry.getKey(), entry.getValue());\n }\n if (allSkipped) {\n // Null = skip the chart\n return null;\n }\n return new JsonObjectBuilder().appendField(\"values\", valuesBuilder.build()).build();\n }\n }\n\n public static class DrilldownPie extends CustomChart {\n\n private final Callable<Map<String, Map<String, Integer>>> callable;\n\n /**\n * Class constructor.\n *\n * @param chartId The id of the chart.\n * @param callable The callable which is used to request the chart data.\n */\n public DrilldownPie(String chartId, Callable<Map<String, Map<String, Integer>>> callable) {\n super(chartId);\n this.callable = callable;\n }\n\n @Override\n public JsonObjectBuilder.JsonObject getChartData() throws Exception {\n JsonObjectBuilder valuesBuilder = new JsonObjectBuilder();\n Map<String, Map<String, Integer>> map = callable.call();\n if (map == null || map.isEmpty()) {\n // Null = skip the chart\n return null;\n }\n boolean reallyAllSkipped = true;\n for (Map.Entry<String, Map<String, Integer>> entryValues : map.entrySet()) {\n JsonObjectBuilder valueBuilder = new JsonObjectBuilder();\n boolean allSkipped = true;\n for (Map.Entry<String, Integer> valueEntry : map.get(entryValues.getKey()).entrySet()) {\n valueBuilder.appendField(valueEntry.getKey(), valueEntry.getValue());\n allSkipped = false;\n }\n if (!allSkipped) {\n reallyAllSkipped = false;\n valuesBuilder.appendField(entryValues.getKey(), valueBuilder.build());\n }\n }\n if (reallyAllSkipped) {\n // Null = skip the chart\n return null;\n }\n return new JsonObjectBuilder().appendField(\"values\", valuesBuilder.build()).build();\n }\n }\n\n public abstract static class CustomChart {\n\n private final String chartId;\n\n protected CustomChart(String chartId) {\n if (chartId == null) {\n throw new IllegalArgumentException(\"chartId must not be null\");\n }\n this.chartId = chartId;\n }\n\n public JsonObjectBuilder.JsonObject getRequestJsonObject(\n BiConsumer<String, Throwable> errorLogger, boolean logErrors) {\n JsonObjectBuilder builder = new JsonObjectBuilder();\n builder.appendField(\"chartId\", chartId);\n try {\n JsonObjectBuilder.JsonObject data = getChartData();\n if (data == null) {\n // If the data is null we don't send the chart.\n return null;\n }\n builder.appendField(\"data\", data);\n } catch (Throwable t) {\n if (logErrors) {\n errorLogger.accept(\"Failed to get data for custom chart with id \" + chartId, t);\n }\n return null;\n }\n return builder.build();\n }\n\n protected abstract JsonObjectBuilder.JsonObject getChartData() throws Exception;\n }\n\n public static class SingleLineChart extends CustomChart {\n\n private final Callable<Integer> callable;\n\n /**\n * Class constructor.\n *\n * @param chartId The id of the chart.\n * @param callable The callable which is used to request the chart data.\n */\n public SingleLineChart(String chartId, Callable<Integer> callable) {\n super(chartId);\n this.callable = callable;\n }\n\n @Override\n protected JsonObjectBuilder.JsonObject getChartData() throws Exception {\n int value = callable.call();\n if (value == 0) {\n // Null = skip the chart\n return null;\n }\n return new JsonObjectBuilder().appendField(\"value\", value).build();\n }\n }\n\n /**\n * An extremely simple JSON builder.\n *\n * <p>While this class is neither feature-rich nor the most performant one, it's sufficient enough\n * for its use-case.\n */\n public static class JsonObjectBuilder {\n\n private StringBuilder builder = new StringBuilder();\n\n private boolean hasAtLeastOneField = false;\n\n public JsonObjectBuilder() {\n builder.append(\"{\");\n }\n\n /**\n * Appends a null field to the JSON.\n *\n * @param key The key of the field.\n * @return A reference to this object.\n */\n public JsonObjectBuilder appendNull(String key) {\n appendFieldUnescaped(key, \"null\");\n return this;\n }\n\n /**\n * Appends a string field to the JSON.\n *\n * @param key The key of the field.\n * @param value The value of the field.\n * @return A reference to this object.\n */\n public JsonObjectBuilder appendField(String key, String value) {\n if (value == null) {\n throw new IllegalArgumentException(\"JSON value must not be null\");\n }\n appendFieldUnescaped(key, \"\\\"\" + escape(value) + \"\\\"\");\n return this;\n }\n\n /**\n * Appends an integer field to the JSON.\n *\n * @param key The key of the field.\n * @param value The value of the field.\n * @return A reference to this object.\n */\n public JsonObjectBuilder appendField(String key, int value) {\n appendFieldUnescaped(key, String.valueOf(value));\n return this;\n }\n\n /**\n * Appends an object to the JSON.\n *\n * @param key The key of the field.\n * @param object The object.\n * @return A reference to this object.\n */\n public JsonObjectBuilder appendField(String key, JsonObject object) {\n if (object == null) {\n throw new IllegalArgumentException(\"JSON object must not be null\");\n }\n appendFieldUnescaped(key, object.toString());\n return this;\n }\n\n /**\n * Appends a string array to the JSON.\n *\n * @param key The key of the field.\n * @param values The string array.\n * @return A reference to this object.\n */\n public JsonObjectBuilder appendField(String key, String[] values) {\n if (values == null) {\n throw new IllegalArgumentException(\"JSON values must not be null\");\n }\n String escapedValues =\n Arrays.stream(values)\n .map(value -> \"\\\"\" + escape(value) + \"\\\"\")\n .collect(Collectors.joining(\",\"));\n appendFieldUnescaped(key, \"[\" + escapedValues + \"]\");\n return this;\n }\n\n /**\n * Appends an integer array to the JSON.\n *\n * @param key The key of the field.\n * @param values The integer array.\n * @return A reference to this object.\n */\n public JsonObjectBuilder appendField(String key, int[] values) {\n if (values == null) {\n throw new IllegalArgumentException(\"JSON values must not be null\");\n }\n String escapedValues =\n Arrays.stream(values).mapToObj(String::valueOf).collect(Collectors.joining(\",\"));\n appendFieldUnescaped(key, \"[\" + escapedValues + \"]\");\n return this;\n }\n\n /**\n * Appends an object array to the JSON.\n *\n * @param key The key of the field.\n * @param values The integer array.\n * @return A reference to this object.\n */\n public JsonObjectBuilder appendField(String key, JsonObject[] values) {\n if (values == null) {\n throw new IllegalArgumentException(\"JSON values must not be null\");\n }\n String escapedValues =\n Arrays.stream(values).map(JsonObject::toString).collect(Collectors.joining(\",\"));\n appendFieldUnescaped(key, \"[\" + escapedValues + \"]\");\n return this;\n }\n\n /**\n * Appends a field to the object.\n *\n * @param key The key of the field.\n * @param escapedValue The escaped value of the field.\n */\n private void appendFieldUnescaped(String key, String escapedValue) {\n if (builder == null) {\n throw new IllegalStateException(\"JSON has already been built\");\n }\n if (key == null) {\n throw new IllegalArgumentException(\"JSON key must not be null\");\n }\n if (hasAtLeastOneField) {\n builder.append(\",\");\n }\n builder.append(\"\\\"\").append(escape(key)).append(\"\\\":\").append(escapedValue);\n hasAtLeastOneField = true;\n }\n\n /**\n * Builds the JSON string and invalidates this builder.\n *\n * @return The built JSON string.\n */\n public JsonObject build() {\n if (builder == null) {\n throw new IllegalStateException(\"JSON has already been built\");\n }\n JsonObject object = new JsonObject(builder.append(\"}\").toString());\n builder = null;\n return object;\n }\n\n /**\n * Escapes the given string like stated in https://www.ietf.org/rfc/rfc4627.txt.\n *\n * <p>This method escapes only the necessary characters '\"', '\\'. and '\\u0000' - '\\u001F'.\n * Compact escapes are not used (e.g., '\\n' is escaped as \"\\u000a\" and not as \"\\n\").\n *\n * @param value The value to escape.\n * @return The escaped value.\n */\n private static String escape(String value) {\n final StringBuilder builder = new StringBuilder();\n for (int i = 0; i < value.length(); i++) {\n char c = value.charAt(i);\n if (c == '\"') {\n builder.append(\"\\\\\\\"\");\n } else if (c == '\\\\') {\n builder.append(\"\\\\\\\\\");\n } else if (c <= '\\u000F') {\n builder.append(\"\\\\u000\").append(Integer.toHexString(c));\n } else if (c <= '\\u001F') {\n builder.append(\"\\\\u00\").append(Integer.toHexString(c));\n } else {\n builder.append(c);\n }\n }\n return builder.toString();\n }\n\n /**\n * A super simple representation of a JSON object.\n *\n * <p>This class only exists to make methods of the {@link JsonObjectBuilder} type-safe and not\n * allow a raw string inputs for methods like {@link JsonObjectBuilder#appendField(String,\n * JsonObject)}.\n */\n public static class JsonObject {\n\n private final String value;\n\n private JsonObject(String value) {\n this.value = value;\n }\n\n @Override\n public String toString() {\n return value;\n }\n }\n }\n}" } ]
import com.squawkykaka.when_pigs_fly.commands.Heal_Feed; import com.squawkykaka.when_pigs_fly.commands.Menu; import com.squawkykaka.when_pigs_fly.commands.Spawn; import com.squawkykaka.when_pigs_fly.util.EventUtil; import com.squawkykaka.when_pigs_fly.util.Metrics; import org.bukkit.plugin.java.JavaPlugin;
9,194
package com.squawkykaka.when_pigs_fly; public final class WhenPigsFly extends JavaPlugin { private static WhenPigsFly instance; @Override public void onEnable() { instance = this; // Set the instance to the current plugin saveDefaultConfig(); getLogger().info("------------------------"); getLogger().info("---- Plugin Loading ----");
package com.squawkykaka.when_pigs_fly; public final class WhenPigsFly extends JavaPlugin { private static WhenPigsFly instance; @Override public void onEnable() { instance = this; // Set the instance to the current plugin saveDefaultConfig(); getLogger().info("------------------------"); getLogger().info("---- Plugin Loading ----");
EventUtil.register(new AxolotlThrowListener(this));
3
2023-10-17 02:07:39+00:00
12k
greatwqs/finance-manager
src/main/java/com/github/greatwqs/app/service/impl/OrderServiceImpl.java
[ { "identifier": "AppException", "path": "src/main/java/com/github/greatwqs/app/common/exception/AppException.java", "snippet": "public class AppException extends RuntimeException {\n\n private ErrorCode errorCode;\n\n // rewrite default msg in i18n/message.properties\n private String errorMsg;\n\n private List<Object> errorMsgParams;\n\n /***\n * use default msg in i18n/message.properties\n * @param errorCode\n */\n public AppException(ErrorCode errorCode) {\n this.errorCode = errorCode;\n }\n\n /***\n * use default msg with ${errorMsgParams} in i18n/message.properties\n * @param errorCode\n * @param errorMsgParams\n */\n public AppException(ErrorCode errorCode, List<Object> errorMsgParams) {\n this.errorCode = errorCode;\n this.errorMsgParams = errorMsgParams;\n }\n\n /***\n * rewrite default msg\n * @param errorCode\n * @param errorMsg\n */\n public AppException(ErrorCode errorCode, String errorMsg) {\n this.errorCode = errorCode;\n this.errorMsg = errorMsg;\n }\n\n public ErrorCode getErrorCode() {\n return errorCode;\n }\n\n public void setErrorCode(ErrorCode errorCode) {\n this.errorCode = errorCode;\n }\n\n public String getErrorMsg() {\n return errorMsg;\n }\n\n public void setErrorMsg(String errorMsg) {\n this.errorMsg = errorMsg;\n }\n\n public List<Object> getErrorMsgParams() {\n return errorMsgParams;\n }\n\n public void setErrorMsgParams(List<Object> errorMsgParams) {\n this.errorMsgParams = errorMsgParams;\n }\n}" }, { "identifier": "ErrorCode", "path": "src/main/java/com/github/greatwqs/app/common/exception/ErrorCode.java", "snippet": "public enum ErrorCode {\n\n /**\n * HTTP STATUS CODE [0-1000)\n **/\n NORMAL_SUCCESS(200, HttpStatus.OK.value()),\n BAD_REQUEST(400, HttpStatus.BAD_REQUEST.value()),\n UNAUTHORIZED(401, HttpStatus.UNAUTHORIZED.value()),\n FORBIDDEN(403, HttpStatus.FORBIDDEN.value()),\n NOT_FOUND(404, HttpStatus.NOT_FOUND.value()),\n METHOD_NOT_ALLOWED(405, HttpStatus.METHOD_NOT_ALLOWED.value()),\n CONFLICT(409, HttpStatus.CONFLICT.value()),\n UNSUPPORTED_MEDIA_TYPE(415, HttpStatus.UNSUPPORTED_MEDIA_TYPE.value()),\n INTERNAL_SERVER_ERROR(500, HttpStatus.INTERNAL_SERVER_ERROR.value()),\n\n /**\n * Bisiness ERROR [1000-2000)\n **/\n BIZ_UNKNOWN_ERROR(1000, HttpStatus.INTERNAL_SERVER_ERROR.value()),\n USER_LOGIN_ERROR(1001, HttpStatus.FOUND.value()),\n USER_LOGIN_TOKEN_ERROR(1002, HttpStatus.FOUND.value()),\n SUBJECT_NOT_FOUND(1003, HttpStatus.NOT_FOUND.value()),\n TICKET_TYPE_NOT_FOUND(1004, HttpStatus.NOT_FOUND.value()),\n ORDER_TIME_CAN_NOT_UPDATE_OR_DELETE(1005, HttpStatus.BAD_REQUEST.value()),\n ORDER_NOT_FOUND(1006, HttpStatus.NOT_FOUND.value()),\n UPDATE_PASSWORD_CAN_NOT_EMPTY(1007, HttpStatus.BAD_REQUEST.value()),\n UPDATE_PASSWORD_OLD_PASSWORD_NOT_MATCH(1008, HttpStatus.BAD_REQUEST.value()),\n UPDATE_PASSWORD_NEW_PASSWORD_CONFIRM_NOT_MATCH(1009, HttpStatus.BAD_REQUEST.value()),\n UPDATE_PASSWORD_NEW_PASSWORD_LENGTH_NOT_OK(1010, HttpStatus.BAD_REQUEST.value()),\n\n /**\n * Outer Call ERROR [2000+)\n **/\n OUT_UNKNOWN_ERROR(3000, HttpStatus.INTERNAL_SERVER_ERROR.value());\n\n\n private Integer errorCode;\n private Integer httpCode;\n private String errorMsgKey;\n\n ErrorCode(Integer errorCode, Integer httpCode) {\n this.errorCode = errorCode;\n this.httpCode = httpCode;\n }\n\n ErrorCode(Integer errorCode, Integer httpCode, String errorMsgKey) {\n this.errorCode = errorCode;\n this.httpCode = httpCode;\n this.errorMsgKey = errorMsgKey;\n }\n\n /***\n * get error message key.\n * @return example `error.code.2000`\n */\n public String getErrorMsgKey() {\n if (StringUtils.isNotEmpty(errorMsgKey)) {\n return errorMsgKey;\n }\n return AppConstants.ERROR_CODE_PREFIX_KEY + this.errorCode;\n }\n\n public Integer getErrorCode() {\n return errorCode;\n }\n\n public Integer getHttpCode() {\n return httpCode;\n }\n}" }, { "identifier": "OrderSearchBo", "path": "src/main/java/com/github/greatwqs/app/domain/bo/OrderSearchBo.java", "snippet": "@Getter\n@Setter\n@ToString\npublic class OrderSearchBo {\n\n // 开始时间:\n private String createTimeStart;\n\n // 结束时间:\n private String createTimeEnd;\n\n // 缴费/收款人:\n private String orderAccount;\n\n // 票据号:\n private String ticketNo;\n\n // 收支方式:\n private String payType;\n\n // 班 级:\n private String orderClass;\n\n // 备 注:\n private String orderDes;\n\n // 项 目:\n private Long subjectId;\n\n /**\n * 收入, 支出, 不限\n * ALL(0), INCOME(1), OUTCOME(2);\n *\n * @see com.github.greatwqs.app.common.enums.OrderPriceType\n */\n private Integer orderPriceType;\n\n /***\n * 分页 LIMIT 参数\n */\n private Integer beginIndex;\n\n private Integer pageSize;\n}" }, { "identifier": "OrderDownloadDto", "path": "src/main/java/com/github/greatwqs/app/domain/dto/OrderDownloadDto.java", "snippet": "@Getter\n@Setter\n@ToString\npublic class OrderDownloadDto {\n\n // 开始时间:\n private String createTimeStart;\n\n // 结束时间:\n private String createTimeEnd;\n\n // 缴费/收款人:\n private String orderAccount;\n\n // 票据号:\n private String ticketNo;\n\n // 收支方式:\n private String payType;\n\n // 班 级:\n private String orderClass;\n\n // 备 注:\n private String orderDes;\n\n // 项 目:\n private String subjectId;\n\n /**\n * 收入, 支出, 不限\n * ALL(0), INCOME(1), OUTCOME(2);\n *\n * @see OrderPriceType\n */\n private Integer orderPriceType;\n\n /***\n * 导出开始页和结束页\n */\n private Integer startPage;\n\n private Integer endPage;\n\n public OrderDownloadDto(){\n }\n\n public OrderDownloadDto(String createTimeStart, String createTimeEnd, String orderAccount, String ticketNo, String payType, String orderClass, String orderDes, String subjectId, Integer orderPriceType, Integer startPage, Integer endPage) {\n this.createTimeStart = createTimeStart;\n this.createTimeEnd = createTimeEnd;\n this.orderAccount = orderAccount;\n this.ticketNo = ticketNo;\n this.payType = payType;\n this.orderClass = orderClass;\n this.orderDes = orderDes;\n this.subjectId = subjectId;\n this.orderPriceType = orderPriceType;\n this.startPage = startPage;\n this.endPage = endPage;\n }\n\n /**\n * 前台DTO 数据转换到 数据库查询 Bo\n *\n * @return\n */\n public OrderSearchBo toOrderSearchBo() {\n OrderSearchBo searchBo = new OrderSearchBo();\n if (StringUtils.isNotEmpty(this.createTimeStart)) {\n searchBo.setCreateTimeStart(this.createTimeStart);\n }\n if (StringUtils.isNotEmpty(this.createTimeEnd)) {\n searchBo.setCreateTimeEnd(this.createTimeEnd);\n }\n if (StringUtils.isNotEmpty(this.orderAccount)) {\n searchBo.setOrderAccount(this.orderAccount);\n }\n if (StringUtils.isNotEmpty(this.ticketNo)) {\n searchBo.setTicketNo(this.ticketNo);\n }\n if (StringUtils.isNotEmpty(this.payType)) {\n searchBo.setPayType(this.payType);\n }\n if (StringUtils.isNotEmpty(this.orderClass)) {\n searchBo.setOrderClass(this.orderClass);\n }\n if (StringUtils.isNotEmpty(this.orderDes)) {\n searchBo.setOrderDes(this.orderDes);\n }\n if (StringUtils.isNotEmpty(this.subjectId) && NumberUtils.isDigits(this.subjectId)) {\n searchBo.setSubjectId(Long.valueOf(this.subjectId));\n }\n searchBo.setOrderPriceType(OrderPriceType.of(this.orderPriceType).getType());\n searchBo.setBeginIndex(this.getBeginIndex());\n searchBo.setPageSize(this.getPageSize());\n return searchBo;\n }\n\n private Integer getBeginIndex(){\n return (startPage - 1) * AppConstants.ORDER_PAGE_SIZE;\n }\n\n private Integer getPageSize(){\n return (endPage - startPage + 1) * AppConstants.ORDER_PAGE_SIZE;\n }\n}" }, { "identifier": "OrderDto", "path": "src/main/java/com/github/greatwqs/app/domain/dto/OrderDto.java", "snippet": "@Getter\n@Setter\n@ToString\npublic class OrderDto {\n private Long id;\n\n private String orderaccount;\n\n private String orderclass;\n\n private Long subjectid;\n\n private Long tickettypeid;\n\n private String ticketno;\n\n private BigDecimal orderprice;\n\n private String paytype;\n\n private Date ordertime;\n\n private String orderdes;\n\n private Long createuserid;\n\n private Long updateuserid;\n\n public OrderDto(){\n }\n\n public OrderDto(Long id, String orderaccount, String orderclass, Long subjectid,\n Long tickettypeid, String ticketno, BigDecimal orderprice, String paytype,\n Date ordertime, String orderdes, Long createuserid, Long updateuserid\n ) {\n this.id = id;\n this.orderaccount = orderaccount;\n this.orderclass = orderclass;\n this.subjectid = subjectid;\n this.tickettypeid = tickettypeid;\n this.ticketno = ticketno;\n this.orderprice = orderprice;\n this.paytype = paytype;\n this.ordertime = ordertime;\n this.orderdes = orderdes;\n this.createuserid = createuserid;\n this.updateuserid = updateuserid;\n }\n}" }, { "identifier": "OrderSearchDto", "path": "src/main/java/com/github/greatwqs/app/domain/dto/OrderSearchDto.java", "snippet": "@Getter\n@Setter\n@ToString\npublic class OrderSearchDto {\n\n // 开始时间:\n private String createTimeStart;\n\n // 结束时间:\n private String createTimeEnd;\n\n // 缴费/收款人:\n private String orderAccount;\n\n // 票据号:\n private String ticketNo;\n\n // 收支方式:\n private String payType;\n\n // 班 级:\n private String orderClass;\n\n // 备 注:\n private String orderDes;\n\n // 项 目:\n private String subjectId;\n\n /**\n * 收入, 支出, 不限\n * ALL(0), INCOME(1), OUTCOME(2);\n *\n * @see com.github.greatwqs.app.common.enums.OrderPriceType\n */\n private Integer orderPriceType;\n\n /***\n * 分页 LIMIT 参数\n */\n private Integer pageIndex;\n\n public OrderSearchDto(){\n }\n\n public OrderSearchDto(String createTimeStart, String createTimeEnd, String orderAccount, String ticketNo, String payType, String orderClass, String orderDes, String subjectId, Integer orderPriceType, Integer pageIndex) {\n this.createTimeStart = createTimeStart;\n this.createTimeEnd = createTimeEnd;\n this.orderAccount = orderAccount;\n this.ticketNo = ticketNo;\n this.payType = payType;\n this.orderClass = orderClass;\n this.orderDes = orderDes;\n this.subjectId = subjectId;\n this.orderPriceType = orderPriceType;\n this.pageIndex = pageIndex;\n }\n\n /***\n * 默认第一页 && 查询全部.\n *\n * @return\n */\n public static OrderSearchDto defaultDto() {\n OrderSearchDto searchDto = new OrderSearchDto();\n searchDto.setPageIndex(1);\n searchDto.setOrderPriceType(OrderPriceType.ALL.getType());\n return searchDto;\n }\n\n /**\n * 前台DTO 数据转换到 数据库查询 Bo\n *\n * @return\n */\n public OrderSearchBo toOrderSearchBo() {\n OrderSearchBo searchBo = new OrderSearchBo();\n if (StringUtils.isNotEmpty(this.createTimeStart)) {\n searchBo.setCreateTimeStart(this.createTimeStart);\n }\n if (StringUtils.isNotEmpty(this.createTimeEnd)) {\n searchBo.setCreateTimeEnd(this.createTimeEnd);\n }\n if (StringUtils.isNotEmpty(this.orderAccount)) {\n searchBo.setOrderAccount(this.orderAccount);\n }\n if (StringUtils.isNotEmpty(this.ticketNo)) {\n searchBo.setTicketNo(this.ticketNo);\n }\n if (StringUtils.isNotEmpty(this.payType)) {\n searchBo.setPayType(this.payType);\n }\n if (StringUtils.isNotEmpty(this.orderClass)) {\n searchBo.setOrderClass(this.orderClass);\n }\n if (StringUtils.isNotEmpty(this.orderDes)) {\n searchBo.setOrderDes(this.orderDes);\n }\n if (StringUtils.isNotEmpty(this.subjectId) && NumberUtils.isDigits(this.subjectId)) {\n searchBo.setSubjectId(Long.valueOf(this.subjectId));\n }\n searchBo.setOrderPriceType(OrderPriceType.of(this.orderPriceType).getType());\n searchBo.setBeginIndex(PublicUtils.getPageBeginIndex(this.pageIndex, AppConstants.ORDER_PAGE_SIZE));\n searchBo.setPageSize(AppConstants.ORDER_PAGE_SIZE);\n return searchBo;\n }\n}" }, { "identifier": "OrderPo", "path": "src/main/java/com/github/greatwqs/app/domain/po/OrderPo.java", "snippet": "@Getter\n@Setter\n@ToString\npublic class OrderPo {\n private Long id;\n\n private String orderaccount;\n\n private String orderclass;\n\n private Long subjectid;\n\n private Long tickettypeid;\n\n private String ticketno;\n\n private BigDecimal orderprice;\n\n private String paytype;\n\n private Date ordertime;\n\n private String orderdes;\n\n private Boolean isvalid;\n\n private Long createuserid;\n\n private Date createtime;\n\n private Long updateuserid;\n\n private Date updatetime;\n}" }, { "identifier": "UserPo", "path": "src/main/java/com/github/greatwqs/app/domain/po/UserPo.java", "snippet": "@Getter\n@Setter\n@ToString\npublic class UserPo {\n\n\tprivate Long id;\n\n\tprivate String username;\n\n\tprivate String password;\n\n\tprivate String content;\n\n\tprivate Boolean issuperadmin;\n\n\tprivate Boolean isvalid;\n\n\tprivate Date createtime;\n\n\tprivate Date updatetime;\n}" }, { "identifier": "OrderVo", "path": "src/main/java/com/github/greatwqs/app/domain/vo/OrderVo.java", "snippet": "@Getter\n@Setter\n@ToString\npublic class OrderVo {\n private Long id;\n\n private String orderaccount;\n\n private String orderclass;\n\n private Long subjectid;\n\n private SubjectVo subject;\n\n private Long tickettypeid;\n\n private TicketTypeVo ticketType;\n\n private String ticketno;\n\n private BigDecimal orderprice;\n\n private String paytype;\n\n private Date ordertime;\n\n private String orderdes;\n\n private Boolean isvalid;\n\n private Long createuserid;\n\n private Date createtime;\n\n private Long updateuserid;\n\n private Date updatetime;\n\n /***\n * 是否可以更新 或者 删除?\n */\n private Boolean canUpdateOrDelete;\n\n @JsonIgnore\n public String getSubjectName() {\n if (this.subject != null) {\n return this.subject.getName();\n } else {\n return \"无\";\n }\n }\n\n @JsonIgnore\n public String getTicketTypeName() {\n if (this.ticketType != null) {\n return this.ticketType.getName();\n } else {\n return \"无\";\n }\n }\n}" }, { "identifier": "SubjectVo", "path": "src/main/java/com/github/greatwqs/app/domain/vo/SubjectVo.java", "snippet": "@Getter\n@Setter\n@ToString\npublic class SubjectVo {\n private Long id;\n\n private String school;\n\n private String name;\n\n private Boolean isvalid;\n\n private Long createuserid;\n\n private Date createtime;\n\n private Long updateuserid;\n\n private Date updatetime;\n}" }, { "identifier": "TicketTypeVo", "path": "src/main/java/com/github/greatwqs/app/domain/vo/TicketTypeVo.java", "snippet": "@Getter\n@Setter\n@ToString\npublic class TicketTypeVo {\n private Long id;\n\n private String name;\n\n private Boolean isvalid;\n\n private Long createuserid;\n\n private Date createtime;\n\n private Long updateuserid;\n\n private Date updatetime;\n}" }, { "identifier": "OrderPageVo", "path": "src/main/java/com/github/greatwqs/app/domain/vo/page/OrderPageVo.java", "snippet": "@Getter\n@Builder\npublic class OrderPageVo {\n\n /**\n * current page index\n */\n private Integer pageIndex;\n\n /***\n * page item count\n */\n private Integer pageSize;\n\n /***\n * total page count\n */\n private Integer pageCount;\n\n /**\n * total item count\n */\n private Integer totalCount;\n\n /**\n * totalCount for price\n */\n private BigDecimal totalPrice;\n\n /***\n * current item details list\n */\n private List<OrderVo> orderList;\n}" }, { "identifier": "OrderManager", "path": "src/main/java/com/github/greatwqs/app/manager/OrderManager.java", "snippet": "public interface OrderManager {\n\n /**\n * 获取 OrderPo\n *\n * @param orderId\n * @return\n */\n OrderPo getPoNotNull(Long orderId);\n\n /***\n * 是否存在 subjectId 的订单记录?\n * @param subjectId\n * @return\n */\n Boolean isSubjectIdOrderExist(Long subjectId);\n\n /***\n * 是否存在 ticketTypeId 的订单记录?\n * @param ticketTypeId\n * @return\n */\n Boolean isTicketTypeIdOrderExist(Long ticketTypeId);\n}" }, { "identifier": "SubjectManager", "path": "src/main/java/com/github/greatwqs/app/manager/SubjectManager.java", "snippet": "public interface SubjectManager {\n\n void insert(SubjectPo subjectlist);\n\n SubjectVo getVo(Long subjectId);\n\n List<SubjectPo> getPoList(List<Long> subjectIdList);\n\n List<SubjectVo> getVoList(List<Long> subjectIdList);\n\n Map<Long, SubjectVo> getVoMap(List<Long> subjectIdList);\n\n Map<String, SubjectVo> getNameVoMap();\n\n void update(SubjectPo subjectlist);\n\n void delete(Long subjectId, Long userId);\n}" }, { "identifier": "TicketTypeManager", "path": "src/main/java/com/github/greatwqs/app/manager/TicketTypeManager.java", "snippet": "public interface TicketTypeManager {\n\n void insert(TicketTypePo ticketTypePo);\n\n TicketTypePo getPo(String ticketTypeName);\n\n List<TicketTypePo> getPoList(List<Long> ticketTypeIdList);\n\n TicketTypeVo getVo(Long ticketTypeId);\n\n List<TicketTypeVo> getVoList(List<Long> ticketTypeIdList);\n\n Map<Long, TicketTypeVo> getVoMap(List<Long> ticketTypeIdList);\n\n Map<String, TicketTypeVo> getNameVoMap();\n\n void update(TicketTypePo ticketTypePo);\n\n void delete(Long ticketTypeId, Long userId);\n}" }, { "identifier": "OrderlistMapper", "path": "src/main/java/com/github/greatwqs/app/mapper/OrderlistMapper.java", "snippet": "@Mapper\npublic interface OrderlistMapper {\n int deleteByPrimaryKey(Long id);\n\n int insert(OrderPo record);\n\n int insertSelective(OrderPo record);\n\n OrderPo selectByPrimaryKey(Long id);\n\n List<OrderPo> selectByOrderSearch(OrderSearchBo searchBo);\n\n List<OrderPo> selectBySubjectId(@Param(\"subjectId\") Long subjectId, @Param(\"limitCount\") Integer limitCount);\n\n List<OrderPo> selectByTicketTypeId(@Param(\"ticketTypeId\") Long ticketTypeId, @Param(\"limitCount\") Integer limitCount);\n\n Integer selectCountByOrderSearch(OrderSearchBo searchBo);\n\n BigDecimal selectTotalPriceByOrderSearch(OrderSearchBo searchBo);\n\n int updateByPrimaryKeySelective(OrderPo record);\n\n int updateByPrimaryKey(OrderPo record);\n}" }, { "identifier": "OrderService", "path": "src/main/java/com/github/greatwqs/app/service/OrderService.java", "snippet": "public interface OrderService {\n\n /***\n * search query order.\n * @param searchDto\n * @param userPo\n * @return\n */\n OrderPageVo getOrderPageVo(OrderSearchDto searchDto, UserPo userPo);\n\n /***\n * 查询下载订单列表\n *\n * @param downloadDto\n * @param userPo\n * @return\n */\n List<OrderVo> queryDownload(OrderDownloadDto downloadDto, UserPo userPo);\n\n /**\n * return created orderId\n *\n * @param orderDto\n * @param userPo\n * @return\n */\n Long create(OrderDto orderDto, UserPo userPo);\n\n /**\n * update\n *\n * @param orderDto\n * @param userPo\n */\n void update(OrderDto orderDto, UserPo userPo);\n\n /***\n * delete, update isValid = 0\n *\n * @param orderId\n * @param userPo\n */\n void delete(Long orderId, UserPo userPo);\n}" }, { "identifier": "FinanceUtils", "path": "src/main/java/com/github/greatwqs/app/utils/FinanceUtils.java", "snippet": "public class FinanceUtils {\n\n /***\n * 替换字符串中JS的敏感字符串: 回车, 两边的空格, 引号, 括号\n * @param orderDes\n * @return\n */\n public static String trimJsChar(String orderDes){\n // 删除两边的空格\n orderDes = StringUtils.trimToEmpty(orderDes);\n\n // 删除回车\n orderDes = orderDes.replace(\"\\n\",\" \");\n\n // 删除单引号和双引号\n orderDes = orderDes.replace(\"'\",\" \");\n orderDes = orderDes.replace(\"\\\"\",\" \");\n\n // 删除括号\n orderDes = orderDes.replace(\"(\",\" \");\n orderDes = orderDes.replace(\")\",\" \");\n\n if (StringUtils.isEmpty(orderDes)){\n return \"空\";\n }\n return StringUtils.trimToEmpty(orderDes);\n }\n\n public static void main(String[] args) {\n String aaa = \" tar -cvf xiangjun-demo.tar xiangjun-demo/\\n\" +\n \"\\n\" +\n \"scp xiangjun-demo.tar [email protected]:/root\\n \";\n System.out.println(trimJsChar(aaa));\n }\n}" }, { "identifier": "PublicUtils", "path": "src/main/java/com/github/greatwqs/app/utils/PublicUtils.java", "snippet": "public class PublicUtils {\n\n\t/***\n\t * getUuid, 36 char\n\t * @return\n\t */\n\tpublic static final String getUuid() {\n\t\treturn UUID.randomUUID().toString();\n\t}\n\n\t/****\n\t * getPageBeginIndex\n\t * @param pageNum The first pageNum is 1\n\t * @param pageSize\n\t * @return\n\t */\n\tpublic static final Integer getPageBeginIndex(Integer pageNum, Integer pageSize) {\n\t\treturn (pageNum - 1) * pageSize;\n\t}\n\n\t/***\n\t * get Total Page\n\t * @param totalRecordCount\n\t * @param onePageRecordSize\n\t * @return\n\t */\n\tpublic static final Integer getTotalPage(Integer totalRecordCount, Integer onePageRecordSize) {\n\t\treturn totalRecordCount / onePageRecordSize + ((totalRecordCount % onePageRecordSize == 0) ? 0 : 1);\n\t}\n\n\t/**\n\t * getClazzOrMethodAnnotation from HandlerMethod\n\t * 1. get annotation from class.\n\t * 2. get annotation from method.\n\t * @param handlerMethod\n\t * @param annotationClass\n\t * @param <T>\n\t * @return\n\t */\n\tpublic static <T extends Annotation> T getClazzOrMethodAnnotation(HandlerMethod handlerMethod,\n\t\tClass<T> annotationClass) {\n\t\tClass<?> clazz = handlerMethod.getBeanType();\n\t\tT annotation = clazz.getAnnotation(annotationClass);\n\t\tif (annotation != null) {\n\t\t\treturn annotation;\n\t\t}\n\n\t\treturn handlerMethod.getMethod().getAnnotation(annotationClass);\n\t}\n\n\tpublic static <T extends Annotation> T findClazzOrMethodAnnotation(HandlerMethod handlerMethod,\n\t\tClass<T> annotationClass) {\n\t\tClass<?> clazz = handlerMethod.getBeanType();\n\n\t\tT annotation = AnnotationUtils.findAnnotation(clazz, annotationClass);\n\t\tif (annotation != null) {\n\t\t\treturn annotation;\n\t\t}\n\n\t\treturn AnnotationUtils.findAnnotation(handlerMethod.getMethod(), annotationClass);\n\t}\n\n\t/***\n\t * isEnglishLetterOrNumber,\n\t * is all the cs param String in [A-Z] || [a-z] || [0-9]\n\t * @param cs\n\t * @return\n\t */\n\tpublic static boolean isEnglishLetterOrNumber(final CharSequence cs) {\n\t\tif (StringUtils.isEmpty(cs)) {\n\t\t\treturn false;\n\t\t}\n\n\t\tfinal int length = cs.length();\n\t\tfor (int index = 0; index < length; index++) {\n\t\t\tif (isEnglishLetterOrNumber(cs.charAt(index)) == false) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}\n\n\t/***\n\t * isEnglishLetterOrNumber,\n\t * is the char in [A-Z] || [a-z] || [0-9]\n\t * @param letter\n\t * @return\n\t */\n\tprivate static boolean isEnglishLetterOrNumber(final char letter) {\n\t\tif (letter >= 48 && letter <= 57) {\n\t\t\treturn true; // 0-9\n\t\t}\n\t\treturn isEnglishLetter(letter);\n\t}\n\n\t/***\n\t * isEnglishLetter, is all the cs param String in [A-Z] || [a-z]\n\t * @param cs\n\t * @return\n\t */\n\tpublic static boolean isEnglishLetter(final CharSequence cs) {\n\t\tif (StringUtils.isEmpty(cs)) {\n\t\t\treturn false;\n\t\t}\n\n\t\tfinal int length = cs.length();\n\t\tfor (int index = 0; index < length; index++) {\n\t\t\tif (isEnglishLetter(cs.charAt(index)) == false) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}\n\n\t/***\n\t * isEnglishLetter, is the char in [A-Z] || [a-z]\n\t * @param letter\n\t * @return\n\t */\n\tprivate static boolean isEnglishLetter(final char letter) {\n\t\tif (letter > 64 && letter < 91) {\n\t\t\treturn true;\n\t\t} else if (letter > 96 && letter < 123) {\n\t\t\treturn true;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t/***\n\t * get call class name\n\t * @return\n\t */\n\tpublic static String getClassName() {\n\t\tString classFulName = Thread.currentThread().getStackTrace()[2].getClassName();\n\t\tint dotIndex = classFulName.lastIndexOf(\".\");\n\t\treturn classFulName.substring(dotIndex + 1);\n\t}\n\n\t/***\n\t * get call method name\n\t * @return\n\t */\n\tpublic static String getMethodName() {\n\t\treturn Thread.currentThread().getStackTrace()[2].getMethodName();\n\t}\n\n}" }, { "identifier": "Lists", "path": "src/main/java/com/github/greatwqs/app/utils/collection/Lists.java", "snippet": "public final class Lists {\n\n\tprivate Lists() {\n\t}\n\n\t/***\n\t * isEmpty\n\t * @param list\n\t * @return\n\t */\n\tpublic static boolean isEmpty(Collection<?> list) {\n\t\treturn list == null || list.isEmpty();\n\t}\n\n\t/***\n\t * isNotEmpty\n\t * @param list\n\t * @return\n\t */\n\tpublic static boolean isNotEmpty(Collection<?> list) {\n\t\treturn !isEmpty(list);\n\t}\n\n\t/***\n\t * newArrayList\n\t * @param elements\n\t * @param <T>\n\t * @return\n\t */\n\t@SafeVarargs\n\tpublic static <T> ArrayList<T> newArrayList(T... elements) {\n\t\treturn com.google.common.collect.Lists.newArrayList(elements);\n\t}\n\n\t/***\n\t * newLinkedList\n\t * @param elements\n\t * @param <T>\n\t * @return\n\t */\n\t@SafeVarargs\n\tpublic static <T> LinkedList<T> newLinkedList(T... elements) {\n\t\tfinal LinkedList<T> linkedList = new LinkedList<T>();\n\t\tif (elements == null || elements.length == 0) {\n\t\t\treturn linkedList;\n\t\t}\n\t\tfor (final T t : elements) {\n\t\t\tlinkedList.add(t);\n\t\t}\n\t\treturn linkedList;\n\t}\n\n\t/***\n\t * newHashSet\n\t * @param elements\n\t * @param <T>\n\t * @return\n\t */\n\t@SafeVarargs\n\tpublic static <T> HashSet<T> newHashSet(T... elements) {\n\t\treturn com.google.common.collect.Sets.newHashSet(elements);\n\t}\n\n\t/****\n\t * splitToInt\n\t * @param str\n\t * @param separator\n\t * @return\n\t */\n\tpublic static List<Integer> splitToInt(String str, String separator) {\n\t\tif (StringUtils.isBlank(str)) {\n\t\t\treturn Collections.emptyList();\n\t\t}\n\t\tString[] parts = StringUtils.splitByWholeSeparator(str, separator);\n\t\tList<Integer> result = new ArrayList<Integer>(parts.length);\n\t\tfor (String num : parts) {\n\t\t\tif (NumberUtils.isDigits(num)) {\n\t\t\t\tresult.add(Integer.valueOf(num));\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\n\t/***\n\t * removeNull\n\t * @param list\n\t */\n\tpublic static void removeNull(Collection<?> list) {\n\t\tif (isEmpty(list)) {\n\t\t\treturn;\n\t\t}\n\t\tfor (Iterator<?> iterator = list.iterator(); iterator.hasNext(); ) {\n\t\t\tif (iterator.next() == null) {\n\t\t\t\titerator.remove();\n\t\t\t}\n\t\t}\n\t}\n\n\t/***\n\t * Collection size\n\t * @param list\n\t * @return\n\t */\n\tpublic static int size(Collection<?> list) {\n\t\treturn list == null ? 0 : list.size();\n\t}\n}" } ]
import com.github.greatwqs.app.common.exception.AppException; import com.github.greatwqs.app.common.exception.ErrorCode; import com.github.greatwqs.app.domain.bo.OrderSearchBo; import com.github.greatwqs.app.domain.dto.OrderDownloadDto; import com.github.greatwqs.app.domain.dto.OrderDto; import com.github.greatwqs.app.domain.dto.OrderSearchDto; import com.github.greatwqs.app.domain.po.OrderPo; import com.github.greatwqs.app.domain.po.UserPo; import com.github.greatwqs.app.domain.vo.OrderVo; import com.github.greatwqs.app.domain.vo.SubjectVo; import com.github.greatwqs.app.domain.vo.TicketTypeVo; import com.github.greatwqs.app.domain.vo.page.OrderPageVo; import com.github.greatwqs.app.manager.OrderManager; import com.github.greatwqs.app.manager.SubjectManager; import com.github.greatwqs.app.manager.TicketTypeManager; import com.github.greatwqs.app.mapper.OrderlistMapper; import com.github.greatwqs.app.service.OrderService; import com.github.greatwqs.app.utils.FinanceUtils; import com.github.greatwqs.app.utils.PublicUtils; import com.github.greatwqs.app.utils.collection.Lists; import lombok.extern.slf4j.Slf4j; import org.modelmapper.ModelMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.math.BigDecimal; import java.util.Date; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import static com.github.greatwqs.app.common.AppConstants.ORDER_PAGE_SIZE;
8,923
package com.github.greatwqs.app.service.impl; /** * @author greatwqs * Create on 2020/7/4 */ @Slf4j @Service public class OrderServiceImpl implements OrderService { // 订单超过多少时间不能进行更新或删除操作 (1天) private static final Long CAN_UPDATE_OR_DELETE_EXPIRE_TIME = 1000L * 60 * 60 * 24 * 1; @Autowired private ModelMapper modelMapper; @Autowired private OrderlistMapper orderlistMapper; @Autowired private OrderManager orderManager; @Autowired private SubjectManager subjectManager; @Autowired private TicketTypeManager ticketTypeManager; @Override public OrderPageVo getOrderPageVo(OrderSearchDto searchDto, UserPo userPo) { OrderSearchBo searchBo = searchDto.toOrderSearchBo(); List<OrderPo> orderPoList = orderlistMapper.selectByOrderSearch(searchBo); Integer totalCount = orderlistMapper.selectCountByOrderSearch(searchBo); BigDecimal totalPrice = orderlistMapper.selectTotalPriceByOrderSearch(searchBo); List<OrderVo> orderVoList = poToVo(orderPoList, userPo); return OrderPageVo.builder().orderList(orderVoList) .totalCount(totalCount) .totalPrice(totalPrice != null ? totalPrice : BigDecimal.valueOf(0)) .pageCount(PublicUtils.getTotalPage(totalCount, ORDER_PAGE_SIZE)) .pageIndex(searchDto.getPageIndex()) .pageSize(ORDER_PAGE_SIZE) .build(); } /*** * po 转 vo */ private List<OrderVo> poToVo(List<OrderPo> orderPoList, UserPo userPo) { List<OrderVo> orderVoList = orderPoList.stream().map(po -> poToVo(po, userPo)).collect(Collectors.toList()); this.setSubject(orderVoList); this.setTicketType(orderVoList); return orderVoList; } private OrderVo poToVo(OrderPo orderPo, UserPo userPo) { OrderVo orderVo = modelMapper.map(orderPo, OrderVo.class); orderVo.setCanUpdateOrDelete(this.canUpdateOrDelete(orderPo, userPo)); return orderVo; } /*** * 为 OrderVo 设置 SubjectVo; * @param orderVoList */ private void setSubject(List<OrderVo> orderVoList) { if (Lists.isEmpty(orderVoList)) { return; } List<Long> subjectIdList = orderVoList.stream() .map(OrderVo::getSubjectid) .distinct() .collect(Collectors.toList()); Map<Long, SubjectVo> subjectVoMap = subjectManager.getVoMap(subjectIdList); for (OrderVo orderVo : orderVoList) { orderVo.setSubject(subjectVoMap.get(orderVo.getSubjectid())); } } /*** * 为 OrderVo 设置 TicketTypeVo; * @param orderVoList */ private void setTicketType(List<OrderVo> orderVoList) { if (Lists.isEmpty(orderVoList)) { return; } List<Long> ticketTypeIdList = orderVoList.stream() .map(OrderVo::getTickettypeid) .distinct() .collect(Collectors.toList()); Map<Long, TicketTypeVo> ticketTypeVoMap = ticketTypeManager.getVoMap(ticketTypeIdList); for (OrderVo orderVo : orderVoList) { orderVo.setTicketType(ticketTypeVoMap.get(orderVo.getTickettypeid())); } } @Override public List<OrderVo> queryDownload(OrderDownloadDto downloadDto, UserPo userPo) { OrderSearchBo orderSearchBo = downloadDto.toOrderSearchBo(); List<OrderPo> orderPoList = orderlistMapper.selectByOrderSearch(orderSearchBo); List<OrderVo> orderVoList = poToVo(orderPoList, userPo); return orderVoList; } /** * 订单是否可以更新或者删除? * 如果是超级管理员可以操作, 非超级管理员只能在某段时间内操作! * * @param orderPo * @param userPo * @return */ private Boolean canUpdateOrDelete(OrderPo orderPo, UserPo userPo) { if (userPo.getIssuperadmin()) { return true; } return System.currentTimeMillis() - orderPo.getCreatetime().getTime() < CAN_UPDATE_OR_DELETE_EXPIRE_TIME; } private void checkCanUpdateOrDelete(OrderPo po, UserPo userPo) { if (!canUpdateOrDelete(po, userPo)) { log.error("ORDER_TIME_CAN_NOT_UPDATE_OR_DELETE, orderId: s%", po.getId()); throw new AppException(ErrorCode.ORDER_TIME_CAN_NOT_UPDATE_OR_DELETE); } } @Override @Transactional
package com.github.greatwqs.app.service.impl; /** * @author greatwqs * Create on 2020/7/4 */ @Slf4j @Service public class OrderServiceImpl implements OrderService { // 订单超过多少时间不能进行更新或删除操作 (1天) private static final Long CAN_UPDATE_OR_DELETE_EXPIRE_TIME = 1000L * 60 * 60 * 24 * 1; @Autowired private ModelMapper modelMapper; @Autowired private OrderlistMapper orderlistMapper; @Autowired private OrderManager orderManager; @Autowired private SubjectManager subjectManager; @Autowired private TicketTypeManager ticketTypeManager; @Override public OrderPageVo getOrderPageVo(OrderSearchDto searchDto, UserPo userPo) { OrderSearchBo searchBo = searchDto.toOrderSearchBo(); List<OrderPo> orderPoList = orderlistMapper.selectByOrderSearch(searchBo); Integer totalCount = orderlistMapper.selectCountByOrderSearch(searchBo); BigDecimal totalPrice = orderlistMapper.selectTotalPriceByOrderSearch(searchBo); List<OrderVo> orderVoList = poToVo(orderPoList, userPo); return OrderPageVo.builder().orderList(orderVoList) .totalCount(totalCount) .totalPrice(totalPrice != null ? totalPrice : BigDecimal.valueOf(0)) .pageCount(PublicUtils.getTotalPage(totalCount, ORDER_PAGE_SIZE)) .pageIndex(searchDto.getPageIndex()) .pageSize(ORDER_PAGE_SIZE) .build(); } /*** * po 转 vo */ private List<OrderVo> poToVo(List<OrderPo> orderPoList, UserPo userPo) { List<OrderVo> orderVoList = orderPoList.stream().map(po -> poToVo(po, userPo)).collect(Collectors.toList()); this.setSubject(orderVoList); this.setTicketType(orderVoList); return orderVoList; } private OrderVo poToVo(OrderPo orderPo, UserPo userPo) { OrderVo orderVo = modelMapper.map(orderPo, OrderVo.class); orderVo.setCanUpdateOrDelete(this.canUpdateOrDelete(orderPo, userPo)); return orderVo; } /*** * 为 OrderVo 设置 SubjectVo; * @param orderVoList */ private void setSubject(List<OrderVo> orderVoList) { if (Lists.isEmpty(orderVoList)) { return; } List<Long> subjectIdList = orderVoList.stream() .map(OrderVo::getSubjectid) .distinct() .collect(Collectors.toList()); Map<Long, SubjectVo> subjectVoMap = subjectManager.getVoMap(subjectIdList); for (OrderVo orderVo : orderVoList) { orderVo.setSubject(subjectVoMap.get(orderVo.getSubjectid())); } } /*** * 为 OrderVo 设置 TicketTypeVo; * @param orderVoList */ private void setTicketType(List<OrderVo> orderVoList) { if (Lists.isEmpty(orderVoList)) { return; } List<Long> ticketTypeIdList = orderVoList.stream() .map(OrderVo::getTickettypeid) .distinct() .collect(Collectors.toList()); Map<Long, TicketTypeVo> ticketTypeVoMap = ticketTypeManager.getVoMap(ticketTypeIdList); for (OrderVo orderVo : orderVoList) { orderVo.setTicketType(ticketTypeVoMap.get(orderVo.getTickettypeid())); } } @Override public List<OrderVo> queryDownload(OrderDownloadDto downloadDto, UserPo userPo) { OrderSearchBo orderSearchBo = downloadDto.toOrderSearchBo(); List<OrderPo> orderPoList = orderlistMapper.selectByOrderSearch(orderSearchBo); List<OrderVo> orderVoList = poToVo(orderPoList, userPo); return orderVoList; } /** * 订单是否可以更新或者删除? * 如果是超级管理员可以操作, 非超级管理员只能在某段时间内操作! * * @param orderPo * @param userPo * @return */ private Boolean canUpdateOrDelete(OrderPo orderPo, UserPo userPo) { if (userPo.getIssuperadmin()) { return true; } return System.currentTimeMillis() - orderPo.getCreatetime().getTime() < CAN_UPDATE_OR_DELETE_EXPIRE_TIME; } private void checkCanUpdateOrDelete(OrderPo po, UserPo userPo) { if (!canUpdateOrDelete(po, userPo)) { log.error("ORDER_TIME_CAN_NOT_UPDATE_OR_DELETE, orderId: s%", po.getId()); throw new AppException(ErrorCode.ORDER_TIME_CAN_NOT_UPDATE_OR_DELETE); } } @Override @Transactional
public Long create(OrderDto orderDto, UserPo userPo) {
4
2023-10-16 12:45:57+00:00
12k
Wind-Gone/Vodka
code/src/main/java/benchmark/olap/OLAPTerminal.java
[ { "identifier": "OLTPClient", "path": "code/src/main/java/benchmark/oltp/OLTPClient.java", "snippet": "@Getter\npublic class OLTPClient implements CommonConfig {\n private static org.apache.log4j.Logger log = Logger.getLogger(OLTPClient.class);\n public static int numWarehouses;\n private static String resultDirName = null;\n private static BufferedWriter resultCSV = null;\n private static BufferedWriter runInfoCSV = null;\n private static String propertyPath;\n private static int runID = 0;\n private int dbType = DB_UNKNOWN;\n static OLTPTerminal[] TPterminals;\n private String[] terminalNames;\n private static OLAPTerminal[] APterminals;\n private String[] APterminalNames;\n private boolean terminalsBlockingExit = false;\n private long terminalsStarted = 0, sessionCount = 0;\n public static long transactionCount = 0;\n public static AtomicInteger rollBackTransactionCount = new AtomicInteger(0);\n private long terminalsAPstarted = 0;\n private Object counterLock = new Object();\n private long newOrderCounter = 0, sessionEndTimestamp, sessionNextTimestamp = Long.MAX_VALUE, sessionNextKounter = 0;\n public static long sessionStartTimestamp = 0;\n private long sessionEndTargetTime = -1, fastNewOrderCounter;\n public long recentTpmC = 0;\n public static long recentTpmTotal = 0;\n public static double txn_add_interval = 49.5;\n private static boolean signalTerminalsRequestEndSent = false;\n private boolean databaseDriverLoaded;\n private boolean signalAPTerminalsRequestEndSent = false;\n private String sessionStart, sessionEnd;\n private int limPerMin_Terminal;\n public static AtomicInteger DeliveryBG = new AtomicInteger(0);\n public static AtomicInteger newOrder = new AtomicInteger(0);\n public static AtomicInteger payment = new AtomicInteger(0);\n public static AtomicInteger orderStatus = new AtomicInteger(0);\n public static AtomicInteger stockLevel = new AtomicInteger(0);\n public static AtomicInteger receiveGoods = new AtomicInteger(0);\n\n private BasicRandom rnd;\n private OSCollector osCollector = null;\n public static long gloabalSysCurrentTime;\n\n // time density for olap queries\n private int timePointDensity = 10; // 平均每小时点的个数 10\n public static double thread_add_interval = 0; // 一分钟内需要增加的时间间隔\n public static Date currTime = null;\n public static int deltaDays;\n public static int deltaDays2 = 0;\n public static ScheduledExecutorService scheduledExecutorService;\n public static ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);\n // fitting functions\n public static double b;\n public static double k;\n public static double b1;\n public static double k1;\n public static double b2;\n public static double k2;\n public static List<double[]> generalOorderTSize = new ArrayList<>();\n public static List<double[]> generalOrderlineTSize = new ArrayList<>();\n public static Vector<String> fitFunc1 = new Vector<>(); //oorder\n public static Vector<String> fitFunc2 = new Vector<>(); //order_line\n public static ArrayList<Triple<Double, Double, Double>> freshnessTime;\n public static ConcurrentLinkedDeque<Pair<Long, Long>> deliveryList = new ConcurrentLinkedDeque<>();\n\n // htap check variables\n private HTAPCheckInfo htapCheckInfo = new HTAPCheckInfo();\n private HTAPCheck htapCheck = null;\n public static AtomicInteger htapCheckQueryNumber;\n\n // TP recorder\n private static TPRecorder tpRecorder = null;\n\n // properties\n private ConnectionProperty connectionProperty;\n public static RunningProperty runningProperty;\n\n // dynamic ap\n private boolean checkInterference;\n private int step;\n private int increaseInterval;\n\n public OLTPClient() throws ParseException, IOException {\n loadConfiguration();\n initParametersForReceiveGoods();\n\n // Connect Parameters\n String iDB = connectionProperty.getDb();\n checkAndSetDBType(iDB);\n String iDriver = connectionProperty.getDriver();\n String iConn = connectionProperty.getConn();\n String iUser = connectionProperty.getUser();\n String iPassword = connectionProperty.getPassword();\n String connAP = connectionProperty.getConnAP();\n\n // Running Parameters\n numWarehouses = runningProperty.getWarehouses();\n int numTerminals = runningProperty.getTPterminals();\n int iRunTxnsPerTerminal = runningProperty.getRunTxnsPerTerminal();\n double iRunMins = runningProperty.getRunMins();\n double TPthreshold = runningProperty.getTPthreshold();\n double limPerMin = runningProperty.getLimitTxnsPerMin();\n boolean terminalWarehouseFixed = runningProperty.isTerminalWarehouseFixed();\n boolean useStoredProcedures = runningProperty.isUseStoredProcedures();\n double newOrderWeightValue = runningProperty.getNewOrderWeight();\n double paymentWeightValue = runningProperty.getPaymentWeight();\n double orderStatusWeightValue = runningProperty.getOrderStatusWeight();\n double deliveryWeightValue = runningProperty.getDeliveryWeight();\n double stockLevelWeightValue = runningProperty.getStockLevelWeight();\n double receiveGoodsWeightValue = runningProperty.getReceiveGoodsWeight();\n int osCollectorInterval = runningProperty.getOsCollectorInterval();\n String resultDirectory = runningProperty.getResultDirectory();\n String osCollectorScript = runningProperty.getOsCollectorScript();\n String osCollectorDevices = runningProperty.getOsCollectorDevices();\n String osCollectorSSHAddr = runningProperty.getOsCollectorSSHAddr();\n boolean parallelSwitch = runningProperty.isParallel();\n int parallel_degree = runningProperty.getParallel_degree();\n int isolation_level = runningProperty.getIsolation_level();\n boolean iIsHtapCheck = runningProperty.isHtapCheck();\n int testTimeInterval = runningProperty.getTestTimeInterval();\n int APTerminals = runningProperty.getAPTerminals();\n int dynamicParam = runningProperty.getDynamicParam();\n\n // dynamic ap\n checkInterference = runningProperty.isCheckInterference();\n step = runningProperty.getStep();\n increaseInterval = runningProperty.getIncreaseInterval();\n htapCheckQueryNumber = new AtomicInteger(runningProperty.getHtapCheckQueryNumber());\n freshnessTime = new ArrayList<>();\n\n // common variables\n double upLimit = 0.0;\n boolean iRunMinsBool = false;\n this.limPerMin_Terminal = (limPerMin != 0) ? (int) ((limPerMin) * (1 + upLimit) / numTerminals) : -1;\n this.fastNewOrderCounter = 0;\n this.newOrderCounter = 0;\n Properties dbProps = new Properties();\n dbProps.setProperty(\"user\", iUser);\n dbProps.setProperty(\"password\", iPassword);\n TPterminals = new OLTPTerminal[numTerminals];\n terminalNames = new String[numTerminals];\n terminalsStarted = numTerminals;\n int htapCheckCrossTerminalNum = 0;\n APterminals = new OLAPTerminal[APTerminals];\n APterminalNames = new String[APTerminals];\n terminalsAPstarted = APTerminals;\n\n try {\n printMessage(\"Loading database driver: \\'\" + iDriver + \"\\'...\");\n printMessage(\"WarehouseNumber is: \" + numWarehouses);\n printMessage(\"Target Throughput is: \" + limPerMin);\n printMessage(\"OLTP Thread Number is: \" + numTerminals);\n printMessage(\"OLAP Thread Number is: \" + APTerminals);\n printMessage(\"Isolation Level is: \" + isolation_level);\n printMessage(\"Transaction\\tWeight\");\n printMessage(\"% New-Order\\t\" + newOrderWeightValue);\n printMessage(\"% Payment\\t\" + paymentWeightValue);\n printMessage(\"% Order-Status\\t\" + orderStatusWeightValue);\n printMessage(\"% Delivery\\t\" + deliveryWeightValue);\n printMessage(\"% Stock-Level\\t\" + stockLevelWeightValue);\n printMessage(\"% Receive-Goods\\t\" + receiveGoodsWeightValue);\n\n Class.forName(iDriver);\n databaseDriverLoaded = true;\n prepareForLog(resultDirectory, osCollectorScript, osCollectorInterval, osCollectorSSHAddr, osCollectorDevices);\n } catch (Exception ex) {\n errorMessage(\"Unable to utils.load the database driver!\");\n databaseDriverLoaded = false;\n }\n\n if (databaseDriverLoaded) {\n try {\n boolean limitIsTime = iRunMinsBool;\n int transactionsPerTerminal = -1;\n int loadWarehouses;\n long executionTimeMillis = -1;\n long CLoad;\n\n try {\n loadWarehouses = Integer.parseInt(jTPCCUtil.getConfig(iConn, dbProps, \"warehouses\"));\n CLoad = Long.parseLong(jTPCCUtil.getConfig(iConn, dbProps, \"nURandCLast\"));\n this.rnd = new BasicRandom(CLoad);\n printMessage(\"C value for C_LAST during utils.load: \" + CLoad);\n printMessage(\"C value for C_LAST this run: \" + rnd.getNURandCLast());\n updateStatusLine();\n } catch (Exception e) {\n errorMessage(e.getMessage());\n throw e;\n }\n\n try {\n if (iRunMins != 0 && iRunTxnsPerTerminal == 0) {\n iRunMinsBool = true;\n } else if (iRunMins == 0 && iRunTxnsPerTerminal != 0) {\n iRunMinsBool = false;\n } else {\n throw new NumberFormatException();\n }\n } catch (NumberFormatException e1) {\n errorMessage(\"Must indicate either entity.transactions per terminal or number of run minutes!\");\n throw new Exception();\n }\n\n if (numWarehouses > loadWarehouses) {\n errorMessage(\"numWarehouses cannot be greater \" + \"than the warehouses loaded in the database\");\n throw new Exception();\n }\n try {\n if (numTerminals > 10 * numWarehouses)\n throw new NumberFormatException();\n } catch (NumberFormatException e1) {\n errorMessage(\"Invalid number of TPterminals!\");\n throw new Exception();\n }\n if (iRunMins != 0 && iRunTxnsPerTerminal == 0) {\n try {\n executionTimeMillis = (long) iRunMins * 60000;\n if (executionTimeMillis <= 0)\n throw new NumberFormatException();\n } catch (NumberFormatException e1) {\n errorMessage(\"Invalid number of minutes!\");\n throw new Exception();\n }\n } else {\n try {\n transactionsPerTerminal = iRunTxnsPerTerminal;\n if (transactionsPerTerminal <= 0)\n throw new NumberFormatException();\n } catch (NumberFormatException e1) {\n errorMessage(\"Invalid number of entity.transactions per terminal!\");\n throw new Exception();\n }\n }\n\n printMessage(\"Session started!\");\n if (!limitIsTime)\n printMessage(\"Creating \" + numTerminals + \" terminal(s) with \" + transactionsPerTerminal + \" transaction(s) per terminal...\");\n else\n printMessage(\"Creating \" + numTerminals + \" terminal(s) with \" + (executionTimeMillis / 60000) + \" minute(s) of execution...\");\n printMessage(\"Transaction Weights: \" + newOrderWeightValue + \"% New-Order, \" + paymentWeightValue + \"% Payment, \" + orderStatusWeightValue + \"% Order-Status, \" + deliveryWeightValue + \"% Delivery, \" + stockLevelWeightValue + \"% Stock-Level\");\n printMessage(\"Number of Terminals\\t\" + numTerminals);\n\n\n // initialize htap check variables\n htapCheckInfo.isHtapCheck = iIsHtapCheck;\n if (htapCheckInfo.isHtapCheck) {\n htapCheckInfo.htapCheckType = Integer.parseInt(runningProperty.getHtapCheckType());\n htapCheckInfo.htapCheckCrossQuantity = Integer.parseInt(runningProperty.getHtapCheckCrossQuantity());\n htapCheckInfo.htapCheckCrossFrequency = Integer.parseInt(runningProperty.getHtapCheckCrossFrequency());\n htapCheckInfo.htapCheckApNum = Integer.parseInt(runningProperty.getHtapCheckApNum());\n htapCheckInfo.gapTime = 0;\n htapCheckInfo.htapCheckApConn = runningProperty.getHtapCheckConnAp();\n htapCheckInfo.htapCheckTpConn = iConn;\n htapCheckInfo.dbType = dbType;\n htapCheckInfo.resultDir = resultDirName + \"/htapcheck\";\n htapCheckInfo.warehouseNum = numWarehouses;\n htapCheckInfo.htapCheckFreshnessDataBound = runningProperty.getHtapCheckFreshnessDataBound();\n htapCheckInfo.lFreshLagBound = Integer.parseInt(runningProperty.getHtapCheckFreshLagThreshold().split(\",\")[0]);\n htapCheckInfo.rFreshLagBound = Integer.parseInt(runningProperty.getHtapCheckFreshLagThreshold().split(\",\")[1]);\n htapCheckInfo.htapCheckQueryNumber = runningProperty.getHtapCheckQueryNumber();\n htapCheckInfo.isWeakRead = runningProperty.isWeakRead();\n htapCheckInfo.weakReadTime = runningProperty.getWeakReadTime();\n\n htapCheck = new HTAPCheck(htapCheckInfo, dbProps);\n htapCheckCrossTerminalNum = (int) (0.01f * htapCheckInfo.htapCheckCrossQuantity * numTerminals);\n switch (htapCheckInfo.dbType) {\n case CommonConfig.DB_FIREBIRD -> htapCheckInfo.dbTypeStr = \"FIREBIRD\";\n case CommonConfig.DB_ORACLE -> htapCheckInfo.dbTypeStr = \"ORACLE\";\n case CommonConfig.DB_POSTGRES -> htapCheckInfo.dbTypeStr = \"POSTGRES\";\n case CommonConfig.DB_OCEANBASE -> htapCheckInfo.dbTypeStr = \"OCEANBASE\";\n case CommonConfig.DB_TIDB -> htapCheckInfo.dbTypeStr = \"TIDB\";\n case CommonConfig.DB_POLARDB -> htapCheckInfo.dbTypeStr = \"POLARDB\";\n case CommonConfig.DB_GAUSSDB -> htapCheckInfo.dbTypeStr = \"GAUSSDB\";\n }\n }\n tpRecorder = new TPRecorder(dbType, iConn, dbProps);\n\n // 设置初始时间密度\n if (APTerminals > 0) {\n getTableSize(iConn, dbProps);\n setTimePointDensity(iConn, dbProps, dbType);\n initFilterRatio(iConn, dbProps, dbType);\n }\n\n try {\n int[][] usedTerminals = new int[numWarehouses][10];\n for (int i = 0; i < numWarehouses; i++)\n for (int j = 0; j < 10; j++)\n usedTerminals[i][j] = 0;\n\n for (int i = 0; i < numTerminals; i++) {\n int terminalWarehouseID;\n int terminalDistrictID;\n do {\n // terminalWarehouseID = rnd.nextInt(1, numWarehouses);\n terminalWarehouseID = i + 1;\n terminalDistrictID = rnd.nextInt(1, 10);\n }\n while (usedTerminals[terminalWarehouseID - 1][terminalDistrictID - 1] == 1);\n usedTerminals[terminalWarehouseID - 1][terminalDistrictID - 1] = 1;\n\n String terminalName = \"Term-\" + (i >= 9 ? \"\" + (i + 1) : \"0\" + (i + 1));\n Connection conn;\n printMessage(\"Creating database connection for \" + terminalName + \"...\");\n conn = DriverManager.getConnection(iConn, dbProps);\n conn.setAutoCommit(false);\n switch (isolation_level) {\n case 0 -> conn.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);\n case 1 -> conn.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);\n case 2 -> conn.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);\n case 3 -> conn.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);\n default -> conn.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);\n }\n HTAPCheck curHTAPCheck = null;\n if (htapCheckCrossTerminalNum > 0) {\n htapCheckCrossTerminalNum--;\n curHTAPCheck = htapCheck;\n }\n\n OLTPTerminal terminal = new OLTPTerminal\n (terminalName, terminalWarehouseID, terminalDistrictID,\n conn, dbType,\n transactionsPerTerminal, terminalWarehouseFixed,\n useStoredProcedures,\n paymentWeightValue, orderStatusWeightValue,\n deliveryWeightValue, stockLevelWeightValue,\n receiveGoodsWeightValue, numWarehouses,\n limPerMin_Terminal, curHTAPCheck, tpRecorder, this);\n TPterminals[i] = terminal;\n terminalNames[i] = terminalName;\n log.trace(terminalName + \"\\t\" + terminalWarehouseID);\n }\n\n sessionEndTargetTime = executionTimeMillis;\n signalTerminalsRequestEndSent = false;\n signalAPTerminalsRequestEndSent = false;\n printMessage(\"Created \" + numTerminals + \" terminal(s) successfully!\");\n // table statistic collect thread\n // 创建Runnable对象并将其作为Thread类的构造函数参数传递\n TableInfoCollector infoCollector = new TableInfoCollector(iConn, dbProps, dbType, (int) limPerMin, newOrderWeightValue, paymentWeightValue, deliveryWeightValue, receiveGoodsWeightValue);\n Thread thread = new Thread(infoCollector);\n thread.start();\n System.out.println(\"Collect Table Info Thread Started: \" + thread.getName());\n\n if (connAP != null && dbType != CommonConfig.DB_OCEANBASE) {\n iConn = connAP;\n }\n\n for (int i = 0; i < APTerminals; i++) {\n String APterminalName = \"Term-\" + (i >= 9 ? \"\" + (i + 1) : \"0\" + (i + 1));\n OLAPTerminal APTerminal = new OLAPTerminal(iConn, dbProps, dbType, testTimeInterval, this, dynamicParam, parallelSwitch, isolation_level, parallel_degree, resultDirName);\n APterminals[i] = APTerminal;\n APterminalNames[i] = APterminalName;\n }\n\n // start AP TPterminals\n if (APTerminals != 0) printMessage(\"Starting AP terminals...\");\n for (int i = 0; i < APTerminals; i++) {\n (new Thread(APterminals[i])).start();\n }\n\n // start dynamic ap\n if (checkInterference) {\n DynamicAP dynamicAP = new DynamicAP(iConn, dbProps, dbType, testTimeInterval, this, dynamicParam, parallelSwitch, isolation_level, parallel_degree, resultDirName, step, increaseInterval);\n Thread dynamicAP_thread = new Thread(dynamicAP);\n dynamicAP_thread.start();\n }\n\n // clean delivery list\n // 开启后台线程,定期检查并清空deliveryMap\n if (htapCheckInfo.isHtapCheck) {\n long cleanupInterval = 20; // 检查间隔(以秒为单位)\n int maxSizeThreshold = 30000; // 阈值,当map大小超过这个值时进行清空\n scheduler.scheduleAtFixedRate(() -> {\n System.out.println(\"Checking and cleaning deliveryMap...\");\n if (deliveryList.size() > maxSizeThreshold) {\n int batchSize = 1000; // 要删除的批次大小\n int count = 0;\n Iterator<Pair<Long, Long>> iterator = deliveryList.iterator();\n while (count < batchSize && iterator.hasNext()) {\n iterator.next();\n iterator.remove();\n count++;\n }\n System.out.println(\"deliveryMap has been cleared.\");\n }\n }, cleanupInterval, cleanupInterval, TimeUnit.SECONDS);\n }\n\n // Create Terminals, Start Transactions\n sessionStart = getCurrentTime();\n sessionStartTimestamp = System.currentTimeMillis();\n sessionNextTimestamp = sessionStartTimestamp;\n if (sessionEndTargetTime != -1)\n sessionEndTargetTime += sessionStartTimestamp;\n // Record run parameters in runInfo.csv\n if (runInfoCSV != null) {\n try {\n StringBuffer infoSB = new StringBuffer();\n Formatter infoFmt = new Formatter(infoSB);\n infoFmt.format(\"%d,simple,%s,%s,%s,%s,%d,%d,%d,%d,%d,1.0,1.0\\n\", runID, VdokaVersion, iDB, new Timestamp(sessionStartTimestamp),\n iRunMins,\n loadWarehouses,\n numWarehouses,\n numTerminals,\n APTerminals,\n (int) limPerMin);\n runInfoCSV.write(infoSB.toString());\n runInfoCSV.close();\n } catch (Exception e) {\n log.error(e.getMessage());\n System.exit(1);\n }\n }\n synchronized (TPterminals) {\n printMessage(\"Starting all TP terminals...\");\n transactionCount = 1;\n for (OLTPTerminal terminal : TPterminals)\n (new Thread(terminal)).start();\n }\n printMessage(\"All TPterminals started executing \" + sessionStart);\n log.info(\"OLTP&OLAP Threads initialize done\");\n TPMonitor tpMonitor = new TPMonitor((int) limPerMin, TPthreshold, APTerminals);\n Thread tpMonitor_thread = new Thread(tpMonitor);\n tpMonitor_thread.start();\n\n } catch (Exception e1) {\n errorMessage(\"This session ended with errors!\");\n e1.printStackTrace();\n }\n\n } catch (Exception e2) {\n e2.printStackTrace();\n }\n }\n updateStatusLine();\n }\n\n public void initParametersForReceiveGoods() {\n for (int i = 0; i < 1000000; i++) {\n OLTPData.devOrderIdPerW[i] = new AtomicInteger(2100);\n OLTPData.recOrderIdPerW[i] = new AtomicInteger(2100);\n }\n }\n\n public void loadConfiguration() throws IOException {\n // get property file location\n propertyPath = System.getProperty(\"prop\");\n connectionProperty = new ConnectionProperty(propertyPath);\n runningProperty = new RunningProperty(propertyPath);\n connectionProperty.loadProperty();\n runningProperty.loadProperty();\n printStartReport();\n }\n\n public boolean checkAndSetDBType(String dbName) {\n boolean checkFlag = true;\n switch (dbName) {\n case \"oracle\" -> dbType = DB_ORACLE;\n case \"postgres\" -> dbType = DB_POSTGRES;\n case \"oceanbase\" -> dbType = DB_OCEANBASE;\n case \"tidb\" -> dbType = DB_TIDB;\n case \"polardb\" -> dbType = DB_POLARDB;\n default -> {\n checkFlag = false;\n log.error(\"unknown database type '\" + dbName + \"'\");\n }\n }\n return checkFlag;\n }\n\n public void prepareForLog(String resultDirectory, String osCollectorScript, int osCollectorInterval, String\n osCollectorSSHAddr, String osCollectorDevices) throws IOException {\n if (databaseDriverLoaded && resultDirectory != null) {\n StringBuffer sb = new StringBuffer();\n Formatter fmt = new Formatter(sb);\n Pattern p = Pattern.compile(\"%t\");\n Calendar cal = Calendar.getInstance();\n String iRunID;\n iRunID = System.getProperty(\"runID\");\n if (iRunID != null)\n runID = Integer.parseInt(iRunID);\n String[] parts = p.split(resultDirectory, -1);\n sb.append(parts[0]);\n for (int i = 1; i < parts.length; i++) {\n fmt.format(\"%t\" + parts[i].charAt(0), cal);\n sb.append(parts[i].substring(1));\n }\n resultDirName = sb.toString();\n File resultDir = new File(resultDirName);\n File resultDataDir = new File(resultDir, \"data\");\n // Create the output directory structure.\n if (!resultDir.mkdir()) {\n log.error(\"Failed to create directory '\" + resultDir.getPath() + \"'\");\n System.exit(1);\n }\n if (!resultDataDir.mkdir()) {\n log.error(\"Failed to create directory '\" + resultDataDir.getPath() + \"'\");\n System.exit(1);\n }\n // Copy the used properties file into the resultDirectory.\n try {\n FileUtil fileUtil = new FileUtil();\n fileUtil.copyFile(new File(System.getProperty(\"prop\")), new File(resultDir, \"run.properties\"));\n } catch (Exception e) {\n log.error(e.getMessage());\n System.exit(1);\n }\n log.info(\"Vodka-DBHammer, copied \" + System.getProperty(\"prop\") + \" to \" + new File(resultDir, \"run.properties\").getPath());\n // Create the runInfo.csv file.\n String runInfoCSVName = new File(resultDataDir, \"runInfo.csv\").getPath();\n try {\n runInfoCSV = new BufferedWriter(new FileWriter(runInfoCSVName));\n runInfoCSV.write(\"run,driver,driverVersion,db,sessionStart,\" + \"runMins,\" + \"loadWarehouses,runWarehouses,numSUTThreads,\" + \"limitTxnsPerMin,\" + \"thinkTimeMultiplier,keyingTimeMultiplier\\n\");\n } catch (IOException e) {\n log.error(e.getMessage());\n System.exit(1);\n }\n log.info(\"Vodka-DBHammer, created \" + runInfoCSVName + \" for runID \" + runID);\n // Open the per transaction result.csv file.\n String resultCSVName = new File(resultDataDir, \"result.csv\").getPath();\n try {\n resultCSV = new BufferedWriter(new FileWriter(resultCSVName));\n resultCSV.write(\"run,elapsed,latency,dblatency,\" + \"ttype,rbk,dskipped,error\\n\");\n } catch (IOException e) {\n log.error(e.getMessage());\n System.exit(1);\n }\n log.info(\"Vodka-DBHammer, writing per transaction results to \" + resultCSVName);\n if (osCollectorScript != null) {\n osCollector = new OSCollector(osCollectorScript, runID, osCollectorInterval, osCollectorSSHAddr, osCollectorDevices, resultDataDir, log);\n osCollector.start();\n }\n log.info(\"osCollector started.\");\n }\n }\n\n\n private void printStartReport() {\n log.info(\"Vodka-DBHammer, \");\n log.info(\"Vodka-DBHammer, +-------------------------------------------------------------+\");\n log.info(\"Vodka-DBHammer, BenchmarkSQL v\" + VdokaVersion);\n log.info(\"Vodka-DBHammer, +-------------------------------------------------------------+\");\n log.info(\"Vodka-DBHammer, (c) 2023, DBHammer@DaSE@ECNU\");\n log.info(\"Vodka-DBHammer, +-------------------------------------------------------------+\");\n log.info(\"Vodka-DBHammer, \");\n log.info(\"\\n\" +\n \" _____ _____ _____ _____ \\n\" +\n \"/ __ \\\\| _ |/ __ \\\\|____ |\\n\" +\n \"`' / /'| |/' |`' / /' / /\\n\" +\n \" / / | /| | / / \\\\ \\\\\\n\" +\n \"./ /___\\\\ |_/ /./ /___.___/ /\\n\" +\n \"\\\\_____/ \\\\___/ \\\\_____/\\\\____/ \\n\" +\n \" \\n\" +\n \" \\n\");\n log.info(\"\\n\" +\n \" _ _ \\n\" +\n \" /\\\\ /\\\\ ___ __| || | __ __ _ \\n\" +\n \" \\\\ \\\\ / // _ \\\\ / _` || |/ // _` |\\n\" +\n \" \\\\ V /| (_) || (_| || <| (_| |\\n\" +\n \" \\\\_/ \\\\___/ \\\\__,_||_|\\\\_\\\\\\\\__,_|\\n\" +\n \" \\n\");\n }\n\n public static void main(String[] args) throws Exception {\n gloabalSysCurrentTime = System.currentTimeMillis();\n PropertyConfigurator.configure(\"../run/log4j.properties\");\n new OLTPClient();\n\n }\n\n\n public static void signalTerminalsRequestEnd(boolean timeTriggered) {\n synchronized (TPterminals) {\n if (!signalTerminalsRequestEndSent) {\n if (runningProperty.isHtapCheck())\n scheduler.shutdown();\n if (timeTriggered)\n printMessage(\"The time limit has been reached.\");\n else\n printMessage(\"The TP throughput is too low.\");\n printMessage(\"Signalling all TPterminals to stop...\");\n signalTerminalsRequestEndSent = true;\n for (OLTPTerminal terminal : TPterminals)\n if (terminal != null)\n terminal.stopRunningWhenPossible();\n printMessage(\"Waiting for all active entity.transactions to end...\");\n for (OLAPTerminal tOlapTerminal : APterminals)\n if (tOlapTerminal != null)\n tOlapTerminal.stopRunningWhenPossible();\n printMessage(\"Waiting for all active ap thread to end...\");\n try {\n tpRecorder.close();\n } catch (Throwable e) {\n Thread.currentThread().interrupt();\n }\n }\n }\n }\n\n public static void stopBecauseOfLowTP() {\n signalTerminalsRequestEnd(false);\n }\n\n public void signalTerminalEnded(OLTPTerminal terminal, long countNewOrdersExecuted) {\n synchronized (TPterminals) {\n boolean found = false;\n terminalsStarted--;\n for (int i = 0; i < TPterminals.length && !found; i++) {\n if (TPterminals[i] == terminal) {\n TPterminals[i] = null;\n terminalNames[i] = \"(\" + terminalNames[i] + \")\";\n newOrderCounter += countNewOrdersExecuted;\n found = true;\n }\n }\n }\n if (terminalsStarted == 0) {\n sessionEnd = getCurrentTime();\n sessionEndTimestamp = System.currentTimeMillis();\n sessionEndTargetTime = -1;\n printMessage(\"All TPterminals finished executing \" + sessionEnd);\n endReport();\n terminalsBlockingExit = false;\n printMessage(\"Session finished!\");\n\n // If we opened a per transaction result file, close it.\n if (resultCSV != null) {\n try {\n resultCSV.close();\n } catch (IOException e) {\n log.error(e.getMessage());\n }\n }\n\n // Stop the OSCollector, if it is active.\n if (osCollector != null) {\n osCollector.stop();\n osCollector = null;\n }\n }\n }\n\n public void signalTerminalEndedTransaction(String terminalName, String transactionType, long executionTime,\n String comment, int newOrder) {\n synchronized (counterLock) {\n transactionCount++;\n fastNewOrderCounter += newOrder;\n }\n if (sessionEndTargetTime != -1 && System.currentTimeMillis() > sessionEndTargetTime) {\n signalTerminalsRequestEnd(true);\n //signalAPTerminalsRequestEnd(true);\n }\n updateStatusLine();\n\n }\n\n public BasicRandom getRnd() {\n return rnd;\n }\n\n public void resultAppend(OLTPData term) {\n if (resultCSV != null) {\n try {\n resultCSV.write(runID + \",\" +\n term.resultLine(sessionStartTimestamp));\n } catch (IOException e) {\n log.error(\"Vodka-DBHammer, \" + e.getMessage());\n }\n }\n }\n\n private void endReport() {\n long currTimeMillis = System.currentTimeMillis();\n long freeMem = Runtime.getRuntime().freeMemory() / (1024 * 1024);\n long totalMem = Runtime.getRuntime().totalMemory() / (1024 * 1024);\n double tpmC = (6000000 * fastNewOrderCounter / (currTimeMillis - sessionStartTimestamp + 0.00001)) / 100.0;\n double tpmTotal = (6000000 * transactionCount / (currTimeMillis - sessionStartTimestamp + 0.00001)) / 100.0;\n\n System.out.println();\n log.info(\"Vodka-DBHammer, \");\n log.info(\"Vodka-DBHammer, \");\n log.info(\"Vodka-DBHammer, Measured tpmC (NewOrders) = \" + tpmC);\n log.info(\"Vodka-DBHammer, Measured tpmTOTAL = \" + tpmTotal);\n log.info(\"Vodka-DBHammer, Session Start = \" + sessionStart);\n log.info(\"Vodka-DBHammer, Session End = \" + sessionEnd);\n log.info(\"Vodka-DBHammer, Transaction Count = \" + (transactionCount - 1));\n\n log.info(\"benchmark.oltp.OLTPClient.transactionCount:\" + benchmark.oltp.OLTPClient.transactionCount);\n log.info(\"benchmark.oltp.OLTPClient.DeliveryBG:\" + benchmark.oltp.OLTPClient.DeliveryBG.get());\n log.info(\"benchmark.oltp.OLTPClient.newOrder:\" + benchmark.oltp.OLTPClient.newOrder.get());\n log.info(\"benchmark.oltp.OLTPClient.orderStatus:\" + benchmark.oltp.OLTPClient.orderStatus.get());\n log.info(\"benchmark.oltp.OLTPClient.payment:\" + benchmark.oltp.OLTPClient.payment.get());\n log.info(\"benchmark.oltp.OLTPClient.receiveGoods:\" + benchmark.oltp.OLTPClient.receiveGoods.get());\n log.info(\"benchmark.oltp.OLTPClient.stockLevel:\" + benchmark.oltp.OLTPClient.stockLevel.get());\n log.info(\"benchmark.oltp.OLTPClient.rollBackTransactionCount\" + benchmark.oltp.OLTPClient.rollBackTransactionCount.get());\n log.info(\"OLAPTerminal.oorderTableSize:\" + OLAPTerminal.oorderTableSize.get());\n log.info(\"OLAPTerminal.orderLineTableSize:\" + OLAPTerminal.orderLineTableSize.get());\n log.info(\"OLAPTerminal.orderlineTableNotNullSize:\" + OLAPTerminal.orderlineTableNotNullSize.get());\n log.info(\"OLAPTerminal.orderlineTableRecipDateNotNullSize:\" + OLAPTerminal.orderlineTableRecipDateNotNullSize.get());\n\n }\n\n private static void printMessage(String message) {\n log.info(\"Vodka-DBHammer, \" + message);\n }\n\n private void errorMessage(String message) {\n log.error(\"Vodka-DBHammer, \" + message);\n }\n\n private void exit() {\n System.exit(0);\n }\n\n private String getCurrentTime() {\n return dateFormat.format(new java.util.Date());\n }\n\n synchronized private void updateStatusLine() {\n long currTimeMillis = System.currentTimeMillis();\n if (currTimeMillis > sessionNextTimestamp) {\n StringBuilder informativeText = new StringBuilder();\n Formatter fmt = new Formatter(informativeText);\n double tpmC = (6000000 * fastNewOrderCounter / (currTimeMillis - sessionStartTimestamp + 0.00001)) / 100.0;\n double tpmTotal = (6000000 * transactionCount / (currTimeMillis - sessionStartTimestamp + 0.00001)) / 100.0;\n sessionNextTimestamp += 1000; /* update this every seconds */\n fmt.format(\"progress: %.1f, tpmTOTAL: %.1f, tpmC: %.1f\", (double) (currTimeMillis - sessionStartTimestamp) / 1000, tpmTotal, tpmC);\n recentTpmTotal = (transactionCount - sessionNextKounter) * 12;\n recentTpmC = (fastNewOrderCounter - sessionNextKounter) * 12;\n sessionNextKounter = fastNewOrderCounter;\n System.out.println(informativeText);\n }\n }\n\n public static double collectTpmC() {\n return (6000000 * transactionCount / (System.currentTimeMillis() - sessionStartTimestamp + 0.00001)) / 100.0;\n }\n\n public static boolean getSignalTerminalsRequestEndSent() {\n return signalTerminalsRequestEndSent;\n }\n\n public void getTableSize(String iConn, Properties dbProps) {\n log.info(\"Getting Table Size...\");\n try {\n Connection connection = DriverManager.getConnection(iConn, dbProps);\n Statement statement = connection.createStatement();\n ResultSet rs = statement.executeQuery(\"select count(*) from vodka_oorder;\");\n if (rs.next())\n baseQuery.orderOriginSize = rs.getInt(1);\n rs = statement.executeQuery(\"select count(*) from vodka_order_line;\");\n if (rs.next())\n baseQuery.olOriginSize = rs.getInt(1);\n rs = statement.executeQuery(\"select count(*) from vodka_order_line where ol_delivery_d is not null;\");\n if (rs.next())\n baseQuery.olNotnullSize = rs.getInt(1);\n rs.close();\n } catch (SQLException e) {\n log.error(\"Set table size error\");\n }\n }\n\n public void setTimePointDensity(String iConn, Properties dbProps, int dbType) {\n log.info(\"Acquiring time density information...\");\n try {\n Connection connection = DriverManager.getConnection(iConn, dbProps);\n String sql;\n switch (dbType) {\n case (CommonConfig.DB_TIDB) ->\n sql = \"select avg(counts) from (select year(o_entry_d),month(o_entry_d),day(o_entry_d),hour(o_entry_d),count(*) as counts \" +\n \" from vodka_oorder group by year(o_entry_d),month(o_entry_d),day(o_entry_d),hour(o_entry_d)) as L;\";\n case (CommonConfig.DB_OCEANBASE) ->\n sql = \"select avg(counts) from (select year(o_entry_d),month(o_entry_d),day(o_entry_d),hour(o_entry_d),count(*) as counts \" +\n \" from vodka_oorder group by year(o_entry_d),month(o_entry_d),day(o_entry_d),hour(o_entry_d));\";\n default -> sql = \"SELECT AVG(counts) \" +\n \"FROM ( \" +\n \" SELECT \" +\n \" EXTRACT(YEAR FROM o_entry_d) AS year, \" +\n \" EXTRACT(MONTH FROM o_entry_d) AS month, \" +\n \" EXTRACT(DAY FROM o_entry_d) AS day, \" +\n \" EXTRACT(HOUR FROM o_entry_d) AS hour, \" +\n \" COUNT(*) AS counts \" +\n \" FROM vodka_oorder \" +\n \" GROUP BY \" +\n \" EXTRACT(YEAR FROM o_entry_d), \" +\n \" EXTRACT(MONTH FROM o_entry_d), \" +\n \" EXTRACT(DAY FROM o_entry_d), \" +\n \" EXTRACT(HOUR FROM o_entry_d) \" +\n \") AS L;\";\n }\n Statement statement = connection.createStatement();\n ResultSet rs = statement.executeQuery(sql);\n if (rs.next())\n this.timePointDensity = rs.getInt(1);\n rs.close();\n statement.close();\n connection.close();\n thread_add_interval = 3600.0 / timePointDensity;\n log.info(\"Current Average Time Density is: \" + timePointDensity);\n log.info(\"Time Interval Per Thread is: \" + thread_add_interval);\n } catch (SQLException e) {\n log.error(\"Set time density error\");\n }\n }\n\n public class LinerFitResult {\n public double b;\n public double k;\n public double w1;\n public double w2;\n public double b2;\n\n public LinerFitResult(double ttb, double ttk) {\n this.b = ttb;\n this.k = ttk;\n }\n\n public LinerFitResult(double w1, double w2, double b2) {\n this.w1 = w1;\n this.w2 = w2;\n this.b2 = b2;\n }\n }\n\n\n public int linearFits() {\n int degree = 1; // 多项式系数\n LinerFitResult lft1 = linearFit(linearScatters(generalOorderTSize), degree);\n LinerFitResult lft2 = linearFit(linearScatters(generalOrderlineTSize), degree);\n if (lft1 == null || lft2 == null)\n return -1;\n else {\n b1 = lft1.b;\n k1 = lft1.k;\n fitFunc1.addElement(k1 + \",\" + b1);\n b2 = lft2.b;\n k2 = lft2.k;\n fitFunc2.addElement(k2 + \",\" + b2);\n return 1;\n }\n }\n\n public LinerFitResult linearFit(double[][] data, int degree) {\n if (data != null) {\n if (degree == 1) {\n List<double[]> fitData = new ArrayList<>(); // 这个fitData有啥用, 没有被访问的话,底下的for-loop不是也没用嘛\n SimpleRegression regression = new SimpleRegression();\n regression.addData(data); // 数据集\n RegressionResults results = regression.regress();\n double tb = results.getParameterEstimate(0);\n double tk = results.getParameterEstimate(1);\n // 重新计算生成拟合曲线\n for (double[] datum : data) {\n double[] xy = {datum[0], tk * datum[0] + tb};\n fitData.add(xy);\n }\n return new LinerFitResult(tb, tk);\n } else {\n return null;\n }\n } else {\n return null;\n }\n }\n\n synchronized public static double[][] linearScatters(List<double[]> tdata) {\n if (tdata.size() > 5) {\n if (tdata.size() > 30)\n tdata = tdata.subList(tdata.size() - 30, tdata.size());\n return tdata.toArray(new double[0][0]);\n } else\n return null;\n }\n\n}" }, { "identifier": "CommonConfig", "path": "code/src/main/java/config/CommonConfig.java", "snippet": "public interface CommonConfig {\n String VdokaVersion = \"1.0 DEV\";\n\n int DB_UNKNOWN = 0,\n DB_FIREBIRD = 1,\n DB_ORACLE = 2,\n DB_POSTGRES = 3,\n DB_OCEANBASE = 4,\n DB_TIDB = 5,\n DB_POLARDB = 6,\n DB_GAUSSDB = 7,\n DB_MYSQL = 8;\n\n int NEW_ORDER = 1,\n PAYMENT = 2,\n ORDER_STATUS = 3,\n DELIVERY = 4,\n STOCK_LEVEL = 5,\n RECIEVE_GOODS = 6;\n\n SimpleDateFormat dateFormat = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\");\n\n\n}" } ]
import benchmark.olap.query.*; import benchmark.oltp.OLTPClient; import config.CommonConfig; import org.apache.log4j.Logger; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.sql.*; import java.sql.Date; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*;
10,476
package benchmark.olap; public class OLAPTerminal implements Runnable { // public static AtomicInteger DeliveryBG=new AtomicInteger(0); public static AtomicLong oorderTableSize = new AtomicLong(benchmark.olap.query.baseQuery.orderOriginSize); // 通过查询获得的oorder表的实时大小 public static AtomicLong orderLineTableSize = new AtomicLong(benchmark.olap.query.baseQuery.olOriginSize); // 通过查询获得的orderline表的实时大小 public static AtomicLong orderlineTableNotNullSize = new AtomicLong(benchmark.olap.query.baseQuery.olNotnullSize); public static AtomicLong orderlineTableRecipDateNotNullSize = new AtomicLong( benchmark.olap.query.baseQuery.olNotnullSize); public static boolean filterRateCheck = false; // 为 TRUE 时获取过滤比分母查询 public static boolean countPlan = false; // 为 TRUE 时记查询计划 public static boolean detailedPlan = false; // 为 TRUE 以 json 格式保存查询计划 private static final Logger log = Logger.getLogger(OLAPTerminal.class);
package benchmark.olap; public class OLAPTerminal implements Runnable { // public static AtomicInteger DeliveryBG=new AtomicInteger(0); public static AtomicLong oorderTableSize = new AtomicLong(benchmark.olap.query.baseQuery.orderOriginSize); // 通过查询获得的oorder表的实时大小 public static AtomicLong orderLineTableSize = new AtomicLong(benchmark.olap.query.baseQuery.olOriginSize); // 通过查询获得的orderline表的实时大小 public static AtomicLong orderlineTableNotNullSize = new AtomicLong(benchmark.olap.query.baseQuery.olNotnullSize); public static AtomicLong orderlineTableRecipDateNotNullSize = new AtomicLong( benchmark.olap.query.baseQuery.olNotnullSize); public static boolean filterRateCheck = false; // 为 TRUE 时获取过滤比分母查询 public static boolean countPlan = false; // 为 TRUE 时记查询计划 public static boolean detailedPlan = false; // 为 TRUE 以 json 格式保存查询计划 private static final Logger log = Logger.getLogger(OLAPTerminal.class);
private final OLTPClient parent;
0
2023-10-22 11:22:32+00:00
12k
ushh789/FinancialCalculator
src/main/java/com/netrunners/financialcalculator/MenuControllers/CreditMenuController.java
[ { "identifier": "ErrorChecker", "path": "src/main/java/com/netrunners/financialcalculator/ErrorHandling/ErrorChecker.java", "snippet": "public class ErrorChecker {\n\n public static boolean areFieldsValidInDeposit(TextField investInput, TextField depositAnnualPercentInput, MenuButton depositWithdrawalOption, DatePicker startDate, DatePicker endDate, DatePicker earlyWithdrawalDate, CheckBox earlyWithdrawal) {\n boolean investValid = InputFieldErrors.checkIfCorrectNumberGiven(investInput);\n boolean annualPercentValid = InputFieldErrors.checkIfCorrectPercentGiven(depositAnnualPercentInput);\n boolean withdrawalOptionValid = InputFieldErrors.withdrawalOptionIsSelected(depositWithdrawalOption);\n\n if (!investValid) {\n highlightError(investInput);\n investInput.setText(\"\");\n } else {\n removeHighlight(investInput);\n }\n\n if (!annualPercentValid) {\n highlightError(depositAnnualPercentInput);\n depositAnnualPercentInput.setText(\"\");\n } else {\n removeHighlight(depositAnnualPercentInput);\n }\n\n if (!withdrawalOptionValid) {\n highlightError(depositWithdrawalOption);\n } else {\n removeHighlight(depositWithdrawalOption);\n }\n if (startDate.getValue() == null) {\n highlightError(startDate);\n } else {\n removeHighlight(startDate);\n }\n if (endDate.getValue() == null) {\n highlightError(endDate);\n } else {\n removeHighlight(endDate);\n }\n if (earlyWithdrawal.isSelected() && earlyWithdrawalDate.getValue() == null) {\n highlightError(earlyWithdrawalDate);\n } else {\n removeHighlight(earlyWithdrawalDate);\n }\n return investValid && annualPercentValid && withdrawalOptionValid && startDate.getValue() != null && endDate.getValue() != null && (!earlyWithdrawal.isSelected() || earlyWithdrawalDate.getValue() != null);\n }\n\n public static boolean areFieldsValidInCredit(TextField creditAmount, TextField creditAnnualPercent, MenuButton paymentOption, DatePicker creditStartDate, DatePicker creditFirstPaymentDate, CheckBox paymentHolidays, DatePicker creditHolidaysStartDate, DatePicker creditHolidaysEndDate) {\n boolean creditAmountValid = InputFieldErrors.checkIfCorrectNumberGiven(creditAmount);\n boolean creditAnnualPercentValid = InputFieldErrors.checkIfCorrectPercentGiven(creditAnnualPercent);\n boolean creditPaymentOptionValid = InputFieldErrors.paymentOptionIsSelected(paymentOption);\n\n\n if (!creditAmountValid) {\n highlightError(creditAmount);\n creditAmount.setText(\"\");\n } else {\n removeHighlight(creditAmount);\n }\n\n if (!creditAnnualPercentValid) {\n highlightError(creditAnnualPercent);\n creditAnnualPercent.setText(\"\");\n } else {\n removeHighlight(creditAnnualPercent);\n }\n\n if (!creditPaymentOptionValid) {\n highlightError(paymentOption);\n } else {\n removeHighlight(paymentOption);\n }\n if (creditStartDate.getValue() == null) {\n highlightError(creditStartDate);\n } else {\n removeHighlight(creditStartDate);\n }\n if (creditFirstPaymentDate.getValue() == null) {\n highlightError(creditFirstPaymentDate);\n } else {\n removeHighlight(creditFirstPaymentDate);\n }\n if (paymentHolidays.isSelected() && creditHolidaysStartDate.getValue() == null) {\n highlightError(creditHolidaysStartDate);\n } else {\n removeHighlight(creditHolidaysStartDate);\n }\n if (paymentHolidays.isSelected() && creditHolidaysEndDate.getValue() == null) {\n highlightError(creditHolidaysEndDate);\n } else {\n removeHighlight(creditHolidaysEndDate);\n }\n return creditAmountValid && creditAnnualPercentValid && creditPaymentOptionValid && creditStartDate.getValue() != null && creditFirstPaymentDate.getValue() != null && (!paymentHolidays.isSelected() || creditHolidaysStartDate.getValue() != null) && (!paymentHolidays.isSelected() || creditHolidaysEndDate.getValue() != null);\n }\n\n public static void highlightError(Control field) {\n field.setStyle(\"-fx-border-color:red;-fx-border-radius:3px\");\n field.focusedProperty().addListener((observable, oldValue, newValue) -> {\n if (newValue) {\n removeHighlight(field);\n }\n });\n }\n\n public static void removeHighlight(Control field) {\n field.setStyle(null);\n }\n\n\n}" }, { "identifier": "OpenFile", "path": "src/main/java/com/netrunners/financialcalculator/LogicalInstrumnts/FileInstruments/OpenFile.java", "snippet": "public class OpenFile {\n\n public static void openFromSave() {\n FileChooser fileChooser = new FileChooser();\n fileChooser.setTitle(LanguageManager.getInstance().getStringBinding(\"ChooseOpenFile\").get());\n fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter(\"JSON files (*.json)\", \"*.json\"));\n File initialDirectory = new File(\"saves/\");\n fileChooser.setInitialDirectory(initialDirectory);\n File selectedFile = fileChooser.showOpenDialog(null);\n if (selectedFile != null) {\n try (FileReader reader = new FileReader(selectedFile)) {\n Gson gson = new Gson();\n JsonObject jsonObject = gson.fromJson(reader, JsonObject.class);\n\n String operationType = jsonObject.get(\"operation\").getAsString();\n switch (operationType) {\n case \"Credit\" -> {\n Credit credit = createCredit(jsonObject);\n credit.sendCreditToResultTable();\n }\n case \"Deposit\" -> {\n Deposit deposit = createDeposit(jsonObject);\n deposit.sendDepositToResultTable();\n }\n default -> LogHelper.log(Level.WARNING, \"Can't open file with operation type: \" + operationType, null);\n }\n } catch (IOException | JsonParseException e) {\n LogHelper.log(Level.SEVERE, \"Error while opening file\", e);\n }\n }\n }\n\n private static Credit createCredit(JsonObject jsonObject) {\n Credit credit = null;\n try {\n float loan = jsonObject.get(\"loan\").getAsFloat();\n float annualPercent = jsonObject.get(\"annualPercent\").getAsFloat();\n int paymentType = jsonObject.get(\"paymentType\").getAsInt();\n String currency = jsonObject.get(\"currency\").getAsString();\n String startDateString = jsonObject.get(\"startDate\").getAsString();\n LocalDate startDate = LocalDate.parse(startDateString);\n String endDateString = jsonObject.get(\"endDate\").getAsString();\n LocalDate endDate = LocalDate.parse(endDateString);\n if (jsonObject.get(\"type\").getAsString().equals(\"WithHolidays\")) {\n String holidaysStartString = jsonObject.get(\"holidaysStart\").getAsString();\n LocalDate holidaysStart = LocalDate.parse(holidaysStartString);\n String holidaysEndString = jsonObject.get(\"holidaysEnd\").getAsString();\n LocalDate holidaysEnd = LocalDate.parse(holidaysEndString);\n credit = new CreditWithHolidays(loan, currency, annualPercent, startDate, endDate, paymentType, holidaysStart, holidaysEnd);\n } else {\n credit = new CreditWithoutHolidays(loan, currency, annualPercent, startDate, endDate, paymentType);\n }\n\n } catch (Exception e) {\n LogHelper.log(Level.SEVERE, \"Error while opening file\", e);\n }\n return credit;\n }\n\n private static Deposit createDeposit(JsonObject jsonObject) {\n Deposit deposit = null;\n try {\n float investment = jsonObject.get(\"investment\").getAsFloat();\n float annualPercent = jsonObject.get(\"annualPercent\").getAsFloat();\n int withdrawalOption = jsonObject.get(\"withdrawalOption\").getAsInt();\n boolean earlyWithdrawal = jsonObject.get(\"earlyWithdrawal\").getAsBoolean();\n String currency = jsonObject.get(\"currency\").getAsString();\n String startDateString = jsonObject.get(\"startDate\").getAsString();\n LocalDate startDate = LocalDate.parse(startDateString);\n String endDateString = jsonObject.get(\"endDate\").getAsString();\n LocalDate endDate = LocalDate.parse(endDateString);\n if (jsonObject.get(\"type\").getAsString().equals(\"Capitalized\") && earlyWithdrawal) {\n String earlyWithdrawalDateString = jsonObject.get(\"earlyWithdrawalDate\").getAsString();\n LocalDate earlyWithdrawalDate = LocalDate.parse(earlyWithdrawalDateString);\n deposit = new CapitalisedDeposit(investment, currency, annualPercent, startDate, endDate, earlyWithdrawal, earlyWithdrawalDate, withdrawalOption);\n } else if (jsonObject.get(\"type\").getAsString().equals(\"Capitalized\") && !earlyWithdrawal) {\n deposit = new CapitalisedDeposit(investment, currency, annualPercent, startDate, endDate, earlyWithdrawal, withdrawalOption);\n } else if (jsonObject.get(\"type\").getAsString().equals(\"Uncapitalized\") && earlyWithdrawal) {\n String earlyWithdrawalDateString = jsonObject.get(\"earlyWithdrawalDate\").getAsString();\n LocalDate earlyWithdrawalDate = LocalDate.parse(earlyWithdrawalDateString);\n deposit = new UncapitalisedDeposit(investment, currency, annualPercent, startDate, endDate, earlyWithdrawal, earlyWithdrawalDate, withdrawalOption);\n } else {\n deposit = new UncapitalisedDeposit(investment, currency, annualPercent, startDate, endDate, earlyWithdrawal, withdrawalOption);\n }\n } catch (Exception e) {\n LogHelper.log(Level.SEVERE, \"Error while creating deposit\", e);\n }\n return deposit;\n }\n}" }, { "identifier": "DatePickerRestrictions", "path": "src/main/java/com/netrunners/financialcalculator/LogicalInstrumnts/TimeFunctions/DatePickerRestrictions.java", "snippet": "public class DatePickerRestrictions {\n\n public static void setDatePickerRestrictionsWithdrawalHolidays(DatePicker start, DatePicker end, DatePicker newDate) {\n final Callback<DatePicker, DateCell> dayCellFactory =\n new Callback<>() {\n @Override\n public DateCell call(final DatePicker datePicker) {\n return new DateCell() {\n @Override\n public void updateItem(LocalDate item, boolean empty) {\n super.updateItem(item, empty);\n\n if (end.getValue() != null && item.isAfter(end.getValue().minusDays(1))) {\n setDisable(true);\n if (StartMenu.currentTheme.equals(\"file:src/main/resources/com/netrunners/financialcalculator/assets/darkTheme.css\")) {\n setStyle(\"-fx-background-color: gray;\");\n } else {\n setStyle(\"-fx-background-color: dimgray;-fx-text-fill: white;\");\n }\n }\n }\n };\n }\n };\n start.setDayCellFactory(dayCellFactory);\n start.valueProperty().addListener((observable, oldValue, newValue) -> start.setDayCellFactory(dayCellFactory));\n\n final Callback<DatePicker, DateCell> dayCellFactoryEnd =\n new Callback<>() {\n @Override\n public DateCell call(final DatePicker datePicker) {\n return new DateCell() {\n @Override\n public void updateItem(LocalDate item, boolean empty) {\n super.updateItem(item, empty);\n\n if (start.getValue() != null && item.isBefore(start.getValue().plusDays(1))) {\n setDisable(true);\n if (StartMenu.currentTheme.equals(\"file:src/main/resources/com/netrunners/financialcalculator/assets/darkTheme.css\")) {\n setStyle(\"-fx-background-color: gray;\");\n } else {\n setStyle(\"-fx-background-color: dimgray;-fx-text-fill: white;\");\n }\n }\n }\n };\n }\n };\n end.setDayCellFactory(dayCellFactoryEnd);\n end.valueProperty().addListener((observable, oldValue, newValue) -> end.setDayCellFactory(dayCellFactoryEnd));\n\n start.valueProperty().addListener((observable, oldValue, newValue) -> {\n if (end.getValue() != null && start.getValue() != null && start.getValue().isAfter(end.getValue())) {\n start.setValue(null);\n\n }\n });\n\n end.valueProperty().addListener((observable, oldValue, newValue) -> {\n if (start.getValue() != null && end.getValue() != null && end.getValue().isBefore(start.getValue())) {\n end.setValue(null);\n }\n\n });\n final Callback<DatePicker, DateCell> dayCellFactoryNew =\n new Callback<>() {\n @Override\n public DateCell call(final DatePicker datePicker) {\n return new DateCell() {\n @Override\n public void updateItem(LocalDate item, boolean empty) {\n super.updateItem(item, empty);\n\n if ((start.getValue() != null && item.isBefore(start.getValue())) ||\n (end.getValue() != null && item.isAfter(end.getValue()))) {\n setDisable(true);\n if (StartMenu.currentTheme.equals(\"file:src/main/resources/com/netrunners/financialcalculator/assets/darkTheme.css\")) {\n setStyle(\"-fx-background-color: gray;\");\n } else {\n setStyle(\"-fx-background-color: dimgray;-fx-text-fill: white;\");\n }\n }\n }\n };\n }\n };\n newDate.setDayCellFactory(dayCellFactoryNew);\n newDate.valueProperty().addListener((observable, oldValue, newValue) -> newDate.setDayCellFactory(dayCellFactoryNew));\n newDate.valueProperty().addListener((observable, oldValue, newValue) -> {\n if (start.getValue() != null && end.getValue() != null && newDate.getValue() != null && (newDate.getValue().isBefore(start.getValue()) || newDate.getValue().isAfter(end.getValue()))) {\n newDate.setValue(null);\n }\n });\n }\n\n public static void setDatePickerRestrictionsHolidays(DatePicker start, DatePicker end, DatePicker newDate1, DatePicker newDate2) {\n final Callback<DatePicker, DateCell> dayCellFactory =\n new Callback<>() {\n @Override\n public DateCell call(final DatePicker datePicker) {\n return new DateCell() {\n @Override\n public void updateItem(LocalDate item, boolean empty) {\n super.updateItem(item, empty);\n\n if (end.getValue() != null && item.isAfter(end.getValue().minusDays(1))) {\n setDisable(true);\n if (StartMenu.currentTheme.equals(\"file:src/main/resources/com/netrunners/financialcalculator/assets/darkTheme.css\")) {\n setStyle(\"-fx-background-color: gray;\");\n } else {\n setStyle(\"-fx-background-color: dimgray;-fx-text-fill: white;\");\n }\n }\n }\n };\n }\n };\n start.setDayCellFactory(dayCellFactory);\n start.valueProperty().addListener((observable, oldValue, newValue) -> start.setDayCellFactory(dayCellFactory));\n\n final Callback<DatePicker, DateCell> dayCellFactoryEnd =\n new Callback<>() {\n @Override\n public DateCell call(final DatePicker datePicker) {\n return new DateCell() {\n @Override\n public void updateItem(LocalDate item, boolean empty) {\n super.updateItem(item, empty);\n\n if (start.getValue() != null && item.isBefore(start.getValue().plusDays(1))) {\n setDisable(true);\n if (StartMenu.currentTheme.equals(\"file:src/main/resources/com/netrunners/financialcalculator/assets/darkTheme.css\")) {\n setStyle(\"-fx-background-color: gray;\");\n } else {\n setStyle(\"-fx-background-color: dimgray;-fx-text-fill: white;\");\n }\n }\n }\n };\n }\n };\n end.setDayCellFactory(dayCellFactoryEnd);\n end.valueProperty().addListener((observable, oldValue, newValue) -> end.setDayCellFactory(dayCellFactoryEnd));\n\n start.valueProperty().addListener((observable, oldValue, newValue) -> {\n if (end.getValue() != null && start.getValue() != null && start.getValue().isAfter(end.getValue())) {\n start.setValue(null);\n\n }\n if (start.getValue() != null && end.getValue() != null && start.getValue().isEqual(end.getValue())) {\n start.setValue(null);\n }\n });\n\n end.valueProperty().addListener((observable, oldValue, newValue) -> {\n if (start.getValue() != null && end.getValue() != null && end.getValue().isBefore(start.getValue())) {\n end.setValue(null);\n }\n if (start.getValue() != null && end.getValue() != null && end.getValue().isEqual(start.getValue())) {\n end.setValue(null);\n }\n\n });\n final Callback<DatePicker, DateCell> dayCellFactoryNew =\n new Callback<>() {\n @Override\n public DateCell call(final DatePicker datePicker) {\n return new DateCell() {\n @Override\n public void updateItem(LocalDate item, boolean empty) {\n super.updateItem(item, empty);\n\n if ((start.getValue() != null && !item.isAfter(start.getValue().minusDays(1))) ||\n (end.getValue() != null && !item.isBefore(end.getValue().plusDays(1))) ||\n (newDate2.getValue() != null && item.isAfter(newDate2.getValue()))) {\n setDisable(true);\n if (StartMenu.currentTheme.equals(\"file:src/main/resources/com/netrunners/financialcalculator/assets/darkTheme.css\")) {\n setStyle(\"-fx-background-color: gray;\");\n } else {\n setStyle(\"-fx-background-color: dimgray;-fx-text-fill: white;\");\n }\n }\n }\n };\n }\n };\n newDate1.setDayCellFactory(dayCellFactoryNew);\n newDate1.valueProperty().addListener((observable, oldValue, newValue) -> newDate1.setDayCellFactory(dayCellFactoryNew));\n\n final Callback<DatePicker, DateCell> dayCellFactoryNew2 =\n new Callback<>() {\n @Override\n public DateCell call(final DatePicker datePicker) {\n return new DateCell() {\n @Override\n public void updateItem(LocalDate item, boolean empty) {\n super.updateItem(item, empty);\n\n if ((start.getValue() != null && item.isBefore(start.getValue().minusDays(1))) ||\n (end.getValue() != null && item.isAfter(end.getValue().plusDays(1))) ||\n (newDate1.getValue() != null && item.isBefore(newDate1.getValue()))) {\n setDisable(true);\n if (StartMenu.currentTheme.equals(\"file:src/main/resources/com/netrunners/financialcalculator/assets/darkTheme.css\")) {\n setStyle(\"-fx-background-color: gray;\");\n } else {\n setStyle(\"-fx-background-color: dimgray;-fx-text-fill: white;\");\n }\n }\n }\n };\n }\n };\n newDate2.setDayCellFactory(dayCellFactoryNew2);\n newDate2.valueProperty().addListener((observable, oldValue, newValue) -> newDate2.setDayCellFactory(dayCellFactoryNew2));\n\n newDate2.valueProperty().addListener((observable, oldValue, newValue) -> {\n if (start.getValue() != null && end.getValue() != null && newDate2.getValue() != null && (newDate2.getValue().isBefore(start.getValue()) || newDate2.getValue().isAfter(end.getValue()))) {\n newDate2.setValue(null);\n }\n if (newDate1.getValue() != null && newDate2.getValue() != null && newDate2.getValue().isBefore(newDate1.getValue())) {\n newDate2.setValue(null);\n }\n if (newDate1.getValue() != null && newDate2.getValue() != null && newDate2.getValue().isEqual(newDate1.getValue())) {\n newDate2.setValue(null);\n }\n });\n\n newDate1.valueProperty().addListener((observable, oldValue, newValue) -> {\n if (start.getValue() != null && end.getValue() != null && newDate1.getValue() != null && (newDate1.getValue().isBefore(start.getValue()) || newDate1.getValue().isAfter(end.getValue()))) {\n newDate1.setValue(null);\n }\n if (newDate2.getValue() != null && newDate1.getValue() != null && newDate1.getValue().isAfter(newDate2.getValue())) {\n newDate1.setValue(null);\n }\n });\n\n\n }\n\n\n}" }, { "identifier": "Credit", "path": "src/main/java/com/netrunners/financialcalculator/LogicalInstrumnts/TypesOfFinancialOpearation/Credit/Credit.java", "snippet": "public class Credit implements Savable {\n protected float loan;\n protected String currency;\n protected float annualPercent;\n protected LocalDate startDate;\n protected LocalDate endDate;\n protected int paymentType;\n protected int contractDuration;\n\n public Credit(float loan, String currency, float annualPercent, LocalDate startDate, LocalDate endDate, int paymentType) {\n this.loan = loan;\n this.currency = currency;\n this.annualPercent = annualPercent;\n this.startDate = startDate;\n this.endDate = endDate;\n this.paymentType = paymentType;\n this.contractDuration = DateTimeFunctions.countDaysBetweenDates(startDate, endDate);\n }\n\n public float countLoan() {\n return loan * (1f / 365f) * (annualPercent / 100f);\n }\n\n public float countCreditBodyPerDay(){\n return loan/contractDuration;\n }\n\n\n public void save() {\n Gson gson = new GsonBuilder()\n .setPrettyPrinting()\n .registerTypeAdapter(LocalDate.class, new LocalDateAdapter())\n .create();\n JsonObject jsonObject = getJsonObject();\n String json = gson.toJson(jsonObject);\n\n FileChooser fileChooser = new FileChooser();\n fileChooser.setTitle(LanguageManager.getInstance().getStringBinding(\"saveButton\").get());\n File initialDirectory = new File(\"saves/\");\n fileChooser.setInitialDirectory(initialDirectory);\n fileChooser.getExtensionFilters().addAll(\n new FileChooser.ExtensionFilter(\"JSON Files\", \"*.json\"));\n File file = fileChooser.showSaveDialog(null);\n\n if (file != null) {\n try (FileWriter writer = new FileWriter(file)) {\n writer.write(json);\n } catch (IOException e) {\n LogHelper.log(Level.SEVERE, \"Error while saving Credit to json\", e);\n }\n }\n }\n\n public void sendCreditToResultTable() {\n FXMLLoader loader = new FXMLLoader(getClass().getResource(\"/com/netrunners/financialcalculator/ResultTable.fxml\"));\n try {\n Parent root = loader.load();\n ResultTableController resultTableController = loader.getController();\n resultTableController.updateTable(this);\n\n Stage stage = new Stage();\n stage.setTitle(LanguageManager.getInstance().getStringBinding(\"ResultTableLabel\").get());\n Scene scene = new Scene(root);\n scene.getStylesheets().add(StartMenu.currentTheme);\n stage.setScene(scene);\n StartMenu.openScenes.add(scene);\n stage.getIcons().add(new Image(\"file:src/main/resources/com/netrunners/financialcalculator/assets/Logo.png\"));\n stage.setMaxHeight(720);\n stage.setMaxWidth(620);\n stage.setMinHeight(820);\n stage.setMinWidth(620);\n stage.show();\n } catch (Exception e) {\n LogHelper.log(Level.SEVERE, \"Error while sending Credit to result table\", e);\n }\n }\n\n protected JsonObject getJsonObject() {\n JsonObject jsonObject = new JsonObject();\n jsonObject.addProperty(\"loan\", this.loan);\n jsonObject.addProperty(\"annualPercent\", this.annualPercent);\n jsonObject.addProperty(\"currency\", this.currency);\n jsonObject.addProperty(\"paymentType\", this.paymentType);\n jsonObject.addProperty(\"startDate\", this.startDate.toString());\n jsonObject.addProperty(\"endDate\", this.endDate.toString());\n return jsonObject;\n }\n\n public float getLoan() {\n return loan;\n }\n\n public String getCurrency() {\n return currency;\n }\n\n public float getAnnualPercent() {\n return annualPercent;\n }\n\n public LocalDate getStartDate() {\n return startDate;\n }\n\n public LocalDate getEndDate() {\n return endDate;\n }\n\n public int getPaymentType() {\n return paymentType;\n }\n\n public void setLoan(float loan) {\n this.loan = loan;\n }\n\n public String getNameOfPaymentType() {\n LanguageManager languageManager = LanguageManager.getInstance();\n switch (paymentType) {\n case 1 -> {\n return \"Months\";\n }\n case 2 -> {\n return \"Quarters\";\n }\n case 3 -> {\n return \"Years\";\n }\n case 4 -> {\n return \"EndofTerm\";\n }\n }\n return languageManager.getStringBinding(\"None\").get();\n }\n}" }, { "identifier": "CreditWithHolidays", "path": "src/main/java/com/netrunners/financialcalculator/LogicalInstrumnts/TypesOfFinancialOpearation/Credit/CreditWithHolidays.java", "snippet": "public class CreditWithHolidays extends Credit{\n private final LocalDate holidaysStart;\n private final LocalDate holidaysEnd;\n\n public CreditWithHolidays(float loan, String currency, float annualPercent, LocalDate startDate, LocalDate endDate, int paymentType, LocalDate holidaysStart, LocalDate holidaysEnd) {\n super(loan, currency, annualPercent, startDate, endDate, paymentType);\n this.holidaysStart = holidaysStart;\n this.holidaysEnd = holidaysEnd;\n }\n\n @Override\n public float countLoan() {\n return super.countLoan();\n }\n\n @Override\n public float countCreditBodyPerDay() {\n return loan / (this.contractDuration - this.countHolidaysDuration());\n }\n\n @Override\n public void save() {\n super.save();\n }\n\n @Override\n protected JsonObject getJsonObject() {\n JsonObject jsonObject = new JsonObject();\n jsonObject.addProperty(\"operation\", \"Credit\");\n jsonObject.addProperty(\"type\", \"WithHolidays\");\n JsonObject superJsonObject = super.getJsonObject();\n for (Map.Entry<String, JsonElement> entry : superJsonObject.entrySet()) {\n jsonObject.add(entry.getKey(), entry.getValue());\n }\n jsonObject.addProperty(\"holidaysStart\", holidaysStart.toString());\n jsonObject.addProperty(\"holidaysEnd\", holidaysEnd.toString());\n return jsonObject;\n }\n\n public LocalDate getHolidaysStart() {\n return holidaysStart;\n }\n\n public LocalDate getHolidaysEnd() {\n return holidaysEnd;\n }\n\n public int countHolidaysDuration() {\n return DateTimeFunctions.countDaysBetweenDates(holidaysStart, holidaysEnd);\n }\n\n}" }, { "identifier": "CreditWithoutHolidays", "path": "src/main/java/com/netrunners/financialcalculator/LogicalInstrumnts/TypesOfFinancialOpearation/Credit/CreditWithoutHolidays.java", "snippet": "public class CreditWithoutHolidays extends Credit{\n\n public CreditWithoutHolidays(float loan, String currency, float annualPercent, LocalDate startDate, LocalDate endDate, int paymentType) {\n super(loan, currency, annualPercent, startDate, endDate, paymentType);\n }\n\n @Override\n public void save() {\n super.save();\n }\n\n @Override\n protected JsonObject getJsonObject() {\n JsonObject jsonObject = new JsonObject();\n jsonObject.addProperty(\"operation\", \"Credit\");\n jsonObject.addProperty(\"type\", \"WithoutHolidays\");\n JsonObject superJsonObject = super.getJsonObject();\n for (Map.Entry<String, JsonElement> entry : superJsonObject.entrySet()) {\n jsonObject.add(entry.getKey(), entry.getValue());\n }\n return jsonObject;\n }\n\n}" }, { "identifier": "WindowsOpener", "path": "src/main/java/com/netrunners/financialcalculator/VisualInstruments/WindowsOpener.java", "snippet": "public class WindowsOpener{\n public static void depositOpener(){\n try {\n FXMLLoader fxmlLoader = new FXMLLoader(StartMenu.class.getResource(\"DepositMenu.fxml\"));\n Stage stage = new Stage();\n stage.titleProperty().bind(LanguageManager.getInstance().getStringBinding(\"DepositButton\"));\n Scene scene = new Scene(fxmlLoader.load());\n scene.getStylesheets().add(StartMenu.currentTheme);\n stage.setScene(scene);\n StartMenu.openScenes.add(scene);\n stage.getIcons().add(new Image(\"file:src/main/resources/com/netrunners/financialcalculator/assets/Logo.png\"));\n stage.setMaxHeight(820);\n stage.setMaxWidth(620);\n stage.setMinHeight(820);\n stage.setMinWidth(620);\n stage.show();\n\n } catch (IOException e) {\n LogHelper.log(Level.SEVERE, \"Error opening DepositMenu.fxml: \", e);\n }\n }\n public static void creditOpener(){\n try {\n FXMLLoader fxmlLoader = new FXMLLoader(StartMenu.class.getResource(\"CreditMenu.fxml\"));\n Stage stage = new Stage();\n stage.titleProperty().bind(LanguageManager.getInstance().getStringBinding(\"CreditButton\"));\n Scene scene = new Scene(fxmlLoader.load());\n scene.getStylesheets().add(StartMenu.currentTheme);\n stage.setScene(scene);\n StartMenu.openScenes.add(scene);\n stage.getIcons().add(new Image(\"file:src/main/resources/com/netrunners/financialcalculator/assets/Logo.png\"));\n stage.setMaxHeight(820);\n stage.setMaxWidth(620);\n stage.setMinHeight(820);\n stage.setMinWidth(620);\n stage.show();\n\n } catch (Exception e) {\n LogHelper.log(Level.SEVERE, \"Error opening CreditMenu.fxml: \", e);\n }\n }\n}" }, { "identifier": "closeCurrentWindow", "path": "src/main/java/com/netrunners/financialcalculator/MenuControllers/closeWindow.java", "snippet": "static void closeCurrentWindow(Scene scene) {\n scene.getWindow().hide();\n}" } ]
import java.time.LocalDate; import java.util.*; import com.netrunners.financialcalculator.ErrorHandling.ErrorChecker; import com.netrunners.financialcalculator.LogicalInstrumnts.FileInstruments.OpenFile; import com.netrunners.financialcalculator.LogicalInstrumnts.TimeFunctions.DatePickerRestrictions; import com.netrunners.financialcalculator.LogicalInstrumnts.TypesOfFinancialOpearation.Credit.Credit; import com.netrunners.financialcalculator.LogicalInstrumnts.TypesOfFinancialOpearation.Credit.CreditWithHolidays; import com.netrunners.financialcalculator.LogicalInstrumnts.TypesOfFinancialOpearation.Credit.CreditWithoutHolidays; import com.netrunners.financialcalculator.VisualInstruments.MenuActions.*; import com.netrunners.financialcalculator.VisualInstruments.WindowsOpener; import javafx.fxml.FXML; import javafx.scene.control.*; import javafx.scene.image.Image; import javafx.stage.Stage; import static com.netrunners.financialcalculator.MenuControllers.closeWindow.closeCurrentWindow;
7,585
package com.netrunners.financialcalculator.MenuControllers; public class CreditMenuController implements CurrencyController { @FXML private MenuItem PaymentOption1; @FXML private MenuItem PaymentOption2; @FXML private MenuItem PaymentOption3; @FXML private MenuItem PaymentOption4; @FXML private Menu aboutButton; @FXML private MenuItem aboutUs; @FXML private TextField annualPercentInput; @FXML private CheckBox checkPaymentHolidays; @FXML private Button closeWindow; @FXML private DatePicker contractBeginning; @FXML private DatePicker contractEnding; @FXML private MenuItem creditButtonMenu; @FXML private Label creditLabel; @FXML private Button creditSaveResult; @FXML private Button creditViewResult; @FXML private MenuItem currency; @FXML private MenuItem darkTheme; @FXML private MenuItem depositButtonMenu; @FXML private MenuItem exitApp; @FXML private Menu fileButton; @FXML private DatePicker holidaysBeginning; @FXML private DatePicker holidaysEnding; @FXML private MenuItem languageButton; @FXML private MenuItem lightTheme; @FXML private TextField loanInput; @FXML private MenuItem openFileButton; @FXML private MenuButton paymentOption; @FXML private MenuItem saveAsButton; @FXML private MenuItem saveButton; @FXML private Menu settingsButton; @FXML private Menu themeButton; @FXML private Menu viewButton; @FXML private MenuItem newButton; private LanguageManager languageManager = LanguageManager.getInstance(); @FXML void initialize() { DatePickerRestrictions.setDatePickerRestrictionsHolidays(contractBeginning, contractEnding, holidaysBeginning, holidaysEnding); holidaysBeginning.setVisible(false); holidaysBeginning.setDisable(true); holidaysEnding.setVisible(false); holidaysEnding.setDisable(true); saveButton.setDisable(true); saveAsButton.setDisable(true); checkPaymentHolidays.setOnAction(event -> { if (checkPaymentHolidays.isSelected()) { holidaysBeginning.setVisible(true); holidaysEnding.setVisible(true); holidaysBeginning.setDisable(false); holidaysEnding.setDisable(false); } else { holidaysBeginning.setVisible(false); holidaysEnding.setVisible(false); holidaysBeginning.setDisable(true); holidaysEnding.setDisable(true); } }); PaymentOption1.setOnAction(event -> { paymentOption.textProperty().unbind(); paymentOption.setText(PaymentOption1.getText()); paymentOption.textProperty().bind(languageManager.getStringBinding("Option1")); }); PaymentOption2.setOnAction(event -> { paymentOption.textProperty().unbind(); paymentOption.setText(PaymentOption2.getText()); paymentOption.textProperty().bind(languageManager.getStringBinding("Option2")); }); PaymentOption3.setOnAction(event -> { paymentOption.textProperty().unbind(); paymentOption.setText(PaymentOption3.getText()); paymentOption.textProperty().bind(languageManager.getStringBinding("Option3")); }); PaymentOption4.setOnAction(event -> { paymentOption.textProperty().unbind(); paymentOption.setText(PaymentOption4.getText()); paymentOption.textProperty().bind(languageManager.getStringBinding("Option4")); });
package com.netrunners.financialcalculator.MenuControllers; public class CreditMenuController implements CurrencyController { @FXML private MenuItem PaymentOption1; @FXML private MenuItem PaymentOption2; @FXML private MenuItem PaymentOption3; @FXML private MenuItem PaymentOption4; @FXML private Menu aboutButton; @FXML private MenuItem aboutUs; @FXML private TextField annualPercentInput; @FXML private CheckBox checkPaymentHolidays; @FXML private Button closeWindow; @FXML private DatePicker contractBeginning; @FXML private DatePicker contractEnding; @FXML private MenuItem creditButtonMenu; @FXML private Label creditLabel; @FXML private Button creditSaveResult; @FXML private Button creditViewResult; @FXML private MenuItem currency; @FXML private MenuItem darkTheme; @FXML private MenuItem depositButtonMenu; @FXML private MenuItem exitApp; @FXML private Menu fileButton; @FXML private DatePicker holidaysBeginning; @FXML private DatePicker holidaysEnding; @FXML private MenuItem languageButton; @FXML private MenuItem lightTheme; @FXML private TextField loanInput; @FXML private MenuItem openFileButton; @FXML private MenuButton paymentOption; @FXML private MenuItem saveAsButton; @FXML private MenuItem saveButton; @FXML private Menu settingsButton; @FXML private Menu themeButton; @FXML private Menu viewButton; @FXML private MenuItem newButton; private LanguageManager languageManager = LanguageManager.getInstance(); @FXML void initialize() { DatePickerRestrictions.setDatePickerRestrictionsHolidays(contractBeginning, contractEnding, holidaysBeginning, holidaysEnding); holidaysBeginning.setVisible(false); holidaysBeginning.setDisable(true); holidaysEnding.setVisible(false); holidaysEnding.setDisable(true); saveButton.setDisable(true); saveAsButton.setDisable(true); checkPaymentHolidays.setOnAction(event -> { if (checkPaymentHolidays.isSelected()) { holidaysBeginning.setVisible(true); holidaysEnding.setVisible(true); holidaysBeginning.setDisable(false); holidaysEnding.setDisable(false); } else { holidaysBeginning.setVisible(false); holidaysEnding.setVisible(false); holidaysBeginning.setDisable(true); holidaysEnding.setDisable(true); } }); PaymentOption1.setOnAction(event -> { paymentOption.textProperty().unbind(); paymentOption.setText(PaymentOption1.getText()); paymentOption.textProperty().bind(languageManager.getStringBinding("Option1")); }); PaymentOption2.setOnAction(event -> { paymentOption.textProperty().unbind(); paymentOption.setText(PaymentOption2.getText()); paymentOption.textProperty().bind(languageManager.getStringBinding("Option2")); }); PaymentOption3.setOnAction(event -> { paymentOption.textProperty().unbind(); paymentOption.setText(PaymentOption3.getText()); paymentOption.textProperty().bind(languageManager.getStringBinding("Option3")); }); PaymentOption4.setOnAction(event -> { paymentOption.textProperty().unbind(); paymentOption.setText(PaymentOption4.getText()); paymentOption.textProperty().bind(languageManager.getStringBinding("Option4")); });
closeWindow.setOnAction(event -> closeCurrentWindow(closeWindow.getScene()));
7
2023-10-18 16:03:09+00:00
12k
Kyrotechnic/KyroClient
Client/src/main/java/me/kyroclient/mixins/MixinMinecraft.java
[ { "identifier": "KyroClient", "path": "Client/src/main/java/me/kyroclient/KyroClient.java", "snippet": "public class KyroClient {\n //Vars\n public static final String MOD_ID = \"dankers\";\n public static String VERSION = \"0.2-b3\";\n public static List<String> changelog;\n public static ModuleManager moduleManager;\n public static NotificationManager notificationManager;\n public static ConfigManager configManager;\n public static ThemeManager themeManager;\n public static FriendManager friendManager;\n public static CapeManager capeManager;\n public static Minecraft mc;\n public static boolean isDev = true;\n public static Color iconColor = new Color(237, 107, 0);\n public static long gameStarted;\n public static boolean banned = false;\n\n //Module Dependencies\n public static Gui clickGui;\n public static NickHider nickHider;\n public static CropNuker cropNuker;\n public static Velocity velocity;\n public static FastPlace fastPlace;\n public static Modless modless;\n public static Speed speed;\n public static AntiBot antiBot;\n public static Interfaces interfaces;\n public static Delays delays;\n public static Hitboxes hitBoxes;\n public static NoSlow noSlow;\n public static FreeCam freeCam;\n public static Giants giants;\n public static Animations animations;\n public static Aura aura;\n public static AutoBlock autoBlock;\n public static PopupAnimation popupAnimation;\n public static GuiMove guiMove;\n public static Camera camera;\n public static Reach reach;\n public static InventoryDisplay inventoryDisplay;\n public static LoreDisplay loreDisplay;\n public static FarmingMacro macro;\n public static MiningQOL miningQol;\n public static Tickless tickless;\n public static TeleportExploit teleportExploit;\n public static Hud hud;\n public static FakeLag fakeLag;\n public static Proxy proxy;\n public static CustomBrand customBrand;\n public static NoFallingBlocks noFallingBlocks;\n public static PlayerVisibility playerVisibility;\n public static NoDebuff noDebuff;\n public static Capes capes;\n\n\n //Methods\n\n /*\n Time to finally make it spoof being any random mod on boot!\n */\n public static List<ForgeRegister> registerEvents()\n {\n /*for (Module module : moduleManager.getModules())\n {\n MinecraftForge.EVENT_BUS.register(module);\n }*/\n\n ForgeSpoofer.update();\n List<ForgeRegister> registers = new ArrayList<>();\n\n for (Module module : moduleManager.getModules())\n {\n List<ForgeRegister> register = ForgeSpoofer.register(module, true);\n if (register.isEmpty()) continue;\n registers.addAll(register);\n }\n\n registers.add(ForgeSpoofer.register(notificationManager = new NotificationManager(), true).get(0));\n registers.add(ForgeSpoofer.register(new BlurUtils(), true).get(0));\n registers.add(ForgeSpoofer.register(new KyroClient(), true).get(0));\n\n Fonts.bootstrap();\n\n capeManager = new CapeManager();\n try {\n capeManager.init();\n } catch (Exception e) {\n e.printStackTrace();\n }\n\n return registers;\n }\n public static void init()\n {\n mc = Minecraft.getMinecraft();\n\n moduleManager = new ModuleManager(\"me.kyroclient.modules\");\n moduleManager.initReflection();\n\n configManager = new ConfigManager();\n themeManager = new ThemeManager();\n friendManager = new FriendManager();\n\n friendManager.init();\n\n CommandManager.init();\n\n KyroClient.proxy.setToggled(false);\n\n gameStarted = System.currentTimeMillis();\n\n //fixCertificate();\n\n Runtime.getRuntime().addShutdownHook(new Thread(() -> {\n friendManager.save();\n try {\n Class clazz = Class.forName(\"me.kyroclient.AgentLoader\");\n Method method = clazz.getMethod(\"downloadUpdate\");\n method.setAccessible(true);\n method.invoke(null);\n } catch (Exception e) {\n e.printStackTrace();\n }\n }));\n\n new Thread(KyroClient::threadTask).start();\n }\n\n @SneakyThrows\n public static void fixCertificate()\n {\n SSLContext sc = SSLContext.getInstance(\"SSL\");\n sc.init(null, new TrustManager[]{new TrustAnyTrustManager()}, new SecureRandom());\n HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());\n HostnameVerifier allHostsValid = new HostnameVerifier() {\n public boolean verify(String hostname, SSLSession session) {\n return true;\n }\n };\n HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);\n }\n\n @SubscribeEvent\n public void sendPacket(PacketSentEvent event)\n {\n if (event.packet instanceof C01PacketChatMessage)\n {\n C01PacketChatMessage message = (C01PacketChatMessage) event.packet;\n\n String str = message.getMessage();\n\n if (CommandManager.handle(str))\n {\n event.setCanceled(true);\n }\n }\n }\n\n public static void sendMessage(String message)\n {\n KyroClient.mc.thePlayer.addChatMessage(new ChatComponentText(message));\n }\n\n @SneakyThrows\n public static void threadTask()\n {\n URL url2 = new URL(\"https://raw.githubusercontent.com/Kyrotechnic/KyroClient/main/update/Changelog.txt\");\n\n List<String> changelog = new ArrayList<String>();\n\n BufferedReader reader = new BufferedReader(new InputStreamReader(url2.openStream()));\n String b = null;\n while ((b = reader.readLine()) != null)\n {\n changelog.add(b);\n }\n\n KyroClient.VERSION = changelog.get(0);\n\n KyroClient.changelog = changelog.stream().filter(c -> !(c.equals(KyroClient.VERSION))).collect(Collectors.toList());\n }\n\n public static void handleKey(int key)\n {\n for (Module module : moduleManager.getModules())\n {\n if (module.getKeycode() == key)\n {\n module.toggle();\n if (!clickGui.disableNotifs.isEnabled())\n notificationManager.showNotification(module.getName() + \" has been \" + (module.isToggled() ? \"Enabled\" : \"Disabled\"), 2000, Notification.NotificationType.INFO);\n }\n }\n }\n\n public static int ticks = 0;\n\n @SubscribeEvent\n public void joinWorld(TickEvent.ClientTickEvent event)\n {\n ticks++;\n SkyblockUtils.tick(event);\n }\n}" }, { "identifier": "KeyboardEvent", "path": "Client/src/main/java/me/kyroclient/events/KeyboardEvent.java", "snippet": "public class KeyboardEvent extends Event\n{\n public int key;\n public char aChar;\n\n public KeyboardEvent(final int key, final char aChar) {\n this.key = key;\n this.aChar = aChar;\n }\n}" }, { "identifier": "LeftClickEvent", "path": "Client/src/main/java/me/kyroclient/events/LeftClickEvent.java", "snippet": "@Cancelable\npublic class LeftClickEvent extends Event {\n}" }, { "identifier": "PostGuiOpenEvent", "path": "Client/src/main/java/me/kyroclient/events/PostGuiOpenEvent.java", "snippet": "public class PostGuiOpenEvent extends Event\n{\n public Gui gui;\n\n public PostGuiOpenEvent(final Gui gui) {\n this.gui = gui;\n }\n}" }, { "identifier": "RightClickEvent", "path": "Client/src/main/java/me/kyroclient/events/RightClickEvent.java", "snippet": "@Cancelable\npublic class RightClickEvent extends Event {\n}" }, { "identifier": "Aura", "path": "Client/src/main/java/me/kyroclient/modules/combat/Aura.java", "snippet": "public class Aura extends Module {\n public static EntityLivingBase target;\n public BooleanSetting namesOnly;\n public BooleanSetting middleClick;\n public BooleanSetting players;\n public BooleanSetting mobs;\n public BooleanSetting walls;\n public BooleanSetting teams;\n public BooleanSetting toggleOnLoad;\n public BooleanSetting toggleInGui;\n public BooleanSetting onlySword;\n public BooleanSetting movementFix;\n public BooleanSetting rotationSwing;\n public BooleanSetting shovelSwap;\n public BooleanSetting attackOnly;\n public BooleanSetting invisibles;\n public ModeSetting sorting;\n public ModeSetting rotationMode;\n public ModeSetting blockMode;\n public ModeSetting namesonlyMode;\n public ModeSetting mode;\n public NumberSetting range;\n public NumberSetting rotationRange;\n public NumberSetting fov;\n public NumberSetting maxRotation;\n public NumberSetting minRotation;\n public NumberSetting maxCps;\n public NumberSetting minCps;\n public NumberSetting smoothing;\n public NumberSetting switchDelay;\n public ModeSetting when = new ModeSetting(\"When Attack\", \"Pre\", \"Pre\", \"Post\");\n public static List<String> names;\n private boolean wasDown;\n private boolean isBlocking;\n private int nextCps;\n private int lastSlot;\n private int targetIndex;\n private int attacks;\n private MilliTimer lastAttack;\n private MilliTimer switchDelayTimer;\n private MilliTimer blockDelay;\n public static final MilliTimer DISABLE;\n\n public Aura() {\n super(\"Aura\", 0, Category.COMBAT);\n this.namesOnly = new BooleanSetting(\"Names only\", false);\n this.middleClick = new BooleanSetting(\"Middle click to add\", false);\n this.players = new BooleanSetting(\"Players\", false);\n this.mobs = new BooleanSetting(\"Mobs\", true);\n this.walls = new BooleanSetting(\"Through walls\", true);\n this.teams = new BooleanSetting(\"Teams\", true);\n this.toggleOnLoad = new BooleanSetting(\"Disable on join\", true);\n this.toggleInGui = new BooleanSetting(\"No containers\", true);\n this.onlySword = new BooleanSetting(\"Only swords\", false);\n this.movementFix = new BooleanSetting(\"Movement fix\", false);\n this.rotationSwing = new BooleanSetting(\"Swing on rotation\", false);\n this.shovelSwap = new BooleanSetting(\"Shovel swap\", false);\n this.attackOnly = new BooleanSetting(\"Click only\", false);\n this.invisibles = new BooleanSetting(\"Invisibles\", false);\n this.sorting = new ModeSetting(\"Sorting\", \"Distance\", new String[] { \"Distance\", \"Health\", \"Hurt\", \"Hp reverse\" });\n this.rotationMode = new ModeSetting(\"Rotation mode\", \"Simple\", new String[] { \"Simple\", \"Smooth\", \"None\" });\n this.blockMode = new ModeSetting(\"Autoblock\", \"None\", new String[] { \"Vanilla\", \"Hypixel\", \"Fake\", \"None\" });\n this.namesonlyMode = new ModeSetting(\"Names mode\", \"Enemies\", new String[] { \"Friends\", \"Enemies\" });\n this.mode = new ModeSetting(\"Mode\", \"Single\", new String[] { \"Single\", \"Switch\" });\n this.range = new NumberSetting(\"Range\", 4.2, 2.0, 6.0, 0.1) {\n @Override\n public void setValue(final double value) {\n super.setValue(value);\n if (this.getValue() > Aura.this.rotationRange.getValue()) {\n this.setValue(Aura.this.rotationRange.getValue());\n }\n }\n };\n this.rotationRange = new NumberSetting(\"Rotation Range\", 6.0, 2.0, 12.0, 0.1) {\n @Override\n public void setValue(final double value) {\n super.setValue(value);\n if (this.getValue() < Aura.this.range.getValue()) {\n this.setValue(Aura.this.range.getValue());\n }\n }\n };\n this.fov = new NumberSetting(\"Fov\", 360.0, 30.0, 360.0, 1.0);\n this.maxRotation = new NumberSetting(\"Max rotation\", 100.0, 10.0, 180.0, 0.1) {\n @Override\n public boolean isHidden() {\n return !Aura.this.rotationMode.is(\"Simple\");\n }\n\n @Override\n public void setValue(final double value) {\n super.setValue(value);\n if (Aura.this.minRotation.getValue() > this.getValue()) {\n this.setValue(Aura.this.minRotation.getValue());\n }\n }\n };\n this.minRotation = new NumberSetting(\"Min rotation\", 60.0, 5.0, 180.0, 0.1) {\n @Override\n public boolean isHidden() {\n return !Aura.this.rotationMode.is(\"Simple\");\n }\n\n @Override\n public void setValue(final double value) {\n super.setValue(value);\n if (this.getValue() > Aura.this.maxRotation.getValue()) {\n this.setValue(Aura.this.maxRotation.getValue());\n }\n }\n };\n this.maxCps = new NumberSetting(\"Max CPS\", 13.0, 1.0, 20.0, 1.0) {\n @Override\n public void setValue(final double value) {\n super.setValue(value);\n if (Aura.this.minCps.getValue() > this.getValue()) {\n this.setValue(Aura.this.minCps.getValue());\n }\n }\n };\n this.minCps = new NumberSetting(\"Min CPS\", 11.0, 1.0, 20.0, 1.0) {\n @Override\n public void setValue(final double value) {\n super.setValue(value);\n if (Aura.this.maxCps.getValue() < this.getValue()) {\n this.setValue(Aura.this.maxCps.getValue());\n }\n }\n };\n this.smoothing = new NumberSetting(\"Smoothing\", 12.0, 1.0, 20.0, 0.1) {\n @Override\n public boolean isHidden() {\n return !Aura.this.rotationMode.is(\"Smooth\");\n }\n };\n this.switchDelay = new NumberSetting(\"Switch delay\", 100.0, 0.0, 250.0, 1.0, aBoolean -> !this.mode.is(\"Switch\"));\n this.nextCps = 10;\n this.lastSlot = -1;\n this.lastAttack = new MilliTimer();\n this.switchDelayTimer = new MilliTimer();\n this.blockDelay = new MilliTimer();\n this.addSettings(this.mode, this.switchDelay, this.range, this.rotationRange, this.minCps, this.maxCps, this.sorting, this.rotationMode, this.smoothing, this.maxRotation, this.minRotation, this.fov, this.blockMode, this.players, this.mobs, this.invisibles, this.teams, this.rotationSwing, this.movementFix, this.namesOnly, this.namesonlyMode, this.middleClick, this.attackOnly, this.walls, this.toggleInGui, this.toggleOnLoad, this.onlySword, this.shovelSwap, when);\n }\n\n public void addAll(String... strs)\n {\n for (String str : strs)\n {\n names.add(str);\n }\n }\n\n @Override\n public void assign()\n {\n KyroClient.aura = this;\n }\n\n @SubscribeEvent\n public void onTick(final TickEvent.ClientTickEvent event) {\n if (KyroClient.mc.thePlayer == null || KyroClient.mc.theWorld == null || !this.middleClick.isEnabled()) {\n return;\n }\n if (Mouse.isButtonDown(2) && KyroClient.mc.currentScreen == null) {\n if (KyroClient.mc.pointedEntity != null && !this.wasDown && !(KyroClient.mc.pointedEntity instanceof EntityArmorStand) && KyroClient.mc.pointedEntity instanceof EntityLivingBase) {\n final String name = ChatFormatting.stripFormatting(KyroClient.mc.pointedEntity.getName());\n if (!Aura.names.contains(name)) {\n Aura.names.add(name);\n KyroClient.notificationManager.showNotification(\"Added \" + ChatFormatting.AQUA + name + ChatFormatting.RESET + \" to name sorting\", 2000, Notification.NotificationType.INFO);\n }\n else {\n Aura.names.remove(name);\n KyroClient.notificationManager.showNotification(\"Removed \" + ChatFormatting.AQUA + name + ChatFormatting.RESET + \" from name sorting\", 2000, Notification.NotificationType.INFO);\n }\n }\n this.wasDown = true;\n }\n else {\n this.wasDown = false;\n }\n }\n\n @Override\n public void onEnable() {\n this.attacks = 0;\n }\n\n @Override\n public void onDisable() {\n Aura.target = null;\n this.isBlocking = false;\n }\n\n @SubscribeEvent(priority = EventPriority.NORMAL)\n public void onMovePre(final MotionUpdateEvent.Pre event) {\n if (!isToggled())\n {\n target = null;\n return;\n }\n\n Aura.target = this.getTarget();\n if (this.attackOnly.isEnabled() && !KyroClient.mc.gameSettings.keyBindAttack.isKeyDown()) {\n return;\n }\n if (Aura.target != null) {\n final Rotation angles = RotationUtils.getRotations(Aura.target, 0.2f);\n if (!KyroClient.speed.isToggled()) {\n final String selected = this.rotationMode.getSelected();\n switch (selected) {\n case \"Smooth\": {\n event.setRotation(RotationUtils.getSmoothRotation(RotationUtils.getLastReportedRotation(), angles, (float)this.smoothing.getValue()));\n break;\n }\n case \"Simple\": {\n event.setRotation(RotationUtils.getLimitedRotation(RotationUtils.getLastReportedRotation(), angles, (float)(this.minRotation.getValue() + Math.abs(this.maxRotation.getValue() - this.minRotation.getValue()) * new Random().nextFloat())));\n break;\n }\n }\n }\n event.setPitch(MathUtil.clamp(event.pitch, 90.0f, -90.0f));\n final String selected2 = this.blockMode.getSelected();\n switch (selected2) {\n }\n if (this.shovelSwap.isEnabled() && Aura.target instanceof EntityPlayer && this.hasDiamondArmor((EntityPlayer)Aura.target)) {\n this.lastSlot = KyroClient.mc.thePlayer.inventory.currentItem;\n for (int i = 0; i < 9; ++i) {\n if (KyroClient.mc.thePlayer.inventory.getStackInSlot(i) != null && KyroClient.mc.thePlayer.inventory.getStackInSlot(i).getItem() instanceof ItemSpade) {\n PlayerUtil.swapSlot(i);\n this.isBlocking = false;\n break;\n }\n }\n }\n }\n\n if (when.is(\"Post\")) return;\n\n if (this.attackOnly.isEnabled() && !KyroClient.mc.gameSettings.keyBindAttack.isKeyDown()) {\n this.attacks = 0;\n return;\n }\n if (Aura.target != null && KyroClient.mc.thePlayer.getDistanceToEntity((Entity)Aura.target) < Math.max(this.rotationRange.getValue(), this.range.getValue()) && this.attacks > 0) {\n final String selected = this.blockMode.getSelected();\n switch (selected) {\n case \"None\":\n case \"Fake\": {}\n case \"Vanilla\": {\n this.stopBlocking();\n break;\n }\n }\n while (this.attacks > 0) {\n KyroClient.mc.thePlayer.swingItem();\n if (KyroClient.mc.thePlayer.getDistanceToEntity((Entity)Aura.target) < this.range.getValue() && (RotationUtils.getRotationDifference(RotationUtils.getRotations(Aura.target), RotationUtils.getLastReportedRotation()) < 15.0 || this.rotationMode.is(\"None\") || KyroClient.speed.isToggled())) {\n KyroClient.mc.playerController.attackEntity((EntityPlayer)KyroClient.mc.thePlayer, (Entity)Aura.target);\n if (this.switchDelayTimer.hasTimePassed((long)this.switchDelay.getValue())) {\n ++this.targetIndex;\n this.switchDelayTimer.reset();\n }\n }\n --this.attacks;\n }\n if (KyroClient.mc.thePlayer.getHeldItem() != null && KyroClient.mc.thePlayer.getHeldItem().getItem() instanceof ItemSword) {\n final String selected2 = this.blockMode.getSelected();\n switch (selected2) {\n case \"Vanilla\": {\n if (!this.isBlocking) {\n this.startBlocking();\n break;\n }\n break;\n }\n case \"Hypixel\": {\n if (this.blockDelay.hasTimePassed(250L)) {\n this.startBlocking();\n KyroClient.mc.thePlayer.sendQueue.addToSendQueue((Packet)new C0BPacketEntityAction((Entity)KyroClient.mc.thePlayer, C0BPacketEntityAction.Action.STOP_SPRINTING));\n KyroClient.mc.thePlayer.sendQueue.addToSendQueue((Packet)new C0BPacketEntityAction((Entity)KyroClient.mc.thePlayer, C0BPacketEntityAction.Action.START_SPRINTING));\n this.blockDelay.reset();\n break;\n }\n break;\n }\n }\n }\n }\n else {\n this.attacks = 0;\n }\n }\n\n @SubscribeEvent\n public void onMoveFlying(final MoveFlyingEvent event) {\n if (this.isToggled() && Aura.target != null && this.movementFix.isEnabled()) {\n event.setYaw(RotationUtils.getRotations(Aura.target).getYaw());\n }\n }\n\n private boolean hasDiamondArmor(final EntityPlayer player) {\n for (int i = 1; i < 5; ++i) {\n if (player.getEquipmentInSlot(i) != null && player.getEquipmentInSlot(i).getItem() instanceof ItemArmor && ((ItemArmor)player.getEquipmentInSlot(i).getItem()).getArmorMaterial() == ItemArmor.ArmorMaterial.DIAMOND) {\n return true;\n }\n }\n return false;\n }\n\n @SubscribeEvent(priority = EventPriority.HIGHEST)\n public void onMovePost(final MotionUpdateEvent.Post event) {\n if (!isToggled()) return;\n if (when.is(\"Pre\")) return;\n if (this.attackOnly.isEnabled() && !KyroClient.mc.gameSettings.keyBindAttack.isKeyDown()) {\n this.attacks = 0;\n return;\n }\n if (Aura.target != null && KyroClient.mc.thePlayer.getDistanceToEntity((Entity)Aura.target) < Math.max(this.rotationRange.getValue(), this.range.getValue()) && this.attacks > 0) {\n final String selected = this.blockMode.getSelected();\n switch (selected) {\n case \"None\":\n case \"Fake\": {}\n case \"Vanilla\": {\n this.stopBlocking();\n break;\n }\n }\n while (this.attacks > 0) {\n KyroClient.mc.thePlayer.swingItem();\n if (KyroClient.mc.thePlayer.getDistanceToEntity((Entity)Aura.target) < this.range.getValue() && (RotationUtils.getRotationDifference(RotationUtils.getRotations(Aura.target), RotationUtils.getLastReportedRotation()) < 15.0 || this.rotationMode.is(\"None\") || KyroClient.speed.isToggled())) {\n KyroClient.mc.playerController.attackEntity((EntityPlayer)KyroClient.mc.thePlayer, (Entity)Aura.target);\n if (this.switchDelayTimer.hasTimePassed((long)this.switchDelay.getValue())) {\n ++this.targetIndex;\n this.switchDelayTimer.reset();\n }\n }\n --this.attacks;\n }\n if (KyroClient.mc.thePlayer.getHeldItem() != null && KyroClient.mc.thePlayer.getHeldItem().getItem() instanceof ItemSword) {\n final String selected2 = this.blockMode.getSelected();\n switch (selected2) {\n case \"Vanilla\": {\n if (!this.isBlocking) {\n this.startBlocking();\n break;\n }\n break;\n }\n case \"Hypixel\": {\n if (this.blockDelay.hasTimePassed(250L)) {\n this.startBlocking();\n KyroClient.mc.thePlayer.sendQueue.addToSendQueue((Packet)new C0BPacketEntityAction((Entity)KyroClient.mc.thePlayer, C0BPacketEntityAction.Action.STOP_SPRINTING));\n KyroClient.mc.thePlayer.sendQueue.addToSendQueue((Packet)new C0BPacketEntityAction((Entity)KyroClient.mc.thePlayer, C0BPacketEntityAction.Action.START_SPRINTING));\n this.blockDelay.reset();\n break;\n }\n break;\n }\n }\n }\n }\n else {\n this.attacks = 0;\n }\n if (this.shovelSwap.isEnabled() && this.lastSlot != -1) {\n PlayerUtil.swapSlot(this.lastSlot);\n this.lastSlot = -1;\n }\n }\n\n @SubscribeEvent(receiveCanceled = true)\n public void onPacket(final PacketReceivedEvent event) {\n if (event.packet instanceof S08PacketPlayerPosLook) {\n Aura.DISABLE.reset();\n }\n }\n\n @SubscribeEvent\n public void onRender(final RenderWorldLastEvent event) {\n if (this.isToggled() && Aura.target != null && this.lastAttack.hasTimePassed(1000 / this.nextCps) && KyroClient.mc.thePlayer.getDistanceToEntity((Entity)Aura.target) < (this.rotationSwing.isEnabled() ? this.getRotationRange() : this.range.getValue())) {\n this.nextCps = (int)(this.minCps.getValue() + Math.abs(this.maxCps.getValue() - this.minCps.getValue()) * new Random().nextFloat());\n this.lastAttack.reset();\n ++this.attacks;\n }\n }\n\n private EntityLivingBase getTarget() {\n if ((KyroClient.mc.currentScreen instanceof GuiContainer && this.toggleInGui.isEnabled()) || KyroClient.mc.theWorld == null) {\n return null;\n }\n final List<Entity> validTargets = (List<Entity>)KyroClient.mc.theWorld.getLoadedEntityList().stream().filter(entity -> entity instanceof EntityLivingBase).filter(entity -> this.isValid((EntityLivingBase) entity)).sorted(Comparator.comparingDouble(e -> e.getDistanceToEntity((Entity)KyroClient.mc.thePlayer))).collect(Collectors.toList());\n final String selected = this.sorting.getSelected();\n switch (selected) {\n case \"Health\": {\n validTargets.sort(Comparator.comparingDouble(e -> ((EntityLivingBase)e).getHealth()));\n break;\n }\n case \"Hurt\": {\n validTargets.sort(Comparator.comparing(e -> ((EntityLivingBase)e).hurtTime));\n break;\n }\n case \"Hp reverse\": {\n validTargets.sort(Comparator.comparingDouble(e -> ((EntityLivingBase)e).getHealth()).reversed());\n break;\n }\n }\n if (!validTargets.isEmpty()) {\n if (this.targetIndex >= validTargets.size()) {\n this.targetIndex = 0;\n }\n final String selected2 = this.mode.getSelected();\n switch (selected2) {\n case \"Switch\": {\n return (EntityLivingBase)validTargets.get(this.targetIndex);\n }\n case \"Single\": {\n return (EntityLivingBase)validTargets.get(0);\n }\n }\n }\n return null;\n }\n public static Pattern pattern = Pattern.compile(\"\\\\[[0-9]+\\\\]\");\n private boolean isValid(final EntityLivingBase entity) {\n if (entity == KyroClient.mc.thePlayer || !AntiBot.isValidEntity((Entity)entity) || (!this.invisibles.isEnabled() && entity.isInvisible()) || entity instanceof EntityArmorStand || (!KyroClient.mc.thePlayer.canEntityBeSeen((Entity)entity) && !this.walls.isEnabled()) || entity.getHealth() <= 0.0f || entity.getDistanceToEntity((Entity)KyroClient.mc.thePlayer) > ((Aura.target != null && Aura.target != entity) ? this.range.getValue() : Math.max(this.rotationRange.getValue(), this.range.getValue())) || RotationUtils.getRotationDifference(RotationUtils.getRotations(entity), RotationUtils.getPlayerRotation()) > this.fov.getValue()) {\n return false;\n }\n String name = ChatFormatting.stripFormatting(entity.getName());\n if (name != null && PlayerUtil.isOnSkyBlock() && namesOnly.isEnabled() && entity instanceof EntityPlayer)\n {\n Matcher matcher = pattern.matcher(ChatFormatting.stripFormatting(name));\n\n EntityPlayer player = (EntityPlayer) entity;\n\n if (matcher.find())\n {\n return false;\n }\n\n return true;\n }\n if (this.namesOnly.isEnabled()) {\n final boolean flag = Aura.names.contains(ChatFormatting.stripFormatting(entity.getName()));\n if (this.namesonlyMode.is(\"Enemies\") || flag) {\n return this.namesonlyMode.is(\"Enemies\") && flag;\n }\n }\n return ((!(entity instanceof EntityMob) && !(entity instanceof EntityAmbientCreature) && !(entity instanceof EntityWaterMob) && !(entity instanceof EntityAnimal) && !(entity instanceof EntitySlime)) || this.mobs.isEnabled()) && (!(entity instanceof EntityPlayer) || ((!EntityUtils.isTeam(entity) || !this.teams.isEnabled()) && this.players.isEnabled())) && !(entity instanceof EntityVillager);\n }\n\n private double getRotationRange() {\n return Math.max(this.rotationRange.getValue(), this.range.getValue());\n }\n\n private void startBlocking() {\n PacketUtils.sendPacket((Packet<?>)new C08PacketPlayerBlockPlacement(KyroClient.mc.thePlayer.getHeldItem()));\n this.isBlocking = true;\n }\n\n private void stopBlocking() {\n if (this.isBlocking) {\n KyroClient.mc.getNetHandler().getNetworkManager().sendPacket((Packet)new C07PacketPlayerDigging(C07PacketPlayerDigging.Action.RELEASE_USE_ITEM, BlockPos.ORIGIN, EnumFacing.DOWN));\n this.isBlocking = false;\n }\n }\n\n @SubscribeEvent\n public void onWorldLoad(final WorldEvent.Load event) {\n if (this.isToggled() && this.toggleOnLoad.isEnabled()) {\n this.toggle();\n }\n }\n\n static {\n Aura.names = new ArrayList<String>();\n DISABLE = new MilliTimer();\n }\n}" }, { "identifier": "ServerRotations", "path": "Client/src/main/java/me/kyroclient/modules/player/ServerRotations.java", "snippet": "public class ServerRotations extends Module\n{\n private static ServerRotations instance;\n public BooleanSetting onlyKillAura;\n\n public static ServerRotations getInstance() {\n return ServerRotations.instance;\n }\n\n public ServerRotations() {\n super(\"Server Rotations\", Category.RENDER);\n this.onlyKillAura = new BooleanSetting(\"Only aura rotations\", false);\n this.setToggled(true);\n this.addSettings(this.onlyKillAura);\n }\n\n static {\n ServerRotations.instance = new ServerRotations();\n }\n}" }, { "identifier": "PlayerUtil", "path": "Client/src/main/java/me/kyroclient/util/PlayerUtil.java", "snippet": "public class PlayerUtil {\n public static boolean lastGround = false;\n public static void swingItem()\n {\n KyroClient.mc.thePlayer.swingItem();\n }\n public static Method clickMouse;\n public static boolean onHypixel()\n {\n return KyroClient.mc.getCurrentServerData().serverIP.endsWith(\"hypixel.net\");\n }\n public static void click()\n {\n if (clickMouse != null)\n {\n try {\n clickMouse.invoke(KyroClient.mc);\n } catch (Exception e)\n {\n e.printStackTrace();\n }\n\n return;\n }\n try {\n try {\n clickMouse = Minecraft.class.getDeclaredMethod(\"func_147116_af\");\n }\n catch (NoSuchMethodException e2) {\n e2.printStackTrace();\n }\n clickMouse.setAccessible(true);\n clickMouse.invoke(Minecraft.getMinecraft(), new Object[0]);\n }\n catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n public static boolean isOnSkyBlock() {\n try {\n final ScoreObjective titleObjective = KyroClient.mc.thePlayer.getWorldScoreboard().getObjectiveInDisplaySlot(1);\n if (KyroClient.mc.thePlayer.getWorldScoreboard().getObjectiveInDisplaySlot(0) != null) {\n return ChatFormatting.stripFormatting(KyroClient.mc.thePlayer.getWorldScoreboard().getObjectiveInDisplaySlot(0).getDisplayName()).contains(\"SKYBLOCK\");\n }\n return ChatFormatting.stripFormatting(KyroClient.mc.thePlayer.getWorldScoreboard().getObjectiveInDisplaySlot(1).getDisplayName()).contains(\"SKYBLOCK\");\n }\n catch (Exception e) {\n return false;\n }\n }\n\n public static boolean isNPC(final Entity entity) {\n if (!(entity instanceof EntityOtherPlayerMP)) {\n return false;\n }\n final EntityLivingBase entityLivingBase = (EntityLivingBase)entity;\n return ChatFormatting.stripFormatting(entity.getDisplayName().getUnformattedText()).startsWith(\"[NPC]\") || (entity.getUniqueID().version() == 2 && entityLivingBase.getHealth() == 20.0f && entityLivingBase.getMaxHealth() == 20.0f);\n }\n\n public static void swapSlot(int i)\n {\n KyroClient.mc.thePlayer.inventory.currentItem = i;\n }\n}" } ]
import me.kyroclient.KyroClient; import me.kyroclient.events.KeyboardEvent; import me.kyroclient.events.LeftClickEvent; import me.kyroclient.events.PostGuiOpenEvent; import me.kyroclient.events.RightClickEvent; import me.kyroclient.modules.combat.Aura; import me.kyroclient.modules.player.ServerRotations; import me.kyroclient.util.PlayerUtil; import net.minecraft.block.material.Material; import net.minecraft.client.Minecraft; import net.minecraft.client.entity.EntityPlayerSP; import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.multiplayer.PlayerControllerMP; import net.minecraft.client.multiplayer.WorldClient; import net.minecraft.client.settings.GameSettings; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.network.play.client.C07PacketPlayerDigging; import net.minecraft.util.BlockPos; import net.minecraft.util.MovingObjectPosition; import net.minecraftforge.common.MinecraftForge; import org.lwjgl.input.Keyboard; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
8,858
package me.kyroclient.mixins; @Mixin(Minecraft.class) public class MixinMinecraft { @Shadow public EntityPlayerSP thePlayer; @Shadow public GuiScreen currentScreen; @Shadow public GameSettings gameSettings; @Shadow public boolean inGameHasFocus; @Shadow public MovingObjectPosition objectMouseOver; @Shadow private Entity renderViewEntity; @Shadow public PlayerControllerMP playerController; @Shadow public WorldClient theWorld; @Shadow private int leftClickCounter; @Shadow private int rightClickDelayTimer; @Inject(method = "startGame", at = @At("HEAD")) public void startGame(CallbackInfo ci) { KyroClient.init(); } @Inject(method = { "runTick" }, at = { @At(value = "INVOKE", target = "Lnet/minecraft/client/Minecraft;dispatchKeypresses()V") }) public void keyPresses(final CallbackInfo ci) { final int k = (Keyboard.getEventKey() == 0) ? (Keyboard.getEventCharacter() + '\u0100') : Keyboard.getEventKey(); final char aChar = Keyboard.getEventCharacter(); if (Keyboard.getEventKeyState()) { if (MinecraftForge.EVENT_BUS.post(new KeyboardEvent(k, aChar))) { return; } if (KyroClient.mc.currentScreen == null) { KyroClient.handleKey(k); } } } @Inject(method = "sendClickBlockToController", at = @At("RETURN")) public void sendClick(CallbackInfo ci) { final boolean click = this.currentScreen == null && gameSettings.keyBindAttack.isKeyDown() && this.inGameHasFocus; if (KyroClient.cropNuker.isToggled() && click && this.objectMouseOver != null && this.objectMouseOver.typeOfHit == MovingObjectPosition.MovingObjectType.BLOCK) { int type = KyroClient.cropNuker.nukerMode.getIndex(); if (type == 0) return; try { int count = KyroClient.cropNuker.roll(); for (int i = 0; i < count; i++) { boolean b = blockNuker(); if (!b) break; } } catch (Exception ex) { ex.printStackTrace(); } } } @Inject(method = { "displayGuiScreen" }, at = { @At("RETURN") }) public void onGuiOpen(final GuiScreen i, final CallbackInfo ci) { MinecraftForge.EVENT_BUS.post(new PostGuiOpenEvent(i)); } @Inject(method = "clickMouse", at = @At("HEAD"), cancellable = true) public void clickMouse(CallbackInfo ci) { if (MinecraftForge.EVENT_BUS.post(new LeftClickEvent())) { ci.cancel(); } if (KyroClient.delays.isToggled()) { this.leftClickCounter = (int) KyroClient.delays.hitDelay.getValue(); } } @Inject(method = { "getRenderViewEntity" }, at = { @At("HEAD") }) public void getRenderViewEntity(final CallbackInfoReturnable<Entity> cir) { if (!ServerRotations.getInstance().isToggled() || this.renderViewEntity == null || this.renderViewEntity != KyroClient.mc.thePlayer) { return; } if (!ServerRotations.getInstance().onlyKillAura.isEnabled() || Aura.target != null) { ((EntityLivingBase)this.renderViewEntity).rotationYawHead = ((PlayerSPAccessor)this.renderViewEntity).getLastReportedYaw(); ((EntityLivingBase)this.renderViewEntity).renderYawOffset = ((PlayerSPAccessor)this.renderViewEntity).getLastReportedYaw(); } } @Inject(method = "rightClickMouse", at = @At("HEAD"), cancellable = true) public void rightClick(CallbackInfo ci) {
package me.kyroclient.mixins; @Mixin(Minecraft.class) public class MixinMinecraft { @Shadow public EntityPlayerSP thePlayer; @Shadow public GuiScreen currentScreen; @Shadow public GameSettings gameSettings; @Shadow public boolean inGameHasFocus; @Shadow public MovingObjectPosition objectMouseOver; @Shadow private Entity renderViewEntity; @Shadow public PlayerControllerMP playerController; @Shadow public WorldClient theWorld; @Shadow private int leftClickCounter; @Shadow private int rightClickDelayTimer; @Inject(method = "startGame", at = @At("HEAD")) public void startGame(CallbackInfo ci) { KyroClient.init(); } @Inject(method = { "runTick" }, at = { @At(value = "INVOKE", target = "Lnet/minecraft/client/Minecraft;dispatchKeypresses()V") }) public void keyPresses(final CallbackInfo ci) { final int k = (Keyboard.getEventKey() == 0) ? (Keyboard.getEventCharacter() + '\u0100') : Keyboard.getEventKey(); final char aChar = Keyboard.getEventCharacter(); if (Keyboard.getEventKeyState()) { if (MinecraftForge.EVENT_BUS.post(new KeyboardEvent(k, aChar))) { return; } if (KyroClient.mc.currentScreen == null) { KyroClient.handleKey(k); } } } @Inject(method = "sendClickBlockToController", at = @At("RETURN")) public void sendClick(CallbackInfo ci) { final boolean click = this.currentScreen == null && gameSettings.keyBindAttack.isKeyDown() && this.inGameHasFocus; if (KyroClient.cropNuker.isToggled() && click && this.objectMouseOver != null && this.objectMouseOver.typeOfHit == MovingObjectPosition.MovingObjectType.BLOCK) { int type = KyroClient.cropNuker.nukerMode.getIndex(); if (type == 0) return; try { int count = KyroClient.cropNuker.roll(); for (int i = 0; i < count; i++) { boolean b = blockNuker(); if (!b) break; } } catch (Exception ex) { ex.printStackTrace(); } } } @Inject(method = { "displayGuiScreen" }, at = { @At("RETURN") }) public void onGuiOpen(final GuiScreen i, final CallbackInfo ci) { MinecraftForge.EVENT_BUS.post(new PostGuiOpenEvent(i)); } @Inject(method = "clickMouse", at = @At("HEAD"), cancellable = true) public void clickMouse(CallbackInfo ci) { if (MinecraftForge.EVENT_BUS.post(new LeftClickEvent())) { ci.cancel(); } if (KyroClient.delays.isToggled()) { this.leftClickCounter = (int) KyroClient.delays.hitDelay.getValue(); } } @Inject(method = { "getRenderViewEntity" }, at = { @At("HEAD") }) public void getRenderViewEntity(final CallbackInfoReturnable<Entity> cir) { if (!ServerRotations.getInstance().isToggled() || this.renderViewEntity == null || this.renderViewEntity != KyroClient.mc.thePlayer) { return; } if (!ServerRotations.getInstance().onlyKillAura.isEnabled() || Aura.target != null) { ((EntityLivingBase)this.renderViewEntity).rotationYawHead = ((PlayerSPAccessor)this.renderViewEntity).getLastReportedYaw(); ((EntityLivingBase)this.renderViewEntity).renderYawOffset = ((PlayerSPAccessor)this.renderViewEntity).getLastReportedYaw(); } } @Inject(method = "rightClickMouse", at = @At("HEAD"), cancellable = true) public void rightClick(CallbackInfo ci) {
if (MinecraftForge.EVENT_BUS.post(new RightClickEvent()))
4
2023-10-15 16:24:51+00:00
12k
AstroDev2023/2023-studio-1-but-better
source/core/src/test/com/csse3200/game/areas/terrain/TerrainCropTileFactoryTest.java
[ { "identifier": "Entity", "path": "source/core/src/main/com/csse3200/game/entities/Entity.java", "snippet": "public class Entity implements Json.Serializable {\n\tprivate static final Logger logger = LoggerFactory.getLogger(Entity.class);\n\tprivate static int nextId = 0;\n\tprivate static final String EVT_NAME_POS = \"setPosition\";\n\tprivate static final String COMPONENTS_STRING = \"components\";\n\tprivate final int id;\n\tprivate EntityType type;\n\tprivate final IntMap<Component> components;\n\tprivate final EventHandler eventHandler;\n\tprivate boolean enabled = true;\n\tprivate boolean created = false;\n\tprivate Vector2 position = Vector2.Zero.cpy();\n\tprivate Vector2 scale = new Vector2(1, 1);\n\tprivate Array<Component> createdComponents;\n\n\tpublic Entity() {\n\t\tthis.type = EntityType.DUMMY;\n\t\tid = nextId;\n\t\tnextId++;\n\n\t\tcomponents = new IntMap<>(4);\n\t\teventHandler = new EventHandler();\n\t}\n\n\tpublic Entity(EntityType type) {\n\t\tthis.type = type;\n\t\tid = nextId;\n\t\tnextId++;\n\n\t\tcomponents = new IntMap<>(4);\n\t\teventHandler = new EventHandler();\n\t}\n\n\t/**\n\t * Enable or disable an entity. Disabled entities do not run update() or\n\t * earlyUpdate() on their\n\t * components, but can still be disposed.\n\t *\n\t * @param enabled true for enable, false for disable.\n\t */\n\tpublic void setEnabled(boolean enabled) {\n\t\tlogger.debug(\"Setting enabled={} on entity {}\", enabled, this);\n\t\tthis.enabled = enabled;\n\t}\n\n\t/**\n\t * Get the entity's game position.\n\t *\n\t * @return position\n\t */\n\tpublic Vector2 getPosition() {\n\t\treturn position.cpy(); // Cpy gives us pass-by-value to prevent bugs\n\t}\n\n\t/**\n\t * Set the entity's game position.\n\t *\n\t * @param position new position.\n\t */\n\tpublic void setPosition(Vector2 position) {\n\t\tthis.position = position.cpy();\n\t\tgetEvents().trigger(EVT_NAME_POS, position.cpy());\n\t}\n\n\tpublic void setCenterPosition(Vector2 position) {\n\t\tthis.position = position.cpy().mulAdd(getScale(), -0.5f);\n\t}\n\n\t/**\n\t * Set the entity's game position.\n\t *\n\t * @param x new x position\n\t * @param y new y position\n\t */\n\tpublic void setPosition(float x, float y) {\n\t\tthis.position.x = x;\n\t\tthis.position.y = y;\n\t\tgetEvents().trigger(EVT_NAME_POS, position.cpy());\n\t}\n\n\t/**\n\t * Set the entity's game position and optionally notifies listeners.\n\t *\n\t * @param position new position.\n\t * @param notify true to notify (default), false otherwise\n\t */\n\tpublic void setPosition(Vector2 position, boolean notify) {\n\t\tthis.position = position;\n\t\tif (notify) {\n\t\t\tgetEvents().trigger(EVT_NAME_POS, position);\n\t\t}\n\t}\n\n\t/**\n\t * Get the entity's scale. Used for rendering and physics bounding box\n\t * calculations.\n\t *\n\t * @return Scale in x and y directions. 1 = 1 metre.\n\t */\n\tpublic Vector2 getScale() {\n\t\treturn scale.cpy(); // Cpy gives us pass-by-value to prevent bugs\n\t}\n\n\t/**\n\t * Set the entity's scale.\n\t *\n\t * @param scale new scale in metres\n\t */\n\tpublic void setScale(Vector2 scale) {\n\t\tthis.scale = scale.cpy();\n\t}\n\n\t/**\n\t * Set the entity's scale.\n\t *\n\t * @param x width in metres\n\t * @param y height in metres\n\t */\n\tpublic void setScale(float x, float y) {\n\t\tthis.scale.x = x;\n\t\tthis.scale.y = y;\n\t}\n\n\t/**\n\t * Set the entity's width and scale the height to maintain aspect ratio.\n\t *\n\t * @param x width in metres\n\t */\n\tpublic void scaleWidth(float x) {\n\t\tthis.scale.y = this.scale.y / this.scale.x * x;\n\t\tthis.scale.x = x;\n\t}\n\n\t/**\n\t * Set the entity's height and scale the width to maintain aspect ratio.\n\t *\n\t * @param y height in metres\n\t */\n\tpublic void scaleHeight(float y) {\n\t\tthis.scale.x = this.scale.x / this.scale.y * y;\n\t\tthis.scale.y = y;\n\t}\n\n\t/**\n\t * Get the entity's center position\n\t *\n\t * @return center position\n\t */\n\tpublic Vector2 getCenterPosition() {\n\t\treturn getPosition().mulAdd(getScale(), 0.5f);\n\t}\n\n\t/**\n\t * Get a component of type T on the entity.\n\t *\n\t * @param type The component class, e.g. RenderComponent.class\n\t * @param <T> The component type, e.g. RenderComponent\n\t * @return The entity component, or null if nonexistent.\n\t */\n\t@SuppressWarnings(\"unchecked\")\n\tpublic <T extends Component> T getComponent(Class<T> type) {\n\t\tComponentType componentType = ComponentType.getFrom(type);\n\t\treturn (T) components.get(componentType.getId());\n\t}\n\n\t/**\n\t * Add a component to the entity. Can only be called before the entity is\n\t * registered in the world.\n\t *\n\t * @param component The component to add. Only one component of a type can be\n\t * added to an entity.\n\t * @return Itself\n\t */\n\tpublic Entity addComponent(Component component) {\n\t\tif (created) {\n\t\t\tlogger.error(\n\t\t\t\t\t\"Adding {} to {} after creation is not supported and will be ignored\", component, this);\n\t\t\treturn this;\n\t\t}\n\t\tComponentType componentType = ComponentType.getFrom(component.getClass());\n\t\tif (components.containsKey(componentType.getId())) {\n\t\t\tlogger.error(\n\t\t\t\t\t\"Attempted to add multiple components of class {} to {}. Only one component of a class \"\n\t\t\t\t\t\t\t+ \"can be added to an entity, this will be ignored.\",\n\t\t\t\t\tcomponent,\n\t\t\t\t\tthis);\n\t\t\treturn this;\n\t\t}\n\t\tcomponents.put(componentType.getId(), component);\n\t\tcomponent.setEntity(this);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Dispose of the entity. This will dispose of all components on this entity.\n\t */\n\tpublic void dispose() {\n\t\tfor (Component component : createdComponents) {\n\t\t\tcomponent.dispose();\n\t\t}\n\t\tServiceLocator.getEntityService().unregister(this);\n\t}\n\n\t/**\n\t * Create the entity and start running. This is called when the entity is\n\t * registered in the world,\n\t * and should not be called manually.\n\t */\n\tpublic void create() {\n\t\tif (created) {\n\t\t\tlogger.error(\n\t\t\t\t\t\"{} was created twice. Entity should only be registered with the entity service once.\",\n\t\t\t\t\tthis);\n\t\t\treturn;\n\t\t}\n\t\tcreatedComponents = components.values().toArray();\n\t\tfor (Component component : createdComponents) {\n\t\t\tcomponent.create();\n\t\t}\n\t\tcreated = true;\n\t}\n\n\t/**\n\t * Perform an early update on all components. This is called by the entity\n\t * service and should not\n\t * be called manually.\n\t */\n\tpublic void earlyUpdate() {\n\t\tif (!enabled) {\n\t\t\treturn;\n\t\t}\n\t\tfor (Component component : createdComponents) {\n\t\t\tcomponent.triggerEarlyUpdate();\n\t\t}\n\t}\n\n\t/**\n\t * Perform an update on all components. This is called by the entity service and\n\t * should not be\n\t * called manually.\n\t */\n\tpublic void update() {\n\t\tif (!enabled) {\n\t\t\treturn;\n\t\t}\n\t\tgetEvents().update();\n\t\tfor (Component component : createdComponents) {\n\t\t\tcomponent.triggerUpdate();\n\t\t}\n\t}\n\n\tpublic void togglePauseAnimations(boolean pausePlayer) {\n\t\tif (!pausePlayer) {\n\t\t\tfor (Component component : createdComponents) {\n\t\t\t\tif (component instanceof KeyboardPlayerInputComponent ||\n\t\t\t\t\t\tcomponent instanceof PlayerAnimationController ||\n\t\t\t\t\t\tcomponent instanceof AnimalAnimationController ||\n\t\t\t\t\t\tcomponent instanceof GhostAnimationController ||\n\t\t\t\t\t\tcomponent instanceof TamableComponent ||\n\t\t\t\t\t\tcomponent instanceof ItemPickupComponent) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor (Component component : createdComponents) {\n\t\t\tif (component instanceof PlayerAnimationController) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tfor (Component component : createdComponents) {\n\t\t\tif (component instanceof AnimationRenderComponent animationRenderComponent) {\n\t\t\t\tanimationRenderComponent.togglePauseAnimation();\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * This entity's unique ID. Used for equality checks\n\t *\n\t * @return unique ID\n\t */\n\tpublic int getId() {\n\t\treturn id;\n\t}\n\n\t/**\n\t * Get the event handler attached to this entity. Can be used to trigger events\n\t * from an attached\n\t * component, or listen to events from a component.\n\t *\n\t * @return entity's event handler\n\t */\n\tpublic EventHandler getEvents() {\n\t\treturn eventHandler;\n\t}\n\n\t@Override\n\tpublic boolean equals(Object obj) {\n\t\treturn (obj instanceof Entity entity) && entity.getId() == this.getId();\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn super.hashCode();\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn String.format(\"Entity{id=%d} {type=%s}\", id, type == null ? \"none\" : type.toString());\n\t}\n\n\t/**\n\t * Writes to the json info about entities.\n\t * Writes the entities x,y coordinates\n\t * ALso loops through the entities associated components and writes information\n\t * to the json about\n\t * the component.\n\t * note each component should have a override write function\n\t *\n\t * @param json which is a valid Json that is written to\n\t */\n\tpublic void write(Json json) {\n\t\t// Should be gone but incase double check\n\t\tif (getType() == EntityType.ITEM || getType() == null) {\n\t\t\treturn;\n\t\t}\n\n\t\tjson.writeValue(\"Entity\", getType());\n\t\tfloat posX = position.x;\n\t\tfloat posY = position.y;\n\t\tjson.writeValue(\"x\", posX);\n\t\tjson.writeValue(\"y\", posY);\n\t\tjson.writeObjectStart(COMPONENTS_STRING);\n\t\tif (createdComponents == null) {\n\t\t\tjson.writeObjectEnd();\n\t\t\treturn;\n\t\t}\n\t\tfor (Component c : createdComponents) {\n\t\t\tc.write(json);\n\t\t}\n\t\tjson.writeObjectEnd();\n\t}\n\n\t/**\n\t * Writes the item to the json file\n\t *\n\t * @param json which is a valid Json that is written to\n\t */\n\tpublic void writeItem(Json json) {\n\t\tjson.writeValue(\"name\", this.getComponent(ItemComponent.class).getItemName());\n\t\tif (createdComponents != null) {\n\t\t\tjson.writeObjectStart(COMPONENTS_STRING);\n\t\t\tfor (Component c : createdComponents) {\n\t\t\t\tc.write(json);\n\t\t\t}\n\t\t\tjson.writeObjectEnd();\n\t\t}\n\t}\n\n\t/**\n\t * Reads the item entity from the json file\n\t *\n\t * @param json which is a valid Json that is read from\n\t * @param jsonMap which is a valid JsonValue that is read from\n\t */\n\tpublic void readItem(Json json, JsonValue jsonMap) {\n\t\tif (createdComponents != null) {\n\t\t\tfor (Component c : createdComponents) {\n\t\t\t\tc.read(json, jsonMap);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Reads the json file and creates the entities based on the information in the\n\t * json file\n\t *\n\t * @param json which is a valid Json that is read from\n\t * @param jsonMap which is a valid JsonValue that is read from\n\t */\n\tpublic void read(Json json, JsonValue jsonMap) {\n\t\t// This method creates an Entity but will not use that Entity for anything that\n\t\t// is being remade as\n\t\t// it makes the code duplication extremely high as it is a whole factory here\n\n\t\t// Saves the position\n\t\tposition = new Vector2(jsonMap.getFloat(\"x\"), jsonMap.getFloat(\"y\"));\n\n\t\t// Gets the type of Entity\n\t\tString value = jsonMap.getString(\"Entity\");\n\t\ttry {\n\t\t\ttype = EntityType.valueOf(value);\n\t\t} catch (IllegalArgumentException e) {\n\t\t\ttype = null;\n\t\t\treturn;\n\t\t}\n\n\t\tswitch (type) {\n\t\t\tcase TRACTOR:\n\t\t\t\treadTractor(jsonMap);\n\t\t\t\tbreak;\n\t\t\tcase TILE:\n\t\t\t\treadTile(json, jsonMap);\n\t\t\t\tbreak;\n\t\t\tcase SHIP_PART_TILE:\n\t\t\t\treadShipPartTile(json, jsonMap);\n\t\t\t\tbreak;\n\t\t\tcase SHIP_DEBRIS:\n\t\t\t\treadShipDebris();\n\t\t\t\tbreak;\n\t\t\tcase SHIP:\n\t\t\t\treadShip(json, jsonMap);\n\t\t\t\tbreak;\n\t\t\tcase PLAYER:\n\t\t\t\treadPlayer(json, jsonMap);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tif (FactoryService.getNpcFactories().containsKey(type)) {\n\t\t\t\t\t// Makes a new NPC\n\t\t\t\t\tEntity npc = FactoryService.getNpcFactories().get(type).get();\n\t\t\t\t\tif (npc.getComponent(TamableComponent.class) != null) {\n\t\t\t\t\t\tnpc.getComponent(TamableComponent.class).read(json, jsonMap.get(COMPONENTS_STRING));\n\t\t\t\t\t}\n\t\t\t\t\tif (npc.getComponent(CombatStatsComponent.class) != null) {\n\t\t\t\t\t\tnpc.getComponent(CombatStatsComponent.class).read(json, jsonMap.get(COMPONENTS_STRING));\n\t\t\t\t\t}\n\t\t\t\t\tServiceLocator.getGameArea().spawnEntity(npc);\n\t\t\t\t\tnpc.setPosition(position);\n\t\t\t\t} else if (FactoryService.getPlaceableFactories().containsKey(type.toString())) {\n\t\t\t\t\t// Makes a new Placeable\n\t\t\t\t\tEntity placeable = FactoryService.getPlaceableFactories().get(type.toString()).get();\n\t\t\t\t\tplaceable.setPosition(position);\n\t\t\t\t\tif (placeable.getType() == EntityType.CHEST) {\n\t\t\t\t\t\tplaceable.getComponent(InventoryComponent.class).read(json, jsonMap.get(COMPONENTS_STRING));\n\t\t\t\t\t}\n\t\t\t\t\tServiceLocator.getGameArea().getMap().getTile(position).setOccupant(placeable);\n\t\t\t\t\tServiceLocator.getGameArea().spawnEntity(placeable);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\tprivate void readPlayer(Json json, JsonValue jsonMap) {\n\t\t// Does not make a new player, instead just updates the current one\n\t\tInventoryComponent inventoryComponent = new InventoryComponent();\n\t\tJsonValue playerComponents = jsonMap.get(COMPONENTS_STRING);\n\t\tinventoryComponent.read(json, playerComponents);\n\t\tthis.addComponent(inventoryComponent);\n\n\t\tCombatStatsComponent combatStats = new CombatStatsComponent(0, 0);\n\t\tcombatStats.read(json, playerComponents);\n\t\tthis.addComponent(combatStats);\n\n\t\tHungerComponent hungerComponent = new HungerComponent(0);\n\t\thungerComponent.read(json, playerComponents);\n\t\tthis.addComponent(hungerComponent);\n\t}\n\n\tprivate void readShip(Json json, JsonValue jsonMap) {\n\t\tEntity ship = ShipFactory.createShip();\n\n\t\tServiceLocator.getGameArea().spawnEntity(ship);\n\n\t\tShipAnimationController shipAnimationController = ship.getComponent(ShipAnimationController.class);\n\t\tshipAnimationController.read(json, jsonMap.get(COMPONENTS_STRING).get(ShipAnimationController.class.getSimpleName()));\n\n\t\tShipProgressComponent progressComponent = ship.getComponent(ShipProgressComponent.class);\n\t\tprogressComponent.read(json, jsonMap.get(COMPONENTS_STRING).get(ShipProgressComponent.class.getSimpleName()));\n\n\t\tShipTimeSkipComponent shipTimeSkipComponent = ship.getComponent(ShipTimeSkipComponent.class);\n\t\tJsonValue shipTimeSkipComponentJson = jsonMap.get(COMPONENTS_STRING).get(ShipTimeSkipComponent.class.getSimpleName());\n\t\tshipTimeSkipComponent.read(json, shipTimeSkipComponentJson);\n\n\t\tShipLightComponent shipLightComponent = ship.getComponent(ShipLightComponent.class);\n\t\tJsonValue shipLightComponentJson = jsonMap.get(COMPONENTS_STRING)\n\t\t\t\t.get(ShipLightComponent.class.getSimpleName());\n\t\tshipLightComponent.read(json, shipLightComponentJson);\n\n\t\tShipDisplay shipDisplay = ship.getComponent(ShipDisplay.class);\n\t\tJsonValue shipDisplayJson = jsonMap.get(COMPONENTS_STRING)\n\t\t\t\t.get(ShipDisplay.class.getSimpleName());\n\t\tshipDisplay.read(json, shipDisplayJson);\n\n\t\tship.setPosition(position);\n\t}\n\n\tprivate void readShipDebris() {\n\t\tEntity shipDebris = ShipDebrisFactory.createShipDebris();\n\t\tServiceLocator.getGameArea().spawnEntity(shipDebris);\n\t\tshipDebris.setPosition(position);\n\n\t\tTerrainTile debrisTerrainTile = ServiceLocator.getGameArea().getMap().getTile(position);\n\t\tdebrisTerrainTile.setOccupant(shipDebris);\n\t\tdebrisTerrainTile.setOccupied();\n\t}\n\n\tprivate void readShipPartTile(Json json, JsonValue jsonMap) {\n\t\tEntity partTile = ShipPartTileFactory.createShipPartTile(position);\n\t\tServiceLocator.getGameArea().spawnEntity(partTile);\n\t\tpartTile.setPosition(position);\n\n\t\tTerrainTile partTerrainTile = ServiceLocator.getGameArea().getMap().getTile(position);\n\t\tif (partTerrainTile.isOccupied() && partTerrainTile.getOccupant().getType() == EntityType.SHIP_DEBRIS) {\n\t\t\t// remove the ship debris that is occupying the terrain tile, since it will\n\t\t\t// be recreated by the ShipPartTileComponent\n\t\t\tEntity unneededShipDebris = partTerrainTile.getOccupant();\n\t\t\tunneededShipDebris.dispose();\n\t\t\tpartTerrainTile.removeOccupant();\n\n\t\t\tpartTile.getComponent(ShipPartTileComponent.class).read(json, jsonMap);\n\n\t\t\tpartTerrainTile.setOccupant(partTile);\n\t\t\tpartTerrainTile.setOccupied();\n\t\t}\n\t}\n\n\tprivate void readTile(Json json, JsonValue jsonMap) {\n\t\tEntity tile = TerrainCropTileFactory.createTerrainEntity(position);\n\t\ttile.getComponent(CropTileComponent.class).read(json, jsonMap);\n\t\tServiceLocator.getGameArea().spawnEntity(tile);\n\t\ttile.setPosition(position);\n\t\tTerrainTile terrainTile = ServiceLocator.getGameArea().getMap().getTile(tile.getPosition());\n\t\tterrainTile.setOccupant(tile);\n\t}\n\n\t/**\n\t * Gets the type of entity\n\t *\n\t * @return the type of entity from EntityType enum\n\t */\n\tpublic EntityType getType() {\n\t\treturn type;\n\t}\n\n\tpublic void readTractor(JsonValue jsonMap) {\n\t\t// Make a new tractor\n\t\tEntity tractor = TractorFactory.createTractor();\n\t\tJsonValue tractorActions = jsonMap.get(COMPONENTS_STRING).get(\"TractorActions\");\n\t\ttractor.getComponent(TractorActions.class).setMuted(tractorActions.getBoolean(\"isMuted\"));\n\t\tJsonValue lightJsonMap = jsonMap.get(COMPONENTS_STRING).get(\"ConeLightComponent\");\n\t\tif (lightJsonMap.getBoolean(\"isActive\")) {\n\t\t\ttractor.getComponent(ConeLightComponent.class).toggleLight();\n\t\t}\n\t\tServiceLocator.getGameArea().setTractor(tractor);\n\t\ttractor.setPosition(position);\n\t\tServiceLocator.getGameArea().spawnEntity(tractor);\n\t}\n}" }, { "identifier": "EntityService", "path": "source/core/src/main/com/csse3200/game/entities/EntityService.java", "snippet": "public class EntityService {\n\tprivate static final Logger logger = LoggerFactory.getLogger(EntityService.class);\n\tprivate static final int INITIAL_CAPACITY = 16;\n\tprivate final Array<Entity> entities = new Array<>(false, INITIAL_CAPACITY);\n\tprivate static boolean paused = false;\n\tprivate boolean pauseStartFlag = false;\n\tprivate boolean pauseEndFlag = false;\n\n\t/**\n\t * Register a new entity with the entity service. The entity will be created and start updating.\n\t *\n\t * @param entity new entity.\n\t */\n\tpublic void register(Entity entity) {\n\t\tlogger.debug(\"Registering {} in entity service\", entity);\n\t\tentities.add(entity);\n\t\tentity.create();\n\t}\n\n\t/**\n\t * Unregister an entity with the entity service. The entity will be removed and stop updating.\n\t *\n\t * @param entity entity to be removed.\n\t */\n\tpublic void unregister(Entity entity) {\n\t\tlogger.debug(\"Unregistering {} in entity service\", entity);\n\t\tentities.removeValue(entity, true);\n\t}\n\n\t/**\n\t * Update all registered entities. Should only be called from the main game loop.\n\t */\n\tpublic void update() {\n\t\tfor (Entity entity : entities) {\n\t\t\tif (!paused) {\n\t\t\t\tif (pauseEndFlag) {\n\t\t\t\t\tentity.togglePauseAnimations(true);\n\t\t\t\t}\n\t\t\t\tentity.earlyUpdate();\n\t\t\t\tentity.update();\n\t\t\t}\n\t\t\tif (pauseStartFlag) {\n\t\t\t\tentity.togglePauseAnimations(true);\n\t\t\t}\n\t\t}\n\t\tpauseStartFlag = false;\n\t\tpauseEndFlag = false;\n\n\t}\n\n\tpublic void pauseAndResume() {\n\t\tpaused = !paused;\n\t\tif (paused) {\n\t\t\tpauseStartFlag = true;\n\t\t} else {\n\t\t\tpauseEndFlag = true;\n\t\t}\n\t}\n\n\tpublic void pauseGame() {\n\t\tpaused = true;\n\t\tpauseStartFlag = true;\n\t}\n\n\tpublic void pauseGame2() {\n\t\tpaused = true;\n\t}\n\n\tpublic void unpauseGame() {\n\t\tpaused = false;\n\t\tpauseEndFlag = true;\n\t}\n\n\tpublic static boolean pauseCheck() {\n\t\treturn paused;\n\t}\n\n\t/**\n\t * Dispose all entities.\n\t */\n\tpublic void dispose() {\n\t\tfor (Entity entity : entities) {\n\t\t\tentity.dispose();\n\t\t}\n\t}\n\n\t/**\n\t * Get number of entities registered\n\t *\n\t * @return number of entities\n\t */\n\tpublic int getSize() {\n\t\treturn entities.size;\n\t}\n\n\t/**\n\t * Returns Array of entities of all entities in game\n\t *\n\t * @return Array of entities in game\n\t */\n\tpublic Array<Entity> getEntities() {\n\t\treturn entities;\n\t}\n}" }, { "identifier": "GameExtension", "path": "source/core/src/test/com/csse3200/game/extensions/GameExtension.java", "snippet": "public class GameExtension implements AfterEachCallback, BeforeAllCallback {\n\tprivate Application game;\n\n\t@Override\n\tpublic void beforeAll(ExtensionContext context) {\n\t\t// 'Headless' back-end, so no rendering happens\n\t\tgame = new HeadlessApplication(new ApplicationAdapter() {\n\t\t});\n\n\t\t// Mock any calls to OpenGL\n\t\tGdx.gl20 = Mockito.mock(GL20.class);\n\t\tGdx.gl = Gdx.gl20;\n\t}\n\n\t@Override\n\tpublic void afterEach(ExtensionContext context) {\n\t\t// Clear the global state from the service locator\n\t\tServiceLocator.clear();\n\t}\n}" }, { "identifier": "PhysicsService", "path": "source/core/src/main/com/csse3200/game/physics/PhysicsService.java", "snippet": "public class PhysicsService {\n\tprivate final PhysicsEngine engine;\n\n\tpublic PhysicsService() {\n\t\tthis(new PhysicsEngine());\n\t}\n\n\tpublic PhysicsService(PhysicsEngine engine) {\n\t\tthis.engine = engine;\n\t}\n\n\tpublic PhysicsEngine getPhysics() {\n\t\treturn engine;\n\t}\n}" }, { "identifier": "RenderService", "path": "source/core/src/main/com/csse3200/game/rendering/RenderService.java", "snippet": "public class RenderService implements Disposable {\n\tprivate static final int INITIAL_LAYER_CAPACITY = 4;\n\tprivate static final int INITIAL_CAPACITY = 4;\n\tprivate Stage stage;\n\tprivate DebugRenderer debugRenderer;\n\n\t/**\n\t * Map from layer to list of renderables, allows us to render each layer in the correct order\n\t */\n\tprivate final SortedIntMap<Array<Renderable>> renderables =\n\t\t\tnew SortedIntMap<>(INITIAL_LAYER_CAPACITY);\n\n\t/**\n\t * Register a new renderable.\n\t *\n\t * @param renderable new renderable.\n\t */\n\tpublic void register(Renderable renderable) {\n\t\tint layerIndex = renderable.getLayer();\n\t\tif (!renderables.containsKey(layerIndex)) {\n\t\t\trenderables.put(layerIndex, new Array<>(INITIAL_CAPACITY));\n\t\t}\n\t\tArray<Renderable> layer = renderables.get(layerIndex);\n\t\tlayer.add(renderable);\n\t}\n\n\t/**\n\t * Unregister a renderable.\n\t *\n\t * @param renderable renderable to unregister.\n\t */\n\tpublic void unregister(Renderable renderable) {\n\t\tArray<Renderable> layer = renderables.get(renderable.getLayer());\n\t\tif (layer != null) {\n\t\t\tlayer.removeValue(renderable, true);\n\t\t}\n\t}\n\n\t/**\n\t * Trigger rendering on the given batch. This should be called only from the main renderer.\n\t *\n\t * @param batch batch to render to.\n\t */\n\tpublic void render(SpriteBatch batch) {\n\t\tfor (Array<Renderable> layer : renderables) {\n\t\t\t// Sort into rendering order\n\t\t\tlayer.sort();\n\n\t\t\tfor (Renderable renderable : layer) {\n\t\t\t\trenderable.render(batch);\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic void setStage(Stage stage) {\n\t\tthis.stage = stage;\n\t}\n\n\tpublic Stage getStage() {\n\t\treturn stage;\n\t}\n\n\tpublic void setDebug(DebugRenderer debugRenderer) {\n\t\tthis.debugRenderer = debugRenderer;\n\t}\n\n\tpublic DebugRenderer getDebug() {\n\t\treturn debugRenderer;\n\t}\n\n\t@Override\n\tpublic void dispose() {\n\t\trenderables.clear();\n\t}\n}" }, { "identifier": "ResourceService", "path": "source/core/src/main/com/csse3200/game/services/ResourceService.java", "snippet": "public class ResourceService implements Disposable {\n\n\tprivate static final Logger logger = LoggerFactory.getLogger(ResourceService.class);\n\tprivate final AssetManager assetManager;\n\n\tpublic ResourceService() {\n\t\tthis(new AssetManager());\n\t}\n\n\t/**\n\t * Initialise this ResourceService to use the provided AssetManager.\n\t *\n\t * @param assetManager AssetManager to use in this service.\n\t * @requires assetManager != null\n\t */\n\tpublic ResourceService(AssetManager assetManager) {\n\t\tthis.assetManager = assetManager;\n\t}\n\n\t/**\n\t * Load an asset from a file.\n\t *\n\t * @param filename Asset path\n\t * @param type Class to load into\n\t * @param <T> Type of class to load into\n\t * @return Instance of class loaded from path\n\t * @see AssetManager#get(String, Class)\n\t */\n\tpublic <T> T getAsset(String filename, Class<T> type) {\n\t\treturn assetManager.get(filename, type);\n\t}\n\n\t/**\n\t * Check if an asset has been loaded already\n\t *\n\t * @param resourceName path of the asset\n\t * @param type Class type of the asset\n\t * @param <T> Type of the asset\n\t * @return true if asset has been loaded, false otherwise\n\t * @see AssetManager#contains(String)\n\t */\n\tpublic <T> boolean containsAsset(String resourceName, Class<T> type) {\n\t\treturn assetManager.contains(resourceName, type);\n\t}\n\n\t/**\n\t * Returns the loading completion progress as a percentage.\n\t *\n\t * @return progress\n\t */\n\tpublic int getProgress() {\n\t\treturn (int) (assetManager.getProgress() * 100);\n\t}\n\n\t/**\n\t * Blocking call to load all assets.\n\t *\n\t * @see AssetManager#finishLoading()\n\t */\n\tpublic void loadAll() {\n\t\tlogger.debug(\"Loading all assets\");\n\t\ttry {\n\t\t\tassetManager.finishLoading();\n\t\t} catch (Exception e) {\n\t\t\tlogger.error(e.getMessage());\n\t\t}\n\t}\n\n\t/**\n\t * Loads assets for the specified duration in milliseconds.\n\t *\n\t * @param duration duration to load for\n\t * @return finished loading\n\t * @see AssetManager#update(int)\n\t */\n\tpublic boolean loadForMillis(int duration) {\n\t\tlogger.debug(\"Loading assets for {} ms\", duration);\n\t\ttry {\n\t\t\treturn assetManager.update(duration);\n\t\t} catch (Exception e) {\n\t\t\tlogger.error(e.getMessage());\n\t\t}\n\t\treturn assetManager.isFinished();\n\t}\n\n\t/**\n\t * Clears all loaded assets and assets in the preloading queue.\n\t *\n\t * @see AssetManager#clear()\n\t */\n\tpublic void clearAllAssets() {\n\t\tlogger.debug(\"Clearing all assets\");\n\t\tassetManager.clear();\n\t}\n\n\t/**\n\t * Loads a single asset into the asset manager.\n\t *\n\t * @param assetName asset name\n\t * @param type asset type\n\t * @param <T> type\n\t */\n\tprivate <T> void loadAsset(String assetName, Class<T> type) {\n\t\tlogger.debug(\"Loading {}: {}\", type.getSimpleName(), assetName);\n\t\ttry {\n\t\t\tassetManager.load(assetName, type);\n\t\t} catch (Exception e) {\n\t\t\tlogger.error(\"Could not load {}: {}\", type.getSimpleName(), assetName);\n\t\t}\n\t}\n\n\t/**\n\t * Loads multiple assets into the asset manager.\n\t *\n\t * @param assetNames list of asset names\n\t * @param type asset type\n\t * @param <T> type\n\t */\n\tprivate <T> void loadAssets(String[] assetNames, Class<T> type) {\n\t\tfor (String resource : assetNames) {\n\t\t\tloadAsset(resource, type);\n\t\t}\n\t}\n\n\t/**\n\t * Loads a list of texture assets into the asset manager.\n\t *\n\t * @param textureNames texture filenames\n\t */\n\tpublic void loadTextures(String[] textureNames) {\n\t\tloadAssets(textureNames, Texture.class);\n\t}\n\n\t/**\n\t * Loads a list of texture atlas assets into the asset manager.\n\t *\n\t * @param textureAtlasNames texture atlas filenames\n\t */\n\tpublic void loadTextureAtlases(String[] textureAtlasNames) {\n\t\tloadAssets(textureAtlasNames, TextureAtlas.class);\n\t}\n\n\t/**\n\t * Loads a list of sounds into the asset manager.\n\t *\n\t * @param soundNames sound filenames\n\t */\n\tpublic void loadSounds(String[] soundNames) {\n\t\tloadAssets(soundNames, Sound.class);\n\t}\n\n\t/**\n\t * Loads a list of music assets into the asset manager.\n\t *\n\t * @param musicNames music filenames\n\t */\n\tpublic void loadMusic(String[] musicNames) {\n\t\tloadAssets(musicNames, Music.class);\n\t}\n\n\t/**\n\t * Loads a list of particle effect assets into the asset manager\n\t *\n\t * @param particleNames particle effect filenames\n\t */\n\tpublic void loadParticleEffects(String[] particleNames) {\n\t\tloadAssets(particleNames, ParticleEffect.class);\n\t}\n\n\tpublic void loadSkins(String[] skinNames) {\n\t\tloadAssets(skinNames, Skin.class);\n\t}\n\n\t/**\n\t * Disposes of assets and all of their dependencies from the resource manager\n\t *\n\t * @param assetNames list of asset names to dispose of\n\t */\n\tpublic void unloadAssets(String[] assetNames) {\n\t\tfor (String assetName : assetNames) {\n\t\t\tlogger.debug(\"Unloading {}\", assetName);\n\t\t\ttry {\n\t\t\t\tassetManager.unload(assetName);\n\t\t\t} catch (Exception e) {\n\t\t\t\tlogger.error(\"Could not unload {}\", assetName);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Disposes of the resource service, clearing the asset manager which clears and disposes of all assets and clears\n\t * the preloading queue\n\t */\n\t@Override\n\tpublic void dispose() {\n\t\tassetManager.clear();\n\t}\n}" }, { "identifier": "ServiceLocator", "path": "source/core/src/main/com/csse3200/game/services/ServiceLocator.java", "snippet": "public class ServiceLocator {\n\tprivate static final Logger logger = LoggerFactory.getLogger(ServiceLocator.class);\n\tprivate static EntityService entityService;\n\tprivate static RenderService renderService;\n\tprivate static PhysicsService physicsService;\n\tprivate static InputService inputService;\n\tprivate static ResourceService resourceService;\n\tprivate static TimeService timeService;\n\tprivate static GameTime timeSource;\n\tprivate static GameArea gameArea;\n\tprivate static LightService lightService;\n\tprivate static GameAreaDisplay pauseMenuArea;\n\tprivate static GameAreaDisplay craftArea;\n\tprivate static GdxGame game;\n\tprivate static InventoryDisplayManager inventoryDisplayManager;\n\tprivate static CameraComponent cameraComponent;\n\tprivate static SaveLoadService saveLoadService;\n\tprivate static MissionManager missions;\n\tprivate static PlanetOxygenService planetOxygenService;\n\tprivate static SoundService soundService;\n\tprivate static UIService uiService;\n\n\tprivate static PlantCommandService plantCommandService;\n\tprivate static PlayerHungerService playerHungerService;\n\n\tprivate static PlayerMapService playerMapService;\n\n\tprivate static PlantInfoService plantInfoService;\n\tprivate static boolean cutSceneRunning; // true for running and false otherwise\n\n\tprivate static ParticleService particleService;\n\n\tpublic static PlantCommandService getPlantCommandService() {\n\t\treturn plantCommandService;\n\t}\n\n\tpublic static PlantInfoService getPlantInfoService() {\n\t\treturn plantInfoService;\n\t}\n\n\tpublic static boolean god = false;\n\n\tpublic static GameArea getGameArea() {\n\t\treturn gameArea;\n\t}\n\n\tpublic static CameraComponent getCameraComponent() {\n\t\treturn cameraComponent;\n\t}\n\n\tpublic static EntityService getEntityService() {\n\t\treturn entityService;\n\t}\n\n\tpublic static RenderService getRenderService() {\n\t\treturn renderService;\n\t}\n\n\tpublic static PhysicsService getPhysicsService() {\n\t\treturn physicsService;\n\t}\n\n\tpublic static InputService getInputService() {\n\t\treturn inputService;\n\t}\n\n\tpublic static ResourceService getResourceService() {\n\t\treturn resourceService;\n\t}\n\n\tpublic static GameTime getTimeSource() {\n\t\treturn timeSource;\n\t}\n\n\tpublic static TimeService getTimeService() {\n\t\treturn timeService;\n\t}\n\n\tpublic static LightService getLightService() {\n\t\treturn lightService;\n\t}\n\n\tpublic static MissionManager getMissionManager() {\n\t\treturn missions;\n\t}\n\n\tpublic static PlanetOxygenService getPlanetOxygenService() {\n\t\treturn planetOxygenService;\n\t}\n\n\tpublic static PlayerHungerService getPlayerHungerService() {\n\t\treturn playerHungerService;\n\t}\n\n\tpublic static PlayerMapService getPlayerMapService() {\n\t\treturn playerMapService;\n\t}\n\n\tpublic static SaveLoadService getSaveLoadService() {\n\t\treturn saveLoadService;\n\t}\n\n\tpublic static SoundService getSoundService() {\n\t\treturn soundService;\n\t}\n\n\tpublic static UIService getUIService() {\n\t\treturn uiService;\n\t}\n\n\tpublic static ParticleService getParticleService() {\n\t\treturn particleService;\n\t}\n\n\t/**\n\t * Sets the cutscene status to either running or not running.\n\t *\n\t * @param isRunning true if cutscene is running, false otherwise\n\t */\n\tpublic static void setCutSceneRunning(boolean isRunning) {\n\t\tcutSceneRunning = isRunning;\n\t}\n\n\t/**\n\t * Gets the cutscene status.\n\t *\n\t * @return true if cutscene is running, false otherwise\n\t */\n\tpublic static boolean getCutSceneStatus() {\n\t\treturn cutSceneRunning;\n\t}\n\n\tpublic static void registerGameArea(GameArea area) {\n\t\tlogger.debug(\"Registering game area {}\", area);\n\t\tgameArea = area;\n\t}\n\n\tpublic static void registerCameraComponent(CameraComponent camera) {\n\t\tlogger.debug(\"Registering game area {}\", camera);\n\t\tcameraComponent = camera;\n\t}\n\n\tpublic static void registerEntityService(EntityService service) {\n\t\tlogger.debug(\"Registering entity service {}\", service);\n\t\tentityService = service;\n\t}\n\n\tpublic static void registerRenderService(RenderService service) {\n\t\tlogger.debug(\"Registering render service {}\", service);\n\t\trenderService = service;\n\t}\n\n\tpublic static void registerPhysicsService(PhysicsService service) {\n\t\tlogger.debug(\"Registering physics service {}\", service);\n\t\tphysicsService = service;\n\t}\n\n\tpublic static void registerTimeService(TimeService service) {\n\t\tlogger.debug(\"Registering time service {}\", service);\n\t\ttimeService = service;\n\t}\n\n\tpublic static void registerInputService(InputService source) {\n\t\tlogger.debug(\"Registering input service {}\", source);\n\t\tinputService = source;\n\t}\n\n\tpublic static void registerResourceService(ResourceService source) {\n\t\tlogger.debug(\"Registering resource service {}\", source);\n\t\tresourceService = source;\n\t}\n\n\tpublic static void registerTimeSource(GameTime source) {\n\t\tlogger.debug(\"Registering time source {}\", source);\n\t\ttimeSource = source;\n\t}\n\n\tpublic static void registerMissionManager(MissionManager source) {\n\t\tlogger.debug(\"Registering mission manager {}\", source);\n\t\tmissions = source;\n\t}\n\n\tpublic static void registerUIService(UIService source) {\n\t\tlogger.debug(\"Registering UI service {}\", source);\n\t\tuiService = source;\n\t}\n\n\tpublic static void registerPlanetOxygenService(PlanetOxygenService source) {\n\t\tlogger.debug(\"Registering planet oxygen service {}\", source);\n\t\tplanetOxygenService = source;\n\t}\n\n\n\tpublic static void registerPlayerHungerService(PlayerHungerService source) {\n\t\tlogger.debug(\"Registering player hunger service {}\", source);\n\t\tplayerHungerService = source;\n\t}\n\n\tpublic static void registerPlayerMapService(PlayerMapService source) {\n\t\tlogger.debug(\"Registering player map service {}\", source);\n\t\tplayerMapService = source;\n\t}\n\n\tpublic static void registerPlantCommandService(PlantCommandService source) {\n\t\tlogger.debug(\"Registering plant command service {}\", source);\n\t\tplantCommandService = source;\n\t}\n\n\tpublic static void registerPlantInfoService(PlantInfoService source) {\n\t\tlogger.debug(\"Registering plant command service {}\", source);\n\t\tplantInfoService = source;\n\t}\n\n\tpublic static void registerLightService(LightService source) {\n\t\tlogger.debug(\"Registering light service {}\", source);\n\t\tlightService = source;\n\t}\n\n\tpublic static void registerInventoryDisplayManager(InventoryDisplayManager source) {\n\t\tlogger.debug(\"Registering inventory display manager {}\", source);\n\t\tinventoryDisplayManager = source;\n\t}\n\n\tpublic static void registerParticleService(ParticleService source) {\n\t\tparticleService = source;\n\t}\n\n\t/**\n\t * Registers the save/load service.\n\t *\n\t * @param source the service to register\n\t */\n\tpublic static void registerSaveLoadService(SaveLoadService source) {\n\t\tlogger.debug(\"Registering Save/Load service {}\", source);\n\t\tsaveLoadService = source;\n\t}\n\n\tpublic static void registerSoundService(SoundService source) {\n\t\tlogger.debug(\"Registering sound service {}\", source);\n\t\tsoundService = source;\n\t}\n\n\t/**\n\t * Clears all registered services.\n\t * Do not clear saveLoadService\n\t */\n\tpublic static void clear() {\n\t\tentityService = null;\n\t\trenderService = null;\n\t\tphysicsService = null;\n\t\ttimeSource = null;\n\t\tinputService = null;\n\t\tresourceService = null;\n\t\tgameArea = null;\n\t\tsoundService = null;\n\t\tlightService = null;\n\t\tparticleService = null;\n\t\ttimeService = null;\n\t\tuiService = null;\n\t}\n\n\tprivate ServiceLocator() {\n\t\tthrow new IllegalStateException(\"Instantiating static util class\");\n\t}\n\n\tpublic static void registerPauseArea(GameAreaDisplay area) {\n\t\tpauseMenuArea = area;\n\t}\n\n\tpublic static GameAreaDisplay getPauseMenuArea() {\n\t\treturn pauseMenuArea;\n\t}\n\n\tpublic static InventoryDisplayManager getInventoryDisplayManager() {\n\t\treturn inventoryDisplayManager;\n\t}\n\n\tpublic static void registerCraftArea(GameAreaDisplay area) {\n\t\tcraftArea = area;\n\t}\n\n\tpublic static GameAreaDisplay getCraftArea() {\n\t\treturn craftArea;\n\t}\n\n\tpublic static void registerGame(GdxGame gameVar) {\n\t\tgame = gameVar;\n\t}\n\n\tpublic static GdxGame getGame() {\n\t\treturn game;\n\t}\n\n\n}" } ]
import com.badlogic.gdx.math.Vector2; import com.csse3200.game.entities.Entity; import com.csse3200.game.entities.EntityService; import com.csse3200.game.extensions.GameExtension; import com.csse3200.game.physics.PhysicsService; import com.csse3200.game.rendering.RenderService; import com.csse3200.game.services.ResourceService; import com.csse3200.game.services.ServiceLocator; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.mockito.Mockito.mock;
9,981
package com.csse3200.game.areas.terrain; @ExtendWith(GameExtension.class) class TerrainCropTileFactoryTest {
package com.csse3200.game.areas.terrain; @ExtendWith(GameExtension.class) class TerrainCropTileFactoryTest {
private static Entity tile;
0
2023-10-17 22:34:04+00:00
12k