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 pri... | 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... | 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 ... | 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 = \"... | 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<?> mClip... | 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 pu... | 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 fi... | 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/... | 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 ... | 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... | 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... | 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 spec... | 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 = \"Automatica... | 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 = 36801... | 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\tpubli... | 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@Col... | 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 ... | 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... | 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... | 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... | 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 ... | 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()) ... | 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(... | 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() {\... | 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 RuntimeExcepti... | 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 i... | 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 线... | 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)... | 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}"
},
{
"... | 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 =... | 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-... | 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\tretu... | 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 ... | 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 Li... | 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 HashMa... | 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 ... | 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 contai... | 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 <apkeditor@protonmail.com> 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 <apkeditor@protonmail.com> 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, Throw... | 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) {... | 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 Strin... | 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... | 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 D... | 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.IDENT... | 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 Str... | 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 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_NO... | 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 por... | 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 CommandRe... | 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 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\... | 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... | 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... | 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... | 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(... | 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 p... | 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.createStateme... | 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 publ... | 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/DragonR... | 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 lo... | 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 ... | 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... | 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 st... | 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_... | 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 ... | 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_M... | 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.getInsta... | 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/... | 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 Comm... | 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, \"올바른 형식의 데이터가 입... | 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 * ... | 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": ... | 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 ... | 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 ... | 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 getPageA... | 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 ... | 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 ... | 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": "@Servi... | 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 circleFi... | 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... | 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 tuxming@sina.com / 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 tuxming@sina.com / 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... | 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 AGRICR... | 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(Coll... | 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... | 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 account... | 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}... | 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 ... | 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 ... | 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 ... | 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 call... | 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... | 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: mosaic@fokus.fraunhofer.de
*/
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: mosaic@fokus.fraunhofer.de
*/
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 AbnormalDis... | 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(P... | 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 re... | 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 <dariusz@luksza.org> 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 <dariusz@luksza.org> 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;\... | 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 ... | 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;\... | 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 stati... | 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 depositWithdrawa... | 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 stati... | 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 ... | 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.