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 |
---|---|---|---|---|---|---|---|---|---|---|
quan100/quan | quan-app/quan-app-pm-bff/src/main/java/cn/javaquan/app/pm/bff/file/controller/FileController.java | [
{
"identifier": "FileAssembler",
"path": "quan-app/quan-app-pm-bff/src/main/java/cn/javaquan/app/pm/bff/file/convert/FileAssembler.java",
"snippet": "@Mapper\npublic interface FileAssembler {\n\n FileAssembler INSTANCE = Mappers.getMapper(FileAssembler.class);\n\n @Mapping(target = \"url\", expression = \"java(toUrl(response))\")\n FileVO toFileVO(MinioResponse response);\n\n @Named(\"toUrl\")\n default String toUrl(MinioResponse response) {\n StringBuffer sb = new StringBuffer();\n sb.append(response.getHost());\n sb.append(File.separator);\n sb.append(response.getBucket());\n sb.append(File.separator);\n sb.append(response.getName());\n return sb.toString();\n }\n}"
},
{
"identifier": "FileVO",
"path": "quan-app/quan-app-common/src/main/java/cn/javaquan/app/common/module/file/FileVO.java",
"snippet": "@Data\npublic class FileVO implements Serializable {\n\n private static final long serialVersionUID = -137770378920503836L;\n\n private String name;\n\n /**\n * 文件访问地址\n */\n private String url;\n}"
},
{
"identifier": "Result",
"path": "quan-common-utils/quan-base-common/src/main/java/cn/javaquan/common/base/message/Result.java",
"snippet": "@Data\npublic class Result<T> implements Serializable {\n\n private static final long serialVersionUID = 485088578586623310L;\n\n /**\n * 标记 JSON字符串中 {@link #uniformFormat} 参数的键值\n */\n public static final String UNIFORM_FORMAT_KEY = \"uniformFormat\";\n\n private Integer code;\n\n private String type;\n\n private String message;\n\n private T data;\n\n /**\n * 标记参数为统一的格式。\n * 在统一参数处理器中,会对所有响应参数进行检查,若响应参数非统一的格式,则将响应参数转换为 {@link Result} 格式并返回。\n * <p>\n * 为了避免当前参数被重复转换,应该设置该参数的值为 {@code true}\n */\n private boolean uniformFormat = true;\n\n public Result(Integer code, String type, String message, T data) {\n this.code = code;\n this.type = type;\n this.message = message;\n this.data = data;\n }\n\n public Result() {\n }\n\n /* 成功结果静态类 **/\n public static <T> Result<T> success() {\n return success(null, null);\n }\n\n public static <T> Result<T> success(T data) {\n return success(null, data);\n }\n\n public static <T> Result<T> success(String msg, T data) {\n return instance(ResultType.MSG_SUCCESS, null, msg, data);\n }\n\n /* 失败结果静态类 **/\n public static <T> Result<T> fail(String msg) {\n return instance(ResultType.MSG_ERROR, null, msg, null);\n }\n\n public static <T> Result<T> fail(int code, String msg) {\n return instance(code, null, msg, null);\n }\n\n public static <T> Result<T> fail(int code, String msg, T data) {\n return instance(code, null, msg, data);\n }\n\n private static <T> Result<T> instance(Integer code, String type, String msg, T data) {\n return new Result<>(code, type, msg, data);\n }\n\n /**\n * 要求业务处理成功\n *\n * @return\n */\n public boolean isSuccess() {\n return ResultType.MSG_SUCCESS.equals(this.code);\n }\n\n /**\n * 要求业务处理成功,且数据不为空\n *\n * @return\n */\n public boolean isData() {\n return isSuccess() && null != data;\n }\n\n public String toJSONString() {\n return JSON.toJSONString(this);\n }\n}"
},
{
"identifier": "MinioResponse",
"path": "quan-tools/quan-file/src/main/java/cn/javaquan/tools/file/minio/MinioResponse.java",
"snippet": "public class MinioResponse {\n\n private String bucket;\n private String region;\n private String object;\n\n private String etag;\n private String versionId;\n\n private String host;\n private String name;\n\n public String getBucket() {\n return bucket;\n }\n\n public void setBucket(String bucket) {\n this.bucket = bucket;\n }\n\n public String getRegion() {\n return region;\n }\n\n public void setRegion(String region) {\n this.region = region;\n }\n\n public String getObject() {\n return object;\n }\n\n public void setObject(String object) {\n this.object = object;\n }\n\n public String getEtag() {\n return etag;\n }\n\n public void setEtag(String etag) {\n this.etag = etag;\n }\n\n public String getVersionId() {\n return versionId;\n }\n\n public void setVersionId(String versionId) {\n this.versionId = versionId;\n }\n\n public String getHost() {\n return host;\n }\n\n public void setHost(String host) {\n this.host = host;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public static MinioResponse build(String name, String host, ObjectWriteResponse response) {\n MinioResponse minioResponse = new MinioResponse();\n minioResponse.setBucket(response.bucket());\n minioResponse.setRegion(response.region());\n minioResponse.setObject(response.object());\n minioResponse.setEtag(response.etag());\n minioResponse.setVersionId(response.versionId());\n minioResponse.setName(name);\n minioResponse.setHost(host);\n return minioResponse;\n }\n}"
},
{
"identifier": "MinioUtil",
"path": "quan-tools/quan-file/src/main/java/cn/javaquan/tools/file/minio/MinioUtil.java",
"snippet": "public class MinioUtil {\n\n private static MinioClient minioClient;\n private static MinioProperties properties;\n\n public MinioUtil(MinioClient minioClient, MinioProperties properties) {\n MinioUtil.minioClient = minioClient;\n MinioUtil.properties = properties;\n }\n\n /**\n * 文件上传\n *\n * @param file\n * @return\n */\n public MinioResponse upload(MultipartFile file) {\n return upload(properties.determineDefaultBucketName(), file);\n }\n\n /**\n * 文件上传\n *\n * @param bucketName\n * @param file\n * @return\n */\n public MinioResponse upload(String bucketName, MultipartFile file) {\n String originalFilename = file.getOriginalFilename();\n\n String fileSuffix = originalFilename.substring(originalFilename.lastIndexOf(\".\"));\n\n StringBuffer sb = new StringBuffer();\n sb.append(UUID.randomUUID());\n sb.append(originalFilename);\n\n String fileName = DigestUtils.md5Hex(sb.toString()) + fileSuffix;\n return MinioResponse.build(fileName, properties.determineDefaultUrl(), uploadBatch(bucketName, fileName, Arrays.asList(file)));\n }\n\n /**\n * 文件批量上传\n *\n * @param files\n * @return\n */\n public void uploadBatch(List<MultipartFile> files) {\n uploadBatch(properties.determineDefaultBucketName(), null, files);\n }\n\n /**\n * 文件上传\n *\n * @param bucketName\n * @param fileName\n * @param files\n * @return\n */\n private ObjectWriteResponse uploadBatch(String bucketName, String fileName, List<MultipartFile> files) {\n Assert.notEmpty(files);\n\n return exceptionHandler(() -> {\n makeBucket(bucketName);\n\n List<SnowballObject> objects = new ArrayList<>(files.size());\n for (MultipartFile file : files) {\n objects.add(new SnowballObject(\n StringUtils.hasText(fileName) ? fileName : file.getOriginalFilename(),\n file.getInputStream(),\n file.getSize(),\n null\n ));\n }\n\n return minioClient.uploadSnowballObjects(\n UploadSnowballObjectsArgs.builder().bucket(bucketName).objects(objects).build()\n );\n });\n }\n\n /**\n * 文件下载\n *\n * @param fileName 文件名称\n */\n public void download(String fileName, HttpServletResponse servletResponse) {\n download(properties.determineDefaultBucketName(), fileName, servletResponse);\n }\n\n /**\n * 文件下载\n *\n * @param bucketName\n * @param fileName 文件名称\n */\n public void download(String bucketName, String fileName, HttpServletResponse servletResponse) {\n InputStream inputStream = download(bucketName, fileName);\n byte[] content;\n try (ByteArrayOutputStream bos = new ByteArrayOutputStream(512)) {\n byte[] b = new byte[512];\n int n;\n while ((n = inputStream.read(b)) != -1) {\n bos.write(b, 0, n);\n }\n inputStream.close();\n content = bos.toByteArray();\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n\n servletResponse.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);\n servletResponse.setHeader(\"Content-Disposition\", \"attachment;filename=\" + fileName);\n servletResponse.setStatus(HttpStatus.ACCEPTED.value());\n try (ServletOutputStream outputStream = servletResponse.getOutputStream()) {\n outputStream.write(content);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n public InputStream download(String bucketName, String fileName) {\n return exceptionHandler(() -> {\n StatObjectResponse objectResponse = statObject(bucketName, fileName);\n if (null == objectResponse || objectResponse.size() <= 0) {\n return null;\n }\n return minioClient.getObject(\n GetObjectArgs.builder()\n .bucket(bucketName)\n .object(fileName)\n .build()\n );\n });\n }\n\n /**\n * 获取预览地址\n *\n * @param fileName\n * @return\n */\n public String preview(String fileName) {\n return preview(properties.determineDefaultBucketName(), fileName);\n }\n\n /**\n * 获取预览地址\n *\n * @param bucketName\n * @param fileName\n * @return\n */\n public String preview(String bucketName, String fileName) {\n return preview(bucketName, fileName, 20);\n }\n\n /**\n * 获取预览地址\n *\n * @param bucketName\n * @param fileName\n * @param duration 持续时间,单位:秒\n * @return\n */\n public String preview(String bucketName, String fileName, int duration) {\n return exceptionHandler(() -> minioClient.getPresignedObjectUrl(\n GetPresignedObjectUrlArgs.builder()\n .method(Method.GET)\n .bucket(bucketName)\n .object(fileName)\n .expiry(duration, TimeUnit.SECONDS)\n .build())\n );\n }\n\n /**\n * 删除文件\n *\n * @param fileName 文件名称\n */\n public void remove(String fileName) {\n remove(properties.determineDefaultBucketName(), fileName);\n }\n\n /**\n * 删除文件\n *\n * @param bucketName\n * @param fileName\n */\n public void remove(String bucketName, String fileName) {\n exceptionHandler(() -> {\n minioClient.removeObject(\n RemoveObjectArgs.builder()\n .bucket(bucketName)\n .object(fileName)\n .bypassGovernanceMode(true)\n .build()\n );\n return null;\n });\n }\n\n /**\n * 判断存储桶是否存在\n *\n * @param bucketName 存储桶名称\n * @return\n * @throws Exception\n */\n public static boolean bucketExists(String bucketName) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {\n return minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());\n }\n\n /**\n * 创建存储桶\n *\n * @param bucketName 存储桶名称\n * @throws Exception\n */\n public static void makeBucket(String bucketName) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {\n if (!bucketExists(bucketName)) {\n // Make a new bucket called 'asiatrip'.\n minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());\n }\n }\n\n /**\n * 获取对象的元数据\n *\n * @param bucketName 存储桶名称\n * @param objectName 存储桶里的对象名称\n * @return\n * @throws Exception\n */\n public static StatObjectResponse statObject(String bucketName, String objectName) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {\n boolean found = bucketExists(bucketName);\n if (found) {\n StatObjectResponse response = minioClient.statObject(\n StatObjectArgs.builder().bucket(bucketName).object(objectName).build()\n );\n return response;\n }\n return null;\n }\n\n private static <V> V exceptionHandler(Consumer<V> consumer) {\n try {\n return consumer.accept();\n } catch (ServerException e) {\n throw new RuntimeException(e);\n } catch (InsufficientDataException e) {\n throw new RuntimeException(e);\n } catch (ErrorResponseException e) {\n throw new RuntimeException(e.errorResponse().message());\n } catch (IOException e) {\n throw new RuntimeException(e);\n } catch (NoSuchAlgorithmException e) {\n throw new RuntimeException(e);\n } catch (InvalidKeyException e) {\n throw new RuntimeException(e);\n } catch (InvalidResponseException e) {\n throw new RuntimeException(e);\n } catch (XmlParserException e) {\n throw new RuntimeException(e);\n } catch (InternalException e) {\n throw new RuntimeException(e);\n }\n }\n\n @FunctionalInterface\n private interface Consumer<V> {\n V accept() throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException;\n }\n\n}"
}
] | import cn.javaquan.app.pm.bff.file.convert.FileAssembler;
import cn.javaquan.app.common.module.file.FileVO;
import cn.javaquan.common.base.message.Result;
import cn.javaquan.tools.file.minio.MinioResponse;
import cn.javaquan.tools.file.minio.MinioUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse; | 3,784 | package cn.javaquan.app.pm.bff.file.controller;
/**
* 文件
*
* @author JavaQuan
* @version 2.2.0
*/
@RequiredArgsConstructor
@RestController
@RequestMapping("/file")
public class FileController {
private final MinioUtil minioUtil;
/**
* 文件上传
*
* @param file
* @return
*/
@PostMapping(value = "/upload")
public Result<FileVO> upload(@RequestPart MultipartFile file) {
MinioResponse response = minioUtil.upload(file); | package cn.javaquan.app.pm.bff.file.controller;
/**
* 文件
*
* @author JavaQuan
* @version 2.2.0
*/
@RequiredArgsConstructor
@RestController
@RequestMapping("/file")
public class FileController {
private final MinioUtil minioUtil;
/**
* 文件上传
*
* @param file
* @return
*/
@PostMapping(value = "/upload")
public Result<FileVO> upload(@RequestPart MultipartFile file) {
MinioResponse response = minioUtil.upload(file); | return Result.success(FileAssembler.INSTANCE.toFileVO(response)); | 0 | 2023-10-08 06:48:41+00:00 | 8k |
Ghost-chu/DoDoSRV | src/main/java/com/ghostchu/plugins/dodosrv/text/TextManager.java | [
{
"identifier": "DoDoSRV",
"path": "src/main/java/com/ghostchu/plugins/dodosrv/DoDoSRV.java",
"snippet": "public final class DoDoSRV extends JavaPlugin {\n\n private DodoBot bot;\n private DatabaseManager databaseManager;\n private UserBindManager userBindManager;\n private TextManager textManager;\n private SimpleCommandManager commandManager;\n private DoDoListener doDoListener;\n private DodoManager dodoManager;\n private static Cache<String, String> MESSAGE_ID_TO_ECHO = CacheBuilder.newBuilder()\n .expireAfterWrite(24, TimeUnit.HOURS)\n .maximumSize(15000)\n .build();\n\n\n @Override\n public void onEnable() {\n // Plugin startup logic\n saveDefaultConfig();\n saveDefTranslations();\n this.textManager = new TextManager(this, new File(getDataFolder(), \"messages.yml\"));\n this.databaseManager = initDatabase();\n this.userBindManager = new UserBindManager(this, databaseManager);\n try {\n initDoDoBot();\n } catch (Exception e) {\n Bukkit.getPluginManager().disablePlugin(this);\n throw new RuntimeException(e);\n }\n this.dodoManager = new DodoManager(this);\n this.commandManager = new SimpleCommandManager(this);\n getCommand(\"dodosrv\").setExecutor(this.commandManager);\n getCommand(\"dodosrv\").setTabCompleter(this.commandManager);\n }\n\n private void postInit() {\n //initListeners();\n }\n\n private void initListeners() {\n Bukkit.getPluginManager().registerEvents(new BukkitListener(this), this);\n this.doDoListener = new DoDoListener(this);\n bot.addEventListener(doDoListener);\n }\n\n private DatabaseManager initDatabase() {\n return new DatabaseManager(this);\n }\n\n private void initDoDoBot() {\n String backupClientId = System.getProperty(\"dodosrv.client-id\");\n if(backupClientId == null) backupClientId = \"0\";\n int clientId = getConfig().getInt(\"client-id\", Integer.parseInt(backupClientId) );\n this.bot = new DodoBot(clientId, getConfig().getString(\"bot-token\", System.getProperty(\"dodosrv.bot-token\")));\n initListeners();\n this.bot.runAfter(this::postInit);\n this.bot.start();\n }\n\n\n @Override\n public void onDisable() {\n // Plugin shutdown logic\n }\n\n public CompletableFuture<String> sendMessageToDefChannel(Message message) {\n return CompletableFuture.supplyAsync(() -> {\n Channel channel = bot().getClient().fetchChannel(getIslandId(), getChatChannel());\n if (!(channel instanceof TextChannel)) {\n return null;\n }\n TextChannel textChannel = (TextChannel) channel;\n String msgId = textChannel.send(message);\n if(message instanceof TextMessage){\n TextMessage msg = (TextMessage) message;\n MESSAGE_ID_TO_ECHO.put(msgId, msg.getContent());\n }\n return msgId;\n });\n }\n\n public CompletableFuture<String> sendMessageToDefChannel(String string) {\n if (!JsonUtil.isJson(string)) {\n return sendMessageToDefChannel(new TextMessage(string));\n } else {\n return sendCardMessageToDefChannel(string);\n }\n }\n\n public CompletableFuture<String> sendCardMessageToDefChannel(String json) {\n return CompletableFuture.supplyAsync(() -> {\n JsonObject finalJson = JsonUtil.readObject(json);\n Channel channel = bot().getClient().fetchChannel(getIslandId(), getChatChannel());\n if (!(channel instanceof TextChannel)) {\n return null;\n }\n TextChannel textChannel = (TextChannel) channel;\n Field gatewayField;\n try {\n gatewayField = ChannelImpl.class.getDeclaredField(\"gateway\");\n gatewayField.setAccessible(true);\n Gateway gateway = (Gateway) gatewayField.get(channel);\n Route route = API.V2.Channel.messageSend().param(\"channelId\", channel.getId()).param(\"messageType\", MessageType.CARD.getCode()).param(\"messageBody\", finalJson);\n return gateway.executeRequest(route).getAsJsonObject().get(\"messageId\").getAsString();\n } catch (NoSuchFieldException | IllegalAccessException e) {\n throw new RuntimeException(e);\n }\n });\n\n }\n\n\n public String getIslandId() {\n return getConfig().getString(\"dodo.island-id\");\n }\n\n public String getChatChannel() {\n return getConfig().getString(\"dodo.chat-channel\");\n }\n\n private void saveDefTranslations() {\n File file = new File(getDataFolder(), \"messages.yml\");\n if (!file.exists()) {\n saveResource(\"messages.yml\", false);\n }\n }\n\n public DodoBot bot() {\n return bot;\n }\n\n public TextManager text() {\n return textManager;\n }\n\n public DatabaseManager database() {\n return databaseManager;\n }\n\n public UserBindManager userBind() {\n return userBindManager;\n }\n\n public CommandManager commandManager() {\n return commandManager;\n }\n\n public DodoManager dodoManager() {\n return dodoManager;\n }\n\n public Cache<String,String> echoCache(){\n return MESSAGE_ID_TO_ECHO;\n }\n\n}"
},
{
"identifier": "JsonUtil",
"path": "src/main/java/com/ghostchu/plugins/dodosrv/util/JsonUtil.java",
"snippet": "public final class JsonUtil {\n private static final Gson STANDARD_GSON = new GsonBuilder()\n .enableComplexMapKeySerialization()\n .setExclusionStrategies(new HiddenAnnotationExclusionStrategy())\n .serializeNulls()\n .disableHtmlEscaping()\n .create();\n\n private static final Gson PRETTY_PRINT_GSON = new GsonBuilder()\n .enableComplexMapKeySerialization()\n .setExclusionStrategies(new HiddenAnnotationExclusionStrategy())\n .serializeNulls()\n .disableHtmlEscaping()\n .setPrettyPrinting()\n .create();\n\n @NotNull\n @Deprecated\n public static Gson get() {\n return standard();\n }\n\n @NotNull\n public static Gson standard() {\n return STANDARD_GSON;\n }\n\n public static Gson getGson() {\n return STANDARD_GSON;\n }\n\n @NotNull\n @Deprecated\n public static Gson getPrettyPrinting() {\n return prettyPrinting();\n }\n\n @NotNull\n public static Gson prettyPrinting() {\n return PRETTY_PRINT_GSON;\n }\n\n @NotNull\n public static JsonObject readObject(@NotNull Reader reader) {\n return JsonParser.parseReader(reader).getAsJsonObject();\n }\n\n @NotNull\n public static JsonObject readObject(@NotNull String s) {\n return JsonParser.parseString(s).getAsJsonObject();\n }\n\n @NotNull\n public static JsonArray readArray(@NotNull String s) {\n return JsonParser.parseString(s).getAsJsonArray();\n }\n @NotNull\n public static JsonArray readArray(@NotNull Reader reader) {\n return JsonParser.parseReader(reader).getAsJsonArray();\n }\n public static Gson regular() {\n return STANDARD_GSON;\n }\n public static boolean isJson(String str) {\n if (str == null || str.isBlank()) {\n return false;\n }\n try {\n JsonElement element = JsonParser.parseString(str);\n return element.isJsonObject() || element.isJsonArray();\n } catch (JsonParseException exception) {\n return false;\n }\n }\n @NotNull\n public static String toString(@NotNull JsonElement element) {\n return Objects.requireNonNull(standard().toJson(element));\n }\n\n @NotNull\n public static String toStringPretty(@NotNull JsonElement element) {\n return Objects.requireNonNull(prettyPrinting().toJson(element));\n }\n\n public static void writeElement(@NotNull Appendable writer, @NotNull JsonElement element) {\n standard().toJson(element, writer);\n }\n\n public static void writeElementPretty(@NotNull Appendable writer, @NotNull JsonElement element) {\n prettyPrinting().toJson(element, writer);\n }\n\n public static void writeObject(@NotNull Appendable writer, @NotNull JsonObject object) {\n standard().toJson(object, writer);\n }\n\n public static void writeObjectPretty(@NotNull Appendable writer, @NotNull JsonObject object) {\n prettyPrinting().toJson(object, writer);\n }\n\n public @interface Hidden {\n\n }\n\n public static class HiddenAnnotationExclusionStrategy implements ExclusionStrategy {\n @Override\n public boolean shouldSkipField(FieldAttributes f) {\n return f.getAnnotation(Hidden.class) != null;\n }\n\n @Override\n public boolean shouldSkipClass(Class<?> clazz) {\n return clazz.getDeclaredAnnotation(Hidden.class) != null;\n }\n }\n\n}"
},
{
"identifier": "Util",
"path": "src/main/java/com/ghostchu/plugins/dodosrv/util/Util.java",
"snippet": "public class Util {\n /**\n * Replace args in raw to args\n *\n * @param raw text\n * @param args args\n * @return filled text\n */\n @NotNull\n public static String fillArgs(@Nullable String raw, @Nullable String... args) {\n if (StringUtils.isEmpty(raw)) {\n return \"\";\n }\n if (args != null) {\n for (int i = 0; i < args.length; i++) {\n raw = StringUtils.replace(raw, \"{\" + i + \"}\", args[i] == null ? \"\" : args[i]);\n }\n }\n return raw;\n }\n\n /**\n * Replace args in origin to args\n *\n * @param origin origin\n * @param args args\n * @return filled component\n */\n @NotNull\n public static Component fillArgs(@NotNull Component origin, @Nullable Component... args) {\n for (int i = 0; i < args.length; i++) {\n origin = origin.replaceText(TextReplacementConfig.builder()\n .matchLiteral(\"{\" + i + \"}\")\n .replacement(args[i] == null ? Component.empty() : args[i])\n .build());\n }\n return origin.compact();\n }\n /**\n * Execute the Runnable in async thread.\n * If it already on main-thread, will be move to async thread.\n *\n * @param runnable The runnable\n */\n public static void asyncThreadRun(@NotNull Runnable runnable) {\n if (!DoDoSRV.getPlugin(DoDoSRV.class).isEnabled()) {\n runnable.run();\n return;\n }\n if (!Bukkit.isPrimaryThread()) {\n runnable.run();\n } else {\n Bukkit.getScheduler().runTaskAsynchronously(DoDoSRV.getPlugin(DoDoSRV.class), runnable);\n }\n }\n /**\n * Execute the Runnable in server main thread.\n * If it already on main-thread, will be executed directly.\n * or post to main-thread if came from any other thread.\n *\n * @param runnable The runnable\n */\n public static void mainThreadRun(@NotNull Runnable runnable) {\n if (Bukkit.isPrimaryThread()) {\n runnable.run();\n } else {\n Bukkit.getScheduler().runTask(DoDoSRV.getPlugin(DoDoSRV.class), runnable);\n }\n }\n\n}"
}
] | import com.ghostchu.plugins.dodosrv.DoDoSRV;
import com.ghostchu.plugins.dodosrv.util.JsonUtil;
import com.ghostchu.plugins.dodosrv.util.Util;
import de.themoep.minedown.adventure.MineDown;
import net.deechael.dodo.api.Member;
import net.deechael.dodo.content.Message;
import net.deechael.dodo.content.TextMessage;
import net.deechael.dodo.types.MessageType;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.ComponentLike;
import net.kyori.adventure.text.TextReplacementConfig;
import net.kyori.adventure.text.minimessage.MiniMessage;
import net.kyori.adventure.text.serializer.bungeecord.BungeeComponentSerializer;
import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer;
import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer;
import org.apache.commons.lang3.StringUtils;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.YamlConfiguration;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture; | 3,953 | String[] found = StringUtils.substringsBetween(content, "<@!", ">");
if (found != null) {
for (int i = 0; i < found.length; i++) {
try {
String cursor = found[i];
String replaceTo = "{" + i + "}";
String origin = "<@!" + cursor + ">";
replaced = replaced.replace(origin, replaceTo);
Member member = plugin.bot().getClient().fetchMember(plugin.getIslandId(), cursor);
replacements.put(replaceTo, plugin.dodoManager().getMemberDisplayComponent(plugin.getIslandId(), member));
} catch (Throwable ignored) {
}
}
}
Component component = new MineDown(replaced).toComponent();
for (Map.Entry<String, Component> e : replacements.entrySet()) {
component = component.replaceText(TextReplacementConfig.builder()
.matchLiteral(e.getKey())
.replacement(e.getValue())
.build());
}
return component;
});
}
public Text of(CommandSender sender, String key, Object... args) {
return new Text(sender, Util.fillArgs(miniMessage.deserialize(config.getString(key, "Missing no: " + key)), convert(args)));
}
public Text of(String key, Object... args) {
return new Text(null, Util.fillArgs(miniMessage.deserialize(config.getString(key, "Missing no: " + key)), convert(args)));
}
@NotNull
public Component[] convert(@Nullable Object... args) {
if (args == null || args.length == 0) {
return new Component[0];
}
Component[] components = new Component[args.length];
for (int i = 0; i < args.length; i++) {
Object obj = args[i];
if (obj == null) {
components[i] = Component.text("null");
continue;
}
Class<?> clazz = obj.getClass();
if (obj instanceof Component) {
Component component = (Component) obj;
components[i] = component;
continue;
}
if (obj instanceof ComponentLike) {
ComponentLike componentLike = (ComponentLike) obj;
components[i] = componentLike.asComponent();
continue;
}
// Check
try {
if (Character.class.equals(clazz)) {
components[i] = Component.text((char) obj);
continue;
}
if (Byte.class.equals(clazz)) {
components[i] = Component.text((Byte) obj);
continue;
}
if (Integer.class.equals(clazz)) {
components[i] = Component.text((Integer) obj);
continue;
}
if (Long.class.equals(clazz)) {
components[i] = Component.text((Long) obj);
continue;
}
if (Float.class.equals(clazz)) {
components[i] = Component.text((Float) obj);
continue;
}
if (Double.class.equals(clazz)) {
components[i] = Component.text((Double) obj);
continue;
}
if (Boolean.class.equals(clazz)) {
components[i] = Component.text((Boolean) obj);
continue;
}
if (String.class.equals(clazz)) {
components[i] = LegacyComponentSerializer.legacySection().deserialize((String) obj);
continue;
}
if (Text.class.equals(clazz)) {
components[i] = ((Text) obj).component();
}
components[i] = LegacyComponentSerializer.legacySection().deserialize(obj.toString());
} catch (Exception exception) {
components[i] = LegacyComponentSerializer.legacySection().deserialize(obj.toString());
}
// undefined
}
return components;
}
public static class Text {
private final Component component;
private final CommandSender sender;
public Text(CommandSender sender, Component component) {
this.sender = sender;
this.component = component.compact();
}
public Message dodoText() {
String raw = PlainTextComponentSerializer.plainText().serialize(component);
if (StringUtils.isBlank(raw)) {
raw = "Missing no: text is null";
}
Message message = new TextMessage(raw); | package com.ghostchu.plugins.dodosrv.text;
public class TextManager {
private final File file;
private final DoDoSRV plugin;
private YamlConfiguration config;
private MiniMessage miniMessage;
public TextManager(DoDoSRV plugin, File file) {
this.plugin = plugin;
this.file = file;
init();
}
private void init() {
this.config = YamlConfiguration.loadConfiguration(file);
this.miniMessage = MiniMessage.miniMessage();
}
public CompletableFuture<Component> dodoToComponent(String content) {
return CompletableFuture.supplyAsync(() -> {
String replaced = content;
Map<String, Component> replacements = new LinkedHashMap<>();
String[] found = StringUtils.substringsBetween(content, "<@!", ">");
if (found != null) {
for (int i = 0; i < found.length; i++) {
try {
String cursor = found[i];
String replaceTo = "{" + i + "}";
String origin = "<@!" + cursor + ">";
replaced = replaced.replace(origin, replaceTo);
Member member = plugin.bot().getClient().fetchMember(plugin.getIslandId(), cursor);
replacements.put(replaceTo, plugin.dodoManager().getMemberDisplayComponent(plugin.getIslandId(), member));
} catch (Throwable ignored) {
}
}
}
Component component = new MineDown(replaced).toComponent();
for (Map.Entry<String, Component> e : replacements.entrySet()) {
component = component.replaceText(TextReplacementConfig.builder()
.matchLiteral(e.getKey())
.replacement(e.getValue())
.build());
}
return component;
});
}
public Text of(CommandSender sender, String key, Object... args) {
return new Text(sender, Util.fillArgs(miniMessage.deserialize(config.getString(key, "Missing no: " + key)), convert(args)));
}
public Text of(String key, Object... args) {
return new Text(null, Util.fillArgs(miniMessage.deserialize(config.getString(key, "Missing no: " + key)), convert(args)));
}
@NotNull
public Component[] convert(@Nullable Object... args) {
if (args == null || args.length == 0) {
return new Component[0];
}
Component[] components = new Component[args.length];
for (int i = 0; i < args.length; i++) {
Object obj = args[i];
if (obj == null) {
components[i] = Component.text("null");
continue;
}
Class<?> clazz = obj.getClass();
if (obj instanceof Component) {
Component component = (Component) obj;
components[i] = component;
continue;
}
if (obj instanceof ComponentLike) {
ComponentLike componentLike = (ComponentLike) obj;
components[i] = componentLike.asComponent();
continue;
}
// Check
try {
if (Character.class.equals(clazz)) {
components[i] = Component.text((char) obj);
continue;
}
if (Byte.class.equals(clazz)) {
components[i] = Component.text((Byte) obj);
continue;
}
if (Integer.class.equals(clazz)) {
components[i] = Component.text((Integer) obj);
continue;
}
if (Long.class.equals(clazz)) {
components[i] = Component.text((Long) obj);
continue;
}
if (Float.class.equals(clazz)) {
components[i] = Component.text((Float) obj);
continue;
}
if (Double.class.equals(clazz)) {
components[i] = Component.text((Double) obj);
continue;
}
if (Boolean.class.equals(clazz)) {
components[i] = Component.text((Boolean) obj);
continue;
}
if (String.class.equals(clazz)) {
components[i] = LegacyComponentSerializer.legacySection().deserialize((String) obj);
continue;
}
if (Text.class.equals(clazz)) {
components[i] = ((Text) obj).component();
}
components[i] = LegacyComponentSerializer.legacySection().deserialize(obj.toString());
} catch (Exception exception) {
components[i] = LegacyComponentSerializer.legacySection().deserialize(obj.toString());
}
// undefined
}
return components;
}
public static class Text {
private final Component component;
private final CommandSender sender;
public Text(CommandSender sender, Component component) {
this.sender = sender;
this.component = component.compact();
}
public Message dodoText() {
String raw = PlainTextComponentSerializer.plainText().serialize(component);
if (StringUtils.isBlank(raw)) {
raw = "Missing no: text is null";
}
Message message = new TextMessage(raw); | if (false && JsonUtil.isJson(raw)) { | 1 | 2023-10-11 16:16:54+00:00 | 8k |
Hartie95/AnimeGamesLua | GILua/src/main/java/org/anime_game_servers/gi_lua/script_lib/ScriptLib.java | [
{
"identifier": "ExhibitionPlayType",
"path": "GILua/src/main/java/org/anime_game_servers/gi_lua/models/constants/ExhibitionPlayType.java",
"snippet": "@LuaStatic\npublic enum ExhibitionPlayType {\n Challenge,\n Gallery,\n}"
},
{
"identifier": "FlowSuiteOperatePolicy",
"path": "GILua/src/main/java/org/anime_game_servers/gi_lua/models/constants/FlowSuiteOperatePolicy.java",
"snippet": "@LuaStatic\npublic enum FlowSuiteOperatePolicy {\n DEFAULT,\n COMPLETE\n}"
},
{
"identifier": "GalleryProgressScoreType",
"path": "GILua/src/main/java/org/anime_game_servers/gi_lua/models/constants/temporary/GalleryProgressScoreType.java",
"snippet": "@LuaStatic\npublic enum GalleryProgressScoreType {\n GALLERY_PROGRESS_SCORE_NONE,\n GALLERY_PROGRESS_SCORE_NO_DEGRADE\n}"
},
{
"identifier": "GalleryProgressScoreUIType",
"path": "GILua/src/main/java/org/anime_game_servers/gi_lua/models/constants/temporary/GalleryProgressScoreUIType.java",
"snippet": "@LuaStatic\npublic enum GalleryProgressScoreUIType {\n GALLERY_PROGRESS_SCORE_UI_TYPE_NONE,\n GALLERY_PROGRESS_SCORE_UI_TYPE_BUOYANT_COMBAT,\n GALLERY_PROGRESS_SCORE_UI_TYPE_SUMO_STAGE,\n GALLERY_PROGRESS_SCORE_UI_TYPE_DIG,\n GALLERY_PROGRESS_SCORE_UI_TYPE_CRYSTAL_LINK,\n GALLERY_PROGRESS_SCORE_UI_TYPE_TREASURE;\n}"
},
{
"identifier": "luaToPos",
"path": "GILua/src/main/java/org/anime_game_servers/gi_lua/utils/ScriptUtils.java",
"snippet": "public static Vector luaToPos(LuaTable position){\n val result = new PositionImpl();\n if(position != null){\n result.setX(position.optInt(\"x\", 0));\n result.setY(position.optInt(\"y\", 0));\n result.setZ(position.optInt(\"z\", 0));\n }\n\n return result;\n}"
},
{
"identifier": "posToLua",
"path": "GILua/src/main/java/org/anime_game_servers/gi_lua/utils/ScriptUtils.java",
"snippet": "public static LuaTable posToLua(Vector position, LuaEngine engine){\n var result = engine.createTable();\n if(position != null){\n result.set(\"x\", position.getX());\n result.set(\"y\", position.getY());\n result.set(\"z\", position.getZ());\n } else {\n result.set(\"x\", 0);\n result.set(\"y\", 0);\n result.set(\"z\", 0);\n }\n\n return result;\n}"
}
] | import io.github.oshai.kotlinlogging.KLogger;
import io.github.oshai.kotlinlogging.KotlinLogging;
import lombok.val;
import org.anime_game_servers.core.base.annotations.lua.LuaStatic;
import org.anime_game_servers.gi_lua.models.constants.*;
import org.anime_game_servers.gi_lua.models.constants.ExhibitionPlayType;
import org.anime_game_servers.gi_lua.models.constants.FlowSuiteOperatePolicy;
import org.anime_game_servers.gi_lua.models.constants.temporary.GalleryProgressScoreType;
import org.anime_game_servers.gi_lua.models.constants.temporary.GalleryProgressScoreUIType;
import org.anime_game_servers.gi_lua.script_lib.handler.ScriptLibStaticHandler;
import org.anime_game_servers.gi_lua.script_lib.handler.parameter.KillByConfigIdParams;
import org.anime_game_servers.lua.engine.LuaTable;
import static org.anime_game_servers.gi_lua.utils.ScriptUtils.luaToPos;
import static org.anime_game_servers.gi_lua.utils.ScriptUtils.posToLua;
import static org.anime_game_servers.gi_lua.script_lib.ScriptLibErrors.*; | 4,369 | public static int ExpeditionChallengeEnterRegion(GroupEventLuaContext context, boolean var1){
return context.getScriptLibHandler().ExpeditionChallengeEnterRegion(context, var1);
}
public static int StartSealBattle(GroupEventLuaContext context, int gadgetId, Object battleParamsTable) {
val battleParams = context.getEngine().getTable(battleParamsTable);
val battleType = battleParams.optInt("battle_type", -1);
if(battleType < 0 || battleType >= SealBattleType.values().length){
scriptLogger.error(() -> "[StartSealBattle] Invalid battle type " + battleType);
return -1;
}
val battleTypeEnum = SealBattleType.values()[battleType];
val handlerParams = switch (battleTypeEnum){
case NONE -> parseSealBattleNoneParams(battleParams);
case KILL_MONSTER -> parseSealBattleMonsterKillParams(battleParams);
case ENERGY_CHARGE -> parseEnergySealBattleTimeParams(battleParams);
};
return context.getScriptLibHandler().StartSealBattle(context, gadgetId, handlerParams);
}
private static SealBattleParams parseSealBattleNoneParams(LuaTable battleParams){
val radius = battleParams.optInt("radius", -1);
val inAdd = battleParams.optInt("in_add", -1);
val outSub = battleParams.optInt("out_sub", -1);
val failTime = battleParams.optInt("fail_time", -1);
val maxProgress = battleParams.optInt("max_progress", -1);
// TODO check params and maybe return error?
return new DefaultSealBattleParams(radius, inAdd, outSub, failTime, maxProgress);
}
private static SealBattleParams parseSealBattleMonsterKillParams(LuaTable battleParams){
val radius = battleParams.optInt("radius", -1);
val killTime = battleParams.optInt("kill_time", -1);
val monsterGroupId = battleParams.optInt("monster_group_id", -1);
val maxProgress = battleParams.optInt("max_progress", -1);
// TODO check params and maybe return error?
return new MonsterSealBattleParams(radius, killTime, monsterGroupId, maxProgress);
}
private static SealBattleParams parseEnergySealBattleTimeParams(LuaTable battleParams){
val radius = battleParams.optInt("radius", -1);
val battleTime = battleParams.optInt("battle_time", -1);
val monsterGroupId = battleParams.optInt("monster_group_id", -1);
val defaultKillCharge = battleParams.optInt("default_kill_charge", -1);
val autoCharge = battleParams.optInt("auto_charge", -1);
val autoDecline = battleParams.optInt("auto_decline", -1);
val maxEnergy = battleParams.optInt("max_energy", -1);
// TODO check params and maybe return error?
return new EnergySealBattleParams(radius, battleTime, monsterGroupId, defaultKillCharge, autoCharge, autoDecline, maxEnergy);
}
public static int InitTimeAxis(GroupEventLuaContext context, String var1, Object var2Table, boolean var3){
val var2 = context.getEngine().getTable(var2Table);
return context.getScriptLibHandler().InitTimeAxis(context, var1, var2, var3);
}
public static int EndTimeAxis(GroupEventLuaContext context, String var1){
return context.getScriptLibHandler().EndTimeAxis(context, var1);
}
public static int SetTeamEntityGlobalFloatValue(GroupEventLuaContext context, Object sceneUidListTable, String var2, int var3){
val sceneUidList = context.getEngine().getTable(sceneUidListTable);
return context.getScriptLibHandler().SetTeamEntityGlobalFloatValue(context, sceneUidList, var2, var3);
}
public static int SetTeamServerGlobalValue(GroupEventLuaContext context, int sceneUid, String var2, int var3){
return context.getScriptLibHandler().SetTeamServerGlobalValue(context, sceneUid, var2, var3);
}
public static int AddTeamServerGlobalValue(GroupEventLuaContext context, int ownerId, String sgvName, int value){
return context.getScriptLibHandler().AddTeamServerGlobalValue(context, ownerId, sgvName, value);
}
public static int GetTeamServerGlobalValue(GroupEventLuaContext context, int ownerId, String sgvName, int value){
return context.getScriptLibHandler().GetTeamServerGlobalValue(context, ownerId, sgvName, value);
}
public static int GetLanternRiteValue(GroupEventLuaContext context){
return context.getScriptLibHandler().GetLanternRiteValue(context);
}
public static int CreateMonsterFaceAvatar(GroupEventLuaContext context, Object rawTable) {
val table = context.getEngine().getTable(rawTable);
return context.getScriptLibHandler().CreateMonsterFaceAvatar(context, table);
}
public static int ChangeToTargetLevelTag(GroupEventLuaContext context, int var1){
return context.getScriptLibHandler().ChangeToTargetLevelTag(context, var1);
}
public static int AddSceneTag(GroupEventLuaContext context, int sceneId, int sceneTagId){
return context.getScriptLibHandler().AddSceneTag(context, sceneId, sceneTagId);
}
public static int DelSceneTag(GroupEventLuaContext context, int sceneId, int sceneTagId){
return context.getScriptLibHandler().DelSceneTag(context, sceneId, sceneTagId);
}
public static boolean CheckSceneTag(GroupEventLuaContext context, int sceneId, int sceneTagId){
return context.getScriptLibHandler().CheckSceneTag(context, sceneId, sceneTagId);
}
public static int StartHomeGallery(GroupEventLuaContext context, int galleryId, int uid){
return context.getScriptLibHandler().StartHomeGallery(context, galleryId, uid);
}
public static int StartGallery(GroupEventLuaContext context, int galleryId){
return context.getScriptLibHandler().StartGallery(context, galleryId);
}
public static int StopGallery(GroupEventLuaContext context, int galleryId, boolean var2){
return context.getScriptLibHandler().StopGallery(context, galleryId, var2);
}
public static int UpdatePlayerGalleryScore(GroupEventLuaContext context, int galleryId, Object var2Table) {
val var2 = context.getEngine().getTable(var2Table);
return context.getScriptLibHandler().UpdatePlayerGalleryScore(context, galleryId, var2);
}
public static int InitGalleryProgressScore(GroupEventLuaContext context, String name, int galleryId, Object progressTable,
int scoreUiTypeIndex, int scoreTypeIndex) {
val progress = context.getEngine().getTable(progressTable);
| package org.anime_game_servers.gi_lua.script_lib;
@LuaStatic
public class ScriptLib {
/**
* Context free functions
*/
private static KLogger scriptLogger = KotlinLogging.INSTANCE.logger(ScriptLib.class.getName());
public static ScriptLibStaticHandler staticHandler;
public static void PrintLog(String msg) {
staticHandler.PrintLog(msg);
}
public static int GetEntityType(int entityId){
return staticHandler.GetEntityType(entityId);
}
/**
* Context independent functions
*/
public static void PrintContextLog(LuaContext context, String msg) {
staticHandler.PrintContextLog(context, msg);
}
/**
* GroupEventLuaContext functions
*/
public static void PrintGroupWarning(GroupEventLuaContext context, String msg) {
context.getScriptLibHandler().PrintGroupWarning(context, msg);
}
public static int SetGadgetStateByConfigId(GroupEventLuaContext context, int configId, int gadgetState) {
return context.getScriptLibHandler().SetGadgetStateByConfigId(context, configId, gadgetState);
}
public static int SetGroupGadgetStateByConfigId(GroupEventLuaContext context, int groupId, int configId, int gadgetState) {
return context.getScriptLibHandler().SetGroupGadgetStateByConfigId(context, groupId, configId, gadgetState);
}
public static int SetWorktopOptionsByGroupId(GroupEventLuaContext context, int groupId, int configId, Object optionsTable) {
val options = context.getEngine().getTable(optionsTable);
return context.getScriptLibHandler().SetWorktopOptionsByGroupId(context, groupId, configId, options);
}
public static int SetWorktopOptions(GroupEventLuaContext context, Object rawTable){
val table = context.getEngine().getTable(rawTable);
return context.getScriptLibHandler().SetWorktopOptions(context, table);
}
public static int DelWorktopOptionByGroupId(GroupEventLuaContext context, int groupId, int configId, int option) {
return context.getScriptLibHandler().DelWorktopOptionByGroupId(context, groupId, configId, option);
}
public static int DelWorktopOption(GroupEventLuaContext context, int var1){
return context.getScriptLibHandler().DelWorktopOption(context, var1);
}
// Some fields are guessed
public static int AutoMonsterTide(GroupEventLuaContext context, int challengeIndex, int groupId, Integer[] ordersConfigId, int tideCount, int sceneLimit, int param6) {
return context.getScriptLibHandler().AutoMonsterTide(context, challengeIndex, groupId, ordersConfigId, tideCount, sceneLimit, param6);
}
public static int GoToGroupSuite(GroupEventLuaContext context, int groupId, int suite) {
return context.getScriptLibHandler().GoToGroupSuite(context, groupId, suite);
}
public static int AddExtraGroupSuite(GroupEventLuaContext context, int groupId, int suite) {
return context.getScriptLibHandler().AddExtraGroupSuite(context, groupId, suite);
}
public static int RemoveExtraGroupSuite(GroupEventLuaContext context, int groupId, int suite) {
return context.getScriptLibHandler().RemoveExtraGroupSuite(context, groupId, suite);
}
public static int KillExtraGroupSuite(GroupEventLuaContext context, int groupId, int suite) {
return context.getScriptLibHandler().KillExtraGroupSuite(context, groupId, suite);
}
public static int AddExtraFlowSuite(GroupEventLuaContext context, int groupId, int suiteId, int flowSuitePolicy){
if(flowSuitePolicy < 0 || flowSuitePolicy >= FlowSuiteOperatePolicy.values().length){
scriptLogger.error(() -> "[AddExtraFlowSuite] Invalid flow suite policy " + flowSuitePolicy);
return 1;
}
val flowSuitePolicyEnum = FlowSuiteOperatePolicy.values()[flowSuitePolicy];
return context.getScriptLibHandler().AddExtraFlowSuite(context, groupId, suiteId, flowSuitePolicyEnum);
}
public static int RemoveExtraFlowSuite(GroupEventLuaContext context, int groupId, int suiteId, int flowSuitePolicy){
if(flowSuitePolicy < 0 || flowSuitePolicy >= FlowSuiteOperatePolicy.values().length){
scriptLogger.error(() -> "[RemoveExtraFlowSuite] Invalid flow suite policy " + flowSuitePolicy);
return 1;
}
val flowSuitePolicyEnum = FlowSuiteOperatePolicy.values()[flowSuitePolicy];
return context.getScriptLibHandler().RemoveExtraFlowSuite(context, groupId, suiteId, flowSuitePolicyEnum);
}
public static int KillExtraFlowSuite(GroupEventLuaContext context, int groupId, int suiteId, int flowSuitePolicy){
if(flowSuitePolicy < 0 || flowSuitePolicy >= FlowSuiteOperatePolicy.values().length){
scriptLogger.error(() -> "[KillExtraFlowSuite] Invalid flow suite policy " + flowSuitePolicy);
return 1;
}
val flowSuitePolicyEnum = FlowSuiteOperatePolicy.values()[flowSuitePolicy];
return context.getScriptLibHandler().KillExtraFlowSuite(context, groupId, suiteId, flowSuitePolicyEnum);
}
public static int ActiveChallenge(GroupEventLuaContext context, int challengeIndex, int challengeId, int timeLimitOrGroupId, int groupId, int objectiveKills, int param5) {
return context.getScriptLibHandler().ActiveChallenge(context, challengeIndex, challengeId, timeLimitOrGroupId, groupId, objectiveKills, param5);
}
public static int StartChallenge(GroupEventLuaContext context, int challengeIndex, int challengeId, Object challengeParams) {
val conditionParamTable = context.getEngine().getTable(challengeParams);
return context.getScriptLibHandler().StartChallenge(context, challengeIndex, challengeId, conditionParamTable);
}
public static int StopChallenge(GroupEventLuaContext context, int challengeIndex, int result) {
return context.getScriptLibHandler().StopChallenge(context, challengeIndex, result);
}
/**
* Adds or removed time from the challenge
* TODO verify and implement
* @param context
* @param challengeId The active target challenges id
* @param duration The duration to add or remove
* @return 0 if success, 1 if no challenge is active, 2 if the challenge id doesn't match the active challenge,
* 3 if modifying the duration failed
*/
public static int AddChallengeDuration(GroupEventLuaContext context, int challengeId, int duration) {
return context.getScriptLibHandler().AddChallengeDuration(context, challengeId, duration);
}
public static int GetGroupMonsterCountByGroupId(GroupEventLuaContext context, int groupId) {
return context.getScriptLibHandler().GetGroupMonsterCountByGroupId(context, groupId);
}
// TODO check existence
public static int CreateVariable(GroupEventLuaContext context, String type, Object value) {
//TODO implement
switch (type){
case "int":
default:
}
return 0;
}
// TODO check existence
public static int SetVariableValue(GroupEventLuaContext context, int var1) {
//TODO implement var1 type
return 0;
}
public static int GetVariableValue(GroupEventLuaContext context, int var1) {
//TODO implement var1 type
return 0;
}
public static int GetGroupVariableValue(GroupEventLuaContext context, String var) {
return context.getScriptLibHandler().GetGroupVariableValue(context, var);
}
public static int GetGroupVariableValueByGroup(GroupEventLuaContext context, String name, int groupId){
return context.getScriptLibHandler().GetGroupVariableValueByGroup(context, name, groupId);
}
public static int SetGroupVariableValue(GroupEventLuaContext context, String varName, int value) {
return context.getScriptLibHandler().SetGroupVariableValue(context, varName, value);
}
public static int SetGroupVariableValueByGroup(GroupEventLuaContext context, String key, int value, int groupId){
return context.getScriptLibHandler().SetGroupVariableValueByGroup(context, key, value, groupId);
}
public static int ChangeGroupVariableValue(GroupEventLuaContext context, String varName, int value) {
return context.getScriptLibHandler().ChangeGroupVariableValue(context, varName, value);
}
public static int ChangeGroupVariableValueByGroup(GroupEventLuaContext context, String name, int value, int groupId){
return context.getScriptLibHandler().ChangeGroupVariableValueByGroup(context, name, value, groupId);
}
/**
* Set the actions and triggers to designated group
*/
public static int RefreshGroup(GroupEventLuaContext context, Object rawTable) {
val table = context.getEngine().getTable(rawTable);
return context.getScriptLibHandler().RefreshGroup(context, table);
}
public static int GetRegionEntityCount(GroupEventLuaContext context, Object rawTable) {
val table = context.getEngine().getTable(rawTable);
int regionId = table.getInt("region_eid");
int entityType = table.getInt("entity_type");
if(entityType < 0 || entityType >= EntityType.values().length){
scriptLogger.error(() -> "[GetRegionEntityCount] Invalid entity type " + entityType);
return 0;
}
val entityTypeEnum = EntityType.values()[entityType];
return context.getScriptLibHandler().GetRegionEntityCount(context, regionId, entityTypeEnum);
}
public int GetRegionConfigId(GroupEventLuaContext context, Object rawTable){
val table = context.getEngine().getTable(rawTable);
val regionEid = table.getInt("region_eid");
return context.getScriptLibHandler().GetRegionConfigId(context, regionEid);
}
public static int TowerCountTimeStatus(GroupEventLuaContext context, int isDone, int var2){
return context.getScriptLibHandler().TowerCountTimeStatus(context, isDone, var2);
}
public static int GetGroupMonsterCount(GroupEventLuaContext context){
return context.getScriptLibHandler().GetGroupMonsterCount(context);
}
public static int SetMonsterBattleByGroup(GroupEventLuaContext context, int configId, int groupId) {
return context.getScriptLibHandler().SetMonsterBattleByGroup(context, configId, groupId);
}
public static int CauseDungeonFail(GroupEventLuaContext context){
return context.getScriptLibHandler().CauseDungeonFail(context);
}
public static int CauseDungeonSuccess(GroupEventLuaContext context){
return context.getScriptLibHandler().CauseDungeonSuccess(context);
}
public static int SetEntityServerGlobalValueByConfigId(GroupEventLuaContext context, int cfgId, String sgvName, int value){
return context.getScriptLibHandler().SetEntityServerGlobalValueByConfigId(context, cfgId, sgvName, value);
}
public static int SetGroupLogicStateValue(GroupEventLuaContext context, String sgvName, int value){
return context.getScriptLibHandler().SetGroupLogicStateValue(context, sgvName, value);
}
public static int SetIsAllowUseSkill(GroupEventLuaContext context, int canUse){
return context.getScriptLibHandler().SetIsAllowUseSkill(context, canUse);
}
public static int KillEntityByConfigId(LuaContext context, Object rawTable) {
val table = context.getEngine().getTable(rawTable);
val configId = table.optInt("config_id", 0);
if (configId == 0){
scriptLogger.error(() -> "[KillEntityByConfigId] Invalid config id " + configId);
return INVALID_PARAMETER.getValue();
}
val groupId = table.optInt("group_id", 0);
val entityTypeValue = table.optInt("entity_type", 0);
if(entityTypeValue < 0 || entityTypeValue >= EntityType.values().length){
scriptLogger.error(() -> "[KillEntityByConfigId] Invalid entity type " + entityTypeValue);
return INVALID_PARAMETER.getValue();
}
val entityType = EntityType.values()[entityTypeValue];
val params = new KillByConfigIdParams(groupId, configId, entityType);
if (context instanceof GroupEventLuaContext gContext){
return gContext.getScriptLibHandlerProvider().getScriptLibHandler().KillEntityByConfigId(gContext, params);
} else if (context instanceof ControllerLuaContext cContext) {
return cContext.getScriptLibHandlerProvider().getGadgetControllerHandler().KillEntityByConfigId(cContext, params);
}
scriptLogger.error(() -> "[KillEntityByConfigId] unknown context type " + context.getClass().getName());
return NOT_IMPLEMENTED.getValue();
}
public static int CreateMonster(GroupEventLuaContext context, Object rawTable){
val table = context.getEngine().getTable(rawTable);
return context.getScriptLibHandler().CreateMonster(context, table);
}
public static int TowerMirrorTeamSetUp(GroupEventLuaContext context, int team, int var1) {
return context.getScriptLibHandler().TowerMirrorTeamSetUp(context, team, var1);
}
public static int CreateGadget(GroupEventLuaContext context, Object rawTable){
val table = context.getEngine().getTable(rawTable);
return context.getScriptLibHandler().CreateGadget(context, table);
}
/**
* Spawn a gadget from the caller group at the specified position
* @param configId The config id of the gadget in the calling group
* @param posTable The position to spawn the gadget at
* @param rotTable The rotation of the gadget when spawned
*/
public static int CreateGadgetByConfigIdByPos(GroupEventLuaContext context, int configId, Object posTable, Object rotTable){
val luaPos = context.getEngine().getTable(posTable);
val luaRot = context.getEngine().getTable(rotTable);
return context.getScriptLibHandler().CreateGadgetByConfigIdByPos(context, configId, luaToPos(luaPos), luaToPos(luaRot));
}
/**
* TODO parse the table before passing it to the handler
* Spawns a gadget based on the caller groups gadget with cfg id matching the specified id. It also applies additional parameters based on the parameters
* @param creationParamsTable parameters to spawn a gadget with
*/
public static int CreateGadgetByParamTable(GroupEventLuaContext context, Object creationParamsTable){
val table = context.getEngine().getTable(creationParamsTable);
return context.getScriptLibHandler().CreateGadget(context, table);
}
public static int CreateVehicle(GroupEventLuaContext context, int uid, int gadgetId, Object posTable, Object rotTable){
val luaPos = context.getEngine().getTable(posTable);
val luaRot = context.getEngine().getTable(rotTable);
return context.getScriptLibHandler().CreateVehicle(context, uid, gadgetId, luaToPos(luaPos), luaToPos(luaRot));
}
public static int CheckRemainGadgetCountByGroupId(GroupEventLuaContext context, Object rawTable) {
val table = context.getEngine().getTable(rawTable);
return context.getScriptLibHandler().CheckRemainGadgetCountByGroupId(context, table);
}
public static int GetGadgetStateByConfigId(GroupEventLuaContext context, int groupId, int configId){
return context.getScriptLibHandler().GetGadgetStateByConfigId(context, groupId, configId);
}
public static int MarkPlayerAction(GroupEventLuaContext context, int var1, int var2, int var3){
return context.getScriptLibHandler().MarkPlayerAction(context, var1, var2, var3);
}
public static int AddQuestProgress(GroupEventLuaContext context, String eventNotifyName){
return context.getScriptLibHandler().AddQuestProgress(context, eventNotifyName);
}
/**
* change the state of gadget
*/
public static int ChangeGroupGadget(GroupEventLuaContext context, Object rawTable) {
val table = context.getEngine().getTable(rawTable);
return context.getScriptLibHandler().ChangeGroupGadget(context, table);
}
public static int GetSceneOwnerUid(GroupEventLuaContext context){
return context.getScriptLibHandler().GetSceneOwnerUid(context);
}
public static int GetHostQuestState(GroupEventLuaContext context, int questId){
return context.getScriptLibHandler().GetHostQuestState(context, questId).getValue();
}
public static int GetQuestState(GroupEventLuaContext context, int entityId, int questId){
return context.getScriptLibHandler().GetQuestState(context, entityId, questId).getValue();
}
public static int ShowReminder(GroupEventLuaContext context, int reminderId){
return context.getScriptLibHandler().ShowReminder(context, reminderId);
}
public static int RemoveEntityByConfigId(GroupEventLuaContext context, int groupId, int entityTypeValue, int configId){
val entityType = EntityType.values()[entityTypeValue];
return context.getScriptLibHandler().RemoveEntityByConfigId(context, groupId, entityType, configId);
}
public static int CreateGroupTimerEvent(GroupEventLuaContext context, int groupID, String source, double time) {
return context.getScriptLibHandler().CreateGroupTimerEvent(context, groupID, source, time);
}
public static int CancelGroupTimerEvent(GroupEventLuaContext context, int groupID, String source) {
return context.getScriptLibHandler().CancelGroupTimerEvent(context, groupID, source);
}
public static int GetGroupSuite(GroupEventLuaContext context, int groupId) {
return context.getScriptLibHandler().GetGroupSuite(context, groupId);
}
public static int SetGroupReplaceable(GroupEventLuaContext context, int groupId, boolean value) {
return context.getScriptLibHandler().SetGroupReplaceable(context, groupId, value);
}
public static Object GetSceneUidList(GroupEventLuaContext context){
val list = context.getScriptLibHandler().GetSceneUidList(context);
val result = context.getEngine().createTable();
for(int i = 0; i< list.length; i++){
result.set(Integer.toString(i+1), list[i]);
}
return result;
}
public static int GetSeaLampActivityPhase(GroupEventLuaContext context){
return context.getScriptLibHandler().GetSeaLampActivityPhase(context);
}
public static int GadgetPlayUidOp(GroupEventLuaContext context, int groupId, int gadget_crucible, int var3, int var4, String var5, int var6 ){
return context.getScriptLibHandler().GadgetPlayUidOp(context, groupId, gadget_crucible, var3, var4, var5, var6);
}
public static long GetServerTime(GroupEventLuaContext context){
return context.getScriptLibHandler().GetServerTime(context);
}
public static long GetServerTimeByWeek(GroupEventLuaContext context){
return context.getScriptLibHandler().GetServerTimeByWeek(context);
}
public static int GetCurTriggerCount(GroupEventLuaContext context){
return context.getScriptLibHandler().GetCurTriggerCount(context);
}
public static int GetChannellerSlabLoopDungeonLimitTime(GroupEventLuaContext context){
return context.getScriptLibHandler().GetChannellerSlabLoopDungeonLimitTime(context);
}
public static boolean IsPlayerAllAvatarDie(GroupEventLuaContext context, int sceneUid){
return context.getScriptLibHandler().IsPlayerAllAvatarDie(context, sceneUid);
}
public static int sendShowCommonTipsToClient(GroupEventLuaContext context, String title, String content, int closeTime) {
return context.getScriptLibHandler().sendShowCommonTipsToClient(context, title, content, closeTime);
}
public static int sendCloseCommonTipsToClient(GroupEventLuaContext context){
return context.getScriptLibHandler().sendCloseCommonTipsToClient(context);
}
public static int updateBundleMarkShowStateByGroupId(GroupEventLuaContext context, int groupId, boolean val2){
return context.getScriptLibHandler().updateBundleMarkShowStateByGroupId(context, groupId, val2);
}
public static int CreateFatherChallenge(GroupEventLuaContext context, int challengeIndex, int challengeId, int timeLimit, Object conditionTable){
val conditionLuaTable = context.getEngine().getTable(conditionTable);
return context.getScriptLibHandler().CreateFatherChallenge(context, challengeIndex, challengeId, timeLimit, conditionLuaTable);
}
public static int StartFatherChallenge(GroupEventLuaContext context, int challengeIndex){
return context.getScriptLibHandler().StartFatherChallenge(context, challengeIndex);
}
public static int ModifyFatherChallengeProperty(GroupEventLuaContext context, int challengeId, int propertyTypeIndex, int value){
val propertyType = FatherChallengeProperty.values()[propertyTypeIndex];
return context.getScriptLibHandler().ModifyFatherChallengeProperty(context, challengeId, propertyType, value);
}
public static int SetChallengeEventMark(GroupEventLuaContext context, int challengeId, int markType){
if(markType < 0 || markType >= ChallengeEventMarkType.values().length){
scriptLogger.error(() -> "[SetChallengeEventMark] Invalid mark type " + markType);
return 1;
}
val markTypeEnum = ChallengeEventMarkType.values()[markType];
return context.getScriptLibHandler().SetChallengeEventMark(context, challengeId, markTypeEnum);
}
public static int AttachChildChallenge(GroupEventLuaContext context, int fatherChallengeIndex, int childChallengeIndex,
int childChallengeId, Object var4Table, Object var5Table, Object var6Table){
val conditionArray = context.getEngine().getTable(var4Table);
val var5 = context.getEngine().getTable(var5Table);
val conditionTable = context.getEngine().getTable(var6Table);
return context.getScriptLibHandler().AttachChildChallenge(context, fatherChallengeIndex, childChallengeIndex,
childChallengeId, conditionArray, var5, conditionTable);
}
public static int CreateEffigyChallengeMonster(GroupEventLuaContext context, int var1, Object var2Table){
val var2 = context.getEngine().getTable(var2Table);
return context.getScriptLibHandler().CreateEffigyChallengeMonster(context, var1, var2);
}
public static int GetEffigyChallengeMonsterLevel(GroupEventLuaContext context){
return context.getScriptLibHandler().GetEffigyChallengeMonsterLevel(context);
}
public static int AddTeamEntityGlobalFloatValue(GroupEventLuaContext context, Object sceneUidListTable, String var2, int var3){
val sceneUidList = context.getEngine().getTable(sceneUidListTable);
return context.getScriptLibHandler().AddTeamEntityGlobalFloatValue(context, sceneUidList, var2, var3);
}
public static int CreateBlossomChestByGroupId(GroupEventLuaContext context, int groupId, int chestConfigId){
return context.getScriptLibHandler().CreateBlossomChestByGroupId(context, groupId, chestConfigId);
}
public static int GetBlossomScheduleStateByGroupId(GroupEventLuaContext context, int groupId){
return context.getScriptLibHandler().GetBlossomScheduleStateByGroupId(context, groupId);
}
public static int SetBlossomScheduleStateByGroupId(GroupEventLuaContext context, int groupId, int state){
return context.getScriptLibHandler().SetBlossomScheduleStateByGroupId(context, groupId, state);
}
public static int RefreshBlossomGroup(GroupEventLuaContext context, Object rawTable) {
val configTable = context.getEngine().getTable(rawTable);
return context.getScriptLibHandler().RefreshBlossomGroup(context, configTable);
}
public static int RefreshBlossomDropRewardByGroupId(GroupEventLuaContext context, int groupId){
return context.getScriptLibHandler().RefreshBlossomDropRewardByGroupId(context, groupId);
}
public static int AddBlossomScheduleProgressByGroupId(GroupEventLuaContext context, int groupId){
return context.getScriptLibHandler().AddBlossomScheduleProgressByGroupId(context, groupId);
}
public static int GetBlossomRefreshTypeByGroupId(GroupEventLuaContext context, int groupId){
return context.getScriptLibHandler().GetBlossomRefreshTypeByGroupId(context, groupId);
}
public static int RefreshHuntingClueGroup(GroupEventLuaContext context){
return context.getScriptLibHandler().RefreshHuntingClueGroup(context);
}
public static int GetHuntingMonsterExtraSuiteIndexVec(GroupEventLuaContext context){
return context.getScriptLibHandler().GetHuntingMonsterExtraSuiteIndexVec(context);
}
public static int SetGroupTempValue(GroupEventLuaContext context, String name, int value, Object var3Table) {
val var3 = context.getEngine().getTable(var3Table);
return context.getScriptLibHandler().SetGroupTempValue(context, name, value, var3);
}
public static int GetGroupTempValue(GroupEventLuaContext context, String name, Object var2Table) {
val var2 = context.getEngine().getTable(var2Table);
return context.getScriptLibHandler().GetGroupTempValue(context, name, var2);
}
public static int FinishExpeditionChallenge(GroupEventLuaContext context){
return context.getScriptLibHandler().FinishExpeditionChallenge(context);
}
public static int ExpeditionChallengeEnterRegion(GroupEventLuaContext context, boolean var1){
return context.getScriptLibHandler().ExpeditionChallengeEnterRegion(context, var1);
}
public static int StartSealBattle(GroupEventLuaContext context, int gadgetId, Object battleParamsTable) {
val battleParams = context.getEngine().getTable(battleParamsTable);
val battleType = battleParams.optInt("battle_type", -1);
if(battleType < 0 || battleType >= SealBattleType.values().length){
scriptLogger.error(() -> "[StartSealBattle] Invalid battle type " + battleType);
return -1;
}
val battleTypeEnum = SealBattleType.values()[battleType];
val handlerParams = switch (battleTypeEnum){
case NONE -> parseSealBattleNoneParams(battleParams);
case KILL_MONSTER -> parseSealBattleMonsterKillParams(battleParams);
case ENERGY_CHARGE -> parseEnergySealBattleTimeParams(battleParams);
};
return context.getScriptLibHandler().StartSealBattle(context, gadgetId, handlerParams);
}
private static SealBattleParams parseSealBattleNoneParams(LuaTable battleParams){
val radius = battleParams.optInt("radius", -1);
val inAdd = battleParams.optInt("in_add", -1);
val outSub = battleParams.optInt("out_sub", -1);
val failTime = battleParams.optInt("fail_time", -1);
val maxProgress = battleParams.optInt("max_progress", -1);
// TODO check params and maybe return error?
return new DefaultSealBattleParams(radius, inAdd, outSub, failTime, maxProgress);
}
private static SealBattleParams parseSealBattleMonsterKillParams(LuaTable battleParams){
val radius = battleParams.optInt("radius", -1);
val killTime = battleParams.optInt("kill_time", -1);
val monsterGroupId = battleParams.optInt("monster_group_id", -1);
val maxProgress = battleParams.optInt("max_progress", -1);
// TODO check params and maybe return error?
return new MonsterSealBattleParams(radius, killTime, monsterGroupId, maxProgress);
}
private static SealBattleParams parseEnergySealBattleTimeParams(LuaTable battleParams){
val radius = battleParams.optInt("radius", -1);
val battleTime = battleParams.optInt("battle_time", -1);
val monsterGroupId = battleParams.optInt("monster_group_id", -1);
val defaultKillCharge = battleParams.optInt("default_kill_charge", -1);
val autoCharge = battleParams.optInt("auto_charge", -1);
val autoDecline = battleParams.optInt("auto_decline", -1);
val maxEnergy = battleParams.optInt("max_energy", -1);
// TODO check params and maybe return error?
return new EnergySealBattleParams(radius, battleTime, monsterGroupId, defaultKillCharge, autoCharge, autoDecline, maxEnergy);
}
public static int InitTimeAxis(GroupEventLuaContext context, String var1, Object var2Table, boolean var3){
val var2 = context.getEngine().getTable(var2Table);
return context.getScriptLibHandler().InitTimeAxis(context, var1, var2, var3);
}
public static int EndTimeAxis(GroupEventLuaContext context, String var1){
return context.getScriptLibHandler().EndTimeAxis(context, var1);
}
public static int SetTeamEntityGlobalFloatValue(GroupEventLuaContext context, Object sceneUidListTable, String var2, int var3){
val sceneUidList = context.getEngine().getTable(sceneUidListTable);
return context.getScriptLibHandler().SetTeamEntityGlobalFloatValue(context, sceneUidList, var2, var3);
}
public static int SetTeamServerGlobalValue(GroupEventLuaContext context, int sceneUid, String var2, int var3){
return context.getScriptLibHandler().SetTeamServerGlobalValue(context, sceneUid, var2, var3);
}
public static int AddTeamServerGlobalValue(GroupEventLuaContext context, int ownerId, String sgvName, int value){
return context.getScriptLibHandler().AddTeamServerGlobalValue(context, ownerId, sgvName, value);
}
public static int GetTeamServerGlobalValue(GroupEventLuaContext context, int ownerId, String sgvName, int value){
return context.getScriptLibHandler().GetTeamServerGlobalValue(context, ownerId, sgvName, value);
}
public static int GetLanternRiteValue(GroupEventLuaContext context){
return context.getScriptLibHandler().GetLanternRiteValue(context);
}
public static int CreateMonsterFaceAvatar(GroupEventLuaContext context, Object rawTable) {
val table = context.getEngine().getTable(rawTable);
return context.getScriptLibHandler().CreateMonsterFaceAvatar(context, table);
}
public static int ChangeToTargetLevelTag(GroupEventLuaContext context, int var1){
return context.getScriptLibHandler().ChangeToTargetLevelTag(context, var1);
}
public static int AddSceneTag(GroupEventLuaContext context, int sceneId, int sceneTagId){
return context.getScriptLibHandler().AddSceneTag(context, sceneId, sceneTagId);
}
public static int DelSceneTag(GroupEventLuaContext context, int sceneId, int sceneTagId){
return context.getScriptLibHandler().DelSceneTag(context, sceneId, sceneTagId);
}
public static boolean CheckSceneTag(GroupEventLuaContext context, int sceneId, int sceneTagId){
return context.getScriptLibHandler().CheckSceneTag(context, sceneId, sceneTagId);
}
public static int StartHomeGallery(GroupEventLuaContext context, int galleryId, int uid){
return context.getScriptLibHandler().StartHomeGallery(context, galleryId, uid);
}
public static int StartGallery(GroupEventLuaContext context, int galleryId){
return context.getScriptLibHandler().StartGallery(context, galleryId);
}
public static int StopGallery(GroupEventLuaContext context, int galleryId, boolean var2){
return context.getScriptLibHandler().StopGallery(context, galleryId, var2);
}
public static int UpdatePlayerGalleryScore(GroupEventLuaContext context, int galleryId, Object var2Table) {
val var2 = context.getEngine().getTable(var2Table);
return context.getScriptLibHandler().UpdatePlayerGalleryScore(context, galleryId, var2);
}
public static int InitGalleryProgressScore(GroupEventLuaContext context, String name, int galleryId, Object progressTable,
int scoreUiTypeIndex, int scoreTypeIndex) {
val progress = context.getEngine().getTable(progressTable);
| if(scoreUiTypeIndex < 0 || scoreUiTypeIndex >= GalleryProgressScoreUIType.values().length){ | 3 | 2023-10-07 16:45:54+00:00 | 8k |
PDC2023/project | src/main/java/pdc/project/entity/Coin.java | [
{
"identifier": "Universe",
"path": "src/main/java/pdc/project/Universe.java",
"snippet": "public final class Universe {\r\n\r\n public Player player = new Player(this, 0, 0);\r\n private int score = 0;\r\n public final Main main;\r\n\r\n public Set<Entity> entities = new HashSet<>();\r\n public List<Entity> entitiesToAdd = new ArrayList<>();\r\n public List<Entity> entitiesToRemove = new ArrayList<>();\r\n\r\n public SavePoint lastSavePoint;\r\n\r\n /**\r\n * Constructs a new game universe with the specified main application instance.\r\n *\r\n * @param main The main application instance associated with this universe.\r\n */\r\n public Universe(Main main) {\r\n this.main = main;\r\n entities.add(player);\r\n lastSavePoint = new SavePoint(0, this, 0, 0);\r\n entities.add(lastSavePoint);\r\n }\r\n\r\n public boolean spacePressed() {\r\n return pressedKeys.contains(KeyEvent.VK_SPACE);\r\n }\r\n\r\n /**\r\n * Gets a list of entities that are colliding with the specified entity.\r\n *\r\n * @param entity The entity for which collision detection is performed.\r\n * @return A list of entities that are colliding with the specified entity.\r\n */\r\n public List<Entity> getCollisionEntities(Entity entity) {\r\n var collisionEntities = new ArrayList<Entity>();\r\n for (var otherEntity : entities) {\r\n if (otherEntity == entity) {\r\n continue;\r\n }\r\n if (Collision.checkCollision(entity, otherEntity)) {\r\n collisionEntities.add(otherEntity);\r\n }\r\n }\r\n return collisionEntities;\r\n }\r\n\r\n public List<CollisionRecord> getCollisionRecords(Entity entity) {\r\n var collisionEntities = new ArrayList<CollisionRecord>();\r\n for (var otherEntity : entities) {\r\n if (otherEntity == entity) {\r\n continue;\r\n }\r\n var result = Collision.getCollision(entity, otherEntity);\r\n if (result.getState() != CollisionState.NONE) {\r\n collisionEntities.add(new CollisionRecord(otherEntity, result));\r\n }\r\n }\r\n return collisionEntities;\r\n }\r\n\r\n public void addScore(int score) {\r\n this.score += score;\r\n }\r\n\r\n public int getCollectedCoins() {\r\n return score;\r\n }\r\n\r\n\r\n /**\r\n * Fixes overlapping entities and returns a list of collision records.\r\n *\r\n * @param entity The entity for which collision resolution is performed.\r\n * @return A list of collision records indicating resolved collisions.\r\n */\r\n public List<CollisionRecord> fixOverlappingAndGetCollisionEntities(Entity entity) {\r\n var collisionEntities = new ArrayList<CollisionRecord>();\r\n for (var otherEntity : entities) {\r\n if (otherEntity == entity) {\r\n continue;\r\n }\r\n var result = Collision.getCollision(entity, otherEntity);\r\n if (result.getState() != CollisionState.NONE) {\r\n collisionEntities.add(new CollisionRecord(otherEntity, result));\r\n }\r\n if (entity instanceof MoveableEntity && !(otherEntity instanceof NoPhysicalCollisionEntity)) {\r\n if (result.getState() == CollisionState.OVERLAPPING) {\r\n var direction = result.getDirection();\r\n var otherBox = otherEntity.getCollisionBox();\r\n var entityBox = entity.getCollisionBox();\r\n var moveableEntity = (MoveableEntity) entity;\r\n\r\n int x;\r\n int y;\r\n switch (direction) {\r\n case DOWN:\r\n var otherTopY = otherEntity.getY() - otherBox.getHeight() / 2;\r\n y = otherTopY - entityBox.getHeight() / 2;\r\n moveableEntity.setY(y);\r\n if (moveableEntity instanceof EntityWithVelocity && ((EntityWithVelocity) moveableEntity).getVelocityY() > 0) {\r\n ((EntityWithVelocity) moveableEntity).setVelocityY(0);\r\n }\r\n break;\r\n case UP:\r\n var otherBottomY = otherEntity.getY() + otherBox.getHeight() / 2;\r\n y = otherBottomY + entityBox.getHeight() / 2;\r\n moveableEntity.setY(y);\r\n if (moveableEntity instanceof EntityWithVelocity && ((EntityWithVelocity) moveableEntity).getVelocityY() < 0) {\r\n ((EntityWithVelocity) moveableEntity).setVelocityY(0);\r\n }\r\n break;\r\n case LEFT:\r\n var otherRightX = otherEntity.getX() + otherBox.getWidth() / 2;\r\n x = otherRightX + entityBox.getWidth() / 2;\r\n moveableEntity.setX(x);\r\n if (moveableEntity instanceof EntityWithVelocity && ((EntityWithVelocity) moveableEntity).getVelocityX() < 0) {\r\n ((EntityWithVelocity) moveableEntity).setVelocityX(0);\r\n }\r\n break;\r\n case RIGHT:\r\n var otherLeftX = otherEntity.getX() - otherBox.getWidth() / 2;\r\n x = otherLeftX - entityBox.getWidth() / 2;\r\n moveableEntity.setX(x);\r\n if (moveableEntity instanceof EntityWithVelocity && ((EntityWithVelocity) moveableEntity).getVelocityX() > 0) {\r\n ((EntityWithVelocity) moveableEntity).setVelocityX(0);\r\n }\r\n break;\r\n }\r\n }\r\n }\r\n }\r\n return collisionEntities;\r\n }\r\n\r\n public Set<Integer> pressedKeys = new HashSet<>();\r\n\r\n public boolean upPressed() {\r\n return pressedKeys.contains(KeyEvent.VK_UP) || pressedKeys.contains(KeyEvent.VK_W);\r\n }\r\n\r\n public boolean leftPressed() {\r\n return pressedKeys.contains(KeyEvent.VK_LEFT) || pressedKeys.contains(KeyEvent.VK_A);\r\n }\r\n\r\n public boolean rightPressed() {\r\n return pressedKeys.contains(KeyEvent.VK_RIGHT) || pressedKeys.contains(KeyEvent.VK_D);\r\n }\r\n\r\n public boolean downPressed() {\r\n return pressedKeys.contains(KeyEvent.VK_DOWN) || pressedKeys.contains(KeyEvent.VK_S);\r\n }\r\n\r\n public void goingToSavePoint() {\r\n var effect = new SavePointResumeEffect(this, player.getX(), player.getY());\r\n effect.facingLeft = player.facingLeft;\r\n entitiesToAdd.add(effect);\r\n entitiesToRemove.add(player);\r\n main.gameScreen.pauseForReturningToSavePoint();\r\n SoundEffect.play(SoundEffect.death);\r\n Timer timer = new Timer(500, e -> {\r\n effect.die();\r\n entitiesToAdd.add(player);\r\n main.gameScreen.resumeForReturningToSavePoint();\r\n player.setVelocityX(0);\r\n player.setVelocityY(0);\r\n player.setX(lastSavePoint.getX());\r\n player.setY(lastSavePoint.getY());\r\n });\r\n timer.setRepeats(false);\r\n timer.start();\r\n }\r\n\r\n public void win() {\r\n main.switchToWinScreen();\r\n }\r\n\r\n private void checkPlayerOutOfBound() {\r\n if (this.player.getY() > 1024) {\r\n this.player.goingToSavePoint();\r\n }\r\n }\r\n\r\n public void preTick() {\r\n this.entities.addAll(this.entitiesToAdd);\r\n this.entitiesToRemove.forEach(this.entities::remove);\r\n this.entitiesToAdd.clear();\r\n this.entitiesToRemove.clear();\r\n }\r\n\r\n public void nextLevel() {\r\n main.switchToLevel1();\r\n }\r\n\r\n public void tick() {\r\n var deaths = new ArrayList<Entity>();\r\n for (Entity entity : entities) {\r\n if (entity.dead()) {\r\n deaths.add(entity);\r\n continue;\r\n }\r\n entity.tick();\r\n }\r\n deaths.forEach(entities::remove);\r\n checkPlayerOutOfBound();\r\n }\r\n\r\n}\r"
},
{
"identifier": "Utils",
"path": "src/main/java/pdc/project/Utils.java",
"snippet": "public final class Utils {\r\n\r\n /**\r\n * Loads an image from the specified resource path.\r\n *\r\n * @param path The path to the image resource.\r\n * @return The loaded image.\r\n */\r\n public static Image loadImage(String path) {\r\n return new ImageIcon(Objects.requireNonNull(Utils.class.getResource(path))).getImage();\r\n }\r\n\r\n /**\r\n * Loads an image from the specified resource path and scales it by the given ratio.\r\n *\r\n * @param path The path to the image resource.\r\n * @param ratio The scaling ratio.\r\n * @return The loaded and scaled image.\r\n */\r\n public static Image loadImage(String path, double ratio) {\r\n return scaleImageByRatio(loadImage(path), ratio);\r\n }\r\n\r\n /**\r\n * Scales an image to the specified width and height.\r\n *\r\n * @param image The image to be scaled.\r\n * @param width The target width.\r\n * @param height The target height.\r\n * @return The scaled image.\r\n */\r\n public static Image scaleImage(Image image, int width, int height) {\r\n return image.getScaledInstance(width, height, Image.SCALE_DEFAULT);\r\n }\r\n\r\n /**\r\n * Scales an image by the specified ratio.\r\n *\r\n * @param image The image to be scaled.\r\n * @param ratio The scaling ratio.\r\n * @return The scaled image.\r\n */\r\n public static Image scaleImageByRatio(Image image, double ratio) {\r\n int newWidth = (int) (image.getWidth(null) * ratio);\r\n int newHeight = (int) (image.getHeight(null) * ratio);\r\n return scaleImage(image, newWidth, newHeight);\r\n }\r\n\r\n /**\r\n * Draws an image on a {@link Graphics2D} context with the center of the image positioned at (x, y).\r\n *\r\n * @param g2d The {@link Graphics2D} context used for drawing.\r\n * @param image The image to be drawn.\r\n * @param x The x-coordinate of the center of the image.\r\n * @param y The y-coordinate of the center of the image.\r\n */\r\n public static void drawImage(Graphics2D g2d, Image image, int x, int y) {\r\n g2d.drawImage(image, (int) x - image.getWidth(null) / 2, (int) y - image.getHeight(null) / 2, null);\r\n }\r\n\r\n /**\r\n * Draws an image flipped horizontally on a {@link Graphics2D} context with the center of the image positioned at (x, y).\r\n *\r\n * @param g2d The {@link Graphics2D} context used for drawing.\r\n * @param image The image to be drawn.\r\n * @param x The x-coordinate of the center of the image.\r\n * @param y The y-coordinate of the center of the image.\r\n */\r\n public static void drawImageFlipX(Graphics2D g2d, Image image, int x, int y) {\r\n g2d.drawImage(image, (int) x + image.getWidth(null) / 2, (int) y - image.getHeight(null) / 2, -image.getWidth(null), image.getHeight(null), null);\r\n }\r\n}\r"
},
{
"identifier": "Database",
"path": "src/main/java/pdc/project/Database.java",
"snippet": "public interface Database {\r\n\r\n /**\r\n * Saves the highest score achieved by a user for a specific level in the database.\r\n *\r\n * @param userName The username of the player.\r\n * @param levelID The identifier of the level.\r\n * @param score The highest score achieved by the player for the level.\r\n * @throws SQLException If there is an error while saving the score in the database.\r\n */\r\n void saveHighestScore(String userName, int levelID, int score) throws SQLException;\r\n\r\n /**\r\n * Queries the highest score achieved by a user for a specific level from the database.\r\n *\r\n * @param userName The username of the player.\r\n * @param levelID The identifier of the level.\r\n * @return The highest score achieved by the player for the level.\r\n * @throws SQLException If there is an error while querying the score from the database.\r\n */\r\n int queryScores(String userName, int levelID) throws SQLException;\r\n\r\n /**\r\n * Clears the database, removing all stored data.\r\n *\r\n * @throws SQLException If there is an error while clearing the database.\r\n */\r\n void clear() throws SQLException;\r\n\r\n /**\r\n * Retrieves a configuration value from the database based on the provided key.\r\n * If the key is not found, the defaultValue is returned.\r\n *\r\n * @param key The key of the configuration value.\r\n * @param defaultValue The default value to be returned if the key is not found.\r\n * @return The value associated with the key or the defaultValue if the key is not found.\r\n * @throws SQLException If there is an error while querying the configuration value from the database.\r\n */\r\n String getConfigValue(String key, String defaultValue) throws SQLException;\r\n\r\n /**\r\n * Saves a configuration key-value pair in the database.\r\n *\r\n * @param key The key of the configuration value.\r\n * @param value The value to be associated with the key.\r\n * @throws SQLException If there is an error while saving the configuration in the database.\r\n */\r\n void saveConfig(String key, String value) throws SQLException;\r\n}\r"
},
{
"identifier": "DatabaseDerby",
"path": "src/main/java/pdc/project/DatabaseDerby.java",
"snippet": "public class DatabaseDerby implements Closeable, Database {\r\n private final Connection conn;\r\n\r\n public DatabaseDerby() throws SQLException {\r\n var DB_URL = \"jdbc:derby:pdcDatabase;create=true\";\r\n conn = DriverManager.getConnection(DB_URL);\r\n createHighscoresTableIfNotExists();\r\n createConfigTableIfNotExists();\r\n }\r\n\r\n private void createHighscoresTableIfNotExists() throws SQLException {\r\n DatabaseMetaData meta = conn.getMetaData();\r\n ResultSet resultSet = meta.getTables(null, null, \"HIGHSCORES\", new String[]{\"TABLE\"});\r\n if (!resultSet.next()) {\r\n String createTableSQL = \"CREATE TABLE HIGHSCORES (\"\r\n + \"UserName VARCHAR(255), \"\r\n + \"LevelID INT, \"\r\n + \"Timestamp VARCHAR(255), \"\r\n + \"Score INT, \"\r\n + \"PRIMARY KEY (UserName, LevelID))\";\r\n try (Statement stmt = conn.createStatement()) {\r\n stmt.execute(createTableSQL);\r\n }\r\n }\r\n }\r\n\r\n private void createConfigTableIfNotExists() throws SQLException {\r\n DatabaseMetaData meta = conn.getMetaData();\r\n ResultSet resultSet = meta.getTables(null, null, \"GLOBAL_CONFIG\", new String[]{\"TABLE\"});\r\n if (!resultSet.next()) {\r\n String createTableSQL = \"CREATE TABLE GLOBAL_CONFIG (\"\r\n + \"ConfigKey VARCHAR(255) PRIMARY KEY, \"\r\n + \"ConfigValue VARCHAR(255))\";\r\n try (Statement stmt = conn.createStatement()) {\r\n stmt.execute(createTableSQL);\r\n }\r\n }\r\n }\r\n\r\n @Override\r\n public String getConfigValue(String key, String defaultValue) throws SQLException {\r\n String queryConfigSQL = \"SELECT ConfigValue FROM GLOBAL_CONFIG WHERE ConfigKey = ?\";\r\n try (PreparedStatement pstmt = conn.prepareStatement(queryConfigSQL)) {\r\n pstmt.setString(1, key);\r\n try (ResultSet rs = pstmt.executeQuery()) {\r\n if (rs.next()) {\r\n return rs.getString(\"ConfigValue\");\r\n } else {\r\n return defaultValue;\r\n }\r\n }\r\n }\r\n }\r\n\r\n @Override\r\n public void saveConfig(String key, String value) throws SQLException {\r\n String checkKeySQL = \"SELECT ConfigKey FROM GLOBAL_CONFIG WHERE ConfigKey = ?\";\r\n\r\n try (PreparedStatement pstmtCheck = conn.prepareStatement(checkKeySQL)) {\r\n pstmtCheck.setString(1, key);\r\n try (ResultSet rs = pstmtCheck.executeQuery()) {\r\n if (rs.next()) {\r\n String updateSQL = \"UPDATE GLOBAL_CONFIG SET ConfigValue = ? WHERE ConfigKey = ?\";\r\n try (PreparedStatement pstmtUpdate = conn.prepareStatement(updateSQL)) {\r\n pstmtUpdate.setString(1, value);\r\n pstmtUpdate.setString(2, key);\r\n pstmtUpdate.executeUpdate();\r\n }\r\n } else {\r\n String insertSQL = \"INSERT INTO GLOBAL_CONFIG (ConfigKey, ConfigValue) VALUES (?, ?)\";\r\n try (PreparedStatement pstmtInsert = conn.prepareStatement(insertSQL)) {\r\n pstmtInsert.setString(1, key);\r\n pstmtInsert.setString(2, value);\r\n pstmtInsert.executeUpdate();\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n @Override\r\n public void saveHighestScore(String userName, int levelID, int score) throws SQLException {\r\n String checkRecordSQL = \"SELECT Score FROM HIGHSCORES WHERE UserName = ? AND LevelID = ?\";\r\n try (PreparedStatement pstmtCheck = conn.prepareStatement(checkRecordSQL)) {\r\n pstmtCheck.setString(1, userName);\r\n pstmtCheck.setInt(2, levelID);\r\n try (ResultSet rs = pstmtCheck.executeQuery()) {\r\n if (rs.next()) {\r\n int existingScore = rs.getInt(\"Score\");\r\n if (score > existingScore) {\r\n String updateScoreSQL = \"UPDATE HIGHSCORES SET Score = ?, Timestamp = ? WHERE UserName = ? AND LevelID = ?\";\r\n try (PreparedStatement pstmtUpdate = conn.prepareStatement(updateScoreSQL)) {\r\n pstmtUpdate.setInt(1, score);\r\n pstmtUpdate.setString(2, LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));\r\n pstmtUpdate.setString(3, userName);\r\n pstmtUpdate.setInt(4, levelID);\r\n pstmtUpdate.executeUpdate();\r\n }\r\n }\r\n } else {\r\n String insertScoreSQL = \"INSERT INTO HIGHSCORES (UserName, LevelID, Timestamp, Score) VALUES (?, ?, ?, ?)\";\r\n try (PreparedStatement pstmtInsert = conn.prepareStatement(insertScoreSQL)) {\r\n pstmtInsert.setString(1, userName);\r\n pstmtInsert.setInt(2, levelID);\r\n pstmtInsert.setString(3, LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));\r\n pstmtInsert.setInt(4, score);\r\n pstmtInsert.executeUpdate();\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n @Override\r\n public int queryScores(String userName, int levelID) throws SQLException {\r\n String queryScoresSQL = \"SELECT Score FROM HIGHSCORES WHERE UserName = ? AND LevelID = ?\";\r\n try (PreparedStatement pstmt = conn.prepareStatement(queryScoresSQL)) {\r\n pstmt.setString(1, userName);\r\n pstmt.setInt(2, levelID);\r\n try (ResultSet rs = pstmt.executeQuery()) {\r\n if (rs.next()) {\r\n return rs.getInt(\"Score\");\r\n } else {\r\n return 0;\r\n }\r\n }\r\n }\r\n }\r\n\r\n @Override\r\n public void close() throws IOException {\r\n try {\r\n conn.close();\r\n } catch (SQLException e) {\r\n throw new IOException(e);\r\n }\r\n }\r\n\r\n @Override\r\n public void clear() throws SQLException {\r\n String clearTableSQL = \"DELETE FROM HIGHSCORES\";\r\n try (Statement stmt = conn.createStatement()) {\r\n stmt.execute(clearTableSQL);\r\n }\r\n }\r\n}\r"
}
] | import pdc.project.Universe;
import pdc.project.Utils;
import pdc.project.Database;
import pdc.project.DatabaseDerby;
| 4,389 | package pdc.project.entity;
public class Coin extends ImageEntity implements NoPhysicalCollisionEntity {
private Database database;
public Coin(Universe universe, int x, int y, int width, int height) {
| package pdc.project.entity;
public class Coin extends ImageEntity implements NoPhysicalCollisionEntity {
private Database database;
public Coin(Universe universe, int x, int y, int width, int height) {
| super(universe, x, y, width, height, Utils.loadImage("/bonus.gif"));
| 1 | 2023-10-09 03:01:39+00:00 | 8k |
qmjy/mapbox-offline-server | src/main/java/io/github/qmjy/mapbox/service/AsyncService.java | [
{
"identifier": "MapServerDataCenter",
"path": "src/main/java/io/github/qmjy/mapbox/MapServerDataCenter.java",
"snippet": "@Component\npublic class MapServerDataCenter {\n private static final Logger logger = LoggerFactory.getLogger(MapServerDataCenter.class);\n\n /**\n * 瓦片数据库文件模型\n */\n private static final Map<String, TilesFileModel> tilesMap = new HashMap<>();\n\n\n private static final Map<String, Map<Long, TPKZoomLevel>> tpkMap = new HashMap<>();\n private static final Map<String, TPKFile> tpkFileMap = new HashMap<>();\n\n /**\n * 字体文件模型\n */\n private static final Map<String, FontsFileModel> fontsMap = new HashMap<>();\n\n /**\n * 行政区划数据。key:行政级别、value:区划对象列表\n */\n @Getter\n private static final Map<Integer, List<SimpleFeature>> administrativeDivisionLevel = new HashMap<>();\n\n /**\n * 行政区划数据。key:区划ID、value:区划对象\n */\n @Getter\n private static final Map<Integer, SimpleFeature> administrativeDivision = new HashMap<>();\n\n /**\n * 行政区划层级树\n */\n @Getter\n private static AdministrativeDivisionTmp simpleAdminDivision;\n\n /**\n * 初始化数据源\n *\n * @param className 驱动名称\n * @param file 待链接的数据库文件\n */\n public static void initJdbcTemplate(String className, File file) {\n TilesFileModel dbFileModel = new TilesFileModel(file, className);\n tilesMap.put(file.getName(), dbFileModel);\n }\n\n /**\n * 初始化TPK文件\n *\n * @param tpk tpk地图数据文件\n */\n public static void initTpk(File tpk) {\n Map<Long, TPKZoomLevel> zoomLevelMap = new HashMap<>();\n TPKFile tpkFile = new TPKFile(tpk, zoomLevelMap);\n tpkMap.put(tpk.getName(), zoomLevelMap);\n tpkFileMap.put(tpk.getName(), tpkFile);\n }\n\n\n /**\n * 初始化字体库文件\n *\n * @param fontFolder 字体文件目录\n */\n public static void initFontsFile(File fontFolder) {\n fontsMap.put(fontFolder.getName(), new FontsFileModel(fontFolder));\n }\n\n /**\n * geojson格式的加载行政区划边界数据。\n *\n * @param boundary 行政区划边界\n */\n public static void initBoundaryFile(File boundary) {\n try {\n GeoJSONReader reader = new GeoJSONReader(new FileInputStream(boundary));\n SimpleFeatureIterator features = reader.getFeatures().features();\n while (features.hasNext()) {\n SimpleFeature feature = features.next();\n\n administrativeDivision.put((int) feature.getAttribute(\"osm_id\"), feature);\n\n int adminLevel = feature.getAttribute(\"admin_level\") == null ? -1 : (int) feature.getAttribute(\"admin_level\");\n if (administrativeDivisionLevel.containsKey(adminLevel)) {\n List<SimpleFeature> simpleFeatures = administrativeDivisionLevel.get(adminLevel);\n simpleFeatures.add(feature);\n } else {\n ArrayList<SimpleFeature> value = new ArrayList<>();\n value.add(feature);\n administrativeDivisionLevel.put(adminLevel, value);\n }\n }\n features.close();\n packageModel();\n } catch (IOException e) {\n logger.error(\"Read OSM file failed:\" + boundary.getAbsolutePath());\n }\n }\n\n private static void packageModel() {\n administrativeDivision.values().forEach(feature -> {\n if (simpleAdminDivision == null) {\n simpleAdminDivision = initRootNode(feature);\n } else {\n Object parentsObj = feature.getAttribute(\"parents\");\n if (parentsObj != null) {\n String[] parents = parentsObj.toString().split(\",\");\n\n AdministrativeDivisionTmp tempNode = new AdministrativeDivisionTmp(feature, Integer.parseInt(parents[0]));\n\n for (int i = 0; i < parents.length; i++) {\n int parentId = Integer.parseInt(parents[i]);\n Optional<AdministrativeDivisionTmp> nodeOpt = findNode(simpleAdminDivision, parentId);\n if (nodeOpt.isPresent()) {\n AdministrativeDivisionTmp child = nodeOpt.get();\n //如果父节点已经在早期全路径时构造过了,则不需要再追加此单节点。\n if (!contains(child, (int) feature.getAttribute(\"osm_id\"))) {\n child.getChildren().add(tempNode);\n }\n break;\n } else {\n AdministrativeDivisionTmp tmp = new AdministrativeDivisionTmp(administrativeDivision.get(parentId), Integer.parseInt(parents[i + 1]));\n tmp.getChildren().add(tempNode);\n tempNode = tmp;\n }\n }\n }\n }\n });\n }\n\n private static boolean contains(AdministrativeDivisionTmp child, int parentId) {\n for (AdministrativeDivisionTmp item : child.getChildren()) {\n if (item.getId() == parentId) {\n return true;\n }\n }\n return false;\n }\n\n\n private static AdministrativeDivisionTmp initRootNode(SimpleFeature feature) {\n Object parents = feature.getAttribute(\"parents\");\n if (parents == null) {\n return new AdministrativeDivisionTmp(feature, -1);\n } else {\n String[] split = parents.toString().split(\",\");\n List<AdministrativeDivisionTmp> children = new ArrayList<>();\n AdministrativeDivisionTmp tmp = null;\n for (int i = 0; i < split.length; i++) {\n int osmId = Integer.parseInt(split[i]);\n if (i + 1 > split.length - 1) {\n tmp = new AdministrativeDivisionTmp(administrativeDivision.get(osmId), -1);\n tmp.setChildren(children);\n } else {\n tmp = new AdministrativeDivisionTmp(administrativeDivision.get(osmId), Integer.parseInt(split[i + 1]));\n tmp.setChildren(children);\n children = new ArrayList<>();\n children.add(tmp);\n }\n }\n return tmp;\n }\n }\n\n private static Optional<AdministrativeDivisionTmp> findNode(AdministrativeDivisionTmp tmp, int parentId) {\n if (tmp.getId() == parentId) {\n return Optional.of(tmp);\n }\n List<AdministrativeDivisionTmp> children = tmp.getChildren();\n for (AdministrativeDivisionTmp item : children) {\n if (item.getId() == parentId) {\n return Optional.of(item);\n } else {\n Optional<AdministrativeDivisionTmp> childOpt = findNode(item, parentId);\n if (childOpt.isPresent()) {\n return childOpt;\n }\n }\n }\n return Optional.empty();\n }\n\n\n /**\n * 通过文件名获取数据源\n *\n * @param fileName 数据库文件名称\n * @return 数据库数据源\n */\n public Optional<JdbcTemplate> getDataSource(String fileName) {\n if (StringUtils.hasLength(fileName)) {\n TilesFileModel model = tilesMap.get(fileName);\n return Optional.of(model.getJdbcTemplate());\n } else {\n return Optional.empty();\n }\n }\n\n\n /**\n * 返回瓦片数据库文件的元数据\n *\n * @param fileName 瓦片数据库文件名\n * @return 瓦片元数据\n */\n public Map<String, String> getTileMetaData(String fileName) {\n if (StringUtils.hasLength(fileName)) {\n TilesFileModel model = tilesMap.get(fileName);\n return model.getMetaDataMap();\n } else {\n return new HashMap<>();\n }\n }\n\n public MetaData getTpkMetaData(String fileName) {\n MetaData metaData = new MetaData();\n if (StringUtils.hasLength(fileName)) {\n TPKFile tpkFile = tpkFileMap.get(fileName);\n metaData.setBounds(tpkFile.getBounds().toString());\n metaData.setCrs(tpkFile.getBounds().getCoordinateReferenceSystem().getName().toString());\n metaData.setFormat(tpkFile.getImageFormat());\n metaData.setMaxzoom(tpkFile.getMaxZoomLevel());\n metaData.setMinzoom(tpkFile.getMinZoomLevel());\n }\n return metaData;\n }\n\n /**\n * 获取字符文件目录\n *\n * @param fontName 字体文件名\n * @return 字体文件目录\n */\n public Optional<FontsFileModel> getFontFolder(String fontName) {\n if (StringUtils.hasLength(fontName)) {\n FontsFileModel fontsFileModel = fontsMap.get(fontName);\n return Optional.of(fontsFileModel);\n } else {\n return Optional.empty();\n }\n }\n}"
},
{
"identifier": "AppConfig",
"path": "src/main/java/io/github/qmjy/mapbox/config/AppConfig.java",
"snippet": "@Component\n@ConfigurationProperties\npublic class AppConfig {\n\n public static final String FILE_EXTENSION_NAME_MBTILES = \".mbtiles\";\n public static final String FILE_EXTENSION_NAME_TPK = \".tpk\";\n public static final String FILE_EXTENSION_NAME_PBF = \".pbf\";\n public static final String FILE_EXTENSION_NAME_JSON = \".json\";\n public static final String FILE_EXTENSION_NAME_GEOJSON = \".geojson\";\n public static final String FILE_EXTENSION_NAME_PNG = \".png\";\n\n public static final MediaType APPLICATION_X_PROTOBUF_VALUE = MediaType.valueOf(\"application/x-protobuf\");\n\n @Value(\"${spring.datasource.driver-class-name}\")\n private String driverClassName;\n\n /**\n * 数据文件存放路径\n */\n @Value(\"${data-path}\")\n private String dataPath = \"\";\n\n\n public String getDriverClassName() {\n return driverClassName;\n }\n\n public String getDataPath() {\n return dataPath;\n }\n}"
},
{
"identifier": "MbtileMergeFile",
"path": "src/main/java/io/github/qmjy/mapbox/model/MbtileMergeFile.java",
"snippet": "public class MbtileMergeFile {\n private final JdbcTemplate jdbcTemplate;\n private final String filePath;\n private final Map<String, String> metaMap = new HashMap<>();\n private long count;\n\n public MbtileMergeFile(String item, JdbcTemplate jdbcTemplate) {\n this.filePath = item;\n this.jdbcTemplate = jdbcTemplate;\n init();\n }\n\n private void init() {\n List<Map<String, Object>> mapList = jdbcTemplate.queryForList(\"SELECT * FROM metadata\");\n mapList.forEach(item -> {\n metaMap.put(item.get(\"name\").toString(), item.get(\"value\").toString());\n });\n\n List<Map<String, Object>> maps = jdbcTemplate.queryForList(\"SELECT COUNT(*) AS count FROM tiles\");\n this.count = Long.parseLong(maps.getFirst().get(\"count\").toString());\n }\n\n public JdbcTemplate getJdbcTemplate() {\n return jdbcTemplate;\n }\n\n public String getFilePath() {\n return filePath;\n }\n\n public long getCount() {\n return count;\n }\n\n public Map<String, String> getMetaMap() {\n return metaMap;\n }\n}"
},
{
"identifier": "MbtileMergeWrapper",
"path": "src/main/java/io/github/qmjy/mapbox/model/MbtileMergeWrapper.java",
"snippet": "public class MbtileMergeWrapper {\n /**\n * 所有需要合并的文件列表。filePath:mbtiles details\n */\n private Map<String, MbtileMergeFile> needMerges = new HashMap<>();\n /**\n * 总计要合并的tiles数据\n */\n private long totalCount = 0;\n /**\n * 最大的文件路径\n */\n private String largestFilePath = \"\";\n\n /**\n * 只能同一种格式进行合并\n */\n private String format = \"\";\n\n private int minZoom = Integer.MAX_VALUE;\n private int maxZoom = 0;\n private double minLat = Double.MAX_VALUE;\n private double maxLat = 0L;\n private double minLon = Double.MAX_VALUE;\n private double maxLon = 0L;\n\n public Map<String, MbtileMergeFile> getNeedMerges() {\n return needMerges;\n }\n\n public void setNeedMerges(Map<String, MbtileMergeFile> needMerges) {\n this.needMerges = needMerges;\n }\n\n public long getTotalCount() {\n return totalCount;\n }\n\n public void setTotalCount(long totalCount) {\n this.totalCount = totalCount;\n }\n\n public void addToTotal(long data) {\n this.totalCount += data;\n }\n\n public String getLargestFilePath() {\n return largestFilePath;\n }\n\n public void setLargestFilePath(String largestFilePath) {\n this.largestFilePath = largestFilePath;\n }\n\n public String getFormat() {\n return format;\n }\n\n public void setFormat(String format) {\n this.format = format;\n }\n\n public int getMinZoom() {\n return minZoom;\n }\n\n public void setMinZoom(int minZoom) {\n this.minZoom = minZoom;\n }\n\n public int getMaxZoom() {\n return maxZoom;\n }\n\n public void setMaxZoom(int maxZoom) {\n this.maxZoom = maxZoom;\n }\n\n public double getMinLat() {\n return minLat;\n }\n\n public void setMinLat(double minLat) {\n this.minLat = minLat;\n }\n\n public double getMaxLat() {\n return maxLat;\n }\n\n public void setMaxLat(double maxLat) {\n this.maxLat = maxLat;\n }\n\n public double getMinLon() {\n return minLon;\n }\n\n public void setMinLon(double minLon) {\n this.minLon = minLon;\n }\n\n public double getMaxLon() {\n return maxLon;\n }\n\n public void setMaxLon(double maxLon) {\n this.maxLon = maxLon;\n }\n}"
},
{
"identifier": "MbtilesOfMergeProgress",
"path": "src/main/java/io/github/qmjy/mapbox/model/MbtilesOfMergeProgress.java",
"snippet": "public class MbtilesOfMergeProgress {\n private String taskId;\n private int progress;\n\n public MbtilesOfMergeProgress(String taskId, int progress) {\n this.taskId = taskId;\n this.progress = progress;\n }\n\n public String getTaskId() {\n return taskId;\n }\n\n public void setTaskId(String taskId) {\n this.taskId = taskId;\n }\n\n public int getProgress() {\n return progress;\n }\n\n public void setProgress(int progress) {\n this.progress = progress;\n }\n}"
},
{
"identifier": "JdbcUtils",
"path": "src/main/java/io/github/qmjy/mapbox/util/JdbcUtils.java",
"snippet": "public class JdbcUtils {\n\n private static final JdbcUtils INSTANCE = new JdbcUtils();\n\n private JdbcUtils() {\n }\n\n public static JdbcUtils getInstance() {\n return INSTANCE;\n }\n\n public JdbcTemplate getJdbcTemplate(String className, String filePath) {\n DataSourceBuilder<?> ds = DataSourceBuilder.create();\n ds.driverClassName(className);\n ds.url(\"jdbc:sqlite:\" + filePath);\n return new JdbcTemplate(ds.build());\n }\n\n public void releaseJdbcTemplate(JdbcTemplate jdbcTemplate) {\n// jdbcTemplate.getDataSource().getConnection().close();\n }\n}"
}
] | import io.github.qmjy.mapbox.MapServerDataCenter;
import io.github.qmjy.mapbox.config.AppConfig;
import io.github.qmjy.mapbox.model.MbtileMergeFile;
import io.github.qmjy.mapbox.model.MbtileMergeWrapper;
import io.github.qmjy.mapbox.model.MbtilesOfMergeProgress;
import io.github.qmjy.mapbox.util.JdbcUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.StringUtils;
import java.io.File;
import java.io.IOException;
import java.sql.PreparedStatement;
import java.util.*; | 5,809 | while (iterator.hasNext()) {
Map.Entry<String, MbtileMergeFile> next = iterator.next();
mergeTo(next.getValue(), targetTmpFile);
completeCount += next.getValue().getCount();
taskProgress.put(taskId, (int) (completeCount * 100 / totalCount));
iterator.remove();
logger.info("Merged file: {}", next.getValue().getFilePath());
}
updateMetadata(wrapper, targetTmpFile);
boolean b = targetTmpFile.renameTo(new File(targetFilePath));
System.out.println("重命名文件结果:" + b);
taskProgress.put(taskId, 100);
} else {
taskProgress.put(taskId, -1);
}
}
private void updateMetadata(MbtileMergeWrapper wrapper, File targetTmpFile) {
String bounds = wrapper.getMinLon() + "," + wrapper.getMinLat() + "," + wrapper.getMaxLon() + "," + wrapper.getMaxLat();
JdbcTemplate jdbcTemplate = JdbcUtils.getInstance().getJdbcTemplate(appConfig.getDriverClassName(), targetTmpFile.getAbsolutePath());
jdbcTemplate.update("UPDATE metadata SET value = " + wrapper.getMinZoom() + " WHERE name = 'minzoom'");
jdbcTemplate.update("UPDATE metadata SET value = " + wrapper.getMaxZoom() + " WHERE name = 'maxzoom'");
jdbcTemplate.update("UPDATE metadata SET value = '" + bounds + "' WHERE name = 'bounds'");
}
private Optional<MbtileMergeWrapper> arrange(List<String> sourceNamePaths) {
MbtileMergeWrapper mbtileMergeWrapper = new MbtileMergeWrapper();
for (String item : sourceNamePaths) {
if (mbtileMergeWrapper.getLargestFilePath() == null || mbtileMergeWrapper.getLargestFilePath().isBlank() || new File(item).length() > new File(mbtileMergeWrapper.getLargestFilePath()).length()) {
mbtileMergeWrapper.setLargestFilePath(item);
}
MbtileMergeFile value = wrapModel(item);
Map<String, String> metadata = value.getMetaMap();
String format = metadata.get("format");
if (mbtileMergeWrapper.getFormat().isBlank()) {
mbtileMergeWrapper.setFormat(format);
} else {
//比较mbtiles文件格式是否一致
if (!mbtileMergeWrapper.getFormat().equals(format)) {
logger.error("These Mbtiles files have different formats!");
return Optional.empty();
}
}
int minZoom = Integer.parseInt(metadata.get("minzoom"));
if (mbtileMergeWrapper.getMinZoom() > minZoom) {
mbtileMergeWrapper.setMinZoom(minZoom);
}
int maxZoom = Integer.parseInt(metadata.get("maxzoom"));
if (mbtileMergeWrapper.getMaxZoom() < maxZoom) {
mbtileMergeWrapper.setMaxZoom(maxZoom);
}
//Such as: 120.85098267,30.68516394,122.03475952,31.87872381
String[] split = metadata.get("bounds").split(",");
if (mbtileMergeWrapper.getMinLat() > Double.parseDouble(split[1])) {
mbtileMergeWrapper.setMinLat(Double.parseDouble(split[1]));
}
if (mbtileMergeWrapper.getMaxLat() < Double.parseDouble(split[3])) {
mbtileMergeWrapper.setMaxLat(Double.parseDouble(split[3]));
}
if (mbtileMergeWrapper.getMinLon() > Double.parseDouble(split[0])) {
mbtileMergeWrapper.setMinLon(Double.parseDouble(split[0]));
}
if (mbtileMergeWrapper.getMaxLon() < Double.parseDouble(split[2])) {
mbtileMergeWrapper.setMaxLon(Double.parseDouble(split[2]));
}
mbtileMergeWrapper.addToTotal(value.getCount());
mbtileMergeWrapper.getNeedMerges().put(item, value);
}
return Optional.of(mbtileMergeWrapper);
}
public void mergeTo(MbtileMergeFile mbtile, File targetTmpFile) {
JdbcTemplate jdbcTemplate = JdbcUtils.getInstance().getJdbcTemplate(appConfig.getDriverClassName(), targetTmpFile.getAbsolutePath());
int pageSize = 5000;
long totalPage = mbtile.getCount() % pageSize == 0 ? mbtile.getCount() / pageSize : mbtile.getCount() / pageSize + 1;
for (long currentPage = 0; currentPage < totalPage; currentPage++) {
List<Map<String, Object>> dataList = mbtile.getJdbcTemplate().queryForList("SELECT * FROM tiles LIMIT " + pageSize + " OFFSET " + currentPage * pageSize);
jdbcTemplate.batchUpdate("INSERT INTO tiles (zoom_level, tile_column, tile_row, tile_data) VALUES (?, ?, ?, ?)",
dataList,
pageSize,
(PreparedStatement ps, Map<String, Object> rowDataMap) -> {
ps.setInt(1, (int) rowDataMap.get("zoom_level"));
ps.setInt(2, (int) rowDataMap.get("tile_column"));
ps.setInt(3, (int) rowDataMap.get("tile_row"));
ps.setBytes(4, (byte[]) rowDataMap.get("tile_data"));
});
}
JdbcUtils.getInstance().releaseJdbcTemplate(jdbcTemplate);
}
private MbtileMergeFile wrapModel(String item) {
JdbcTemplate jdbcTemplate = JdbcUtils.getInstance().getJdbcTemplate(appConfig.getDriverClassName(), item);
return new MbtileMergeFile(item, jdbcTemplate);
}
/**
* data format from: <a href="https://osm-boundaries.com/">OSM-Boundaries</a>
*
* @param dataFolder 行政区划边界数据
*/
private void wrapOSMBFile(File dataFolder) {
File boundariesFolder = new File(dataFolder, "OSMB");
File[] files = boundariesFolder.listFiles();
if (files != null) {
for (File boundary : files) {
if (!boundary.isDirectory() && boundary.getName().endsWith(AppConfig.FILE_EXTENSION_NAME_GEOJSON)) {
logger.info("Load boundary file: {}", boundary.getName()); | /*
* Copyright (c) 2023 QMJY.
*
* 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 io.github.qmjy.mapbox.service;
@Service
public class AsyncService {
private final Logger logger = LoggerFactory.getLogger(AsyncService.class);
@Autowired
private AppConfig appConfig;
/**
* taskId:完成百分比
*/
private final Map<String, Integer> taskProgress = new HashMap<>();
/**
* 每10秒检查一次,数据有更新则刷新
*/
@Scheduled(fixedRate = 1000)
public void processFixedRate() {
//TODO nothing to do yet
}
/**
* 加载数据文件
*/
@Async("asyncServiceExecutor")
public void asyncTask() {
if (StringUtils.hasLength(appConfig.getDataPath())) {
File dataFolder = new File(appConfig.getDataPath());
if (dataFolder.isDirectory() && dataFolder.exists()) {
wrapTilesFile(dataFolder);
wrapFontsFile(dataFolder);
wrapOSMBFile(dataFolder);
}
}
}
/**
* 提交文件合并任务。合并任务失败,则process is -1。
*
* @param sourceNamePaths 待合并的文件列表
* @param targetFilePath 目标文件名字
*/
@Async("asyncServiceExecutor")
public void submit(String taskId, List<String> sourceNamePaths, String targetFilePath) {
taskProgress.put(taskId, 0);
Optional<MbtileMergeWrapper> wrapperOpt = arrange(sourceNamePaths);
if (wrapperOpt.isPresent()) {
MbtileMergeWrapper wrapper = wrapperOpt.get();
Map<String, MbtileMergeFile> needMerges = wrapper.getNeedMerges();
long totalCount = wrapper.getTotalCount();
String largestFilePath = wrapper.getLargestFilePath();
long completeCount = 0;
//直接拷贝最大的文件,提升合并速度
File targetTmpFile = new File(targetFilePath + ".tmp");
try {
FileCopyUtils.copy(new File(largestFilePath), targetTmpFile);
completeCount = needMerges.get(largestFilePath).getCount();
taskProgress.put(taskId, (int) (completeCount * 100 / totalCount));
needMerges.remove(largestFilePath);
} catch (IOException e) {
logger.info("Copy the largest file failed: {}", largestFilePath);
taskProgress.put(taskId, -1);
return;
}
Iterator<Map.Entry<String, MbtileMergeFile>> iterator = needMerges.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, MbtileMergeFile> next = iterator.next();
mergeTo(next.getValue(), targetTmpFile);
completeCount += next.getValue().getCount();
taskProgress.put(taskId, (int) (completeCount * 100 / totalCount));
iterator.remove();
logger.info("Merged file: {}", next.getValue().getFilePath());
}
updateMetadata(wrapper, targetTmpFile);
boolean b = targetTmpFile.renameTo(new File(targetFilePath));
System.out.println("重命名文件结果:" + b);
taskProgress.put(taskId, 100);
} else {
taskProgress.put(taskId, -1);
}
}
private void updateMetadata(MbtileMergeWrapper wrapper, File targetTmpFile) {
String bounds = wrapper.getMinLon() + "," + wrapper.getMinLat() + "," + wrapper.getMaxLon() + "," + wrapper.getMaxLat();
JdbcTemplate jdbcTemplate = JdbcUtils.getInstance().getJdbcTemplate(appConfig.getDriverClassName(), targetTmpFile.getAbsolutePath());
jdbcTemplate.update("UPDATE metadata SET value = " + wrapper.getMinZoom() + " WHERE name = 'minzoom'");
jdbcTemplate.update("UPDATE metadata SET value = " + wrapper.getMaxZoom() + " WHERE name = 'maxzoom'");
jdbcTemplate.update("UPDATE metadata SET value = '" + bounds + "' WHERE name = 'bounds'");
}
private Optional<MbtileMergeWrapper> arrange(List<String> sourceNamePaths) {
MbtileMergeWrapper mbtileMergeWrapper = new MbtileMergeWrapper();
for (String item : sourceNamePaths) {
if (mbtileMergeWrapper.getLargestFilePath() == null || mbtileMergeWrapper.getLargestFilePath().isBlank() || new File(item).length() > new File(mbtileMergeWrapper.getLargestFilePath()).length()) {
mbtileMergeWrapper.setLargestFilePath(item);
}
MbtileMergeFile value = wrapModel(item);
Map<String, String> metadata = value.getMetaMap();
String format = metadata.get("format");
if (mbtileMergeWrapper.getFormat().isBlank()) {
mbtileMergeWrapper.setFormat(format);
} else {
//比较mbtiles文件格式是否一致
if (!mbtileMergeWrapper.getFormat().equals(format)) {
logger.error("These Mbtiles files have different formats!");
return Optional.empty();
}
}
int minZoom = Integer.parseInt(metadata.get("minzoom"));
if (mbtileMergeWrapper.getMinZoom() > minZoom) {
mbtileMergeWrapper.setMinZoom(minZoom);
}
int maxZoom = Integer.parseInt(metadata.get("maxzoom"));
if (mbtileMergeWrapper.getMaxZoom() < maxZoom) {
mbtileMergeWrapper.setMaxZoom(maxZoom);
}
//Such as: 120.85098267,30.68516394,122.03475952,31.87872381
String[] split = metadata.get("bounds").split(",");
if (mbtileMergeWrapper.getMinLat() > Double.parseDouble(split[1])) {
mbtileMergeWrapper.setMinLat(Double.parseDouble(split[1]));
}
if (mbtileMergeWrapper.getMaxLat() < Double.parseDouble(split[3])) {
mbtileMergeWrapper.setMaxLat(Double.parseDouble(split[3]));
}
if (mbtileMergeWrapper.getMinLon() > Double.parseDouble(split[0])) {
mbtileMergeWrapper.setMinLon(Double.parseDouble(split[0]));
}
if (mbtileMergeWrapper.getMaxLon() < Double.parseDouble(split[2])) {
mbtileMergeWrapper.setMaxLon(Double.parseDouble(split[2]));
}
mbtileMergeWrapper.addToTotal(value.getCount());
mbtileMergeWrapper.getNeedMerges().put(item, value);
}
return Optional.of(mbtileMergeWrapper);
}
public void mergeTo(MbtileMergeFile mbtile, File targetTmpFile) {
JdbcTemplate jdbcTemplate = JdbcUtils.getInstance().getJdbcTemplate(appConfig.getDriverClassName(), targetTmpFile.getAbsolutePath());
int pageSize = 5000;
long totalPage = mbtile.getCount() % pageSize == 0 ? mbtile.getCount() / pageSize : mbtile.getCount() / pageSize + 1;
for (long currentPage = 0; currentPage < totalPage; currentPage++) {
List<Map<String, Object>> dataList = mbtile.getJdbcTemplate().queryForList("SELECT * FROM tiles LIMIT " + pageSize + " OFFSET " + currentPage * pageSize);
jdbcTemplate.batchUpdate("INSERT INTO tiles (zoom_level, tile_column, tile_row, tile_data) VALUES (?, ?, ?, ?)",
dataList,
pageSize,
(PreparedStatement ps, Map<String, Object> rowDataMap) -> {
ps.setInt(1, (int) rowDataMap.get("zoom_level"));
ps.setInt(2, (int) rowDataMap.get("tile_column"));
ps.setInt(3, (int) rowDataMap.get("tile_row"));
ps.setBytes(4, (byte[]) rowDataMap.get("tile_data"));
});
}
JdbcUtils.getInstance().releaseJdbcTemplate(jdbcTemplate);
}
private MbtileMergeFile wrapModel(String item) {
JdbcTemplate jdbcTemplate = JdbcUtils.getInstance().getJdbcTemplate(appConfig.getDriverClassName(), item);
return new MbtileMergeFile(item, jdbcTemplate);
}
/**
* data format from: <a href="https://osm-boundaries.com/">OSM-Boundaries</a>
*
* @param dataFolder 行政区划边界数据
*/
private void wrapOSMBFile(File dataFolder) {
File boundariesFolder = new File(dataFolder, "OSMB");
File[] files = boundariesFolder.listFiles();
if (files != null) {
for (File boundary : files) {
if (!boundary.isDirectory() && boundary.getName().endsWith(AppConfig.FILE_EXTENSION_NAME_GEOJSON)) {
logger.info("Load boundary file: {}", boundary.getName()); | MapServerDataCenter.initBoundaryFile(boundary); | 0 | 2023-10-09 03:18:52+00:00 | 8k |
Aywen1/reciteeasily | src/fr/nicolas/main/frames/AFrameMenu.java | [
{
"identifier": "ATools",
"path": "src/fr/nicolas/main/ATools.java",
"snippet": "public class ATools {\n\n\tpublic static String[] matiereList = { \"Histoire\", \"Géographie\", \"Emc\", \"Phys-Chim\", \"Svt\", \"Maths\",\n\t\t\t\"Anglais\", \"Espagnol\" };\n\tpublic static ArrayList<String> elements;\n\tpublic static int nombrePartiesTotal;\n\tpublic static int nombrePartiesNow;\n\tprivate static ArrayList<ArrayList<String>> listFalseItems = new ArrayList<ArrayList<String>>();\n\tprivate static String categoryNow;\n\tprivate static int nombreRestart;\n\tpublic static String nameFiche;\n\tpublic static AFrameMenuNavig menuNavig;\n\n\tpublic static String clearText(String text) {\n\t\treturn (text.replace(\"[T]\", \"\").replace(\"[D]\", \"\").replace(\"[M]\", \"\").replace(\"[DA]\", \"\").replace(\"[P]\", \"\")\n\t\t\t\t.replace(\"[E]\", \"\").replace(\"[L]\", \"\").replace(\"[C]\", \"\").replace(\"[I]\", \"\"));\n\t}\n\n\tpublic static ArrayList<String> readFile(String matiere, String nameFiche) {\n\t\tString line;\n\t\tArrayList<String> newElements = new ArrayList<String>();\n\t\ttry {\n\t\t\tBufferedReader bufferedReader = new BufferedReader(\n\t\t\t\t\tnew FileReader(\"ReciteEasily/Fiches/\" + matiere + \"/\" + nameFiche + \"/\" + nameFiche + \".txt\"));\n\t\t\ttry {\n\t\t\t\twhile ((line = bufferedReader.readLine()) != null) {\n\t\t\t\t\tnewElements.add(line);\n\t\t\t\t}\n\t\t\t\tbufferedReader.close();\n\t\t\t} catch (IOException e) {\n\t\t\t}\n\t\t} catch (FileNotFoundException e) {\n\t\t}\n\n\t\treturn newElements;\n\t}\n\n\tpublic static void nextFrame(Point loc) {\n\t\tnextFrameSuite(loc);\n\t}\n\n\tpublic static void nextFrame(Point loc, ArrayList<String> falseItems) {\n\t\tlistFalseItems.add(falseItems);\n\n\t\tnextFrameSuite(loc);\n\t}\n\n\tprivate static void nextFrameSuite(Point loc) {\n\t\tif (elements.size() > 0) {\n\n\t\t\tint i = 0;\n\n\t\t\tnombrePartiesNow = 0;\n\t\t\twhile (elements.get(i) != null) {\n\t\t\t\tif (elements.get(i).startsWith(\"[C]\") || elements.get(i).startsWith(\"[L]\")\n\t\t\t\t\t\t|| elements.get(i).startsWith(\"[I]\")) {\n\t\t\t\t\tnombrePartiesNow++;\n\t\t\t\t}\n\t\t\t\tif (i == elements.size() - 1) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\ti++;\n\t\t\t}\n\n\t\t\tif (elements.get(0).startsWith(\"[C]\")) {\n\t\t\t\tArrayList<String> items = new ArrayList<String>();\n\t\t\t\tString name = clearText(elements.get(0));\n\t\t\t\telements.remove(0);\n\n\t\t\t\ti = 0;\n\t\t\t\twhile (elements.get(i) != null) {\n\t\t\t\t\tif (elements.get(i).startsWith(\"[C]\")) {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t} else if (elements.get(i).startsWith(\"[L]\")) {\n\t\t\t\t\t\titems.add(clearText(elements.get(i)));\n\t\t\t\t\t}\n\t\t\t\t\tif (i == elements.size() - 1) {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\ti++;\n\t\t\t\t}\n\n\t\t\t\tcategoryNow = name;\n\n\t\t\t\tnew AFrameCategory(loc, name, items);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (elements.get(0).startsWith(\"[L]\")) {\n\t\t\t\tArrayList<String> items = new ArrayList<String>();\n\t\t\t\tString name = clearText(elements.get(0));\n\t\t\t\telements.remove(0);\n\n\t\t\t\twhile (elements.size() > 0) {\n\t\t\t\t\tif (elements.get(0).startsWith(\"[E]\")) {\n\t\t\t\t\t\titems.add(clearText(elements.get(0)));\n\t\t\t\t\t\telements.remove(0);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tnew AFrameListe(loc, name, categoryNow, items);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (elements.get(0).startsWith(\"[I]\")) {\n\t\t\t\tString name = clearText(elements.get(0));\n\t\t\t\telements.remove(0);\n\t\t\t\tnew AFrameImage(loc, name);\n\t\t\t}\n\n\t\t} else {\n\t\t\tif (listFalseItems.size() > 0) {\n\t\t\t\tString name = listFalseItems.get(0).get(0);\n\t\t\t\tlistFalseItems.get(0).remove(0);\n\t\t\t\tString category = listFalseItems.get(0).get(0);\n\t\t\t\tlistFalseItems.get(0).remove(0);\n\t\t\t\tnew AFrameListe(loc, \"[x] \" + name, category, listFalseItems.get(0));\n\t\t\t\tlistFalseItems.remove(0);\n\t\t\t\tnombreRestart++;\n\t\t\t} else {\n\t\t\t\tnew AFrameEnd(loc, nombreRestart);\n\t\t\t}\n\t\t}\n\t}\n\n}"
},
{
"identifier": "ABackground",
"path": "src/fr/nicolas/main/components/ABackground.java",
"snippet": "public class ABackground extends JPanel {\n\n\tprivate Image bg;\n\tprivate boolean color = false;\n\n\tpublic enum ABgType {\n\t\tNewFiche, Summary, Color, End\n\t}\n\n\tpublic ABackground() {\n\t\tthis.setLayout(null);\n\t\tbg = new ImageIcon(getClass().getResource(\"/img/bgDefault.png\")).getImage();\n\t}\n\n\tpublic ABackground(ABgType type) {\n\t\tthis.setLayout(null);\n\t\tif (type == ABgType.NewFiche) {\n\t\t\tbg = new ImageIcon(getClass().getResource(\"/img/bgNewFiche.png\")).getImage();\n\t\t} else if (type == ABgType.Summary) {\n\t\t\tbg = new ImageIcon(getClass().getResource(\"/img/bgSummary.png\")).getImage();\n\t\t} else if (type == ABgType.Color) {\n\t\t\tcolor = true;\n\t\t} else if (type == ABgType.End) {\n\t\t\tbg = new ImageIcon(getClass().getResource(\"/img/imgEnd.png\")).getImage();\n\t\t}\n\t}\n\n\tpublic void paintComponent(Graphics g) {\n\t\tif (!color) {\n\t\t\tg.drawImage(bg, 0, 0, this.getWidth(), this.getHeight(), null);\n\t\t} else {\n\t\t\tg.setColor(new Color(22, 22, 22));\n\t\t\tg.fillRect(0, 0, this.getWidth(), this.getHeight());\n\t\t\tg.setColor(Color.WHITE);\n\t\t\tg.drawLine(0, 0, 0, this.getHeight());\n\t\t}\n\t}\n\n}"
},
{
"identifier": "AButtonImg",
"path": "src/fr/nicolas/main/components/AButtonImg.java",
"snippet": "public class AButtonImg extends JButton {\n\n\tprivate Image img;\n\n\tpublic AButtonImg(String name) {\n\t\tthis.setFocusPainted(false);\n\t\tthis.setBorderPainted(false);\n\t\tthis.setContentAreaFilled(false);\n\n\t\tchangeType(name);\n\t}\n\n\tpublic AButtonImg(String path, String name) {\n\t\tthis.setFocusPainted(false);\n\t\tthis.setBorderPainted(false);\n\t\tthis.setContentAreaFilled(false);\n\n\t\ttry {\n\t\t\timg = ImageIO.read(new File(path + \"/\" + name));\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\n\t\tsetSize(new Dimension(img.getWidth(null), img.getHeight(null)));\n\t}\n\n\tpublic void paintComponent(Graphics g) {\n\t\tg.drawImage(img, 0, 0, this.getWidth(), this.getHeight(), null);\n\t}\n\n\tpublic void changeType(String name) {\n\t\timg = new ImageIcon(getClass().getResource(\"/img/button\" + name + \".png\")).getImage();\n\n\t\trepaint();\n\t}\n\n\tpublic Image getImg() {\n\t\treturn img;\n\t}\n\n}"
},
{
"identifier": "AButtonMatiere",
"path": "src/fr/nicolas/main/components/AButtonMatiere.java",
"snippet": "public class AButtonMatiere extends JButton {\n\n\tprivate ALabel label;\n\tprivate boolean isSelected = false;\n\n\tpublic AButtonMatiere(String name) {\n\t\tthis.setFocusPainted(false);\n\t\tthis.setBorderPainted(false);\n\t\tthis.setContentAreaFilled(false);\n\n\t\tlabel = new ALabel(name, 16);\n\t\tadd(label);\n\t}\n\n\tpublic void paintComponent(Graphics g) {\n\t\tg.setColor(new Color(22, 22, 22));\n\t\tg.fillRect(0, 0, getWidth(), getHeight());\n\n\t\tg.setColor(new Color(65, 120, 35));\n\t\tg.drawRect(0, 0, getWidth() - 1, getHeight() - 1);\n\n\t\tif (isSelected) {\n\t\t\tg.setColor(new Color(65, 120, 35));\n\t\t\tg.drawLine(1, 26, 109, 26);\n\t\t}\n\t}\n\n\tpublic void setSelected(boolean isSelected) {\n\t\tthis.isSelected = isSelected;\n\t\trepaint();\n\t}\n\n}"
},
{
"identifier": "ALabel",
"path": "src/fr/nicolas/main/components/ALabel.java",
"snippet": "public class ALabel extends JLabel {\n\n\tpublic enum ALabelType {\n\t\tBold, Italic\n\t}\n\n\tpublic ALabel(String text, int size) {\n\t\tsuper(text);\n\t\tsetForeground(Color.WHITE);\n\t\tsetFont(new Font(\"Calibri\", Font.PLAIN, size));\n\t}\n\n\tpublic ALabel(String text, int size, ALabelType type) {\n\t\tsuper(text);\n\t\tsetForeground(Color.WHITE);\n\t\tif (type == ALabelType.Bold) {\n\t\t\tsetFont(new Font(\"Calibri\", Font.BOLD, size));\n\t\t} else if (type == ALabelType.Italic) {\n\t\t\tsetFont(new Font(\"Calibri\", Font.ITALIC, size));\n\t\t}\n\t}\n\n\tpublic void setText(String text, int size) {\n\t\tsetText(text);\n\t\tsetFont(new Font(\"Calibri\", Font.PLAIN, size));\n\t}\n\n}"
},
{
"identifier": "ATextArea",
"path": "src/fr/nicolas/main/components/ATextArea.java",
"snippet": "public class ATextArea extends JTextArea {\n\n\tpublic ATextArea(String text) {\n\t\tsuper(text);\n\t\tsetFont(new Font(\"Calibri\", Font.PLAIN, 18));\n\t\tinitSuite();\n\t}\n\n\tpublic ATextArea(String text, int size) {\n\t\tsuper(text);\n\t\tsetFont(new Font(\"Calibri\", Font.PLAIN, size));\n\t\tinitSuite();\n\t}\n\n\tprivate void initSuite() {\n\t\tsetLineWrap(true);\n\t\tsetWrapStyleWord(true);\n\t\tsetEditable(false);\n\t\tsetOpaque(false);\n\n\t\tsetForeground(Color.WHITE);\n\t}\n\n}"
},
{
"identifier": "ABgType",
"path": "src/fr/nicolas/main/components/ABackground.java",
"snippet": "public enum ABgType {\n\tNewFiche, Summary, Color, End\n}"
},
{
"identifier": "APanelTop",
"path": "src/fr/nicolas/main/panel/APanelTop.java",
"snippet": "public class APanelTop extends JPanel {\n\n\tprivate ALabel labelTitle = new ALabel(\"ReciteEasily\", 50);\n\tprivate ALabel labelVersion = new ALabel(\"v\" + Main.version, 20);\n\n\tpublic APanelTop() {\n\t\tinit();\n\t}\n\n\tpublic APanelTop(String text) {\n\t\tlabelTitle.setText(text, 35);\n\t\tlabelVersion.setText(\"\");\n\n\t\tinit();\n\t}\n\n\tprivate void init() {\n\t\tthis.setLayout(null);\n\n\t\tadd(labelTitle);\n\t\tadd(labelVersion);\n\n\t\tlabelTitle.setBounds(35, 20, 1000, 40);\n\t\tlabelVersion.setBounds(280, 40, 1000, 40);\n\t}\n\n\tpublic void paintComponent(Graphics g) {\n\n\t}\n}"
}
] | import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.ArrayList;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.filechooser.FileNameExtensionFilter;
import fr.nicolas.main.ATools;
import fr.nicolas.main.components.ABackground;
import fr.nicolas.main.components.AButtonImg;
import fr.nicolas.main.components.AButtonMatiere;
import fr.nicolas.main.components.ALabel;
import fr.nicolas.main.components.ATextArea;
import fr.nicolas.main.components.ABackground.ABgType;
import fr.nicolas.main.panel.APanelTop; | 3,757 | package fr.nicolas.main.frames;
public class AFrameMenu extends JFrame {
private JPanel base = new JPanel();
private APanelTop panelTop = new APanelTop();
private ABackground bg = new ABackground();
private AButtonImg buttonOpenFile = new AButtonImg("OpenFile");
private ALabel labelText = new ALabel("Fiches enregistrées", 34);
private JFileChooser fileChooser = new JFileChooser();
private JFrame frame = this;
private JPanel panel = new JPanel();
private String nameFiche;
private String nameFolder;
private JPanel fiches = new JPanel();
private CardLayout cardLayout = new CardLayout();
private ArrayList<AButtonMatiere> buttonMatiereList = new ArrayList<AButtonMatiere>();
public AFrameMenu() {
this.setTitle("ReciteEasily - Menu");
this.setSize(1050, 600);
this.setLocationRelativeTo(null);
this.setResizable(false);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setContentPane(base);
this.setIconImage(new ImageIcon(getClass().getResource("/img/icone.png")).getImage());
init();
build();
this.setVisible(true);
}
private void init() {
base.setLayout(new BorderLayout());
fiches.setLayout(cardLayout);
JScrollPane scrollpanePanel = new JScrollPane(panel);
scrollpanePanel.getViewport().setOpaque(false);
scrollpanePanel.setOpaque(false);
scrollpanePanel.setBorder(null);
scrollpanePanel.getVerticalScrollBar().setUnitIncrement(5);
FileNameExtensionFilter extensionFileChooser = new FileNameExtensionFilter(".html", "html");
fileChooser.setFileFilter(extensionFileChooser);
fileChooser.setAcceptAllFileFilterUsed(false);
fileChooser.setDialogTitle("Charger une fiche");
panel.add(fiches);
base.add(bg);
bg.add(panelTop);
bg.add(buttonOpenFile);
bg.add(labelText);
bg.add(scrollpanePanel);
fiches.setBounds(0, 40, 985, 250);
panelTop.setBounds(1, 1, 1200, 90);
buttonOpenFile.setBounds(40, 110, 985, 80);
labelText.setBounds(40, 210, 400, 40);
scrollpanePanel.setBounds(40, 260, 985, 290);
buttonOpenFile.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int fileChooserValue = fileChooser.showOpenDialog(frame);
if (fileChooserValue == JFileChooser.APPROVE_OPTION) {
new AFrameNewFiche(fileChooser.getSelectedFile(), getLocation());
dispose();
}
}
});
}
private void build() {
panel.setLayout(null);
panel.setOpaque(false);
int locX = 0;
File folder = new File("ReciteEasily/Fiches");
String[] listFolders = folder.list();
if (listFolders.length != 0) {
for (int i = 0; i < listFolders.length; i++) {
nameFolder = listFolders[i];
AButtonMatiere buttonMatiere = new AButtonMatiere(nameFolder);
JPanel matierePanel = new JPanel();
matierePanel.setLayout(null);
matierePanel.setBackground(new Color(30, 30, 30));
buttonMatiere.setBounds(locX, 0, 110, 30);
buttonMatiereList.add(buttonMatiere);
if (i == 0) {
buttonMatiere.setSelected(true);
}
panel.add(buttonMatiere);
fiches.add(matierePanel, nameFolder);
buttonMatiere.addActionListener(new ActionListener() {
private String name = nameFolder;
public void actionPerformed(ActionEvent e) {
setMatiereSelected(buttonMatiere);
cardLayout.show(fiches, name);
}
});
locX += 120;
// Charger les fiches
int locY = 0;
File file = new File("ReciteEasily/Fiches/" + nameFolder);
String[] listFiles = file.list();
if (listFiles.length != 0) {
for (int i2 = 0; i2 < listFiles.length; i2++) {
nameFiche = listFiles[i2].replace(".txt", "");
| package fr.nicolas.main.frames;
public class AFrameMenu extends JFrame {
private JPanel base = new JPanel();
private APanelTop panelTop = new APanelTop();
private ABackground bg = new ABackground();
private AButtonImg buttonOpenFile = new AButtonImg("OpenFile");
private ALabel labelText = new ALabel("Fiches enregistrées", 34);
private JFileChooser fileChooser = new JFileChooser();
private JFrame frame = this;
private JPanel panel = new JPanel();
private String nameFiche;
private String nameFolder;
private JPanel fiches = new JPanel();
private CardLayout cardLayout = new CardLayout();
private ArrayList<AButtonMatiere> buttonMatiereList = new ArrayList<AButtonMatiere>();
public AFrameMenu() {
this.setTitle("ReciteEasily - Menu");
this.setSize(1050, 600);
this.setLocationRelativeTo(null);
this.setResizable(false);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setContentPane(base);
this.setIconImage(new ImageIcon(getClass().getResource("/img/icone.png")).getImage());
init();
build();
this.setVisible(true);
}
private void init() {
base.setLayout(new BorderLayout());
fiches.setLayout(cardLayout);
JScrollPane scrollpanePanel = new JScrollPane(panel);
scrollpanePanel.getViewport().setOpaque(false);
scrollpanePanel.setOpaque(false);
scrollpanePanel.setBorder(null);
scrollpanePanel.getVerticalScrollBar().setUnitIncrement(5);
FileNameExtensionFilter extensionFileChooser = new FileNameExtensionFilter(".html", "html");
fileChooser.setFileFilter(extensionFileChooser);
fileChooser.setAcceptAllFileFilterUsed(false);
fileChooser.setDialogTitle("Charger une fiche");
panel.add(fiches);
base.add(bg);
bg.add(panelTop);
bg.add(buttonOpenFile);
bg.add(labelText);
bg.add(scrollpanePanel);
fiches.setBounds(0, 40, 985, 250);
panelTop.setBounds(1, 1, 1200, 90);
buttonOpenFile.setBounds(40, 110, 985, 80);
labelText.setBounds(40, 210, 400, 40);
scrollpanePanel.setBounds(40, 260, 985, 290);
buttonOpenFile.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int fileChooserValue = fileChooser.showOpenDialog(frame);
if (fileChooserValue == JFileChooser.APPROVE_OPTION) {
new AFrameNewFiche(fileChooser.getSelectedFile(), getLocation());
dispose();
}
}
});
}
private void build() {
panel.setLayout(null);
panel.setOpaque(false);
int locX = 0;
File folder = new File("ReciteEasily/Fiches");
String[] listFolders = folder.list();
if (listFolders.length != 0) {
for (int i = 0; i < listFolders.length; i++) {
nameFolder = listFolders[i];
AButtonMatiere buttonMatiere = new AButtonMatiere(nameFolder);
JPanel matierePanel = new JPanel();
matierePanel.setLayout(null);
matierePanel.setBackground(new Color(30, 30, 30));
buttonMatiere.setBounds(locX, 0, 110, 30);
buttonMatiereList.add(buttonMatiere);
if (i == 0) {
buttonMatiere.setSelected(true);
}
panel.add(buttonMatiere);
fiches.add(matierePanel, nameFolder);
buttonMatiere.addActionListener(new ActionListener() {
private String name = nameFolder;
public void actionPerformed(ActionEvent e) {
setMatiereSelected(buttonMatiere);
cardLayout.show(fiches, name);
}
});
locX += 120;
// Charger les fiches
int locY = 0;
File file = new File("ReciteEasily/Fiches/" + nameFolder);
String[] listFiles = file.list();
if (listFiles.length != 0) {
for (int i2 = 0; i2 < listFiles.length; i2++) {
nameFiche = listFiles[i2].replace(".txt", "");
| ATextArea textArea = new ATextArea(getTextFile(ATools.readFile(nameFolder, nameFiche)), 22); | 0 | 2023-10-13 13:17:51+00:00 | 8k |
rgrosa/comes-e-bebes | src/main/java/br/com/project/domain/service/imp/UserServiceImpl.java | [
{
"identifier": "CreateUserDTO",
"path": "src/main/java/br/com/project/domain/dto/CreateUserDTO.java",
"snippet": "public class CreateUserDTO {\n\n private String username;\n private String password;\n private String address;\n private String registrationDocument;\n private RestaurantDTO restaurant;\n private Boolean status;\n\n public String getUsername() {\n return username;\n }\n\n public void setUsername(String username) {\n this.username = username;\n }\n\n public String getPassword() {\n return password;\n }\n\n public void setPassword(String password) {\n this.password = password;\n }\n\n public String getAddress() {\n return address;\n }\n\n public void setAddress(String address) {\n this.address = address;\n }\n\n public String getRegistrationDocument() {\n return registrationDocument;\n }\n\n public void setRegistrationDocument(String registrationDocument) {\n this.registrationDocument = registrationDocument;\n }\n\n public RestaurantDTO getRestaurant() {\n return restaurant;\n }\n\n public void setRestaurant(RestaurantDTO restaurant) {\n this.restaurant = restaurant;\n }\n\n public Boolean getStatus() {\n return status;\n }\n\n public void setStatus(Boolean status) {\n this.status = status;\n }\n}"
},
{
"identifier": "LoggedUserDTO",
"path": "src/main/java/br/com/project/domain/dto/LoggedUserDTO.java",
"snippet": "public class LoggedUserDTO {\n\n private Long id;\n private String username;\n private String password;\n private String jwtToken;\n private Integer userTypeId;\n private String address;\n private String registrationDocument;\n private LocalDateTime updatedAt;\n private LocalDateTime insertedAt;\n private Long restaurantId;\n private Boolean status;\n\n public LoggedUserDTO(Long id, String username, String password, String jwtToken, Integer userTypeId, String address, String registrationDocument, LocalDateTime updatedAt, LocalDateTime insertedAt, Long restaurantId, Boolean status) {\n this.id = id;\n this.username = username;\n this.password = password;\n this.jwtToken = jwtToken;\n this.userTypeId = userTypeId;\n this.address = address;\n this.registrationDocument = registrationDocument;\n this.updatedAt = updatedAt;\n this.insertedAt = insertedAt;\n this.restaurantId = restaurantId;\n this.status = status;\n }\n\n public Integer getUserTypeId() {\n return userTypeId;\n }\n\n public void setUserTypeId(Integer userTypeId) {\n this.userTypeId = userTypeId;\n }\n\n public String getAddress() {\n return address;\n }\n\n public void setAddress(String address) {\n this.address = address;\n }\n\n public String getRegistrationDocument() {\n return registrationDocument;\n }\n\n public void setRegistrationDocument(String registrationDocument) {\n this.registrationDocument = registrationDocument;\n }\n\n public LocalDateTime getUpdatedAt() {\n return updatedAt;\n }\n\n public void setUpdatedAt(LocalDateTime updatedAt) {\n this.updatedAt = updatedAt;\n }\n\n public LocalDateTime getInsertedAt() {\n return insertedAt;\n }\n\n public void setInsertedAt(LocalDateTime insertedAt) {\n this.insertedAt = insertedAt;\n }\n\n public Long getRestaurantId() {\n return restaurantId;\n }\n\n public void setRestaurantId(Long restaurantId) {\n this.restaurantId = restaurantId;\n }\n\n public Boolean getStatus() {\n return status;\n }\n\n public void setStatus(Boolean status) {\n this.status = status;\n }\n\n public Long getId() {\n return id;\n }\n\n public void setId(Long id) {\n this.id = id;\n }\n\n public String getUsername() {\n return username;\n }\n\n public void setUsername(String username) {\n this.username = username;\n }\n\n public String getPassword() {\n return password;\n }\n\n public void setPassword(String password) {\n this.password = password;\n }\n\n public String getJwtToken() {\n return jwtToken;\n }\n\n public void setJwtToken(String jwtToken) {\n this.jwtToken = jwtToken;\n }\n}"
},
{
"identifier": "LoggedUserDetailsDTO",
"path": "src/main/java/br/com/project/domain/dto/LoggedUserDetailsDTO.java",
"snippet": "public class LoggedUserDetailsDTO implements UserDetails {\n\n private static final long serialVersionUID = 1L;\n\n private LoggedUserDTO loggedUser;\n\n public LoggedUserDetailsDTO(LoggedUserDTO loggedUser) {\n this.loggedUser = loggedUser;\n }\n\n @Override\n public Collection<? extends GrantedAuthority> getAuthorities() {\n return null;\n }\n\n @Override\n public String getPassword() {\n return this.loggedUser.getPassword();\n }\n\n @Override\n public String getUsername() {\n return this.loggedUser.getUsername();\n }\n\n @Override\n public boolean isAccountNonExpired() {\n return true;\n }\n\n @Override\n public boolean isAccountNonLocked() {\n return true;\n }\n\n @Override\n public boolean isCredentialsNonExpired() {\n return true;\n }\n\n @Override\n public boolean isEnabled() {\n return true;\n }\n\n public LoggedUserDTO getLoggedUser() {\n return loggedUser;\n }\n\n public void setLoggedUser(LoggedUserDTO loggedUser) {\n this.loggedUser = loggedUser;\n }\n}"
},
{
"identifier": "UserLoginDTO",
"path": "src/main/java/br/com/project/domain/dto/UserLoginDTO.java",
"snippet": "public class UserLoginDTO implements Serializable {\n @Serial\n private static final long serialVersionUID = 1L;\n\n private String userName;\n private String password;\n\n public String getUserName() {\n return userName;\n }\n\n public void setUserName(String userName) {\n this.userName = userName;\n }\n\n public String getPassword() {\n return password;\n }\n\n public void setPassword(String password) {\n this.password = password;\n }\n\n\n}"
},
{
"identifier": "RestaurantEntity",
"path": "src/main/java/br/com/project/domain/entity/RestaurantEntity.java",
"snippet": "@Entity\n@Table(name = \"RESTAURANT\")\npublic class RestaurantEntity {\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n @Column(name = \"ID\")\n private Long id;\n @Column(name = \"RESTAURANT_NAME\")\n private String restaurantName;\n @Column(name = \"ADDRESS\")\n private String address;\n @Column(name = \"WORK_TIME\")\n private String workTime;\n @Column(name = \"RESTAURANT_IMAGE\")\n private String restaurantImage;\n @Column(name = \"UPDATED_AT\")\n private LocalDateTime updatedAt;\n @Column(name = \"INSERTED_AT\")\n private LocalDateTime createdAt;\n\n @PrePersist\n private void prePersist(){\n this.createdAt = LocalDateTime.now();\n this.updatedAt = LocalDateTime.now();\n }\n\n @PreUpdate\n private void preUpdate(){\n this.updatedAt = LocalDateTime.now();\n }\n\n\n public Long getId() {\n return id;\n }\n\n public void setId(Long id) {\n this.id = id;\n }\n\n public String getRestaurantName() {\n return restaurantName;\n }\n\n public void setRestaurantName(String restaurantName) {\n this.restaurantName = restaurantName;\n }\n\n public String getAddress() {\n return address;\n }\n\n public void setAddress(String address) {\n this.address = address;\n }\n\n public String getWorkTime() {\n return workTime;\n }\n\n public void setWorkTime(String workTime) {\n this.workTime = workTime;\n }\n\n public LocalDateTime getUpdatedAt() {\n return updatedAt;\n }\n\n public void setUpdatedAt(LocalDateTime updatedAt) {\n this.updatedAt = updatedAt;\n }\n\n public LocalDateTime getCreatedAt() {\n return createdAt;\n }\n\n public void setCreatedAt(LocalDateTime createdAt) {\n this.createdAt = createdAt;\n }\n\n public String getRestaurantImage() {\n return restaurantImage;\n }\n\n public void setRestaurantImage(String restaurantImage) {\n this.restaurantImage = restaurantImage;\n }\n}"
},
{
"identifier": "UserEntity",
"path": "src/main/java/br/com/project/domain/entity/UserEntity.java",
"snippet": "@Entity\n@Table(name = \"USERS\")\npublic class UserEntity {\n\n @Id\n @GeneratedValue(strategy = GenerationType.IDENTITY)\n @Column(name = \"ID\")\n private Long id;\n @Column(name = \"USERNAME\")\n private String userName;\n @Column(name = \"PASSWORD\")\n private String password;\n @Column(name = \"USER_TYPE_ID\")\n private Integer userTypeId;\n @Column(name = \"ADDRESS\")\n private String address;\n @Column(name = \"REGISTRATION_DOCUMENT\")\n private String registrationDocument;\n @Column(name = \"UPDATED_AT\")\n private LocalDateTime updatedAt;\n @Column(name = \"INSERTED_AT\")\n private LocalDateTime createdAt;\n @Column(name = \"RESTAURANT_ID\")\n private Long restaurantId;\n @Column(name = \"STATUS\")\n private Boolean status;\n\n\n @PrePersist\n private void prePersist(){\n this.createdAt = LocalDateTime.now();\n this.updatedAt = LocalDateTime.now();\n }\n\n @PreUpdate\n private void preUpdate(){\n this.updatedAt = LocalDateTime.now();\n }\n\n public Long getId() {\n return id;\n }\n\n public void setId(Long id) {\n this.id = id;\n }\n\n public String getUserName() {\n return userName;\n }\n\n public void setUserName(String userName) {\n this.userName = userName;\n }\n\n public String getPassword() {\n return password;\n }\n\n public void setPassword(String password) {\n this.password = password;\n }\n\n public Integer getUserTypeId() {\n return userTypeId;\n }\n\n public void setUserTypeId(Integer userTypeId) {\n this.userTypeId = userTypeId;\n }\n\n public String getAddress() {\n return address;\n }\n\n public void setAddress(String address) {\n this.address = address;\n }\n\n public String getRegistrationDocument() {\n return registrationDocument;\n }\n\n public void setRegistrationDocument(String registrationDocument) {\n this.registrationDocument = registrationDocument;\n }\n\n public LocalDateTime getUpdatedAt() {\n return updatedAt;\n }\n\n public void setUpdatedAt(LocalDateTime updatedAt) {\n this.updatedAt = updatedAt;\n }\n\n public LocalDateTime getCreatedAt() {\n return createdAt;\n }\n\n public void setCreatedAt(LocalDateTime createdAt) {\n this.createdAt = createdAt;\n }\n\n public Long getRestaurantId() {\n return restaurantId;\n }\n\n public void setRestaurantId(Long restaurantId) {\n this.restaurantId = restaurantId;\n }\n\n public Boolean getStatus() {\n return status;\n }\n\n public void setStatus(Boolean status) {\n this.status = status;\n }\n}"
},
{
"identifier": "RestaurantRepository",
"path": "src/main/java/br/com/project/domain/repository/RestaurantRepository.java",
"snippet": "@Repository\npublic interface RestaurantRepository extends JpaRepository<RestaurantEntity, Long> {\n\n}"
},
{
"identifier": "PasswordException",
"path": "src/main/java/br/com/project/infrasctructure/exception/PasswordException.java",
"snippet": "@ResponseStatus(value = HttpStatus.UNAUTHORIZED)\npublic class PasswordException extends Exception{\n\n @Serial\n private static final long serialVersionUID = 1L;\n\n public PasswordException(final String message) {\n super(message);\n }\n}"
},
{
"identifier": "ResourceNotFoundException",
"path": "src/main/java/br/com/project/infrasctructure/exception/ResourceNotFoundException.java",
"snippet": "@ResponseStatus(value = HttpStatus.NOT_FOUND)\npublic class ResourceNotFoundException extends Exception{\n\n\t@Serial\n\tprivate static final long serialVersionUID = 1L;\n\n\tpublic ResourceNotFoundException(final String message) {\n \tsuper(message);\n }\n}"
},
{
"identifier": "UserRepository",
"path": "src/main/java/br/com/project/domain/repository/UserRepository.java",
"snippet": "@Repository\npublic interface UserRepository extends JpaRepository<UserEntity, Long> {\n\n Optional<UserEntity> findByUserName(String name);\n\n}"
},
{
"identifier": "UserService",
"path": "src/main/java/br/com/project/domain/service/UserService.java",
"snippet": "public interface UserService {\n\n LoggedUserDTO postLogin(UserLoginDTO userLoginDto) throws PasswordException;\n\n UserDetails loadUserByUsername(String username) throws ResourceNotFoundException;\n\n UserDetails createClient(CreateUserDTO createUserDTO) throws Exception;\n\n UserDetails createOwner(CreateUserDTO createUserDTO) throws Exception;\n}"
},
{
"identifier": "CryptPassword",
"path": "src/main/java/br/com/project/infrasctructure/util/auth/CryptPassword.java",
"snippet": "@Component\npublic class CryptPassword implements PasswordEncoder {\n\n private static SecretKey myKey;\n\n static char[] hexChar = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };\n\n private static final Logger log = LoggerFactory.getLogger(CryptPassword.class);\n\n\n @Override\n public boolean matches(CharSequence rawPassword, String encodedPassword) {\n return encodedPassword.equals(encode(rawPassword));\n }\n\n @Override\n public String encode(CharSequence msg) {\n Cipher c;\n String ret = \"\";\n try {\n String strKey = \"EIR=5EXA\";\n byte[] byteKey = strKey.getBytes();\n DESKeySpec desKeySpec = new DESKeySpec(byteKey);\n SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(\"DES\");\n myKey = keyFactory.generateSecret(desKeySpec);\n c = Cipher.getInstance(\"DES\");\n c.init(Cipher.ENCRYPT_MODE, myKey);\n byte[] cipherText = c.doFinal(((String) msg).getBytes());\n ret = toHexString(cipherText);\n } catch (Exception e) {\n log.error(\"Exception password\");\n }\n return ret;\n }\n\n private String toHexString(byte[] b) {\n StringBuffer sb = new StringBuffer(b.length * 2);\n for (int i = 0; i < b.length; i++) {\n // look up high nibble char\n sb.append(hexChar[(b[i] & 0xf0) >>> 4]);\n // look up low nibble char\n sb.append(hexChar[b[i] & 0x0f]);\n }\n return sb.toString();\n }\n}"
},
{
"identifier": "JwtTokenUtil",
"path": "src/main/java/br/com/project/infrasctructure/util/auth/JwtTokenUtil.java",
"snippet": "@Component\npublic class JwtTokenUtil {\n\n public static final long JWT_TOKEN_VALIDITY = 604800;//seven days in seconds\n\n private final String secret = \"project\";\n\n public String getUsernameFromToken(String token) {\n return getClaimFromToken(token, Claims::getSubject);\n }\n\n public Date getExpirationDateFromToken(String token) {\n return getClaimFromToken(token, Claims::getExpiration);\n }\n\n public <T> T getClaimFromToken(String token, Function<Claims, T> claimsResolver) {\n final Claims claims = getAllClaimsFromToken(token);\n return claimsResolver.apply(claims);\n }\n\n private Claims getAllClaimsFromToken(String token) {\n return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();\n }\n\n private Boolean isTokenExpired(String token) {\n final Date expiration = getExpirationDateFromToken(token);\n return expiration.before(new Date());\n }\n\n public String generateToken(UserDetails userDetails) {\n Map<String, Object> claims = new HashMap<String, Object>();\n return doGenerateToken(claims, userDetails.getUsername());\n }\n\n private String doGenerateToken(Map<String, Object> claims, String subject) {\n return Jwts.builder().setClaims(claims).setSubject(subject).setIssuedAt(new Date(System.currentTimeMillis()))\n .setExpiration(new Date(System.currentTimeMillis() + JWT_TOKEN_VALIDITY*1000)).signWith(SignatureAlgorithm.HS512, secret).compact();\n }\n\n public Boolean validateToken(String token, UserDetails userDetails) {\n final String userName = getUsernameFromToken(token);\n return (userName.equals(userDetails.getUsername()) && !isTokenExpired(token));\n }\n\n public static Long getIdFromCurrentUser(Principal principal){\n LoggedUserDetailsDTO userLoginDTO = (LoggedUserDetailsDTO) ((UsernamePasswordAuthenticationToken) principal).getPrincipal();\n return userLoginDTO.getLoggedUser().getId();\n }\n}"
}
] | import br.com.project.domain.dto.CreateUserDTO;
import br.com.project.domain.dto.LoggedUserDTO;
import br.com.project.domain.dto.LoggedUserDetailsDTO;
import br.com.project.domain.dto.UserLoginDTO;
import br.com.project.domain.entity.RestaurantEntity;
import br.com.project.domain.entity.UserEntity;
import br.com.project.domain.repository.RestaurantRepository;
import br.com.project.infrasctructure.exception.PasswordException;
import br.com.project.infrasctructure.exception.ResourceNotFoundException;
import br.com.project.domain.repository.UserRepository;
import br.com.project.domain.service.UserService;
import br.com.project.infrasctructure.util.auth.CryptPassword;
import br.com.project.infrasctructure.util.auth.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import java.util.Optional; | 4,303 | package br.com.project.domain.service.imp;
@Service
public class UserServiceImpl implements UserService {
@Autowired
UserRepository userRepository;
@Autowired
RestaurantRepository restaurantRepository;
@Autowired
CryptPassword cryptPassword;
@Autowired
JwtTokenUtil jwtTokenUtil;
private final static int C_CLIENT_ID = 1;
private final static int C_OWNER_ID = 2;
@Override
public LoggedUserDTO postLogin(UserLoginDTO userLoginDto) throws PasswordException {
try {
return generateUserLogin(userLoginDto);
} catch (Exception ex) {
throw new PasswordException(ex.getMessage());
}
}
@Override | package br.com.project.domain.service.imp;
@Service
public class UserServiceImpl implements UserService {
@Autowired
UserRepository userRepository;
@Autowired
RestaurantRepository restaurantRepository;
@Autowired
CryptPassword cryptPassword;
@Autowired
JwtTokenUtil jwtTokenUtil;
private final static int C_CLIENT_ID = 1;
private final static int C_OWNER_ID = 2;
@Override
public LoggedUserDTO postLogin(UserLoginDTO userLoginDto) throws PasswordException {
try {
return generateUserLogin(userLoginDto);
} catch (Exception ex) {
throw new PasswordException(ex.getMessage());
}
}
@Override | public UserDetails loadUserByUsername(String username) throws ResourceNotFoundException { | 8 | 2023-10-10 23:22:15+00:00 | 8k |
Stachelbeere1248/zombies-utils | src/main/java/com/github/stachelbeere1248/zombiesutils/mixin/MixinNetHandlerPlayClient.java | [
{
"identifier": "ZombiesUtils",
"path": "src/main/java/com/github/stachelbeere1248/zombiesutils/ZombiesUtils.java",
"snippet": "@Mod(modid = \"zombiesutils\", useMetadata = true, clientSideOnly = true, guiFactory = \"com.github.stachelbeere1248.zombiesutils.config.GuiFactory\")\npublic class ZombiesUtils {\n private static ZombiesUtils instance;\n private final Hotkeys hotkeys;\n private Logger logger;\n\n public ZombiesUtils() {\n hotkeys = new Hotkeys();\n instance = this;\n }\n\n public static ZombiesUtils getInstance() {\n return instance;\n }\n\n @Mod.EventHandler\n public void preInit(@NotNull FMLPreInitializationEvent event) {\n logger = event.getModLog();\n ZombiesUtilsConfig.config = new Configuration(\n event.getSuggestedConfigurationFile(),\n \"1.2.4\"\n );\n ZombiesUtilsConfig.load();\n }\n\n @Mod.EventHandler\n public void init(FMLInitializationEvent event) {\n HandlerRegistry.registerAll();\n CommandRegistry.registerAll();\n hotkeys.registerAll();\n }\n\n public Logger getLogger() {\n return logger;\n }\n\n public Hotkeys getHotkeys() {\n return hotkeys;\n }\n}"
},
{
"identifier": "Timer",
"path": "src/main/java/com/github/stachelbeere1248/zombiesutils/timer/Timer.java",
"snippet": "public class Timer {\n\n public static Timer instance;\n private final GameMode gameMode;\n private final String serverNumber;\n private final GameFile gameFile;\n public Category category;\n private long savedTotalWorldTime;\n private int passedRoundsTickSum = 0;\n private boolean pbTracking = false;\n private int round;\n private boolean r1Corrected = false;\n\n /**\n * @param serverNumber The game's server the timer should be bound to.\n * @param map The map the timer should be started for.\n * @param round If available, round to begin splitting.\n */\n public Timer(@NotNull String serverNumber, @NotNull Map map, byte round) throws TimerException.ServerNumberException {\n this.savedTotalWorldTime = getCurrentTotalWorldTime();\n if (!serverNumber.trim().isEmpty()) this.serverNumber = serverNumber.trim();\n else throw new Timer.TimerException.ServerNumberException();\n\n this.category = new Category();\n this.gameFile = new GameFile(serverNumber.trim(), map);\n\n this.gameMode = new GameMode(map);\n this.round = round;\n if (ZombiesUtilsConfig.isSlaToggled()) SLA.instance = new SLA(map);\n\n MinecraftForge.EVENT_BUS.register(new Round1Correction());\n }\n\n public static Optional<Timer> getInstance() {\n return Optional.ofNullable(instance);\n }\n\n /**\n * Call to invalidate {@link #instance} to trigger the garbage collector\n */\n public static void dropInstances() {\n instance = null;\n }\n\n /**\n * The main splitting function.\n * Cancels on the second occurring sound-effect, important for {@link RecordManager} to not override values incorrectly.\n *\n * @param passedRound The round that has been passed.\n */\n public void split(byte passedRound) {\n final int gameTime = gameTime();\n final short roundTime = (short) (gameTime - passedRoundsTickSum);\n\n if ((round == passedRound) || (passedRound == 0) || (roundTime < 100)) {\n ZombiesUtils.getInstance().getLogger().debug(\"SPLIT CANCELLED\");\n return;\n }\n\n try {\n record(passedRound, roundTime, gameTime);\n } catch (Exception e) {\n ZombiesUtils.getInstance().getLogger().error(ExceptionUtils.getStackTrace(e));\n Minecraft.getMinecraft().thePlayer.addChatMessage(new ChatComponentText(\"Error saving splits\"));\n }\n\n passedRoundsTickSum = gameTime;\n round = passedRound;\n }\n\n public void correctRn() {\n if (r1Corrected) return;\n savedTotalWorldTime = getCurrentTotalWorldTime() - 200L;\n r1Corrected = true;\n }\n\n private void record(byte passedRound, short roundTime, int gameTime) {\n if (passedRound == (byte) 1) pbTracking = true;\n\n try {\n RecordManager.compareSegment(passedRound, roundTime, category);\n if (pbTracking) RecordManager.compareBest(passedRound, gameTime, category);\n\n gameFile.setSegment(passedRound, roundTime);\n } catch (IndexOutOfBoundsException exception) {\n Minecraft.getMinecraft().thePlayer.addChatMessage(new ChatComponentText(\n String.format(\"Split not recorded. (invalid round parsed from scoreboard: %s)\", passedRound)\n ));\n }\n }\n\n private long getCurrentTotalWorldTime() {\n if (Minecraft.getMinecraft() == null) return 0;\n if (Minecraft.getMinecraft().theWorld == null) return 0;\n return Minecraft.getMinecraft().theWorld.getTotalWorldTime();\n }\n\n public int gameTime() {\n return (int) (getCurrentTotalWorldTime() - savedTotalWorldTime);\n }\n\n public short roundTime() {\n return (short) (gameTime() - passedRoundsTickSum);\n }\n\n /**\n * @param serverNumber Servernumber to be compared\n * @return false, if and only if input exists and is unequal to {@link #serverNumber}\n */\n public boolean equalsServerOrNull(String serverNumber) {\n return (serverNumber == null || serverNumber.equals(this.serverNumber) || serverNumber.isEmpty());\n }\n\n public void setCategory(Category category) {\n this.category = category;\n }\n\n public byte getRound() {\n return (byte) (round + 1);\n }\n\n public GameMode getGameMode() {\n return gameMode;\n }\n\n public static abstract class TimerException extends Exception {\n\n public static class MapException extends TimerException {\n }\n\n public static class ServerNumberException extends TimerException {\n }\n }\n}"
},
{
"identifier": "LanguageSupport",
"path": "src/main/java/com/github/stachelbeere1248/zombiesutils/utils/LanguageSupport.java",
"snippet": "@SuppressWarnings(\"SpellCheckingInspection\")\npublic class LanguageSupport {\n private static final String[] LANGUAGEs = {\n \"EN\",\n \"FR\",\n \"DE\"\n };\n\n public static boolean isLoss(@NotNull String input) {\n final String[] words = {\n \"§cGame Over!\",\n \"§cPartie terminée!\",\n \"§cDas Spiel ist vorbei!\"\n };\n return Arrays.asList(words).contains(input);\n }\n\n public static boolean isWin(@NotNull String input) {\n final String[] words = {\n \"§aYou Win!\",\n \"§aVous avez gagné!\",\n \"§aDu gewinnst!\"\n };\n return Arrays.asList(words).contains(input);\n }\n\n public static boolean containsHard(@NotNull String input) {\n final String[] words = {\n \"Hard Difficulty\",\n \"Difficulté Hard\",\n \"Hard Schwierigkeitsgrad\",\n \"困难\",\n \"困難\"\n };\n return Arrays.stream(words).anyMatch(input::contains);\n }\n\n public static boolean containsRIP(@NotNull String input) {\n final String[] words = {\n \"RIP Difficulty\",\n \"Difficulté RIP\",\n \"RIP Schwierigkeitsgrad\",\n \"安息\"\n };\n return Arrays.stream(words).anyMatch(input::contains);\n }\n\n public static @NotNull Pattern roundPattern(@NotNull String language) {\n switch (language) {\n case \"EN\":\n return Pattern.compile(\"Round ([0-9]{1,3})\");\n case \"FR\":\n return Pattern.compile(\"Manche ([0-9]{1,3})\");\n case \"DE\":\n return Pattern.compile(\"Runde ([0-9]{1,3})\");\n default:\n throw new IllegalStateException(\"Unexpected value: \" + language);\n }\n }\n\n public static @NotNull Pattern mapPattern(@NotNull String language) {\n switch (language) {\n case \"EN\":\n return Pattern.compile(\"Map:.*(Dead End|Bad Blood|Alien Arcadium)\");\n case \"FR\":\n return Pattern.compile(\"Carte:.*(Dead End|Bad Blood|Alien Arcadium)\");\n case \"DE\":\n return Pattern.compile(\"Karte:.*(Dead End|Bad Blood|Alien Arcadium)\");\n default:\n throw new IllegalStateException(\"Unexpected value: \" + language);\n }\n }\n\n public static String[] getLanguages() {\n return LANGUAGEs;\n }\n}"
},
{
"identifier": "Scoreboard",
"path": "src/main/java/com/github/stachelbeere1248/zombiesutils/utils/Scoreboard.java",
"snippet": "public class Scoreboard {\n @SuppressWarnings(\"UnnecessaryUnicodeEscape\")\n private static final Pattern SIDEBAR_EMOJI_PATTERN = Pattern.compile(\"[\\uD83D\\uDD2B\\uD83C\\uDF6B\\uD83D\\uDCA3\\uD83D\\uDC7D\\uD83D\\uDD2E\\uD83D\\uDC0D\\uD83D\\uDC7E\\uD83C\\uDF20\\uD83C\\uDF6D\\u26BD\\uD83C\\uDFC0\\uD83D\\uDC79\\uD83C\\uDF81\\uD83C\\uDF89\\uD83C\\uDF82]+\");\n private static final Pattern STRIP_COLOR_PATTERN = Pattern.compile(\"§[0-9A-FK-ORZ]\", Pattern.CASE_INSENSITIVE);\n private static final Pattern SERVER_NUMBER_PATTERN = Pattern.compile(\".*([mLM][0-9A-Z]+)\");\n\n private static String title = null;\n private static List<String> lines = null;\n\n /**\n * Overrides {@link #title} and {@link #lines} if a valid scoreboard is present\n */\n public static void refresh() {\n // Null-checks\n if ((Minecraft.getMinecraft() == null)\n || (Minecraft.getMinecraft().theWorld == null)\n || Minecraft.getMinecraft().isSingleplayer()\n ) return;\n if (Minecraft.getMinecraft().thePlayer == null) return;\n net.minecraft.scoreboard.Scoreboard scoreboard = Minecraft.getMinecraft().theWorld.getScoreboard();\n ScoreObjective sidebar = scoreboard.getObjectiveInDisplaySlot(1);\n if (sidebar == null) return;\n\n // get\n title = STRIP_COLOR_PATTERN.matcher(sidebar.getDisplayName().trim()).replaceAll(\"\");\n Collection<Score> scoreCollection = scoreboard.getSortedScores(sidebar);\n List<Score> filteredScores = scoreCollection.stream().filter(input -> input.getPlayerName() != null && !input.getPlayerName().startsWith(\"#\")).collect(Collectors.toList());\n\n List<Score> scores;\n if (filteredScores.size() > 15)\n scores = Lists.newArrayList(Iterables.skip(filteredScores, scoreCollection.size() - 15));\n else scores = filteredScores;\n scores = Lists.reverse(scores);\n\n lines = new ArrayList<>();\n for (Score score : scores\n ) {\n ScorePlayerTeam team = scoreboard.getPlayersTeam(score.getPlayerName());\n String scoreboardLine = ScorePlayerTeam.formatPlayerName(team, score.getPlayerName()).trim();\n lines.add(STRIP_COLOR_PATTERN.matcher(SIDEBAR_EMOJI_PATTERN.matcher(scoreboardLine).replaceAll(\"\")).replaceAll(\"\"));\n }\n }\n\n public static byte getRound() {\n String line;\n try {\n line = lines.get(2);\n } catch (IndexOutOfBoundsException | NullPointerException ignored) {\n return 0;\n }\n final Pattern ROUND_LINE_PATTERN = LanguageSupport.roundPattern(ZombiesUtilsConfig.getLanguage());\n\n String string = ROUND_LINE_PATTERN.matcher(line).replaceAll(\"$1\");\n\n byte round;\n try {\n round = Byte.parseByte(string);\n ZombiesUtils.getInstance().getLogger().debug(\"Round: \" + round);\n return round;\n } catch (NumberFormatException ignored) {\n return 0;\n }\n }\n\n public static Optional<String> getServerNumber() {\n String line;\n try {\n line = lines.get(0);\n } catch (IndexOutOfBoundsException | NullPointerException ignored) {\n return Optional.empty();\n }\n\n String string = SERVER_NUMBER_PATTERN.matcher(line).replaceAll(\"$1\");\n ZombiesUtils.getInstance().getLogger().debug(\"Servernumber: \" + string);\n return Optional.ofNullable(string);\n }\n\n public static Optional<Map> getMap() {\n String line;\n try {\n line = lines.get(12);\n } catch (Exception couldBePregame) {\n try {\n line = lines.get(2);\n } catch (IndexOutOfBoundsException | NullPointerException ignored) {\n return Optional.empty();\n }\n }\n final Pattern MAP_PATTERN = LanguageSupport.mapPattern(ZombiesUtilsConfig.getLanguage());\n String mapString = MAP_PATTERN.matcher(line).replaceAll(\"$1\");\n switch (mapString) {\n case \"Dead End\":\n return Optional.of(Map.DEAD_END);\n case \"Bad Blood\":\n return Optional.of(Map.BAD_BLOOD);\n case \"Alien Arcadium\":\n return Optional.of(Map.ALIEN_ARCADIUM);\n default:\n return Optional.empty();\n }\n\n }\n\n public static int getLineCount() {\n return lines.size();\n }\n\n public static boolean isNotZombies() {\n return (!\"ZOMBIES\".equals(title));\n }\n}"
}
] | import com.github.stachelbeere1248.zombiesutils.ZombiesUtils;
import com.github.stachelbeere1248.zombiesutils.timer.Timer;
import com.github.stachelbeere1248.zombiesutils.utils.LanguageSupport;
import com.github.stachelbeere1248.zombiesutils.utils.Scoreboard;
import net.minecraft.client.Minecraft;
import net.minecraft.client.network.NetHandlerPlayClient;
import net.minecraft.network.play.server.S29PacketSoundEffect;
import net.minecraft.network.play.server.S45PacketTitle;
import net.minecraft.util.ChatComponentText;
import org.jetbrains.annotations.NotNull;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; | 3,623 | package com.github.stachelbeere1248.zombiesutils.mixin;
@Mixin(NetHandlerPlayClient.class)
public class MixinNetHandlerPlayClient {
@Unique
private boolean zombies_utils$alienUfoOpened;
@Inject(method = "handleSoundEffect", at = @At(value = "HEAD"))
private void handleSound(S29PacketSoundEffect packetIn, CallbackInfo ci) {
zombies_utils$handleSound(packetIn);
}
@Inject(method = "handleTitle", at = @At(value = "HEAD"))
private void handleTitle(S45PacketTitle packetIn, CallbackInfo ci) {
zombies_utils$handleTitle(packetIn);
}
@Unique
private void zombies_utils$handleSound(@NotNull S29PacketSoundEffect packet) {
if (Scoreboard.isNotZombies()) return;
final String soundEffect = packet.getSoundName();
if (!(
soundEffect.equals("mob.wither.spawn")
|| (soundEffect.equals("mob.guardian.curse") && !zombies_utils$alienUfoOpened)
)) return;
zombies_utils$alienUfoOpened = soundEffect.equals("mob.guardian.curse");
try { | package com.github.stachelbeere1248.zombiesutils.mixin;
@Mixin(NetHandlerPlayClient.class)
public class MixinNetHandlerPlayClient {
@Unique
private boolean zombies_utils$alienUfoOpened;
@Inject(method = "handleSoundEffect", at = @At(value = "HEAD"))
private void handleSound(S29PacketSoundEffect packetIn, CallbackInfo ci) {
zombies_utils$handleSound(packetIn);
}
@Inject(method = "handleTitle", at = @At(value = "HEAD"))
private void handleTitle(S45PacketTitle packetIn, CallbackInfo ci) {
zombies_utils$handleTitle(packetIn);
}
@Unique
private void zombies_utils$handleSound(@NotNull S29PacketSoundEffect packet) {
if (Scoreboard.isNotZombies()) return;
final String soundEffect = packet.getSoundName();
if (!(
soundEffect.equals("mob.wither.spawn")
|| (soundEffect.equals("mob.guardian.curse") && !zombies_utils$alienUfoOpened)
)) return;
zombies_utils$alienUfoOpened = soundEffect.equals("mob.guardian.curse");
try { | if (Timer.getInstance().isPresent()) { | 1 | 2023-10-11 01:30:28+00:00 | 8k |
gustavofg1pontes/Tickets-API | infrastructure/src/main/java/br/com/ifsp/tickets/api/infra/config/usecases/GuestUseCaseConfig.java | [
{
"identifier": "CreateGuestUseCase",
"path": "application/src/main/java/br/com/ifsp/tickets/api/app/guest/create/CreateGuestUseCase.java",
"snippet": "public abstract class CreateGuestUseCase extends UseCase<CreateGuestCommand, CreateGuestOutput>{\n}"
},
{
"identifier": "DefaultCreateGuestUseCase",
"path": "application/src/main/java/br/com/ifsp/tickets/api/app/guest/create/DefaultCreateGuestUseCase.java",
"snippet": "public class DefaultCreateGuestUseCase extends CreateGuestUseCase {\n private final GuestGateway guestGateway;\n private final EventGateway eventGateway;\n\n public DefaultCreateGuestUseCase(final GuestGateway guestGateway, final EventGateway eventGateway) {\n this.guestGateway = guestGateway;\n this.eventGateway = eventGateway;\n }\n\n @Override\n public CreateGuestOutput execute(final CreateGuestCommand anIn) {\n final EventID eventID = EventID.from(anIn.eventID());\n final String name = anIn.name();\n final Integer age = anIn.age();\n final String document = anIn.document();\n final String phoneNumber = anIn.phoneNumber();\n final String email = anIn.email();\n final Profile profile = anIn.profile();\n\n final Event event = eventGateway.findById(eventID).orElseThrow(notFound(eventID));\n final Guest guest = Guest.with(GuestID.unique(), eventID, null, name, age, document, false, false, false, phoneNumber,\n email, profile);\n\n final Notification notification = Notification.create();\n guest.validate(notification);\n\n if (notification.hasError())\n throw new NotificationException(\"Could not create guest\", notification);\n\n event.addTicketSold();\n this.update(event);\n return CreateGuestOutput.from(this.create(guest));\n }\n\n private void update(final Event event){\n try{\n this.eventGateway.update(event);\n }catch (final Throwable t){\n throw InternalErrorException.with(\n \"an error on update event was observed [eventID:%s]\".formatted(event.getId().getValue()),\n t);\n }\n }\n\n private Guest create(final Guest aGuest) {\n try {\n return this.guestGateway.create(aGuest);\n } catch (final Throwable t) {\n throw InternalErrorException.with(\n \"An error on create guest was observed [guestID:%s]\".formatted(aGuest.getId().getValue()),\n t\n );\n }\n }\n\n private Supplier<NotFoundException> notFound(final EventID anId) {\n return () -> NotFoundException.with(Event.class, anId);\n }\n\n}"
},
{
"identifier": "DefaultDeleteGuestsByEventUseCase",
"path": "application/src/main/java/br/com/ifsp/tickets/api/app/guest/delete/event/DefaultDeleteGuestsByEventUseCase.java",
"snippet": "public class DefaultDeleteGuestsByEventUseCase extends DeleteGuestsByEventUseCase {\n\n private final GuestGateway guestGateway;\n private final EventGateway eventGateway;\n\n public DefaultDeleteGuestsByEventUseCase(GuestGateway guestGateway, EventGateway eventGateway) {\n this.guestGateway = guestGateway;\n this.eventGateway = eventGateway;\n }\n\n @Override\n public void execute(String anIn) {\n EventID eventID = EventID.from(anIn);\n\n if (!this.eventGateway.existsById(eventID))\n throw NotFoundException.with(Event.class, eventID);\n\n this.guestGateway.deleteAllByEvent(eventID);\n\n final Event event = eventGateway.findById(eventID)\n .orElseThrow(notFound(eventID));\n event.setSoldTickets(0);\n this.update(event);\n }\n\n private void update(final Event event){\n try{\n this.eventGateway.update(event);\n }catch (final Throwable t){\n throw InternalErrorException.with(\n \"an error on update event was observed [eventID:%s]\".formatted(event.getId().getValue()),\n t);\n }\n }\n\n private Supplier<NotFoundException> notFound(final GuestID anId) {\n return () -> NotFoundException.with(Guest.class, anId);\n }\n private Supplier<NotFoundException> notFound(final EventID anId) {\n return () -> NotFoundException.with(Event.class, anId);\n }\n\n}"
},
{
"identifier": "DeleteGuestsByEventUseCase",
"path": "application/src/main/java/br/com/ifsp/tickets/api/app/guest/delete/event/DeleteGuestsByEventUseCase.java",
"snippet": "public abstract class DeleteGuestsByEventUseCase extends UnitUseCase<String> {\n}"
},
{
"identifier": "DefaultDeleteGuestByEventAndNameUseCase",
"path": "application/src/main/java/br/com/ifsp/tickets/api/app/guest/delete/eventIdAndName/DefaultDeleteGuestByEventAndNameUseCase.java",
"snippet": "public class DefaultDeleteGuestByEventAndNameUseCase extends DeleteGuestByEventAndNameUseCase {\n private final GuestGateway guestGateway;\n private final EventGateway eventGateway;\n\n public DefaultDeleteGuestByEventAndNameUseCase(GuestGateway guestGateway, EventGateway eventGateway) {\n this.guestGateway = guestGateway;\n this.eventGateway = eventGateway;\n }\n\n @Override\n public void execute(DeleteGuestByEventAndNameCommand anIn) {\n final EventID eventID = EventID.from(anIn.eventId());\n final String name = anIn.name();\n\n if (!this.eventGateway.existsById(eventID))\n throw NotFoundException.with(Event.class, eventID);\n\n final Guest guest = guestGateway.findByEventIdAndName(eventID, name).orElseThrow(notFound(eventID, name));\n final Event event = eventGateway.findById(guest.getEventId()).orElseThrow(notFound(guest.getEventId()));\n\n event.removeTicketSold();\n this.update(event);\n this.guestGateway.deleteByEventIdAndName(eventID.getValue(), name);\n }\n\n private void update(final Event event){\n try{\n this.eventGateway.update(event);\n }catch (final Throwable t){\n throw InternalErrorException.with(\n \"an error on update event was observed [eventID:%s]\".formatted(event.getId().getValue()),\n t);\n }\n }\n\n private Supplier<NotFoundException> notFound(final EventID eventID, String name) {\n return () -> NotFoundException.with(new Error(\"Guest not found by [eventID:%s] and [name:%s]\".formatted(eventID, name)));\n }\n private Supplier<NotFoundException> notFound(final EventID anId) {\n return () -> NotFoundException.with(Event.class, anId);\n }\n}"
},
{
"identifier": "DeleteGuestByEventAndNameUseCase",
"path": "application/src/main/java/br/com/ifsp/tickets/api/app/guest/delete/eventIdAndName/DeleteGuestByEventAndNameUseCase.java",
"snippet": "public abstract class DeleteGuestByEventAndNameUseCase extends UnitUseCase<DeleteGuestByEventAndNameCommand> {\n}"
},
{
"identifier": "DefaultDeleteGuestUseCase",
"path": "application/src/main/java/br/com/ifsp/tickets/api/app/guest/delete/id/DefaultDeleteGuestUseCase.java",
"snippet": "public class DefaultDeleteGuestUseCase extends DeleteGuestUseCase {\n private final GuestGateway guestGateway;\n private final EventGateway eventGateway;\n\n public DefaultDeleteGuestUseCase(final GuestGateway guestGateway, final EventGateway eventGateway) {\n this.guestGateway = guestGateway;\n this.eventGateway = eventGateway;\n }\n\n @Override\n public void execute(String anIn) {\n final GuestID guestID = GuestID.from(anIn);\n\n if (!this.guestGateway.existsById(guestID))\n throw NotFoundException.with(Guest.class, guestID);\n\n final Guest guest = guestGateway.findById(guestID).orElseThrow(notFound(guestID));\n final Event event = eventGateway.findById(guest.getEventId()).orElseThrow(notFound(guest.getEventId()));\n\n event.removeTicketSold();\n this.update(event);\n this.guestGateway.deleteById(guestID);\n }\n\n private void update(final Event event){\n try{\n this.eventGateway.update(event);\n }catch (final Throwable t){\n throw InternalErrorException.with(\n \"an error on update event was observed [eventID:%s]\".formatted(event.getId().getValue()),\n t);\n }\n }\n\n private Supplier<NotFoundException> notFound(final GuestID anId) {\n return () -> NotFoundException.with(Guest.class, anId);\n }\n private Supplier<NotFoundException> notFound(final EventID anId) {\n return () -> NotFoundException.with(Event.class, anId);\n }\n}"
},
{
"identifier": "DeleteGuestUseCase",
"path": "application/src/main/java/br/com/ifsp/tickets/api/app/guest/delete/id/DeleteGuestUseCase.java",
"snippet": "public abstract class DeleteGuestUseCase extends UnitUseCase<String> {\n}"
},
{
"identifier": "DefaultGetGuestByIdUseCase",
"path": "application/src/main/java/br/com/ifsp/tickets/api/app/guest/retrieve/get/DefaultGetGuestByIdUseCase.java",
"snippet": "public class DefaultGetGuestByIdUseCase extends GetGuestByIdUseCase{\n private final GuestGateway guestGateway;\n\n public DefaultGetGuestByIdUseCase(final GuestGateway guestGateway) {\n this.guestGateway = guestGateway;\n }\n @Override\n public GuestOutput execute(String anIn) {\n final GuestID guestID = GuestID.from(anIn);\n final Guest guest = this.guestGateway.findById(guestID).orElseThrow(notFound(guestID));\n return GuestOutput.from(guest);\n }\n\n\n private Supplier<NotFoundException> notFound(final GuestID GuestID) {\n return () -> NotFoundException.with(Guest.class, GuestID);\n }\n}"
},
{
"identifier": "GetGuestByIdUseCase",
"path": "application/src/main/java/br/com/ifsp/tickets/api/app/guest/retrieve/get/GetGuestByIdUseCase.java",
"snippet": "public abstract class GetGuestByIdUseCase extends UseCase<String, GuestOutput> {\n}"
},
{
"identifier": "DefaultListGuestsUseCase",
"path": "application/src/main/java/br/com/ifsp/tickets/api/app/guest/retrieve/list/DefaultListGuestsUseCase.java",
"snippet": "public class DefaultListGuestsUseCase extends ListGuestsUseCase{\n private final GuestGateway guestGateway;\n\n public DefaultListGuestsUseCase(final GuestGateway guestGateway) {\n this.guestGateway = guestGateway;\n }\n @Override\n public Pagination<GuestListOutput> execute(SearchQuery anIn) {\n return this.guestGateway.findAll(anIn).map(GuestListOutput::from);\n }\n}"
},
{
"identifier": "ListGuestsUseCase",
"path": "application/src/main/java/br/com/ifsp/tickets/api/app/guest/retrieve/list/ListGuestsUseCase.java",
"snippet": "public abstract class ListGuestsUseCase extends UseCase<SearchQuery, Pagination<GuestListOutput>> {\n}"
},
{
"identifier": "DefaultToggleBlockedGuestUseCase",
"path": "application/src/main/java/br/com/ifsp/tickets/api/app/guest/toggle/blocked/DefaultToggleBlockedGuestUseCase.java",
"snippet": "public class DefaultToggleBlockedGuestUseCase extends ToggleBlockedGuestUseCase{\n private final GuestGateway guestGateway;\n\n public DefaultToggleBlockedGuestUseCase(GuestGateway guestGateway) {\n this.guestGateway = guestGateway;\n }\n\n @Override\n public void execute(String anIn) {\n final GuestID guestID = GuestID.from(anIn);\n\n final Guest guest = this.guestGateway.findById(guestID).orElseThrow(notFound(guestID));\n guest.toggleBlocked();\n\n this.guestGateway.update(guest);\n }\n\n private Supplier<NotFoundException> notFound(final GuestID GuestID) {\n return () -> NotFoundException.with(Guest.class, GuestID);\n }\n}"
},
{
"identifier": "ToggleBlockedGuestUseCase",
"path": "application/src/main/java/br/com/ifsp/tickets/api/app/guest/toggle/blocked/ToggleBlockedGuestUseCase.java",
"snippet": "public abstract class ToggleBlockedGuestUseCase extends UnitUseCase<String> {\n}"
},
{
"identifier": "DefaultToggleEnterGuestUseCase",
"path": "application/src/main/java/br/com/ifsp/tickets/api/app/guest/toggle/enter/DefaultToggleEnterGuestUseCase.java",
"snippet": "public class DefaultToggleEnterGuestUseCase extends ToggleEnterGuestUseCase{\n private final GuestGateway guestGateway;\n\n public DefaultToggleEnterGuestUseCase(GuestGateway guestGateway) {\n this.guestGateway = guestGateway;\n }\n\n @Override\n public void execute(String anIn) {\n final GuestID guestID = GuestID.from(anIn);\n\n final Guest guest = this.guestGateway.findById(guestID).orElseThrow(notFound(guestID));\n guest.toggleEnter();\n\n this.guestGateway.update(guest);\n }\n\n private Supplier<NotFoundException> notFound(final GuestID GuestID) {\n return () -> NotFoundException.with(Guest.class, GuestID);\n }\n}"
},
{
"identifier": "ToggleEnterGuestUseCase",
"path": "application/src/main/java/br/com/ifsp/tickets/api/app/guest/toggle/enter/ToggleEnterGuestUseCase.java",
"snippet": "public abstract class ToggleEnterGuestUseCase extends UnitUseCase<String> {\n}"
},
{
"identifier": "DefaultToggleLeftGuestUseCase",
"path": "application/src/main/java/br/com/ifsp/tickets/api/app/guest/toggle/left/DefaultToggleLeftGuestUseCase.java",
"snippet": "public class DefaultToggleLeftGuestUseCase extends ToggleLeftGuestUseCase {\n private final GuestGateway guestGateway;\n\n public DefaultToggleLeftGuestUseCase(GuestGateway guestGateway) {\n this.guestGateway = guestGateway;\n }\n\n @Override\n public void execute(String anIn) {\n final GuestID guestID = GuestID.from(anIn);\n\n final Guest guest = this.guestGateway.findById(guestID).orElseThrow(notFound(guestID));\n guest.toggleLeft();\n\n this.guestGateway.update(guest);\n }\n\n private Supplier<NotFoundException> notFound(final GuestID GuestID) {\n return () -> NotFoundException.with(Guest.class, GuestID);\n }\n}"
},
{
"identifier": "ToggleLeftGuestUseCase",
"path": "application/src/main/java/br/com/ifsp/tickets/api/app/guest/toggle/left/ToggleLeftGuestUseCase.java",
"snippet": "public abstract class ToggleLeftGuestUseCase extends UnitUseCase<String> {\n}"
},
{
"identifier": "DefaultUpdateGuestUseCase",
"path": "application/src/main/java/br/com/ifsp/tickets/api/app/guest/update/DefaultUpdateGuestUseCase.java",
"snippet": "public class DefaultUpdateGuestUseCase extends UpdateGuestUseCase{\n private final GuestGateway guestGateway;\n\n public DefaultUpdateGuestUseCase(final GuestGateway guestGateway) {\n this.guestGateway = guestGateway;\n }\n\n @Override\n public UpdateGuestOutput execute(UpdateGuestCommand anIn) {\n final GuestID guestID = GuestID.from(anIn.id());\n final String name = anIn.name();\n final Integer age = anIn.age();\n final String document = anIn.document();\n final String phoneNumber = anIn.phoneNumber();\n final String email = anIn.email();\n final Profile profile = anIn.profile();\n\n final Guest guest = guestGateway.findById(guestID).orElseThrow(notFound(guestID));\n guest.update(name, age, document, phoneNumber, email, profile);\n\n final Notification notification = Notification.create();\n guest.validate(notification);\n\n if (notification.hasError())\n throw new NotificationException(\"Could not update guest\", notification);\n\n return UpdateGuestOutput.from(this.update(guest));\n }\n\n private Guest update(final Guest aGuest) {\n try {\n return this.guestGateway.update(aGuest);\n } catch (final Throwable t) {\n throw InternalErrorException.with(\n \"An error on update guest was observed [guestID:%s]\".formatted(aGuest.getId().getValue()),\n t\n );\n }\n }\n\n private Supplier<NotFoundException> notFound(final GuestID anId) {\n return () -> NotFoundException.with(Guest.class, anId);\n }\n}"
},
{
"identifier": "UpdateGuestUseCase",
"path": "application/src/main/java/br/com/ifsp/tickets/api/app/guest/update/UpdateGuestUseCase.java",
"snippet": "public abstract class UpdateGuestUseCase extends UseCase<UpdateGuestCommand, UpdateGuestOutput> {\n}"
},
{
"identifier": "DefaultValidateGuestQRUseCase",
"path": "application/src/main/java/br/com/ifsp/tickets/api/app/guest/validate/DefaultValidateGuestQRUseCase.java",
"snippet": "public class DefaultValidateGuestQRUseCase extends ValidateGuestQRUseCase{\n private final GuestGateway guestGateway;\n\n public DefaultValidateGuestQRUseCase(GuestGateway guestGateway) {\n this.guestGateway = guestGateway;\n }\n\n @Override\n public ValidateGuestQROutput execute(String anIn) {\n final GuestID guestID = GuestID.from(anIn);\n\n final Guest guest = guestGateway.findById(guestID).orElseThrow(notFound(guestID));\n\n final Notification notification = Notification.create();\n guest.validate(notification);\n\n if (notification.hasError())\n throw new NotificationException(\"Could not create guest's qr code\", notification);\n\n return ValidateGuestQROutput.from(QRCodeGenerator.generateQRCode(anIn), guest.getName(), guest.getEmail());\n }\n\n private Supplier<NotFoundException> notFound(final GuestID anId) {\n return () -> NotFoundException.with(Guest.class, anId);\n }\n}"
},
{
"identifier": "ValidateGuestQRUseCase",
"path": "application/src/main/java/br/com/ifsp/tickets/api/app/guest/validate/ValidateGuestQRUseCase.java",
"snippet": "public abstract class ValidateGuestQRUseCase extends UseCase<String, ValidateGuestQROutput> {\n}"
},
{
"identifier": "EventGateway",
"path": "domain/src/main/java/br/com/ifsp/tickets/api/domain/event/gateway/EventGateway.java",
"snippet": "public interface EventGateway {\n Event create(final Event aEvent);\n\n Optional<Event> findById(final EventID EventID);\n\n boolean existsById(final EventID EventID);\n\n Pagination<Event> findAll(final SearchQuery searchQuery);\n\n Event update(final Event Event);\n\n void deleteById(final EventID EventID);\n}"
},
{
"identifier": "GuestGateway",
"path": "domain/src/main/java/br/com/ifsp/tickets/api/domain/guest/gateway/GuestGateway.java",
"snippet": "public interface GuestGateway {\n Guest create(final Guest aGuest);\n\n Optional<Guest> findById(final GuestID aGuestID);\n Optional<Guest> findByEventIdAndName(EventID eventID, String name);\n\n boolean existsById(final GuestID aGuestID);\n\n Pagination<Guest> findAll(final SearchQuery searchQuery);\n\n Guest update(final Guest aGuest);\n\n void deleteById(final GuestID aGuestID);\n void deleteAllByEvent(final EventID eventID);\n void deleteByEventIdAndName(UUID eventId, String name);\n\n Set<Guest> findAllByEventId(final EventID eventID);\n\n}"
}
] | import br.com.ifsp.tickets.api.app.guest.create.CreateGuestUseCase;
import br.com.ifsp.tickets.api.app.guest.create.DefaultCreateGuestUseCase;
import br.com.ifsp.tickets.api.app.guest.delete.event.DefaultDeleteGuestsByEventUseCase;
import br.com.ifsp.tickets.api.app.guest.delete.event.DeleteGuestsByEventUseCase;
import br.com.ifsp.tickets.api.app.guest.delete.eventIdAndName.DefaultDeleteGuestByEventAndNameUseCase;
import br.com.ifsp.tickets.api.app.guest.delete.eventIdAndName.DeleteGuestByEventAndNameUseCase;
import br.com.ifsp.tickets.api.app.guest.delete.id.DefaultDeleteGuestUseCase;
import br.com.ifsp.tickets.api.app.guest.delete.id.DeleteGuestUseCase;
import br.com.ifsp.tickets.api.app.guest.retrieve.get.DefaultGetGuestByIdUseCase;
import br.com.ifsp.tickets.api.app.guest.retrieve.get.GetGuestByIdUseCase;
import br.com.ifsp.tickets.api.app.guest.retrieve.list.DefaultListGuestsUseCase;
import br.com.ifsp.tickets.api.app.guest.retrieve.list.ListGuestsUseCase;
import br.com.ifsp.tickets.api.app.guest.toggle.blocked.DefaultToggleBlockedGuestUseCase;
import br.com.ifsp.tickets.api.app.guest.toggle.blocked.ToggleBlockedGuestUseCase;
import br.com.ifsp.tickets.api.app.guest.toggle.enter.DefaultToggleEnterGuestUseCase;
import br.com.ifsp.tickets.api.app.guest.toggle.enter.ToggleEnterGuestUseCase;
import br.com.ifsp.tickets.api.app.guest.toggle.left.DefaultToggleLeftGuestUseCase;
import br.com.ifsp.tickets.api.app.guest.toggle.left.ToggleLeftGuestUseCase;
import br.com.ifsp.tickets.api.app.guest.update.DefaultUpdateGuestUseCase;
import br.com.ifsp.tickets.api.app.guest.update.UpdateGuestUseCase;
import br.com.ifsp.tickets.api.app.guest.validate.DefaultValidateGuestQRUseCase;
import br.com.ifsp.tickets.api.app.guest.validate.ValidateGuestQRUseCase;
import br.com.ifsp.tickets.api.domain.event.gateway.EventGateway;
import br.com.ifsp.tickets.api.domain.guest.gateway.GuestGateway;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; | 4,866 | package br.com.ifsp.tickets.api.infra.config.usecases;
@Configuration
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class GuestUseCaseConfig {
private final GuestGateway guestGateway;
private final EventGateway eventGateway;
@Bean
public CreateGuestUseCase createGuestUseCase() {
return new DefaultCreateGuestUseCase(guestGateway, eventGateway);
}
@Bean
public GetGuestByIdUseCase getGuestByIdUseCase() {
return new DefaultGetGuestByIdUseCase(guestGateway);
}
@Bean
public UpdateGuestUseCase updateGuestUseCase() {
return new DefaultUpdateGuestUseCase(guestGateway);
}
@Bean
public ListGuestsUseCase listGuestsUseCase() {
return new DefaultListGuestsUseCase(guestGateway);
}
@Bean
public DeleteGuestUseCase deleteGuestUseCase() {
return new DefaultDeleteGuestUseCase(guestGateway, eventGateway);
}
@Bean | package br.com.ifsp.tickets.api.infra.config.usecases;
@Configuration
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class GuestUseCaseConfig {
private final GuestGateway guestGateway;
private final EventGateway eventGateway;
@Bean
public CreateGuestUseCase createGuestUseCase() {
return new DefaultCreateGuestUseCase(guestGateway, eventGateway);
}
@Bean
public GetGuestByIdUseCase getGuestByIdUseCase() {
return new DefaultGetGuestByIdUseCase(guestGateway);
}
@Bean
public UpdateGuestUseCase updateGuestUseCase() {
return new DefaultUpdateGuestUseCase(guestGateway);
}
@Bean
public ListGuestsUseCase listGuestsUseCase() {
return new DefaultListGuestsUseCase(guestGateway);
}
@Bean
public DeleteGuestUseCase deleteGuestUseCase() {
return new DefaultDeleteGuestUseCase(guestGateway, eventGateway);
}
@Bean | public DeleteGuestByEventAndNameUseCase deleteGuestByEventAndNameUseCase() { | 5 | 2023-10-11 00:05:05+00:00 | 8k |
DeeChael/dcg | src/main/java/net/deechael/dcg/source/structure/execution/DyExecutable.java | [
{
"identifier": "DyTranstringable",
"path": "src/main/java/net/deechael/dcg/DyTranstringable.java",
"snippet": "public interface DyTranstringable {\n\n String toCompilableString();\n\n}"
},
{
"identifier": "DyLabel",
"path": "src/main/java/net/deechael/dcg/source/structure/DyLabel.java",
"snippet": "public final class DyLabel {\n\n private final String name;\n\n public DyLabel(String name) {\n this.name = name;\n }\n\n public String getName() {\n return name;\n }\n\n}"
},
{
"identifier": "DyStructure",
"path": "src/main/java/net/deechael/dcg/source/structure/DyStructure.java",
"snippet": "public interface DyStructure {\n\n /**\n * Get parents domains to which this structure object belongs\n *\n * @return parent domains\n */\n @NotNull\n DyStructure[] getParentDomains();\n\n default boolean isStaticStructure() {\n return false;\n }\n\n}"
},
{
"identifier": "DyInvokable",
"path": "src/main/java/net/deechael/dcg/source/structure/invokation/DyInvokable.java",
"snippet": "public interface DyInvokable {\n\n void addInvokation(Invokation invokation);\n\n @NotNull\n List<Invokation> listInvokations();\n\n void clearInvokations();\n\n}"
},
{
"identifier": "Invokation",
"path": "src/main/java/net/deechael/dcg/source/structure/invokation/Invokation.java",
"snippet": "public interface Invokation extends DyTranstringable {\n\n}"
},
{
"identifier": "Invoker",
"path": "src/main/java/net/deechael/dcg/source/structure/invokation/Invoker.java",
"snippet": "public interface Invoker {\n\n @NotNull\n String toInvokerString();\n\n}"
},
{
"identifier": "IfElseSelection",
"path": "src/main/java/net/deechael/dcg/source/structure/selection/IfElseSelection.java",
"snippet": "public class IfElseSelection implements Invokation {\n\n private final DyStructure parent;\n\n private final List<Map.Entry<Requirement, DyExecutable>> ifs = new ArrayList<>();\n private DyExecutable _else = null;\n\n public IfElseSelection(DyStructure parent) {\n this.parent = parent;\n }\n\n public IfElseSelection doIf(Requirement requirement, Consumer<DyExecutable> invokation) {\n DyInnerExecutable executable = new DyInnerExecutable(new DyStructure[]{parent});\n invokation.accept(executable);\n this.ifs.add(new AbstractMap.SimpleEntry<>(requirement, executable));\n return this;\n }\n\n public IfElseSelection doElse(Consumer<DyExecutable> invokation) {\n DyInnerExecutable executable = new DyInnerExecutable(new DyStructure[]{parent});\n invokation.accept(executable);\n this._else = executable;\n return this;\n }\n\n @Override\n public String toCompilableString() {\n if (this.ifs.isEmpty())\n throw new IllegalCallerException(\"There is no if in selection!\");\n StringBuilder builder = new StringBuilder();\n Iterator<Map.Entry<Requirement, DyExecutable>> iterator = this.ifs.iterator();\n if (iterator.hasNext())\n for (Map.Entry<Requirement, DyExecutable> entry = iterator.next(); iterator.hasNext(); entry = iterator.next()) {\n builder.append(\"if\")\n .append(\" \")\n .append(\"(\")\n .append(entry.getKey().toRequirementString())\n .append(\")\")\n .append(\" \")\n .append(\"{\")\n .append(\"\\n\")\n .append(entry.getValue().toCompilableString())\n .append(\"\\n\")\n .append(\"}\");\n if (iterator.hasNext())\n builder.append(\" \")\n .append(\"else\")\n .append(\" \");\n }\n if (this._else != null) {\n builder.append(\" \")\n .append(\"else\")\n .append(\" \")\n .append(\"{\")\n .append(this._else.toCompilableString())\n .append(\"\\n\")\n .append(\"}\");\n }\n builder.append(\"\\n\");\n return builder.toString();\n }\n\n}"
},
{
"identifier": "SwitchCaseSelection",
"path": "src/main/java/net/deechael/dcg/source/structure/selection/SwitchCaseSelection.java",
"snippet": "public class SwitchCaseSelection implements Invokation {\n\n private final DyStructure parent;\n\n private final Variable selector;\n private final List<Map.Entry<Variable[], DyExecutable>> cases = new ArrayList<>();\n\n private DySwitchExecutable defaultExecutable = null;\n\n public SwitchCaseSelection(DyStructure parent, Variable selector) {\n this.parent = parent;\n this.selector = selector;\n }\n\n public SwitchCaseSelection doCase(Variable variable, Consumer<DySwitchExecutable> invokation) {\n return this.doCase(new Variable[]{variable}, invokation);\n }\n\n public SwitchCaseSelection doCase(Variable[] variables, Consumer<DySwitchExecutable> invokation) {\n DySwitchExecutable executable = new DySwitchExecutable(new DyStructure[]{this.parent});\n invokation.accept(executable);\n this.cases.add(new AbstractMap.SimpleEntry<>(variables, executable));\n return this;\n }\n\n public SwitchCaseSelection doDefault(Consumer<DySwitchExecutable> invokation) {\n DySwitchExecutable executable = new DySwitchExecutable(new DyStructure[]{this.parent});\n invokation.accept(executable);\n this.defaultExecutable = executable;\n return this;\n }\n\n @Override\n public String toCompilableString() {\n StringBuilder builder = new StringBuilder();\n builder.append(\"switch\")\n .append(\" \")\n .append(\"(\")\n .append(this.selector.toVariableString())\n .append(\")\")\n .append(\" \")\n .append(\"{\")\n .append(\"\\n\");\n for (Map.Entry<Variable[], DyExecutable> entry : cases) {\n for (Variable variable : entry.getKey()) {\n builder.append(\"case\")\n .append(\" \")\n .append(variable.toVariableString())\n .append(\":\")\n .append(\"\\n\");\n }\n builder.append(entry.getValue().toCompilableString())\n .append(\"\\n\");\n }\n if (this.defaultExecutable != null)\n builder.append(\"default\")\n .append(\":\")\n .append(this.defaultExecutable.toCompilableString())\n .append(\"\\n\");\n builder.append(\"}\");\n return builder.toString();\n }\n\n}"
},
{
"identifier": "TryCatchSelection",
"path": "src/main/java/net/deechael/dcg/source/structure/selection/TryCatchSelection.java",
"snippet": "public final class TryCatchSelection implements Invokation {\n\n private final DyStructure parent;\n\n private final List<Map.Entry<Variable, Variable>> initialVariables = new ArrayList<>();\n\n private final DyExecutable tryExecutable;\n private final List<Map.Entry<Map.Entry<List<DyType>, String>, DyExecutable>> catchesExecutable = new ArrayList<>();\n private DyExecutable finallyExecutable = null;\n\n public TryCatchSelection(DyStructure parent) {\n this.parent = parent;\n\n this.tryExecutable = new DyInnerExecutable(new DyStructure[]{parent});\n }\n\n public TryCatchSelection doTry(Consumer<DyExecutable> invokation) {\n this.tryExecutable.clearInvokations();\n invokation.accept(this.tryExecutable);\n return this;\n }\n\n public TryCatchSelection doCatch(BiConsumer<DyExecutable, Variable> invokation, String throwableParamterName, DyType... throwableTypes) {\n if (throwableTypes.length == 0)\n throw new IllegalArgumentException(\"Throwable types must be over at least 1!\");\n DyExecutable catchExecutable = new DyInnerExecutable(new DyStructure[]{parent});\n ReferringVariable variable = new ReferringVariable(catchExecutable, null, throwableParamterName);\n invokation.accept(catchExecutable, variable);\n this.catchesExecutable.add(new AbstractMap.SimpleEntry<>(new AbstractMap.SimpleEntry<>(List.of(throwableTypes), throwableParamterName), catchExecutable));\n return this;\n }\n\n public TryCatchSelection doFinally(Consumer<DyExecutable> invokation) {\n DyExecutable finallyExecutable = new DyInnerExecutable(new DyStructure[]{parent});\n invokation.accept(finallyExecutable);\n this.finallyExecutable = finallyExecutable;\n return this;\n }\n\n public ReferringVariable initialize(DyType type, String name, Variable value) {\n ReferringVariable variable = new ReferringVariable(this.tryExecutable, type, name);\n this.initialVariables.add(new AbstractMap.SimpleEntry<>(variable, value));\n return variable;\n }\n\n @Override\n public String toCompilableString() {\n if (this.finallyExecutable == null && this.catchesExecutable.isEmpty())\n throw new IllegalCallerException(\"Try-Catch must have at one catch or one finally\");\n StringBuilder builder = new StringBuilder();\n builder.append(\"try\")\n .append(\" \");\n if (!this.initialVariables.isEmpty()) {\n builder.append(\"(\")\n .append(String.join(\n \"; \",\n this.initialVariables.stream()\n .map( entry -> {\n StringBuilder stringBuilder = new StringBuilder();\n stringBuilder.append(entry.getKey().getType().toTypeString())\n .append(\" \")\n .append(entry.getKey().getName())\n .append(\" \")\n .append(\"=\")\n .append(\" \")\n .append(entry.getValue().toVariableString());\n return stringBuilder.toString();\n })\n .toList()\n .toArray(new String[0])\n )\n )\n .append(\")\")\n .append(\" \");\n }\n builder.append(\"{\")\n .append(\"\\n\")\n .append(this.tryExecutable.toCompilableString())\n .append(\"\\n\")\n .append(\"}\");\n Iterator<Map.Entry<Map.Entry<List<DyType>, String>, DyExecutable>> iterator = this.catchesExecutable.iterator();\n for (Map.Entry<Map.Entry<List<DyType>, String>, DyExecutable> entry = iterator.next(); iterator.hasNext(); entry = iterator.next()) {\n builder.append(\" \")\n .append(\"catch\")\n .append(\" \")\n .append(\"(\")\n .append(String.join(\n \" | \",\n entry.getKey().getKey().stream()\n .map(DyType::toTypeString)\n .toList()\n .toArray(new String[0])\n ))\n .append(\" \")\n .append(entry.getKey().getValue())\n .append(\")\")\n .append(\" \")\n .append(\"{\")\n .append(\"\\n\")\n .append(entry.getValue().toCompilableString())\n .append(\"\\n\")\n .append(\"}\");\n }\n if (this.finallyExecutable != null)\n builder.append(\" \")\n .append(\"fiannly\")\n .append(\" \")\n .append(\"{\")\n .append(\"\\n\")\n .append(this.finallyExecutable.toCompilableString())\n .append(\"\\n\")\n .append(\"}\");\n return builder.toString();\n }\n}"
},
{
"identifier": "DyType",
"path": "src/main/java/net/deechael/dcg/source/type/DyType.java",
"snippet": "public interface DyType extends DyExportable, Invoker {\n\n // Default provided JTypes\n DyType VOID = classType(void.class);\n DyType INT = classType(int.class);\n DyType BOOLEAN = classType(boolean.class);\n DyType DOUBLE = classType(double.class);\n DyType FLOAT = classType(float.class);\n DyType LONG = classType(long.class);\n DyType SHORT = classType(short.class);\n DyType BYTE = classType(byte.class);\n DyType CHAR = classType(char.class);\n DyType OBJECT = classType(Object.class);\n DyType STRING = classType(String.class);\n DyType CLASS = classType(Class.class);\n\n /**\n * Get type for normal class type\n *\n * @param clazz class type\n * @return type\n */\n @NotNull\n static DyType classType(@NotNull Class<?> clazz) {\n return new DyJvmType(clazz);\n }\n\n /**\n * Get type for a generic type </br>\n * Example: List<T>, Map<K, V> etc.\n *\n * @param clazz base type\n * @param types generic parameters\n * @return type\n */\n @NotNull\n static DyType genericClassType(@NotNull Class<?> clazz, @NotNull DyType... types) {\n return new DyJvmGenericType(clazz, types);\n }\n\n @NotNull\n static DyType unknownGenericType(@Nullable DyType extending) {\n return new UnknownGenericType(extending);\n }\n\n /**\n * To check if this type is primitive type\n *\n * @return if is primitive type\n */\n boolean isPrimitive();\n\n /**\n * Get the base type of this type </br>\n * Example: if this type is java.lang.String[][], this method will return java.lang.String\n *\n * @return base type of this type\n */\n @NotNull\n DyType getBaseType();\n\n /**\n * Generate compilable string\n *\n * @return compilable string\n */\n @NotNull\n String toTypeString();\n\n /**\n * To check if this type is array\n *\n * @return if this type self is an array\n */\n boolean isArray();\n\n @Override\n @NotNull\n default String toExportableString() {\n return this.toTypeString();\n }\n\n @Override\n @NotNull\n default String toInvokerString() {\n return this.toTypeString();\n }\n\n @Override\n default boolean isStaticExportable() {\n return false;\n }\n\n}"
},
{
"identifier": "Variable",
"path": "src/main/java/net/deechael/dcg/source/variable/Variable.java",
"snippet": "public interface Variable extends Invoker, Requirement {\n\n /**\n * Get the type of this variable\n *\n * @return variable type\n */\n @NotNull\n DyType getType();\n\n /**\n * Get the name of the variable, only exists if it's a defined variable\n *\n * @return name, exception when not exists\n */\n String getName();\n\n /**\n * Get the domain of this variable, defining the availability of the variable\n *\n * @return domain\n */\n @NotNull\n DyStructure getDomain();\n\n /**\n * Generate compilable string for compiling use\n *\n * @return compilable string\n */\n String toVariableString();\n\n @Override\n @NotNull\n default String toInvokerString() {\n return this.toVariableString();\n }\n\n @Override\n default String toRequirementString() {\n return this.toVariableString();\n }\n\n static JvmVariable nullVariable() {\n return NullVariable.INSTANCE;\n }\n\n static JvmVariable stringVariable(String value) {\n return new StringVariable(value);\n }\n\n static Variable invokeMethodVariable(@Nullable Invoker invoker, @NotNull String methodName, Variable... parameters) {\n return new InvokeMethodVariable(DyUndefinedStructure.INSTANCE, invoker, methodName, parameters);\n }\n\n static Variable superVariable(DyType type) {\n return new SuperVariable(DyUndefinedStructure.INSTANCE, type);\n }\n\n static Variable thisVariable(DyType type) {\n return new ThisVariable(DyUndefinedStructure.INSTANCE, type);\n }\n\n}"
},
{
"identifier": "InvokeMethodVariable",
"path": "src/main/java/net/deechael/dcg/source/variable/internal/InvokeMethodVariable.java",
"snippet": "public class InvokeMethodVariable implements Variable {\n\n private final DyStructure domain;\n\n private final Invoker invoker;\n private final String methodName;\n private final Variable[] parameters;\n\n public InvokeMethodVariable(DyStructure domain, Invoker invoker, String methodName, Variable... parameters) {\n this.domain = domain;\n\n this.invoker = invoker;\n this.methodName = methodName;\n this.parameters = parameters;\n }\n\n @Override\n public @NotNull DyType getType() {\n throw new RuntimeException(\"InvokeMethodVariable cannot get type!\");\n }\n\n @Override\n public String getName() {\n throw new RuntimeException(\"InvokeMethodVariable cannot get name!\");\n }\n\n @Override\n public @NotNull DyStructure getDomain() {\n return this.domain;\n }\n\n @Override\n public String toVariableString() {\n StringBuilder builder = new StringBuilder();\n if (this.invoker != null)\n builder.append(this.invoker.toInvokerString())\n .append(\".\");\n builder.append(this.methodName)\n .append(\"(\")\n .append(String.join(\", \", Arrays.stream(this.parameters).map(Variable::toVariableString).toList().toArray(new String[0])))\n .append(\")\");\n return builder.toString();\n }\n\n}"
},
{
"identifier": "ReferringVariable",
"path": "src/main/java/net/deechael/dcg/source/variable/internal/ReferringVariable.java",
"snippet": "public class ReferringVariable implements Variable {\n\n private final DyStructure structure;\n\n private final DyType type;\n private final String name;\n\n public ReferringVariable(DyStructure structure, DyType type, String name) {\n this.structure = structure;\n\n this.type = type;\n this.name = name;\n }\n\n @Override\n public @NotNull DyType getType() {\n if (this.type == null)\n throw new RuntimeException(\"This referring variable may be a multi-type available variable!\");\n return this.type;\n }\n\n @Override\n public String getName() {\n return this.name;\n }\n\n @Override\n public @NotNull DyStructure getDomain() {\n return this.structure;\n }\n\n @Override\n public String toVariableString() {\n return this.getName();\n }\n\n}"
},
{
"identifier": "Preconditions",
"path": "src/main/java/net/deechael/dcg/util/Preconditions.java",
"snippet": "public final class Preconditions {\n\n @NotNull\n public static <T> T notNull(@Nullable T obj, String message) {\n if (obj == null)\n throw new RuntimeException(message);\n return obj;\n }\n\n @NotNull\n public static String regex(@NotNull String value, Pattern pattern, String message) {\n if (!pattern.matcher(value).matches())\n throw new IllegalArgumentException(message);\n return value;\n }\n\n public static void domain(@NotNull DyStructure current, @NotNull DyStructure another) {\n if (domain0(current, another))\n return;\n try {\n throw new IllegalAccessException(\"This object is not accessible in this structure!\");\n } catch (IllegalAccessException e) {\n throw new RuntimeException(e);\n }\n }\n\n private static boolean domain0(DyStructure current, DyStructure another) {\n if (current.isStaticStructure() && !another.isStaticStructure())\n return false;\n if (current instanceof DyUndefinedStructure)\n return true;\n if (another == current)\n return true;\n if (another instanceof DyUndefinedStructure)\n return true;\n if (another.getParentDomains().length == 0)\n for (DyStructure parent : another.getParentDomains())\n if (domain0(current, parent))\n return true;\n return false;\n }\n\n\n private Preconditions() {\n }\n\n}"
}
] | import net.deechael.dcg.DyTranstringable;
import net.deechael.dcg.source.structure.DyLabel;
import net.deechael.dcg.source.structure.DyStructure;
import net.deechael.dcg.source.structure.invokation.DyInvokable;
import net.deechael.dcg.source.structure.invokation.Invokation;
import net.deechael.dcg.source.structure.invokation.Invoker;
import net.deechael.dcg.source.structure.invokation.internal.*;
import net.deechael.dcg.source.structure.selection.IfElseSelection;
import net.deechael.dcg.source.structure.selection.SwitchCaseSelection;
import net.deechael.dcg.source.structure.selection.TryCatchSelection;
import net.deechael.dcg.source.type.DyType;
import net.deechael.dcg.source.variable.Variable;
import net.deechael.dcg.source.variable.internal.InvokeMethodVariable;
import net.deechael.dcg.source.variable.internal.ReferringVariable;
import net.deechael.dcg.util.Preconditions;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer; | 4,990 | package net.deechael.dcg.source.structure.execution;
public abstract class DyExecutable implements DyInvokable, DyStructure, DyTranstringable {
private final List<Invokation> invokations = new ArrayList<>();
@NotNull
public CreateVariableInvokation createVariable(@NotNull DyType type, @NotNull String name, @NotNull Variable variable) {
CreateVariableInvokation invokation = new CreateVariableInvokation(type, name, variable, new ReferringVariable(this, type, name));
this.invokations.add(invokation);
return invokation;
}
public void modifyVariable(Variable referring, @Nullable Variable newValue) {
Preconditions.domain(this, referring.getDomain());
if (newValue != null)
Preconditions.domain(this, newValue.getDomain());
ModifyVariableInvokation invokation = new ModifyVariableInvokation(referring, newValue != null ? newValue : Variable.nullVariable());
this.invokations.add(invokation);
}
public DyLabel createLabel(String name) {
this.invokations.add(new CreateLabelInvokation(name));
return new DyLabel(name);
}
| package net.deechael.dcg.source.structure.execution;
public abstract class DyExecutable implements DyInvokable, DyStructure, DyTranstringable {
private final List<Invokation> invokations = new ArrayList<>();
@NotNull
public CreateVariableInvokation createVariable(@NotNull DyType type, @NotNull String name, @NotNull Variable variable) {
CreateVariableInvokation invokation = new CreateVariableInvokation(type, name, variable, new ReferringVariable(this, type, name));
this.invokations.add(invokation);
return invokation;
}
public void modifyVariable(Variable referring, @Nullable Variable newValue) {
Preconditions.domain(this, referring.getDomain());
if (newValue != null)
Preconditions.domain(this, newValue.getDomain());
ModifyVariableInvokation invokation = new ModifyVariableInvokation(referring, newValue != null ? newValue : Variable.nullVariable());
this.invokations.add(invokation);
}
public DyLabel createLabel(String name) {
this.invokations.add(new CreateLabelInvokation(name));
return new DyLabel(name);
}
| public InvokeMethodVariable invoke(@Nullable Invoker invoker, @NotNull String methodName, Variable... parameters) { | 5 | 2023-10-15 13:45:11+00:00 | 8k |
giteecode/supermarket2Public | src/main/java/com/ruoyi/project/system/checkout/controller/CheckOutController.java | [
{
"identifier": "ShiroUtils",
"path": "src/main/java/com/ruoyi/common/utils/security/ShiroUtils.java",
"snippet": "public class ShiroUtils\n{\n public static Subject getSubject()\n {\n return SecurityUtils.getSubject();\n }\n\n public static Session getSession()\n {\n return SecurityUtils.getSubject().getSession();\n }\n\n public static void logout()\n {\n getSubject().logout();\n }\n\n public static User getSysUser()\n {\n User user = null;\n Object obj = getSubject().getPrincipal();\n if (StringUtils.isNotNull(obj))\n {\n user = new User();\n BeanUtils.copyBeanProp(user, obj);\n }\n return user;\n }\n\n public static void setSysUser(User user)\n {\n Subject subject = getSubject();\n PrincipalCollection principalCollection = subject.getPrincipals();\n String realmName = principalCollection.getRealmNames().iterator().next();\n PrincipalCollection newPrincipalCollection = new SimplePrincipalCollection(user, realmName);\n // 重新加载Principal\n subject.runAs(newPrincipalCollection);\n }\n\n public static Long getUserId()\n {\n return getSysUser().getUserId().longValue();\n }\n\n public static String getLoginName()\n {\n return getSysUser().getLoginName();\n }\n\n public static String getIp()\n {\n return getSubject().getSession().getHost();\n }\n\n public static String getSessionId()\n {\n return String.valueOf(getSubject().getSession().getId());\n }\n}"
},
{
"identifier": "BaseController",
"path": "src/main/java/com/ruoyi/framework/web/controller/BaseController.java",
"snippet": "public class BaseController\n{\n protected final Logger logger = LoggerFactory.getLogger(this.getClass());\n \n /**\n * 将前台传递过来的日期格式的字符串,自动转化为Date类型\n */\n @InitBinder\n public void initBinder(WebDataBinder binder)\n {\n // Date 类型转换\n binder.registerCustomEditor(Date.class, new PropertyEditorSupport()\n {\n @Override\n public void setAsText(String text)\n {\n setValue(DateUtils.parseDate(text));\n }\n });\n }\n\n /**\n * 设置请求分页数据\n */\n protected void startPage()\n {\n PageUtils.startPage();\n }\n\n /**\n * 设置请求排序数据\n */\n protected void startOrderBy()\n {\n PageDomain pageDomain = TableSupport.buildPageRequest();\n if (StringUtils.isNotEmpty(pageDomain.getOrderBy()))\n {\n String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());\n PageHelper.orderBy(orderBy);\n }\n }\n\n /**\n * 响应请求分页数据\n */\n @SuppressWarnings({ \"rawtypes\", \"unchecked\" })\n protected TableDataInfo getDataTable(List<?> list)\n {\n TableDataInfo rspData = new TableDataInfo();\n rspData.setCode(0);\n rspData.setRows(list);\n rspData.setTotal(new PageInfo(list).getTotal());\n return rspData;\n }\n\n /**\n * 响应返回结果\n * \n * @param rows 影响行数\n * @return 操作结果\n */\n protected AjaxResult toAjax(int rows)\n {\n return rows > 0 ? success() : error();\n }\n\n /**\n * 响应返回结果\n * \n * @param result 结果\n * @return 操作结果\n */\n protected AjaxResult toAjax(boolean result)\n {\n return result ? success() : error();\n }\n\n /**\n * 返回成功\n */\n public AjaxResult success()\n {\n return AjaxResult.success();\n }\n\n /**\n * 返回失败消息\n */\n public AjaxResult error()\n {\n return AjaxResult.error();\n }\n\n /**\n * 返回成功消息\n */\n public AjaxResult success(String message)\n {\n return AjaxResult.success(message);\n }\n\n /**\n * 返回成功数据\n */\n public static AjaxResult success(Object data)\n {\n return AjaxResult.success(\"操作成功\", data);\n }\n\n /**\n * 返回失败消息\n */\n public AjaxResult error(String message)\n {\n return AjaxResult.error(message);\n }\n\n /**\n * 返回错误码消息\n */\n public AjaxResult error(Type type, String message)\n {\n return new AjaxResult(type, message);\n }\n\n /**\n * 页面跳转\n */\n public String redirect(String url)\n {\n return StringUtils.format(\"redirect:{}\", url);\n }\n\n /**\n * 获取用户缓存信息\n */\n public User getSysUser()\n {\n return ShiroUtils.getSysUser();\n }\n\n /**\n * 设置用户缓存信息\n */\n public void setSysUser(User user)\n {\n ShiroUtils.setSysUser(user);\n }\n\n /**\n * 获取登录用户id\n */\n public Long getUserId()\n {\n return getSysUser().getUserId();\n }\n\n /**\n * 获取登录用户名\n */\n public String getLoginName()\n {\n return getSysUser().getLoginName();\n }\n}"
},
{
"identifier": "AjaxResult",
"path": "src/main/java/com/ruoyi/framework/web/domain/AjaxResult.java",
"snippet": "public class AjaxResult extends HashMap<String, Object>\n{\n private static final long serialVersionUID = 1L;\n\n /** 状态码 */\n public static final String CODE_TAG = \"code\";\n\n /** 返回内容 */\n public static final String MSG_TAG = \"msg\";\n\n /** 数据对象 */\n public static final String DATA_TAG = \"data\";\n\n /**\n * 状态类型\n */\n public enum Type\n {\n /** 成功 */\n SUCCESS(0),\n /** 警告 */\n WARN(301),\n /** 错误 */\n ERROR(500);\n private final int value;\n\n Type(int value)\n {\n this.value = value;\n }\n\n public int value()\n {\n return this.value;\n }\n }\n\n /**\n * 初始化一个新创建的 AjaxResult 对象,使其表示一个空消息。\n */\n public AjaxResult()\n {\n }\n\n /**\n * 初始化一个新创建的 AjaxResult 对象\n *\n * @param type 状态类型\n * @param msg 返回内容\n */\n public AjaxResult(Type type, String msg)\n {\n super.put(CODE_TAG, type.value);\n super.put(MSG_TAG, msg);\n }\n\n /**\n * 初始化一个新创建的 AjaxResult 对象\n *\n * @param type 状态类型\n * @param msg 返回内容\n * @param data 数据对象\n */\n public AjaxResult(Type type, String msg, Object data)\n {\n super.put(CODE_TAG, type.value);\n super.put(MSG_TAG, msg);\n if (StringUtils.isNotNull(data))\n {\n super.put(DATA_TAG, data);\n }\n }\n\n /**\n * 方便链式调用\n *\n * @param key 键\n * @param value 值\n * @return 数据对象\n */\n @Override\n public AjaxResult put(String key, Object value)\n {\n super.put(key, value);\n return this;\n }\n\n /**\n * 返回成功消息\n *\n * @return 成功消息\n */\n public static AjaxResult success()\n {\n return AjaxResult.success(\"操作成功\");\n }\n\n /**\n * 返回成功数据\n *\n * @return 成功消息\n */\n public static AjaxResult success(Object data)\n {\n return AjaxResult.success(\"操作成功\", data);\n }\n\n /**\n * 返回成功消息\n *\n * @param msg 返回内容\n * @return 成功消息\n */\n public static AjaxResult success(String msg)\n {\n return AjaxResult.success(msg, null);\n }\n\n /**\n * 返回成功消息\n *\n * @param msg 返回内容\n * @param data 数据对象\n * @return 成功消息\n */\n public static AjaxResult success(String msg, Object data)\n {\n return new AjaxResult(Type.SUCCESS, msg, data);\n }\n\n /**\n * 返回警告消息\n *\n * @param msg 返回内容\n * @return 警告消息\n */\n public static AjaxResult warn(String msg)\n {\n return AjaxResult.warn(msg, null);\n }\n\n /**\n * 返回警告消息\n *\n * @param msg 返回内容\n * @param data 数据对象\n * @return 警告消息\n */\n public static AjaxResult warn(String msg, Object data)\n {\n return new AjaxResult(Type.WARN, msg, data);\n }\n\n /**\n * 返回错误消息\n *\n * @return\n */\n public static AjaxResult error()\n {\n return AjaxResult.error(\"操作失败\");\n }\n\n /**\n * 返回错误消息\n *\n * @param msg 返回内容\n * @return 警告消息\n */\n public static AjaxResult error(String msg)\n {\n return AjaxResult.error(msg, null);\n }\n\n /**\n * 返回错误消息\n *\n * @param msg 返回内容\n * @param data 数据对象\n * @return 警告消息\n */\n public static AjaxResult error(String msg, Object data)\n {\n return new AjaxResult(Type.ERROR, msg, data);\n }\n}"
},
{
"identifier": "TableDataInfo",
"path": "src/main/java/com/ruoyi/framework/web/page/TableDataInfo.java",
"snippet": "public class TableDataInfo implements Serializable\n{\n private static final long serialVersionUID = 1L;\n\n /** 总记录数 */\n private long total;\n\n /** 列表数据 */\n private List<?> rows;\n\n /** 消息状态码 */\n private int code;\n\n /** 消息内容 */\n private String msg;\n\n /**\n * 表格数据对象\n */\n public TableDataInfo()\n {\n }\n\n /**\n * 分页\n * \n * @param list 列表数据\n * @param total 总记录数\n */\n public TableDataInfo(List<?> list, int total)\n {\n this.rows = list;\n this.total = total;\n }\n\n public long getTotal()\n {\n return total;\n }\n\n public void setTotal(long total)\n {\n this.total = total;\n }\n\n public List<?> getRows()\n {\n return rows;\n }\n\n public void setRows(List<?> rows)\n {\n this.rows = rows;\n }\n\n public int getCode()\n {\n return code;\n }\n\n public void setCode(int code)\n {\n this.code = code;\n }\n\n public String getMsg()\n {\n return msg;\n }\n\n public void setMsg(String msg)\n {\n this.msg = msg;\n }\n}"
},
{
"identifier": "AddTempBillItemDto",
"path": "src/main/java/com/ruoyi/project/system/checkout/domain/AddTempBillItemDto.java",
"snippet": "public class AddTempBillItemDto {\n\n private String productId;\n private Long number;\n\n public String getProductId() {\n return productId;\n }\n\n public void setProductId(String productId) {\n this.productId = productId;\n }\n\n public Long getNumber() {\n return number;\n }\n\n public void setNumber(Long number) {\n this.number = number;\n }\n}"
},
{
"identifier": "CheckoutService",
"path": "src/main/java/com/ruoyi/project/system/checkout/service/CheckoutService.java",
"snippet": "public interface CheckoutService {\n\n List<String[]> matchProductSuggestByProductId(String id);\n\n boolean saveTempBillItem(Long userId, AddTempBillItemDto addTempBillItemDto);\n\n List<TempBillItem> getTempBillItems(Long userId);\n\n BigDecimal countTempBillItemsTotalShouldPay(Long userId);\n\n int removeTempBillItem(Long userId, int index);\n\n void closeTempBillItem(Long userId);\n\n int submitTempBillItem(Long userId);\n}"
},
{
"identifier": "User",
"path": "src/main/java/com/ruoyi/project/system/user/domain/User.java",
"snippet": "public class User extends BaseEntity\n{\n private static final long serialVersionUID = 1L;\n\n /** 用户ID */\n @Excel(name = \"用户序号\", cellType = ColumnType.NUMERIC, prompt = \"用户编号\")\n private Long userId;\n\n /** 部门ID */\n @Excel(name = \"部门编号\", type = Type.IMPORT)\n private Long deptId;\n\n /** 部门父ID */\n private Long parentId;\n\n /** 角色ID */\n private Long roleId;\n\n /** 登录名称 */\n @Excel(name = \"登录名称\")\n private String loginName;\n\n /** 用户名称 */\n @Excel(name = \"用户名称\")\n private String userName;\n\n /** 用户类型 */\n private String userType;\n\n /** 用户邮箱 */\n @Excel(name = \"用户邮箱\")\n private String email;\n\n /** 手机号码 */\n @Excel(name = \"手机号码\")\n private String phonenumber;\n\n /** 用户性别 */\n @Excel(name = \"用户性别\", readConverterExp = \"0=男,1=女,2=未知\")\n private String sex;\n\n /** 用户头像 */\n private String avatar;\n\n /** 密码 */\n private String password;\n\n /** 盐加密 */\n private String salt;\n\n /** 帐号状态(0正常 1停用) */\n @Excel(name = \"帐号状态\", readConverterExp = \"0=正常,1=停用\")\n private String status;\n\n /** 删除标志(0代表存在 2代表删除) */\n private String delFlag;\n\n /** 最后登录IP */\n @Excel(name = \"最后登录IP\", type = Type.EXPORT)\n private String loginIp;\n\n /** 最后登录时间 */\n @Excel(name = \"最后登录时间\", width = 30, dateFormat = \"yyyy-MM-dd HH:mm:ss\", type = Type.EXPORT)\n private Date loginDate;\n\n /** 密码最后更新时间 */\n private Date pwdUpdateDate;\n\n /** 部门对象 */\n @Excels({\n @Excel(name = \"部门名称\", targetAttr = \"deptName\", type = Type.EXPORT),\n @Excel(name = \"部门负责人\", targetAttr = \"leader\", type = Type.EXPORT)\n })\n private Dept dept;\n\n private List<Role> roles;\n\n /** 角色组 */\n private Long[] roleIds;\n\n /** 岗位组 */\n private Long[] postIds;\n\n public User()\n {\n\n }\n\n public User(Long userId)\n {\n this.userId = userId;\n }\n\n public Long getUserId()\n {\n return userId;\n }\n\n public void setUserId(Long userId)\n {\n this.userId = userId;\n }\n\n public boolean isAdmin()\n {\n return isAdmin(this.userId);\n }\n\n public static boolean isAdmin(Long userId)\n {\n return userId != null && 1L == userId;\n }\n\n public Long getDeptId()\n {\n return deptId;\n }\n\n public void setDeptId(Long deptId)\n {\n this.deptId = deptId;\n }\n\n public Long getParentId()\n {\n return parentId;\n }\n\n public void setParentId(Long parentId)\n {\n this.parentId = parentId;\n }\n\n public Long getRoleId()\n {\n return roleId;\n }\n\n public void setRoleId(Long roleId)\n {\n this.roleId = roleId;\n }\n\n @Xss(message = \"登录账号不能包含脚本字符\")\n @NotBlank(message = \"登录账号不能为空\")\n @Size(min = 0, max = 30, message = \"登录账号长度不能超过30个字符\")\n public String getLoginName()\n {\n return loginName;\n }\n\n public void setLoginName(String loginName)\n {\n this.loginName = loginName;\n }\n\n @Xss(message = \"用户昵称不能包含脚本字符\")\n @Size(min = 0, max = 30, message = \"用户昵称长度不能超过30个字符\")\n public String getUserName()\n {\n return userName;\n }\n\n public void setUserName(String userName)\n {\n this.userName = userName;\n }\n\n public String getUserType()\n {\n return userType;\n }\n\n public void setUserType(String userType)\n {\n this.userType = userType;\n }\n\n @Email(message = \"邮箱格式不正确\")\n @Size(min = 0, max = 50, message = \"邮箱长度不能超过50个字符\")\n public String getEmail()\n {\n return email;\n }\n\n public void setEmail(String email)\n {\n this.email = email;\n }\n\n @Size(min = 0, max = 11, message = \"手机号码长度不能超过11个字符\")\n public String getPhonenumber()\n {\n return phonenumber;\n }\n\n public void setPhonenumber(String phonenumber)\n {\n this.phonenumber = phonenumber;\n }\n\n public String getSex()\n {\n return sex;\n }\n\n public void setSex(String sex)\n {\n this.sex = sex;\n }\n\n public String getAvatar()\n {\n return avatar;\n }\n\n public void setAvatar(String avatar)\n {\n this.avatar = avatar;\n }\n\n @JsonIgnore\n public String getPassword()\n {\n return password;\n }\n\n public void setPassword(String password)\n {\n this.password = password;\n }\n\n public String getSalt()\n {\n return salt;\n }\n\n public void setSalt(String salt)\n {\n this.salt = salt;\n }\n\n /**\n * 生成随机盐\n */\n public void randomSalt()\n {\n // 一个Byte占两个字节,此处生成的3字节,字符串长度为6\n SecureRandomNumberGenerator secureRandom = new SecureRandomNumberGenerator();\n String hex = secureRandom.nextBytes(3).toHex();\n setSalt(hex);\n }\n\n public String getStatus()\n {\n return status;\n }\n\n public void setStatus(String status)\n {\n this.status = status;\n }\n\n public String getDelFlag()\n {\n return delFlag;\n }\n\n public void setDelFlag(String delFlag)\n {\n this.delFlag = delFlag;\n }\n\n public String getLoginIp()\n {\n return loginIp;\n }\n\n public void setLoginIp(String loginIp)\n {\n this.loginIp = loginIp;\n }\n\n public Date getLoginDate()\n {\n return loginDate;\n }\n\n public void setLoginDate(Date loginDate)\n {\n this.loginDate = loginDate;\n }\n\n public Date getPwdUpdateDate()\n {\n return pwdUpdateDate;\n }\n\n public void setPwdUpdateDate(Date pwdUpdateDate)\n {\n this.pwdUpdateDate = pwdUpdateDate;\n }\n\n public Dept getDept()\n {\n if (dept == null)\n {\n dept = new Dept();\n }\n return dept;\n }\n\n public void setDept(Dept dept)\n {\n this.dept = dept;\n }\n\n public List<Role> getRoles()\n {\n return roles;\n }\n\n public void setRoles(List<Role> roles)\n {\n this.roles = roles;\n }\n\n public Long[] getRoleIds()\n {\n return roleIds;\n }\n\n public void setRoleIds(Long[] roleIds)\n {\n this.roleIds = roleIds;\n }\n\n public Long[] getPostIds()\n {\n return postIds;\n }\n\n public void setPostIds(Long[] postIds)\n {\n this.postIds = postIds;\n }\n\n @Override\n public String toString() {\n return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE)\n .append(\"userId\", getUserId())\n .append(\"deptId\", getDeptId())\n .append(\"loginName\", getLoginName())\n .append(\"userName\", getUserName())\n .append(\"userType\", getUserType())\n .append(\"email\", getEmail())\n .append(\"phonenumber\", getPhonenumber())\n .append(\"sex\", getSex())\n .append(\"avatar\", getAvatar())\n .append(\"password\", getPassword())\n .append(\"salt\", getSalt())\n .append(\"status\", getStatus())\n .append(\"delFlag\", getDelFlag())\n .append(\"loginIp\", getLoginIp())\n .append(\"loginDate\", getLoginDate())\n .append(\"createBy\", getCreateBy())\n .append(\"createTime\", getCreateTime())\n .append(\"updateBy\", getUpdateBy())\n .append(\"updateTime\", getUpdateTime())\n .append(\"remark\", getRemark())\n .append(\"dept\", getDept())\n .append(\"roles\", getRoles())\n .toString();\n }\n}"
}
] | import com.ruoyi.common.utils.security.ShiroUtils;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.system.checkout.domain.AddTempBillItemDto;
import com.ruoyi.project.system.checkout.service.CheckoutService;
import com.ruoyi.project.system.user.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
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.bind.annotation.ResponseBody; | 5,848 | package com.ruoyi.project.system.checkout.controller;
@Controller
@RequestMapping("/system/checkout")
public class CheckOutController extends BaseController {
private String prefix = "system/checkout";
@Autowired
private CheckoutService checkoutService;
// @RequiresPermissions("system:checkout:view")
@GetMapping()
public String product() {
return prefix + "/checkout";
}
/**
* 新增保存商品分类
*/
@PostMapping("/tmp-bill-item/add")
@ResponseBody
public AjaxResult saveTempBillItem(AddTempBillItemDto addTempBillItemDto)
{
User currentUser = ShiroUtils.getSysUser();
Long userId = currentUser.getUserId();
boolean success = checkoutService.saveTempBillItem(userId, addTempBillItemDto);
if (success) {
return AjaxResult.success("添加成功");
} else {
return AjaxResult.error("找不到商品,请检查商品编号是否正确");
}
}
/**
* 获取数据集合
*/
@PostMapping("/tmp-bill-item")
@ResponseBody | package com.ruoyi.project.system.checkout.controller;
@Controller
@RequestMapping("/system/checkout")
public class CheckOutController extends BaseController {
private String prefix = "system/checkout";
@Autowired
private CheckoutService checkoutService;
// @RequiresPermissions("system:checkout:view")
@GetMapping()
public String product() {
return prefix + "/checkout";
}
/**
* 新增保存商品分类
*/
@PostMapping("/tmp-bill-item/add")
@ResponseBody
public AjaxResult saveTempBillItem(AddTempBillItemDto addTempBillItemDto)
{
User currentUser = ShiroUtils.getSysUser();
Long userId = currentUser.getUserId();
boolean success = checkoutService.saveTempBillItem(userId, addTempBillItemDto);
if (success) {
return AjaxResult.success("添加成功");
} else {
return AjaxResult.error("找不到商品,请检查商品编号是否正确");
}
}
/**
* 获取数据集合
*/
@PostMapping("/tmp-bill-item")
@ResponseBody | public TableDataInfo getTempBillItem() { | 3 | 2023-10-14 02:27:47+00:00 | 8k |
davidsaltacc/shadowclient | src/main/java/net/shadowclient/main/module/modules/render/Trajectories.java | [
{
"identifier": "Event",
"path": "src/main/java/net/shadowclient/main/event/Event.java",
"snippet": "public abstract class Event {\n public boolean cancelled = false;\n public void cancel() {\n this.cancelled = true;\n }\n public void uncancel() {\n this.cancelled = false;\n }\n}"
},
{
"identifier": "Render3DEvent",
"path": "src/main/java/net/shadowclient/main/event/events/Render3DEvent.java",
"snippet": "public class Render3DEvent extends Event {\n public final MatrixStack matrices;\n public final float tickDelta;\n public Render3DEvent(MatrixStack matrices, float tickDelta) {\n this.matrices = matrices;\n this.tickDelta = tickDelta;\n }\n}"
},
{
"identifier": "Module",
"path": "src/main/java/net/shadowclient/main/module/Module.java",
"snippet": "public abstract class Module {\n\n public final ModuleCategory category;\n public final String moduleName;\n public final String friendlyName;\n public final String description;\n\n public KeyBinding keybinding;\n\n public ModuleButton moduleButton = null;\n\n public boolean enabled;\n\n public List<Setting> getSettings() {\n return settings;\n }\n\n public void addSetting(Setting setting) {\n settings.add(setting);\n }\n\n public void addSettings(Setting...settings) {\n for (Setting setting : settings) {\n addSetting(setting);\n }\n }\n\n public final List<Setting> settings = new ArrayList<>();\n\n public final MinecraftClient mc = MinecraftClient.getInstance();\n\n public Module(String name, String friendlyName, String description, ModuleCategory category) {\n moduleName = name;\n this.category = category;\n this.friendlyName = friendlyName;\n this.description = description;\n }\n\n public void setEnabled() {\n this.enabled = true;\n this.onEnable();\n if (this.getClass().isAnnotationPresent(OneClick.class)) {\n setDisabled();\n }\n }\n public void setDisabled() {\n this.enabled = false;\n this.onDisable();\n }\n\n public void setEnabled(boolean event) {\n if (event) {\n this.onEnable();\n }\n this.enabled = true;\n }\n public void setDisabled(boolean event) {\n if (event) {\n this.onDisable();\n }\n this.enabled = false;\n }\n\n public boolean showMessage = true;\n\n public void setEnabled(boolean event, boolean message) {\n if (event) {\n boolean msgOld = showMessage;\n showMessage = message;\n this.onEnable();\n showMessage = msgOld;\n }\n this.enabled = true;\n }\n public void setDisabled(boolean event, boolean message) {\n if (event) {\n boolean msgOld = showMessage;\n showMessage = message;\n this.onDisable();\n showMessage = msgOld;\n }\n this.enabled = false;\n }\n\n public void toggle() {\n if (enabled) {\n setDisabled();\n return;\n }\n setEnabled();\n }\n\n public void onEnable() {\n if (showMessage && !this.getClass().isAnnotationPresent(OneClick.class)) {\n SCMain.moduleToggleChatMessage(friendlyName);\n }\n }\n public void onDisable() {\n if (showMessage && !this.getClass().isAnnotationPresent(OneClick.class)) {\n SCMain.moduleToggleChatMessage(friendlyName);\n }\n }\n public void onEvent(Event event) {}\n\n public void postInit() {}\n\n}"
},
{
"identifier": "ModuleCategory",
"path": "src/main/java/net/shadowclient/main/module/ModuleCategory.java",
"snippet": "public enum ModuleCategory {\n COMBAT(\"Combat\"),\n PLAYER(\"Player\"),\n MOVEMENT(\"Movement\"),\n WORLD(\"World\"),\n RENDER(\"Render\"),\n FUN(\"Fun\"),\n OTHER(\"Other\"),\n MENUS(\"Menus\");\n\n public final String name;\n\n ModuleCategory(String name) {\n this.name = name;\n }\n}"
},
{
"identifier": "PlayerUtils",
"path": "src/main/java/net/shadowclient/main/util/PlayerUtils.java",
"snippet": "public class PlayerUtils {\n public static Vec3d getHandOffset(Hand hand, double yaw) {\n Arm arm = SCMain.mc.options.getMainArm().getValue();\n\n boolean right = arm == Arm.RIGHT && hand == Hand.MAIN_HAND || arm == Arm.LEFT && hand == Hand.OFF_HAND;\n\n double sideMul = right ? -1 : 1;\n double offX = Math.cos(yaw) * 0.16 * sideMul;\n double offY = SCMain.mc.player.getStandingEyeHeight() - 0.1;\n double offZ = Math.sin(yaw) * 0.16 * sideMul;\n\n return new Vec3d(offX, offY, offZ);\n }\n}"
},
{
"identifier": "RenderUtils",
"path": "src/main/java/net/shadowclient/main/util/RenderUtils.java",
"snippet": "public class RenderUtils {\n\n public static Vec3d getInterpolationOffset(Entity e) {\n if (MinecraftClient.getInstance().isPaused()) {\n return Vec3d.ZERO;\n }\n\n double tickDelta = MinecraftClient.getInstance().getTickDelta();\n return new Vec3d(e.getX() - MathHelper.lerp(tickDelta, e.lastRenderX, e.getX()), e.getY() - MathHelper.lerp(tickDelta, e.lastRenderY, e.getY()), e.getZ() - MathHelper.lerp(tickDelta, e.lastRenderZ, e.getZ()));\n }\n\n public static void drawLine(double x1, double y1, double z1, double x2, double y2, double z2, float[] color, float width) {\n\n RenderSystem.enableBlend();\n RenderSystem.defaultBlendFunc();\n\n MatrixStack matrices = matrixFrom(x1, y1, z1);\n\n Tessellator tessellator = Tessellator.getInstance();\n BufferBuilder buffer = tessellator.getBuffer();\n\n RenderSystem.disableDepthTest();\n RenderSystem.disableCull();\n RenderSystem.setShader(GameRenderer::getRenderTypeLinesProgram);\n RenderSystem.lineWidth(width);\n\n buffer.begin(VertexFormat.DrawMode.LINES, VertexFormats.LINES);\n vertexLine(matrices, buffer, 0f, 0f, 0f, (float) (x2 - x1), (float) (y2 - y1), (float) (z2 - z1), color);\n tessellator.draw();\n\n RenderSystem.enableCull();\n RenderSystem.enableDepthTest();\n RenderSystem.disableBlend();\n }\n\n public static void vertexLine(MatrixStack matrices, VertexConsumer vertexConsumer, float x1, float y1, float z1, float x2, float y2, float z2, float[] lineColor) {\n Matrix4f model = matrices.peek().getPositionMatrix();\n Matrix3f normal = matrices.peek().getNormalMatrix();\n\n Vector3f normalVec = getNormal(x1, y1, z1, x2, y2, z2);\n\n vertexConsumer.vertex(model, x1, y1, z1).color(lineColor[0], lineColor[1], lineColor[2], lineColor[3]).normal(normal, normalVec.x(), normalVec.y(), normalVec.z()).next();\n vertexConsumer.vertex(model, x2, y2, z2).color(lineColor[0], lineColor[1], lineColor[2], lineColor[3]).normal(normal, normalVec.x(), normalVec.y(), normalVec.z()).next();\n }\n\n public static Vector3f getNormal(float x1, float y1, float z1, float x2, float y2, float z2) {\n float xNormal = x2 - x1;\n float yNormal = y2 - y1;\n float zNormal = z2 - z1;\n float normalSqrt = MathHelper.sqrt(xNormal * xNormal + yNormal * yNormal + zNormal * zNormal);\n\n return new Vector3f(xNormal / normalSqrt, yNormal / normalSqrt, zNormal / normalSqrt);\n }\n\n public static MatrixStack matrixFrom(double x, double y, double z) {\n MatrixStack matrices = new MatrixStack();\n\n Camera camera = MinecraftClient.getInstance().gameRenderer.getCamera();\n matrices.multiply(RotationAxis.POSITIVE_X.rotationDegrees(camera.getPitch()));\n matrices.multiply(RotationAxis.POSITIVE_Y.rotationDegrees(camera.getYaw() + 180.0F));\n\n matrices.translate(x - camera.getPos().x, y - camera.getPos().y, z - camera.getPos().z);\n\n return matrices;\n }\n\n public static void loadShader(@Nullable Identifier id) {\n ((IGameRenderer) MinecraftClient.getInstance().gameRenderer).loadShader(id);\n }\n\n public static void drawOutlinedBox(Box box, MatrixStack matrices) {\n\n Matrix4f matrix = matrices.peek().getPositionMatrix();\n Tessellator tessellator = RenderSystem.renderThreadTesselator();\n BufferBuilder bufferBuilder = tessellator.getBuffer();\n RenderSystem.setShader(GameRenderer::getPositionProgram);\n\n bufferBuilder.begin(VertexFormat.DrawMode.DEBUG_LINES, VertexFormats.POSITION);\n\n bufferBuilder.vertex(matrix, (float) box.minX, (float) box.minY, (float) box.minZ).next(); // TODO someone please fucking optimize this for me\n bufferBuilder.vertex(matrix, (float) box.maxX, (float) box.minY, (float) box.minZ).next();\n bufferBuilder.vertex(matrix, (float) box.maxX, (float) box.minY, (float) box.minZ).next();\n bufferBuilder.vertex(matrix, (float) box.maxX, (float) box.minY, (float) box.maxZ).next();\n bufferBuilder.vertex(matrix, (float) box.maxX, (float) box.minY, (float) box.maxZ).next();\n bufferBuilder.vertex(matrix, (float) box.minX, (float) box.minY, (float) box.maxZ).next();\n bufferBuilder.vertex(matrix, (float) box.minX, (float) box.minY, (float) box.maxZ).next();\n bufferBuilder.vertex(matrix, (float) box.minX, (float) box.minY, (float) box.minZ).next();\n bufferBuilder.vertex(matrix, (float) box.minX, (float) box.minY, (float) box.minZ).next();\n bufferBuilder.vertex(matrix, (float) box.minX, (float) box.maxY, (float) box.minZ).next();\n bufferBuilder.vertex(matrix, (float) box.maxX, (float) box.minY, (float) box.minZ).next();\n bufferBuilder.vertex(matrix, (float) box.maxX, (float) box.maxY, (float) box.minZ).next();\n bufferBuilder.vertex(matrix, (float) box.maxX, (float) box.minY, (float) box.maxZ).next();\n bufferBuilder.vertex(matrix, (float) box.maxX, (float) box.maxY, (float) box.maxZ).next();\n bufferBuilder.vertex(matrix, (float) box.minX, (float) box.minY, (float) box.maxZ).next();\n bufferBuilder.vertex(matrix, (float) box.minX, (float) box.maxY, (float) box.maxZ).next();\n bufferBuilder.vertex(matrix, (float) box.minX, (float) box.maxY, (float) box.minZ).next();\n bufferBuilder.vertex(matrix, (float) box.maxX, (float) box.maxY, (float) box.minZ).next();\n bufferBuilder.vertex(matrix, (float) box.maxX, (float) box.maxY, (float) box.minZ).next();\n bufferBuilder.vertex(matrix, (float) box.maxX, (float) box.maxY, (float) box.maxZ).next();\n bufferBuilder.vertex(matrix, (float) box.maxX, (float) box.maxY, (float) box.maxZ).next();\n bufferBuilder.vertex(matrix, (float) box.minX, (float) box.maxY, (float) box.maxZ).next();\n bufferBuilder.vertex(matrix, (float) box.minX, (float) box.maxY, (float) box.maxZ).next();\n bufferBuilder.vertex(matrix, (float) box.minX, (float) box.maxY, (float) box.minZ).next();\n\n tessellator.draw();\n }\n}"
},
{
"identifier": "WorldUtils",
"path": "src/main/java/net/shadowclient/main/util/WorldUtils.java",
"snippet": "public class WorldUtils {\n public static boolean lineOfSight(Vec3d from, Vec3d to) {\n RaycastContext context = new RaycastContext(from, to, RaycastContext.ShapeType.COLLIDER, RaycastContext.FluidHandling.NONE, SCMain.mc.player);\n return SCMain.mc.world.raycast(context).getType() == HitResult.Type.MISS;\n }\n public static boolean lineOfSight(Entity from, Vec3d to) {\n return lineOfSight(from.getEyePos(), to);\n }\n public static boolean lineOfSight(Vec3d from, Entity to) {\n return lineOfSight(from, to.getEyePos());\n }\n public static boolean lineOfSight(Entity from, Entity to) {\n return lineOfSight(from.getEyePos(), to.getEyePos());\n }\n\n public static BlockHitResult raycast(Vec3d from, Vec3d to) {\n RaycastContext context = new RaycastContext(from, to, RaycastContext.ShapeType.COLLIDER, RaycastContext.FluidHandling.NONE, SCMain.mc.player);\n return SCMain.mc.world.raycast(context);\n }\n}"
}
] | import com.mojang.blaze3d.systems.RenderSystem;
import net.minecraft.client.render.*;
import net.minecraft.client.util.math.MatrixStack;
import net.minecraft.entity.Entity;
import net.minecraft.entity.projectile.ProjectileUtil;
import net.minecraft.item.*;
import net.minecraft.util.Hand;
import net.minecraft.util.hit.BlockHitResult;
import net.minecraft.util.hit.EntityHitResult;
import net.minecraft.util.hit.HitResult;
import net.minecraft.util.math.Box;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.math.Vec3d;
import net.shadowclient.main.annotations.EventListener;
import net.shadowclient.main.annotations.SearchTags;
import net.shadowclient.main.event.Event;
import net.shadowclient.main.event.events.Render3DEvent;
import net.shadowclient.main.module.Module;
import net.shadowclient.main.module.ModuleCategory;
import net.shadowclient.main.util.PlayerUtils;
import net.shadowclient.main.util.RenderUtils;
import net.shadowclient.main.util.WorldUtils;
import org.joml.Matrix4f;
import org.lwjgl.opengl.GL11;
import java.util.ArrayList;
import java.util.function.Predicate; | 4,249 | package net.shadowclient.main.module.modules.render;
@EventListener({Render3DEvent.class})
@SearchTags({"trajectories", "bow aim laser", "aim assist"})
public class Trajectories extends Module {
public Trajectories() {
super("trajectories", "Trajectories", "Draws a line where projectiles will go.", ModuleCategory.RENDER);
}
public ArrayList<Vec3d> trajPath;
public HitResult.Type trajHit;
public final Box endBox = new Box(0, 0, 0, 1, 1, 1);
@Override
public void onEvent(Event event) {
Render3DEvent evt = (Render3DEvent) event;
evt.matrices.push();
getTrajectory(evt.tickDelta);
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
GL11.glDisable(GL11.GL_DEPTH_TEST);
GL11.glDepthMask(false);
drawLine(evt.matrices, trajPath);
if (!trajPath.isEmpty()) {
drawEnd(evt.matrices, trajPath.get(trajPath.size() - 1));
}
RenderSystem.setShaderColor(1, 1, 1, 1);
GL11.glDisable(GL11.GL_BLEND);
GL11.glEnable(GL11.GL_DEPTH_TEST);
GL11.glDepthMask(true);
evt.matrices.pop();
}
public void getTrajectory(float delta) {
trajHit = HitResult.Type.MISS;
trajPath = new ArrayList<>();
Item item = mc.player.getMainHandStack().getItem(); // todo offhand too
if (!(item instanceof RangedWeaponItem || item instanceof SnowballItem || item instanceof EggItem || item instanceof EnderPearlItem || item instanceof ThrowablePotionItem || item instanceof FishingRodItem || item instanceof TridentItem)) {
return;
}
double power;
if (!(item instanceof RangedWeaponItem)) {
power = 1.5;
} else {
power = (72000 - mc.player.getItemUseTimeLeft()) / 20F;
power = power * power + power * 2F;
if (power > 3 || power <= 0.3F) {
power = 3;
}
}
double gravity;
if (item instanceof RangedWeaponItem) {
gravity = 0.05;
} else if (item instanceof ThrowablePotionItem) {
gravity = 0.4;
} else if (item instanceof FishingRodItem) {
gravity = 0.15;
} else if (item instanceof TridentItem) {
gravity = 0.015;
} else {
gravity = 0.03;
}
double yaw = Math.toRadians(mc.player.getYaw());
double pitch = Math.toRadians(mc.player.getPitch());
Vec3d arrawPos = new Vec3d(MathHelper.lerp(delta, mc.player.lastRenderX, mc.player.getX()),
MathHelper.lerp(delta, mc.player.lastRenderY, mc.player.getY()),
MathHelper.lerp(delta, mc.player.lastRenderZ, mc.player.getZ())).add(PlayerUtils.getHandOffset(Hand.MAIN_HAND, yaw));
double cospitch = Math.cos(pitch);
Vec3d arrowMotion = new Vec3d(-Math.sin(yaw) * cospitch, -Math.sin(pitch), Math.cos(yaw) * cospitch).normalize().multiply(power);
for (int i = 0; i < 1000; i++) {
trajPath.add(arrawPos);
arrawPos = arrawPos.add(arrowMotion.multiply(0.1));
arrowMotion = arrowMotion.multiply(0.999);
arrowMotion = arrowMotion.add(0, -gravity * 0.1, 0);
Vec3d lastPos = trajPath.size() > 1 ? trajPath.get(trajPath.size() - 2) : mc.player.getEyePos();
| package net.shadowclient.main.module.modules.render;
@EventListener({Render3DEvent.class})
@SearchTags({"trajectories", "bow aim laser", "aim assist"})
public class Trajectories extends Module {
public Trajectories() {
super("trajectories", "Trajectories", "Draws a line where projectiles will go.", ModuleCategory.RENDER);
}
public ArrayList<Vec3d> trajPath;
public HitResult.Type trajHit;
public final Box endBox = new Box(0, 0, 0, 1, 1, 1);
@Override
public void onEvent(Event event) {
Render3DEvent evt = (Render3DEvent) event;
evt.matrices.push();
getTrajectory(evt.tickDelta);
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
GL11.glDisable(GL11.GL_DEPTH_TEST);
GL11.glDepthMask(false);
drawLine(evt.matrices, trajPath);
if (!trajPath.isEmpty()) {
drawEnd(evt.matrices, trajPath.get(trajPath.size() - 1));
}
RenderSystem.setShaderColor(1, 1, 1, 1);
GL11.glDisable(GL11.GL_BLEND);
GL11.glEnable(GL11.GL_DEPTH_TEST);
GL11.glDepthMask(true);
evt.matrices.pop();
}
public void getTrajectory(float delta) {
trajHit = HitResult.Type.MISS;
trajPath = new ArrayList<>();
Item item = mc.player.getMainHandStack().getItem(); // todo offhand too
if (!(item instanceof RangedWeaponItem || item instanceof SnowballItem || item instanceof EggItem || item instanceof EnderPearlItem || item instanceof ThrowablePotionItem || item instanceof FishingRodItem || item instanceof TridentItem)) {
return;
}
double power;
if (!(item instanceof RangedWeaponItem)) {
power = 1.5;
} else {
power = (72000 - mc.player.getItemUseTimeLeft()) / 20F;
power = power * power + power * 2F;
if (power > 3 || power <= 0.3F) {
power = 3;
}
}
double gravity;
if (item instanceof RangedWeaponItem) {
gravity = 0.05;
} else if (item instanceof ThrowablePotionItem) {
gravity = 0.4;
} else if (item instanceof FishingRodItem) {
gravity = 0.15;
} else if (item instanceof TridentItem) {
gravity = 0.015;
} else {
gravity = 0.03;
}
double yaw = Math.toRadians(mc.player.getYaw());
double pitch = Math.toRadians(mc.player.getPitch());
Vec3d arrawPos = new Vec3d(MathHelper.lerp(delta, mc.player.lastRenderX, mc.player.getX()),
MathHelper.lerp(delta, mc.player.lastRenderY, mc.player.getY()),
MathHelper.lerp(delta, mc.player.lastRenderZ, mc.player.getZ())).add(PlayerUtils.getHandOffset(Hand.MAIN_HAND, yaw));
double cospitch = Math.cos(pitch);
Vec3d arrowMotion = new Vec3d(-Math.sin(yaw) * cospitch, -Math.sin(pitch), Math.cos(yaw) * cospitch).normalize().multiply(power);
for (int i = 0; i < 1000; i++) {
trajPath.add(arrawPos);
arrawPos = arrawPos.add(arrowMotion.multiply(0.1));
arrowMotion = arrowMotion.multiply(0.999);
arrowMotion = arrowMotion.add(0, -gravity * 0.1, 0);
Vec3d lastPos = trajPath.size() > 1 ? trajPath.get(trajPath.size() - 2) : mc.player.getEyePos();
| BlockHitResult result = WorldUtils.raycast(lastPos, arrawPos); | 6 | 2023-10-07 06:55:12+00:00 | 8k |
MRkto/MappetVoice | src/main/java/mrkto/mvoice/client/ClientEventHandler.java | [
{
"identifier": "MappetVoice",
"path": "src/main/java/mrkto/mvoice/MappetVoice.java",
"snippet": "@Mod.EventBusSubscriber\n@Mod(\n modid = MappetVoice.MOD_ID,\n name = MappetVoice.NAME,\n version = MappetVoice.VERSION\n)\npublic class MappetVoice {\n\n public static final String MOD_ID = \"mvoice\";\n public static final String NAME = \"MappetVoice\";\n public static final String VERSION = \"0.0.12\";\n @SidedProxy(serverSide = \"mrkto.mvoice.proxy.ServerProxy\", clientSide = \"mrkto.mvoice.proxy.ClientProxy\")\n public static ServerProxy proxy;\n @Mod.Instance(MOD_ID)\n public static MappetVoice INSTANCE;\n public static Logger logger;\n public static VoiceManager voice;\n public static MinecraftServer server;\n public static File config;\n public static Item radio = new RadioItem();\n @SideOnly(Side.CLIENT)\n public static IAudioSystemManager AudioManager;\n //configuration\n public static ValueBoolean push;\n public static ValueBoolean opus;\n public static ValueInt volumes;\n public static ValueInt volumem;\n public static ValueFloat fadetime;\n public static ValueFloat numofaction;\n public static ValueInt range;\n public static ValueBoolean radioItem;\n public static ValueBoolean hearOther;\n public static ValueBoolean hearOtherRadio;\n public static ValueBoolean onRadioSound;\n public static ValueBoolean offRadioSound;\n public static ValueBoolean needInArm;\n public static ValueBoolean noise;\n public static ValueBoolean switchRadioSound;\n public static ValueBoolean onRangeNoise;\n public static ValueInt maxNoise;\n public static ValueInt minNoise;\n public static ValueInt NoiseRange;\n public static ValueBoolean voiceaction;\n\n @SubscribeEvent\n public void onConfigRegister(RegisterConfigEvent event) {\n\n ConfigBuilder builder = event.createBuilder(MOD_ID);\n\n builder.category(\"client\").register(new ValueVoiceButtons(\"buttons\").clientSide()).getCategory();\n push = builder.getBoolean(\"push\", true);\n push.clientSide();\n volumes = builder.getInt(\"volumes\", 100, 0, 200);\n volumes.clientSide();\n volumem = builder.getInt(\"volumem\", 100, 0, 200);\n volumem.clientSide();\n fadetime = builder.getFloat(\"fadetime\", 0.1f, 0.01f, 2);\n fadetime.clientSide();\n voiceaction = builder.getBoolean(\"voiceAction\", false);\n voiceaction.clientSide();\n numofaction = builder.getFloat(\"numofaction\", 0.3f, 0.0f, 1.0f);\n numofaction.clientSide();\n builder.category(\"general\");\n range = builder.getInt(\"hearrange\", 25, 1, 200);\n range.syncable();\n opus = builder.category(\"Voicesettings\").getBoolean(\"calcSoundOnServer\", false);\n builder.category(\"radios\");\n onRadioSound = builder.getBoolean(\"onRadioSound\", true);\n onRadioSound.syncable();\n offRadioSound = builder.getBoolean(\"offRadioSound\", true);\n offRadioSound.syncable();\n switchRadioSound = builder.getBoolean(\"switchRadioSound\", true);\n switchRadioSound.syncable();\n onRangeNoise = builder.getBoolean(\"onRangeNoise\", true);\n onRangeNoise.syncable();\n noise = builder.getBoolean(\"noise\", true);\n noise.syncable();\n minNoise = builder.getInt(\"minNoise\", 50, 0, 100);\n minNoise.syncable();\n maxNoise = builder.getInt(\"maxNoise\", 90, 0, 100);\n maxNoise.syncable();\n NoiseRange = builder.getInt(\"NoiseRange\", 50, 0, 10000);\n NoiseRange.syncable();\n radioItem = builder.getBoolean(\"useItem\", true);\n radioItem.syncable();\n hearOther = builder.getBoolean(\"hearOther\", true);\n hearOther.syncable();\n hearOtherRadio = builder.getBoolean(\"hearOtherRadio\", true);\n hearOtherRadio.syncable();\n needInArm = builder.getBoolean(\"needInArm\", true);\n needInArm.syncable();\n\n }\n @EventHandler\n public void preInit(FMLPreInitializationEvent event) throws OpusNotLoadedException {\n logger = event.getModLog();\n config = event.getModConfigurationDirectory();\n\n McLib.EVENT_BUS.register(this);\n MinecraftForge.EVENT_BUS.register(new mrkto.mvoice.EventHandler());\n Dispatcher.register();\n CapabilityManager.INSTANCE.register(IProfile.class, new ProfileStorage(), Profile::new);\n\n proxy.preInit(event);\n }\n\n @EventHandler\n public void init(FMLInitializationEvent event) {\n MVIcons.register();\n\n proxy.init(event);\n }\n\n @EventHandler\n public void postInit(FMLPostInitializationEvent event) {\n proxy.postInit(event);\n }\n\n @EventHandler\n public void serverStart(FMLServerStartingEvent event) {\n voice = new VoiceManager();\n server = event.getServer();\n logger.info(\"hello world!\");\n\n\n }\n\n\n @EventHandler\n public void serverStop(FMLServerStoppingEvent event){\n voice = null;\n server = null;\n logger.info(\"gg\");\n\n\n }\n @SideOnly(Side.CLIENT)\n @EventHandler\n public void disableMod(FMLModDisabledEvent event){\n AudioManager.fullTerminate();\n SpeakerListener.instance.close();\n logger.info(\"bye\");\n }\n @SubscribeEvent\n public static void onRegistryItem(Register<Item> e){\n e.getRegistry().register(radio);\n }\n @SubscribeEvent\n @SideOnly(Side.CLIENT)\n public static void onRegistryModel(ModelRegistryEvent e) {\n registryModel(radio);\n }\n @SideOnly(Side.CLIENT)\n private static void registryModel(Item item) {\n final ResourceLocation regName = item.getRegistryName();\n final ModelResourceLocation mrl = new ModelResourceLocation(regName != null ? regName : RLUtils.create(\"\"), \"inventory\");\n ModelBakery.registerItemVariants(item, mrl);\n ModelLoader.setCustomModelResourceLocation(item, 0, mrl);\n\n }\n}"
},
{
"identifier": "OnEngineRegistry",
"path": "src/main/java/mrkto/mvoice/api/Events/OnEngineRegistry.java",
"snippet": "public class OnEngineRegistry extends Event {\n public OnEngineRegistry() {\n\n }\n public void registry(String EngineName, IAudioSystemManager AudioSystemManager){\n AudioEngineLoader.registeredEngines.put(EngineName, AudioSystemManager);\n MappetVoice.logger.info(\"registered \" + EngineName + \" sound engine\");\n }\n}"
},
{
"identifier": "Profile",
"path": "src/main/java/mrkto/mvoice/capability/Profile.java",
"snippet": "public class Profile implements IProfile{\n private EntityPlayer player;\n private boolean isMuted = false;\n private String wave = \"\";\n private final ArrayList<String> MutedList = new ArrayList<>();\n @Override\n public void setMuted(boolean value) {\n isMuted = value;\n if(Side.SERVER.isServer())\n sync();\n }\n @Override\n public void setWave(String value) {\n wave = value;\n if(Side.SERVER.isServer())\n sync();\n }\n @Override\n public String getWave() {\n return wave;\n }\n\n @Override\n public boolean getMuted() {\n return isMuted;\n }\n\n @Override\n public void addMuted(String name) {\n MutedList.add(name);\n if(Side.SERVER.isServer())\n sync();\n }\n\n @Override\n public ArrayList<String> getMutedList() {\n return MutedList;\n }\n\n @Override\n public void removeMuted(String name) {\n MutedList.remove(name);\n if(Side.SERVER.isServer())\n sync();\n }\n public static Profile get(EntityPlayer player)\n {\n IProfile profileCapability = player == null ? null : player.getCapability(ProfileProvider.MAIN, null);\n\n if (profileCapability instanceof Profile)\n {\n Profile profile = (Profile) profileCapability;\n profile.player = player;\n\n return profile;\n }\n return null;\n }\n private void sync()\n {\n Dispatcher.sendTo(new SyncCapabilityPacket(serializeNBT()), (EntityPlayerMP) player);\n }\n @Override\n public NBTTagCompound serializeNBT() {\n NBTTagCompound nbtTagCompound = new NBTTagCompound();\n nbtTagCompound.setBoolean(\"isMuted\", this.isMuted);\n NBTTagList list = new NBTTagList();\n for(int i = 0; i < this.MutedList.size(); i++){\n list.set(i, new NBTTagString(this.MutedList.get(i)));\n }\n nbtTagCompound.setTag(\"List\", list);\n return nbtTagCompound;\n }\n\n @Override\n public void deserializeNBT(NBTTagCompound tag) {\n if (tag.hasKey(\"isMuted\")) {\n this.isMuted = tag.getBoolean(\"isMuted\");\n }\n if (tag.hasKey(\"List\")) {\n for (NBTBase i : (NBTTagList) tag.getTag(\"List\")) {\n this.MutedList.add(i.toString());\n }\n }\n }\n}"
},
{
"identifier": "AudioEngineLoader",
"path": "src/main/java/mrkto/mvoice/client/audio/AudioEngineLoader.java",
"snippet": "public class AudioEngineLoader {\n public static final String defaultEngine = \"kostil\";\n public static final Map<String, IAudioSystemManager> registeredEngines = new HashMap<>();\n public static String selectedEngine = \"kostil\";\n\n public static void loadEngine(String engineName){\n if(MappetVoice.AudioManager != null){\n MappetVoice.AudioManager.terminate();\n }\n IAudioSystemManager audioSystemManager = registeredEngines.get(engineName);\n selectedEngine = engineName;\n if(audioSystemManager == null){\n audioSystemManager = registeredEngines.get(defaultEngine);\n selectedEngine = defaultEngine;\n }\n MappetVoice.AudioManager = audioSystemManager.getNewInstance();\n MappetVoice.AudioManager.preInitiate();\n }\n public static void reloadEngine(){\n if(MappetVoice.AudioManager == null){\n MappetVoice.logger.error(\"the engine cannot be restarted because it is not loaded\");\n }\n loadEngine(selectedEngine);\n MappetVoice.AudioManager.initiate();\n }\n public static void stopEngineLoader(){\n\n }\n}"
},
{
"identifier": "CoolAudioSystem",
"path": "src/main/java/mrkto/mvoice/client/audio/better/CoolAudioSystem.java",
"snippet": "public class CoolAudioSystem implements IAudioSystemManager {\n protected DefaultRecorder input;\n\n protected CoolSpeaker output;\n public CoolAudioSystem(){\n this.input = new DefaultRecorder();\n this.output = new CoolSpeaker();\n }\n\n @Override\n public IAudioInput getInput() {\n return input;\n }\n\n @Override\n public IAudioOutput getOutput() {\n return output;\n }\n\n @Override\n public void processSound(byte[] data, BlockPos position, double posX, double posY, double posZ, float rotationPitch, float rotationYaw, double distance, String name) {\n output.playSound(data, position.getX(), position.getY(), position.getZ(), posX, posY, posZ, rotationPitch, rotationYaw, distance, name);\n }\n\n @Override\n public boolean preInitiate() {\n return true;\n }\n\n @Override\n public boolean initiate() {\n return true;\n }\n\n @Override\n public void terminate() {\n input.stopRecording();\n output.stopAllSounds();\n }\n\n @Override\n public void fullTerminate() {\n input = null;\n\n }\n\n @Override\n public IAudioSystemManager getNewInstance() {\n return new CoolAudioSystem();\n }\n\n\n}"
},
{
"identifier": "DefaultAudioSystemManager",
"path": "src/main/java/mrkto/mvoice/client/audio/DefaultAudioSystemManager.java",
"snippet": "public class DefaultAudioSystemManager implements IAudioSystemManager {\n protected DefaultRecorder input;\n protected DefaultSpeaker output;\n public DefaultAudioSystemManager(){\n this.input = new DefaultRecorder();\n this.output = new DefaultSpeaker();\n }\n\n @Override\n public IAudioInput getInput() {\n return input;\n }\n\n @Override\n public IAudioOutput getOutput() {\n return output;\n }\n\n @Override\n public void processSound(byte[] data, BlockPos position, double posX, double posY, double posZ, float rotationPitch, float rotationYaw, double distance, String name) {\n output.playSound(data, position.getX(), position.getY(), position.getZ(), posX, posY, posZ, rotationPitch, rotationYaw, distance, name);\n }\n\n @Override\n public boolean preInitiate() {\n return true;\n }\n\n @Override\n public boolean initiate() {\n try{\n output.createDefault();\n }catch (Exception e){\n e.printStackTrace();\n return false;\n }\n return true;\n }\n\n @Override\n public void terminate() {\n output.deleteAllChanels();\n input.stopRecording();\n }\n\n @Override\n public void fullTerminate() {\n input = null;\n output = null;\n }\n\n @Override\n public IAudioSystemManager getNewInstance() {\n return new DefaultAudioSystemManager();\n }\n\n\n}"
},
{
"identifier": "Dispatcher",
"path": "src/main/java/mrkto/mvoice/network/Dispatcher.java",
"snippet": "public class Dispatcher{\n private static final AbstractDispatcher DISPATCHER = new AbstractDispatcher(MappetVoice.MOD_ID) {\n public void register() {\n this.register(EventPacket.class, EventPacket.ServerHandler.class, Side.SERVER);\n this.register(RadioPacket.class, RadioPacket.ServerHandler.class, Side.SERVER);\n this.register(SyncCapabilityPacket.class, SyncCapabilityPacket.ClientHandler.class, Side.CLIENT);\n\n }\n };\n private static final AbstractDispatcher VOICE_DISPATCHER = new AbstractDispatcher(\"VOICEDISPATCHER\") {\n public void register() {\n this.register(SoundPacketClient.class, SoundPacketClient.ClientHandler.class, Side.CLIENT);\n this.register(SoundPacket.class, SoundPacket.ServerHandler.class, Side.SERVER);\n\n\n }\n };\n public static void sendTo(IMessage message, EntityPlayerMP player) {\n DISPATCHER.sendTo(message, player);\n }\n\n public static void sendToServer(IMessage message) {\n DISPATCHER.sendToServer(message);\n }\n public static void sendSoundTo(byte[] data, BlockPos DataPos, EntityPlayerMP player, String name, double distance) {\n VOICE_DISPATCHER.sendTo(new SoundPacketClient(data, DataPos, name, distance, 0f), player);\n }\n public static void sendSoundTo(byte[] data, BlockPos DataPos, EntityPlayerMP player, String name, double distance, float balance) {\n VOICE_DISPATCHER.sendTo(new SoundPacketClient(data, DataPos, name, distance, balance), player);\n }\n public static boolean sending = false;\n public static float value = 0.0f;\n public static void sendSoundToServer(byte[] data, boolean isRadio) {\n float volume = AudioUtils.calcVolume(data);\n boolean high = volume > MappetVoice.numofaction.get();\n value = Math.max(0f, Math.min(MappetVoice.numofaction.get(), high ? value - MappetVoice.numofaction.get() / 20 : value + MappetVoice.numofaction.get() / 5));\n sending = !MappetVoice.voiceaction.get() || value != MappetVoice.numofaction.get();\n if(!sending)\n return;\n byte[] encodedData = AudioUtils.encode(data);\n VOICE_DISPATCHER.sendToServer(new SoundPacket(encodedData, isRadio, volume));\n }\n public static void sendEndToServer() {\n\n VOICE_DISPATCHER.sendToServer(new SoundPacket());\n }\n public static void postEventOnServer(String event, boolean isRadio) {\n DISPATCHER.sendToServer(new EventPacket(event, isRadio));\n }\n public static void postEventOnServer(String event) {\n DISPATCHER.sendToServer(new EventPacket(event, false));\n }\n public static void register() {\n DISPATCHER.register();\n VOICE_DISPATCHER.register();\n }\n}"
},
{
"identifier": "UnableInitiateEngineException",
"path": "src/main/java/mrkto/mvoice/utils/other/UnableInitiateEngineException.java",
"snippet": "public class UnableInitiateEngineException extends Exception{\n public UnableInitiateEngineException() {\n super();\n }\n public UnableInitiateEngineException(String message) {\n super(message);\n }\n}"
},
{
"identifier": "MVIcons",
"path": "src/main/java/mrkto/mvoice/utils/other/mclib/MVIcons.java",
"snippet": "public class MVIcons {\n public static final ResourceLocation TEXTURE = new ResourceLocation(MappetVoice.MOD_ID, \"textures/voice.png\");\n\n public static final Icon MutedD = new Icon(TEXTURE, 0, 0, 16, 16, 64, 64);\n public static final Icon MutedMicro = new Icon(TEXTURE, 16, 0, 16, 16, 64, 64);\n public static final Icon MutedSpeaker = new Icon(TEXTURE, 32, 0, 16, 16, 64, 64);\n public static final Icon MutedEarphones = new Icon(TEXTURE, 48, 0, 16, 16, 64, 64);\n public static final Icon D = new Icon(TEXTURE, 0, 16, 16, 16, 64, 64);\n public static final Icon Micro = new Icon(TEXTURE, 16, 16, 16, 16, 64, 64);\n public static final Icon Speaker = new Icon(TEXTURE, 32, 16, 16, 16, 64, 64);\n public static final Icon Earphones = new Icon(TEXTURE, 48, 16, 16, 16, 64, 64);\n\n public static void register()\n {\n IconRegistry.register(\"MutedDinamo\", MutedD);\n IconRegistry.register(\"MutedMicro\", MutedMicro);\n IconRegistry.register(\"MutedSpeaker\", MutedSpeaker);\n IconRegistry.register(\"MutedEarphones\", MutedEarphones);\n\n IconRegistry.register(\"Dinamo\", D);\n IconRegistry.register(\"Micro\", Micro);\n IconRegistry.register(\"Speaker\", Speaker);\n IconRegistry.register(\"Earphones\", Earphones);\n }\n}"
}
] | import mrkto.mvoice.MappetVoice;
import mrkto.mvoice.api.Events.OnEngineRegistry;
import mrkto.mvoice.capability.Profile;
import mrkto.mvoice.client.audio.AudioEngineLoader;
import mrkto.mvoice.client.audio.better.CoolAudioSystem;
import mrkto.mvoice.client.audio.DefaultAudioSystemManager;
import mrkto.mvoice.network.Dispatcher;
import mrkto.mvoice.utils.other.UnableInitiateEngineException;
import mrkto.mvoice.utils.other.mclib.MVIcons;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.Gui;
import net.minecraft.client.gui.ScaledResolution;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.client.event.RenderGameOverlayEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.gameevent.PlayerEvent;
import net.minecraftforge.fml.common.gameevent.TickEvent;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly; | 4,697 | package mrkto.mvoice.client;
@SideOnly(Side.CLIENT)
public class ClientEventHandler {
private static int i = 0;
public boolean canSpeak = true;
@SubscribeEvent
public void onClientTick(TickEvent.ClientTickEvent event) { | package mrkto.mvoice.client;
@SideOnly(Side.CLIENT)
public class ClientEventHandler {
private static int i = 0;
public boolean canSpeak = true;
@SubscribeEvent
public void onClientTick(TickEvent.ClientTickEvent event) { | Profile profile = Profile.get(Minecraft.getMinecraft().player); | 2 | 2023-10-14 19:20:12+00:00 | 8k |
batmatt/cli-rpg-java | src/com/clirpg/locations/Arena.java | [
{
"identifier": "Round",
"path": "src/com/clirpg/game/Round.java",
"snippet": "public class Round {\n private int level;\n private Player player;\n private Soldier roundSoldierArray[];\n private int currentSoldierNumber = 0;\n private Monster roundMonsterArray[];\n private int currentMonsterNumber = 0;\n \n\n public Round(int level)\n {\n this.level = level;\n this.roundSoldierArray = new Soldier [1000];\n this.roundMonsterArray = new Monster [1000];\n }\n\n public Round(int level, Player player)\n {\n this.level = level;\n this.player = player;\n this.roundSoldierArray = new Soldier [1000];\n this.roundMonsterArray = new Monster [1000];\n }\n\n public int getLevel()\n {\n return this.level;\n }\n\n public void setLevel(int level)\n {\n this.level = level;\n }\n\n public int startRound()\n {\n player.health = 100;\n Random random = new Random();\n //System.out.println(\"started round at level: \" + this.getLevel());\n // Get enemies\n int soldierNumber = 0;\n int monsterNumber = 0;\n // Generate a random double between 0 (inclusive) and 1 (exclusive)\n for (int i = this.getLevel(); i > 0; i--) {\n //System.out.println(i);\n // chane do disable monsters\n int randomNumber = random.nextInt(2);\n //System.out.println(randomNumber);\n switch (randomNumber) {\n case 0:\n soldierNumber++;\n break;\n case 1:\n monsterNumber++;\n i-=2;\n break;\n }\n }\n //System.out.println(\"remainder = \" + (this.getLevel() - (soldierNumber + (monsterNumber * 3))));\n //System.out.println(\"soldier number = \" + soldierNumber);\n //System.out.println(\"monster number = \" + monsterNumber);\n\n for (int i = soldierNumber; i > 0; i--) {\n //System.out.println(i);\n int randomNumber = random.nextInt(10);\n //System.out.println(randomNumber);\n switch (randomNumber) {\n case 0:\n appendSoldier(new Soldier(\"Billy\"));\n break;\n case 1:\n appendSoldier(new Soldier(\"Brian\"));\n break;\n case 2:\n appendSoldier(new Soldier(\"Luc\"));\n break;\n case 3:\n appendSoldier(new Soldier(\"Matthew\"));\n break;\n case 4:\n appendSoldier(new Soldier(\"Mary\"));\n break;\n case 5:\n appendSoldier(new Soldier(\"Antoinette\"));\n break;\n case 6:\n appendSoldier(new Soldier(\"James\"));\n break;\n case 7:\n appendSoldier(new Soldier(\"Ryan\"));\n break;\n case 8:\n appendSoldier(new Soldier(\"Robert\"));\n break;\n case 9:\n appendSoldier(new Soldier(\"Edward\"));\n break;\n }\n }\n\n for (int i = monsterNumber; i > 0; i--) {\n //System.out.println(i);\n int randomNumber = random.nextInt(10);\n //System.out.println(randomNumber);\n switch (randomNumber) {\n case 0:\n appendMonster(new Monster(\"Balrog\"));\n break;\n case 1:\n appendMonster(new Monster(\"Banshee\"));\n break;\n case 2:\n appendMonster(new Monster(\"Lockjaw\"));\n break;\n case 3:\n appendMonster(new Monster(\"DiamondHead\"));\n break;\n case 4:\n appendMonster(new Monster(\"Ogre\"));\n break;\n case 5:\n appendMonster(new Monster(\"Witch\"));\n break;\n case 6:\n appendMonster(new Monster(\"ManEater\"));\n break;\n case 7:\n appendMonster(new Monster(\"Basilisk\"));\n break;\n case 8:\n appendMonster(new Monster(\"Zombie\"));\n break;\n case 9:\n appendMonster(new Monster(\"Warg\"));\n break; \n }\n }\n this.roundLoop();\n if(player.health >= 0)\n {\n return 1;\n }\n else\n {\n return 0;\n }\n }\n\n public void roundLoop() {\n Scanner choiceReader = new Scanner(System.in);\n int enemiesRemain = 1;\n int playerAlive = 1;\n\n while ((enemiesRemain == 1) && (playerAlive == 1))\n {\n System.out.println(ConsoleColors.RED + \"~~~~~~~~~~~~\" + ConsoleColors.RESET);\n System.out.println(this.toString());\n System.out.println(\"Enter '1' to attack soldier or '2' to attack monster\");\n int choice = choiceReader.nextInt();\n \n // Check the value of 'choice' and perform actions accordingly\n switch (choice) {\n case 1:\n if(currentSoldierNumber <= 0)\n {\n break;\n }\n // Code to attack a soldier\n // For example: player.attackSoldier();\n //System.out.println(\"player chooses soldier\");\n System.out.println(ConsoleColors.YELLOW_UNDERLINED + \"Choose Soldier in range 0-\" + (currentSoldierNumber - 1) + ConsoleColors.RESET);\n choice = choiceReader.nextInt();\n while ((choice > (currentSoldierNumber - 1)) || (choice < 0))\n {\n System.out.println(ConsoleColors.RED_BOLD_BRIGHT + \"Invalid integer, pick again\" + ConsoleColors.RESET);\n System.out.println(ConsoleColors.YELLOW_UNDERLINED + \"Choose Soldier in range 0-\" + (currentSoldierNumber - 1) + ConsoleColors.RESET);\n choice = choiceReader.nextInt();\n }\n System.out.println(ConsoleColors.RED + \"~~~~~~~~~~~~\" + ConsoleColors.RESET);\n System.out.println(\"Selected soldier: \" + roundSoldierArray[choice].toString());\n roundSoldierArray[choice].setHealth(player.combat());\n break;\n case 2:\n if(currentMonsterNumber <= 0)\n {\n break;\n }\n // Code to attack a monster\n // For example: player.attackMonster();\n //System.out.println(\"player chooses Monster\");\n System.out.println(ConsoleColors.YELLOW_UNDERLINED + \"Choose Monster in range 0-\" + (currentMonsterNumber - 1) + ConsoleColors.RESET);\n choice = choiceReader.nextInt();\n while ((choice > (currentMonsterNumber - 1)) || (choice < 0))\n {\n System.out.println(ConsoleColors.RED_BOLD_BRIGHT+ \"Invalid integer, pick again\" + ConsoleColors.RESET);\n System.out.println(ConsoleColors.YELLOW_UNDERLINED + \"Choose Monster in range 0-\" + (currentMonsterNumber - 1) + ConsoleColors.RESET);\n choice = choiceReader.nextInt();\n }\n System.out.println(ConsoleColors.RED + \"~~~~~~~~~~~~\" + ConsoleColors.RESET);\n System.out.println(\"Selected Monster: \" + roundMonsterArray[choice].toString());\n roundMonsterArray[choice].setHealth(player.combat());\n break;\n default:\n System.out.println(ConsoleColors.RED_BOLD_BRIGHT + \"Invalid choice. Try again.\" + ConsoleColors.RESET);\n break;\n }\n enemiesRemain = checkAndUpdate();\n if (enemiesRemain == 1)\n {\n Random random = new Random();\n if (currentSoldierNumber > 0)\n {\n System.out.println(ConsoleColors.RED + \"~~~~~~~~~~~~\" + ConsoleColors.RESET);\n int randomNumber = random.nextInt(currentSoldierNumber);\n Soldier selectedSoldier = roundSoldierArray[randomNumber];\n player.health -= selectedSoldier.combat();\n }\n if (currentMonsterNumber > 0)\n {\n System.out.println(ConsoleColors.RED + \"~~~~~~~~~~~~\" + ConsoleColors.RESET);\n int randomNumber = random.nextInt(currentMonsterNumber);\n Monster selectedMonster = roundMonsterArray[randomNumber];\n player.health -= selectedMonster.combat();\n }\n }\n if (player.health < 0)\n {\n System.out.println(ConsoleColors.RED_BACKGROUND + \"You died!\" + ConsoleColors.RESET);\n System.exit(0);\n }\n }\n }\n \n public int checkAndUpdate()\n {\n if (currentSoldierNumber > 0)\n {\n for (int i = 0; i < currentSoldierNumber; i++)\n {\n if (roundSoldierArray[i] != null)\n {\n if (roundSoldierArray[i].health <= 0)\n {\n System.out.println(ConsoleColors.RED_BACKGROUND + roundSoldierArray[i].name + \" died\" + ConsoleColors.RESET);\n removeSoldier(i);\n }\n }\n else\n {\n System.out.println(\"soldier lost error at \" + i);\n return 1;\n }\n }\n }\n\n if (currentMonsterNumber > 0)\n {\n for (int i = 0; i < currentMonsterNumber; i++)\n {\n if (roundMonsterArray[i] != null)\n {\n if (roundMonsterArray[i].health <= 0)\n {\n System.out.println(ConsoleColors.RED_BACKGROUND + roundMonsterArray[i].name + \" died\" + ConsoleColors.RESET);\n removeMonster(i);\n }\n }\n else\n {\n System.out.println(\"monster lost error at \" + i);\n return 1;\n }\n }\n }\n if ((currentMonsterNumber + currentSoldierNumber) == 0)\n {\n return 0;\n }\n return 1;\n }\n\n public void removeSoldier(int toRemove)\n {\n Soldier[] tmpRoundSoldierArray = roundSoldierArray;\n int tmpSoldierNumber = currentSoldierNumber;\n //System.out.println(\"target to remove \" + tmpRoundSoldierArray[toRemove]);\n this.roundSoldierArray = new Soldier [1000];\n this.currentSoldierNumber = 0;\n for (int i = 0; (i < tmpSoldierNumber); i++)\n {\n //System.out.println(\"adding: \" + tmpRoundSoldierArray[i]);\n if(i != toRemove)\n {\n appendSoldier(tmpRoundSoldierArray[i]);\n }\n }\n }\n\n public void removeMonster(int toRemove)\n {\n Monster[] tmpRoundMonsterArray = roundMonsterArray;\n int tmpMonsterNumber = currentMonsterNumber;\n //System.out.println(\"target to remove \" + tmpRoundMonsterArray[toRemove]);\n this.roundMonsterArray = new Monster [1000];\n this.currentMonsterNumber = 0;\n for (int i = 0; (i < tmpMonsterNumber); i++)\n {\n //System.out.println(\"adding: \" + tmpRoundMonsterArray[i]);\n if(i != toRemove)\n {\n appendMonster(tmpRoundMonsterArray[i]);\n }\n }\n }\n\n public void appendMonster(Monster newMonster) {\n if (currentMonsterNumber < roundMonsterArray.length) {\n roundMonsterArray[currentMonsterNumber] = newMonster;\n currentMonsterNumber++; // Increment the count of Monsters in the array\n } else {\n // Handle the case where the array is full and cannot append more Monsters\n System.out.println(\"The array is full. Cannot append more Monsters.\");\n }\n }\n\n public void appendSoldier(Soldier newSoldier) {\n if (currentSoldierNumber < roundSoldierArray.length) {\n roundSoldierArray[currentSoldierNumber] = newSoldier;\n currentSoldierNumber++; // Increment the count of soldiers in the array\n } else {\n // Handle the case where the array is full and cannot append more soldiers\n System.out.println(\"The array is full. Cannot append more soldiers.\");\n }\n }\n\n public String toString() {\n String toPrint = (ConsoleColors.CYAN + this.player.toString() + \"\\n\" + ConsoleColors.RESET);\n toPrint += (ConsoleColors.GREEN_BACKGROUND + \"Soldiers: \" + ConsoleColors.RESET);\n for (int i = 0; i < currentSoldierNumber; i++) {\n if (roundSoldierArray[i] != null) {\n toPrint = toPrint + \"[\" + i + \"]:\" + roundSoldierArray[i].toString() + \", \";\n }\n else\n {\n //System.out.println(\"soldier lost\");\n }\n }\n toPrint += \"\\n\";\n toPrint += (ConsoleColors.GREEN_BACKGROUND + \"Monsters: \" + ConsoleColors.RESET);\n for (int i = 0; i < currentMonsterNumber; i++) {\n if (roundMonsterArray[i] != null) {\n toPrint = toPrint + \"[\" + i + \"]:\" + roundMonsterArray[i].toString() + \", \";\n }\n else\n {\n //System.out.println(\"monster lost\");\n }\n }\n return toPrint;\n }\n \n}"
},
{
"identifier": "Civillian",
"path": "src/com/clirpg/characters/Civillian.java",
"snippet": "public class Civillian extends Entity implements Talk{\n final static boolean friendly = true;\n String job;\n\n public Civillian(String name, String job)\n {\n super(name);\n this.job = job;\n this.health = 100;\n }\n\n public Civillian(String name, String job, int health)\n {\n super(name, health);\n this.job = job;\n }\n\n public void talk()\n {\n System.out.println(ConsoleColors.GREEN + \"\\n\" + toString() + \": I saw enemies. Do you want to fight them? You would get 10 coins for it\\n\" + ConsoleColors.RESET);\n }\n\n public String toString()\n {\n return this.job + \" \" + this.name; \n }\n\n public void talkEnd()\n {\n System.out.println(ConsoleColors.GREEN + \"\\n\" + toString() + \": Thank you for killing the enemies. Here is your reward.\\n\" + ConsoleColors.RESET);\n }\n}"
},
{
"identifier": "Player",
"path": "src/com/clirpg/characters/Player.java",
"snippet": "public class Player extends Entity implements Combat {\n public int attackStrength;\n public int hitProbability;\n public int money;\n public int maxLevelArena;\n\n final boolean friendly = true;\n \n public Player(String name, CharacterClass characterClass)\n {\n super(name);\n money = 100;\n maxLevelArena = 0;\n this.health = characterClass.health;\n this.attackStrength = characterClass.attackStrength;\n this.hitProbability = characterClass.hitProbability; \n }\n\n @Override\n public String toString() {\n return \"Name: \" + this.name + \", Health: \" + health + \", Attack Strength: \" + attackStrength + \", Hit Probability: \" + hitProbability + \", Money: \" + money;\n }\n\n public int combat()\n {\n int randomNumber;\n Random random = new Random();\n randomNumber = random.nextInt(100);\n //System.out.println(\"rng: \" + randomNumber);\n if(randomNumber < this.hitProbability)\n {\n System.out.println(\"Attack hits for \" + this.attackStrength + \" damage\");\n return this.attackStrength;\n }\n else\n {\n System.out.println(\"Attack fails\");\n }\n return 0;\n }\n}"
},
{
"identifier": "ConsoleColors",
"path": "src/com/utils/ConsoleColors.java",
"snippet": "public class ConsoleColors {\n // Reset\n public static final String RESET = \"\\033[0m\"; // Text Reset\n\n // Regular Colors\n public static final String BLACK = \"\\033[0;30m\"; // BLACK\n public static final String RED = \"\\033[0;31m\"; // RED\n public static final String GREEN = \"\\033[0;32m\"; // GREEN\n public static final String YELLOW = \"\\033[0;33m\"; // YELLOW\n public static final String BLUE = \"\\033[0;34m\"; // BLUE\n public static final String PURPLE = \"\\033[0;35m\"; // PURPLE\n public static final String CYAN = \"\\033[0;36m\"; // CYAN\n public static final String WHITE = \"\\033[0;37m\"; // WHITE\n\n // Bold\n public static final String BLACK_BOLD = \"\\033[1;30m\"; // BLACK\n public static final String RED_BOLD = \"\\033[1;31m\"; // RED\n public static final String GREEN_BOLD = \"\\033[1;32m\"; // GREEN\n public static final String YELLOW_BOLD = \"\\033[1;33m\"; // YELLOW\n public static final String BLUE_BOLD = \"\\033[1;34m\"; // BLUE\n public static final String PURPLE_BOLD = \"\\033[1;35m\"; // PURPLE\n public static final String CYAN_BOLD = \"\\033[1;36m\"; // CYAN\n public static final String WHITE_BOLD = \"\\033[1;37m\"; // WHITE\n\n // Underline\n public static final String BLACK_UNDERLINED = \"\\033[4;30m\"; // BLACK\n public static final String RED_UNDERLINED = \"\\033[4;31m\"; // RED\n public static final String GREEN_UNDERLINED = \"\\033[4;32m\"; // GREEN\n public static final String YELLOW_UNDERLINED = \"\\033[4;33m\"; // YELLOW\n public static final String BLUE_UNDERLINED = \"\\033[4;34m\"; // BLUE\n public static final String PURPLE_UNDERLINED = \"\\033[4;35m\"; // PURPLE\n public static final String CYAN_UNDERLINED = \"\\033[4;36m\"; // CYAN\n public static final String WHITE_UNDERLINED = \"\\033[4;37m\"; // WHITE\n\n // Background\n public static final String BLACK_BACKGROUND = \"\\033[40m\"; // BLACK\n public static final String RED_BACKGROUND = \"\\033[41m\"; // RED\n public static final String GREEN_BACKGROUND = \"\\033[42m\"; // GREEN\n public static final String YELLOW_BACKGROUND = \"\\033[43m\"; // YELLOW\n public static final String BLUE_BACKGROUND = \"\\033[44m\"; // BLUE\n public static final String PURPLE_BACKGROUND = \"\\033[45m\"; // PURPLE\n public static final String CYAN_BACKGROUND = \"\\033[46m\"; // CYAN\n public static final String WHITE_BACKGROUND = \"\\033[47m\"; // WHITE\n\n // High Intensity\n public static final String BLACK_BRIGHT = \"\\033[0;90m\"; // BLACK\n public static final String RED_BRIGHT = \"\\033[0;91m\"; // RED\n public static final String GREEN_BRIGHT = \"\\033[0;92m\"; // GREEN\n public static final String YELLOW_BRIGHT = \"\\033[0;93m\"; // YELLOW\n public static final String BLUE_BRIGHT = \"\\033[0;94m\"; // BLUE\n public static final String PURPLE_BRIGHT = \"\\033[0;95m\"; // PURPLE\n public static final String CYAN_BRIGHT = \"\\033[0;96m\"; // CYAN\n public static final String WHITE_BRIGHT = \"\\033[0;97m\"; // WHITE\n\n // Bold High Intensity\n public static final String BLACK_BOLD_BRIGHT = \"\\033[1;90m\"; // BLACK\n public static final String RED_BOLD_BRIGHT = \"\\033[1;91m\"; // RED\n public static final String GREEN_BOLD_BRIGHT = \"\\033[1;92m\"; // GREEN\n public static final String YELLOW_BOLD_BRIGHT = \"\\033[1;93m\";// YELLOW\n public static final String BLUE_BOLD_BRIGHT = \"\\033[1;94m\"; // BLUE\n public static final String PURPLE_BOLD_BRIGHT = \"\\033[1;95m\";// PURPLE\n public static final String CYAN_BOLD_BRIGHT = \"\\033[1;96m\"; // CYAN\n public static final String WHITE_BOLD_BRIGHT = \"\\033[1;97m\"; // WHITE\n\n // High Intensity backgrounds\n public static final String BLACK_BACKGROUND_BRIGHT = \"\\033[0;100m\";// BLACK\n public static final String RED_BACKGROUND_BRIGHT = \"\\033[0;101m\";// RED\n public static final String GREEN_BACKGROUND_BRIGHT = \"\\033[0;102m\";// GREEN\n public static final String YELLOW_BACKGROUND_BRIGHT = \"\\033[0;103m\";// YELLOW\n public static final String BLUE_BACKGROUND_BRIGHT = \"\\033[0;104m\";// BLUE\n public static final String PURPLE_BACKGROUND_BRIGHT = \"\\033[0;105m\"; // PURPLE\n public static final String CYAN_BACKGROUND_BRIGHT = \"\\033[0;106m\"; // CYAN\n public static final String WHITE_BACKGROUND_BRIGHT = \"\\033[0;107m\"; // WHITE\n}"
}
] | import java.util.InputMismatchException;
import java.util.Scanner;
import src.com.clirpg.game.Round;
import src.com.clirpg.characters.Civillian;
import src.com.clirpg.characters.Player;
import src.com.utils.ConsoleColors; | 5,045 | package src.com.clirpg.locations;
public class Arena implements Visit{
private Civillian trainer; | package src.com.clirpg.locations;
public class Arena implements Visit{
private Civillian trainer; | private Player player; | 2 | 2023-10-14 15:38:50+00:00 | 8k |
lukas-mb/ABAP-SQL-Beautifier | ABAP SQL Beautifier/src/com/abap/sql/beautifier/statement/AbapSql.java | [
{
"identifier": "Abap",
"path": "ABAP SQL Beautifier/src/com/abap/sql/beautifier/Abap.java",
"snippet": "public final class Abap {\n\n\t// class to store keywords and stuff\n\t// --> easier to find use with 'where used list'\n\n\tpublic static final List<String> JOINS = Arrays.asList(\"INNER JOIN\", \"JOIN\", \"CROSS JOIN\", \"OUTER JOIN\",\n\t\t\t\"FULL OUTER JOIN\", \"LEFT OUTER JOIN\", \"RIGHT OUTER JOIN\", \"LEFT JOIN\", \"RIGHT JOIN\");\n\n\tpublic static final String ORDERBY = \"ORDER BY\";\n\tpublic static final String SELECT = \"SELECT\";\n\tpublic static final String UPTO = \"UP TO\";\n\tpublic static final String FROM = \"FROM\";\n\tpublic static final String SELECTFROM = \"SELECT FROM\";\n\tpublic static final String SELECT_SINGLE_FROM = \"SELECT SINGLE FROM\";\n\tpublic static final String INTO = \"INTO\";\n\tpublic static final String WHERE = \"WHERE\";\n\tpublic static final String GROUPBY = \"GROUP BY\";\n\tpublic static final String HAVING = \"HAVING\";\n\tpublic static final String FIELDS = \"FIELDS\";\n\tpublic static final String CONNECTION = \"CONNECTION\";\n\tpublic static final String FORALLENTRIES = \"FOR ALL ENTRIES\";\n\tpublic static final String APPENDING = \"APPENDING\";\n\tpublic static final String OFFSET = \"OFFSET\";\n\tpublic static final String COMMENT = \"COMMENT\";\n\tpublic static final String SINGLE = \"SINGLE\";\n\tpublic static final String INTO_COR_FI_OF = \"INTO CORRESPONDING FIELDS\";\n}"
},
{
"identifier": "Activator",
"path": "ABAP SQL Beautifier/src/com/abap/sql/beautifier/Activator.java",
"snippet": "public class Activator extends AbstractUIPlugin {\n\n\t// The shared instance\n\tprivate static Activator plugin;\n\n\t// The plug-in ID\n\tpublic static final String PLUGIN_ID = \"com.abap.sql.beautifier\"; //$NON-NLS-1$\n\n\t/**\n\t * Returns the shared instance\n\t *\n\t * @return the shared instance\n\t */\n\tpublic static Activator getDefault() {\n\t\treturn plugin;\n\t}\n\n\t/**\n\t * The constructor\n\t */\n\tpublic Activator() {\n\t}\n\n\t@Override\n\tpublic void start(BundleContext context) throws Exception {\n\t\tsuper.start(context);\n\t\tplugin = this;\n\t}\n\n\t@Override\n\tpublic void stop(BundleContext context) throws Exception {\n\t\tplugin = null;\n\t\tsuper.stop(context);\n\t}\n\n}"
},
{
"identifier": "PreferenceConstants",
"path": "ABAP SQL Beautifier/src/com/abap/sql/beautifier/preferences/PreferenceConstants.java",
"snippet": "public class PreferenceConstants {\n\n\tpublic static final String ALLIGN_OPERS = \"ALLIGN_OPERS\";\n\n\tpublic static final String COMBINE_CHAR_LIMIT = \"COMBINE_CHAR_LIMIT\";\n\n\tpublic static final String COMBINE_SMALL_SELECT = \"COMBINE_SMALL_SELECT\";\n\n\tpublic static final String COMMAS = \"COMMAS\";\n\n\tpublic static final String ESCAPING = \"ESCAPING\";\n\n\tpublic static final String OPERSTYLE = \"OPERSTYLE\";\n\n\tpublic static final String ORDER_OLD_SYNTAX = \"ORDER_OLD_SYNTAX\";\n\t\n\tpublic static final String ORDER_NEW_SYNTAX = \"ORDER_NEW_SYNTAX\";\n\n\tpublic static final String TAB_ALL = \"TAB_ALL\";\n\n\tpublic static final String TAB_CONDITIONS = \"TAB_CONDITIONS\";\n\n\tpublic static final String LINE_CHAR_LIMIT = \"LINE_CHAR_LIMIT\";\n\n\tpublic static final String COMBINE_SMALL_JOINS_LIMIT = \"COMBINE_SMALL_JOINS_LIMIT\";\n\n\tpublic static final String COMBINE_SMALL_JOINS = \"COMBINE_SMALL_JOINS\";\n\n\tpublic static final String TAB_CONDITIONS_NEW_SYNTAX = \"TAB_CONDITIONS_NEW_SYNTAX\";\n\n\tpublic static final String TAB_ALL_NEW_SYNTAX = \"TAB_ALL_NEW_SYNTAX\";\n\n\tpublic static final String COMMENTSTYLE = \"COMMENTSTYLE\";\n\n}"
},
{
"identifier": "Into",
"path": "ABAP SQL Beautifier/src/com/abap/sql/beautifier/statement/parts/Into.java",
"snippet": "public class Into extends AbapSqlPart {\n\n\tpublic Into(List<String> lines) {\n\t\tsuper(lines);\n\t}\n\n\t\n\n}"
},
{
"identifier": "Utility",
"path": "ABAP SQL Beautifier/src/com/abap/sql/beautifier/utility/Utility.java",
"snippet": "public class Utility {\n\n\tpublic final static String placeholder = \"@!%&\";\n\n\tpublic static int countKeyword(String statement, String keyword) {\n\n\t\tkeyword = keyword.toUpperCase();\n\n\t\tint count = 0;\n\n\t\tList<String> cleanTokenList = convertToCleanTokenList(statement);\n\n\t\tfor (int i = 0; i < cleanTokenList.size(); i++) {\n\t\t\tString token = cleanTokenList.get(i).trim();\n\t\t\tif (token.equalsIgnoreCase(keyword)) {\n\n\t\t\t\tif (i == 0) {\n\t\t\t\t\tcount++;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tif (i < cleanTokenList.size()) {\n\t\t\t\t\tString tokenBefore = cleanTokenList.get(i - 1);\n\t\t\t\t\tString tokenAfter = cleanTokenList.get(i + 1);\n\n\t\t\t\t\tif (!tokenBefore.trim().matches(\"'\") && !tokenAfter.trim().matches(\"'\")) {\n\t\t\t\t\t\tcount++;\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t}\n\t\t}\n\n\t\treturn count;\n\t}\n\n\tpublic static boolean isLiteral(String statement, int start, int end) {\n\t\tString statementStart;\n\n\t\tif (start == 0) {\n\t\t\tstatementStart = statement.substring(0, start);\n\t\t} else {\n\t\t\tstatementStart = statement.substring(0, start - 1);\n\t\t}\n\n\t\tString statementMid = statement.substring(statementStart.length(), end + 1) + placeholder + \" \";\n\t\tString statementEnd = statement.substring(end + 1, statement.length());\n\n\t\tstatement = statementStart + statementMid + statementEnd;\n\n\t\tList<String> cleanTokenList = convertToCleanTokenList(statement);\n\n\t\tboolean isLiteral = false;\n\t\tint count = 0;\n\n\t\tfor (int i = 1; i < cleanTokenList.size(); i++) {\n\n\t\t\tString curToken = cleanTokenList.get(i);\n\n\t\t\t// count all \" ' \"\n\t\t\tif (curToken.matches(\"'\")) {\n\t\t\t\tcount++;\n\t\t\t}\n\n\t\t\tif (curToken.contains(placeholder)) {\n\n\t\t\t\tcurToken = curToken.replaceAll(placeholder, \"\");\n\n\t\t\t\tString tokenBefore = cleanTokenList.get(i - 1).trim();\n\t\t\t\tString tokenAfter = cleanTokenList.get(i + 1).trim();\n\n\t\t\t\tboolean startLiteral = (tokenBefore.matches(\"'\") || curToken.startsWith(\"'\"));\n\t\t\t\tboolean endsLiteral = (tokenAfter.matches(\"'\") || curToken.endsWith(\"'\"));\n\n\t\t\t\tif (startLiteral && endsLiteral) {\n\t\t\t\t\tif (count % 2 != 0) {\n\t\t\t\t\t\tisLiteral = true;\n\t\t\t\t\t}\n\n\t\t\t\t}\n\n\t\t\t\tbreak;\n\n\t\t\t}\n\t\t}\n\n\t\treturn isLiteral;\n\t}\n\n\tprivate static List<String> convertToCleanTokenList(String statement) {\n\t\tstatement = statement.toUpperCase();\n\n\t\tList<String> tokenList = Arrays.asList(statement.trim().split(\" \"));\n\n\t\tList<String> cleanTokenList = new ArrayList<String>();\n\n\t\t// clean tokenList\n\t\tfor (String token : tokenList) {\n\t\t\ttoken = token.replaceAll(\"\\r\\n\", \" \");\n\t\t\tif (!token.isBlank()) {\n\t\t\t\tcleanTokenList.add(token);\n\t\t\t}\n\t\t}\n\n\t\treturn cleanTokenList;\n\n\t}\n\n\tpublic static String deleteSpaces(String statement) {\n\t\t// delete mulitple spaces\n\t\twhile (statement.contains(\" \") || statement.contains(\"\t \")) {\n\t\t\tstatement = statement.replace(\" \", \" \");\n\t\t\tstatement = statement.replace(\"\t\", \" \");\n\t\t}\n\n\t\treturn statement;\n\t}\n\n\tpublic static String deleteLines(String statement) {\n\t\t// return statement.replace(\"\\r\\n\", \" \");\n\t\treturn statement.replace(System.lineSeparator(), \" \");\n\t}\n\n\tpublic static String cleanString(String statement) {\n\t\tString cleanedString = deleteLines(statement);\n\t\tcleanedString = deleteSpaces(cleanedString);\n\t\treturn cleanedString;\n\t}\n\n\tpublic static List<String> getAllOperators() {\n\t\tList<String> opers = new ArrayList<>();\n\n\t\topers.addAll(getTwoCharOpers());\n\n\t\topers.addAll(getOneCharOpers());\n\n\t\treturn opers;\n\t}\n\n\tpublic static List<String> getOneCharOpers() {\n\t\tList<String> opers = new ArrayList<>();\n\n\t\topers.add(\" = \");\n\t\topers.add(\" < \");\n\t\topers.add(\" > \");\n\n\t\treturn opers;\n\n\t}\n\n\tpublic static List<String> getTwoCharOpers() {\n\t\tList<String> opers = new ArrayList<>();\n\n\t\topers.add(\" EQ \");\n\t\topers.add(\" NE \");\n\t\topers.add(\" LT \");\n\t\topers.add(\" GT \");\n\t\topers.add(\" LE \");\n\t\topers.add(\" GE \");\n\n\t\topers.add(\" <> \");\n\t\topers.add(\" <= \");\n\t\topers.add(\" >= \");\n\n\t\topers.add(\" IN \");\n\n\t\treturn opers;\n\t}\n\n\tpublic static List<String> splitLine(String statement, int limit) {\n\t\tList<String> lines = new ArrayList<String>();\n\n\t\tint lengthBefore = statement.length();\n\t\tstatement = statement.strip();\n\t\tString whiteChars = Utility.getWhiteChars(lengthBefore - statement.length());\n\t\tString whiteCharsTabLines = whiteChars + \" \";\n\n\t\tif (statement.length() > limit) {\n\n\t\t\tint count = 0;\n\t\t\tint subStrLength = limit;\n\t\t\twhile (statement != null) {\n\n\t\t\t\tif (statement.length() < subStrLength) {\n\t\t\t\t\tsubStrLength = statement.length();\n\t\t\t\t}\n\n\t\t\t\tString curLine = statement.substring(0, subStrLength);\n\n\t\t\t\tString regex = escapeRegex(statement.trim());\n\n\t\t\t\tif (!curLine.matches(regex)) {\n\n\t\t\t\t\t// get index of last space in this line\n\t\t\t\t\tint curIndex = curLine.lastIndexOf(\" \");\n\n\t\t\t\t\tif (curIndex != -1) {\n\t\t\t\t\t\t// index found\n\t\t\t\t\t\tcurLine = curLine.substring(0, curIndex);\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// no space found --> find next space\n\t\t\t\t\t\tfor (int i = (subStrLength + 1); i < statement.length(); i++) {\n\t\t\t\t\t\t\tcurLine = statement.substring(0, i);\n\t\t\t\t\t\t\tcurIndex = curLine.lastIndexOf(\" \");\n\t\t\t\t\t\t\tif (curIndex != -1) {\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// still not found? take whole statement\n\t\t\t\t\t\tif (curIndex == -1) {\n\t\t\t\t\t\t\tcurLine = statement;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (count == 0) {\n\t\t\t\t\tcurLine = whiteChars + curLine;\n\t\t\t\t} else {\n\t\t\t\t\tcurLine = whiteCharsTabLines + curLine;\n\t\t\t\t}\n\n\t\t\t\tlines.add(curLine);\n\n\t\t\t\tregex = escapeRegex(curLine.trim());\n\n\t\t\t\tstatement = statement.replaceFirst(regex, \"\").trim();\n\n\t\t\t\tif (statement.isBlank()) {\n\t\t\t\t\tstatement = null;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tcount++;\n\t\t\t}\n\n\t\t} else {\n\t\t\tstatement = whiteChars + statement;\n\t\t\tlines.add(statement);\n\t\t}\n\n\t\treturn lines;\n\n\t}\n\n\tpublic static String getWhiteChars(int amount) {\n\t\tString white = \"\";\n\n\t\tfor (int i = 0; i < amount; i++) {\n\t\t\twhite = white + \" \";\n\t\t}\n\n\t\treturn white;\n\t}\n\n\tpublic static String escapeRegex(String regex) {\n\t\tregex = regex.replace(\"*\", \"\\\\*\");\n\t\tregex = regex.replace(\"(\", \"\\\\(\");\n\t\tregex = regex.replace(\")\", \"\\\\)\");\n\n\t\treturn regex;\n\t}\n\n}"
}
] | import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.abap.sql.beautifier.Abap;
import com.abap.sql.beautifier.Activator;
import com.abap.sql.beautifier.preferences.PreferenceConstants;
import com.abap.sql.beautifier.statement.parts.Into;
import com.abap.sql.beautifier.utility.Utility; | 3,637 | package com.abap.sql.beautifier.statement;
public class AbapSql {
private Map<String, AbapSqlPart> parts;
private List<String> order;
private boolean isOldSyntax = true;
private List<String> comments = new ArrayList<String>();
private String startWhite = "";
public AbapSql(String sql, int diff) {
startWhite = Utility.getWhiteChars(diff);
parts = new HashMap<String, AbapSqlPart>();
// get order
isOldSyntax = checkIfOldSyntax(sql);
if (isOldSyntax) {
setOrder(buildOrder(PreferenceConstants.ORDER_OLD_SYNTAX));
} else {
setOrder(buildOrder(PreferenceConstants.ORDER_NEW_SYNTAX));
}
appendSecWords();
sql = filterComments(sql);
sql = Utility.cleanString(sql);
setFromString(sql);
resetFormat();
}
private void appendSecWords() {
// append keywords, which are introducing the same part
int index;
// INTO ~ APPENDING
index = order.indexOf(Abap.INTO);
if (index != -1) {
order.add(index, Abap.APPENDING);
}
// UPTO ~ OFFSET
index = order.indexOf(Abap.UPTO);
if (index != -1) {
order.add(index, Abap.OFFSET);
}
// INTO ~ INTO CORRESPONDING FIELDS OF
index = order.indexOf(Abap.INTO);
if (index != -1) {
order.add(index, Abap.INTO_COR_FI_OF);
}
}
private String filterComments(String sql) {
String returnSql = "";
String asterisks = "*";
String apostrophes = "\"";
if (sql.contains(asterisks) || sql.contains(apostrophes)) {
List<String> lines = Arrays.asList(sql.split("\r\n"));
for (String line : lines) {
if (line.contains(asterisks) || line.contains(apostrophes)) {
int pos = line.indexOf(asterisks);
// check if asterisks is first char --> full line comment
if (pos == 0) {
comments.add(line.trim());
continue;
}
// asterisks was not a comment --> check apostrophes
pos = line.indexOf(apostrophes);
if (pos == -1) {
returnSql = returnSql + line + "\r\n";
} else {
comments.add(line.substring(pos).trim());
returnSql = returnSql + line.substring(0, pos) + "\r\n";
}
} else {
returnSql = returnSql + line + "\r\n";
}
}
return returnSql;
} else {
// does not contain any comments, return original
return sql;
}
}
private List<String> buildOrder(String syntaxType) {
List<String> returnOrder = new ArrayList<>();
| package com.abap.sql.beautifier.statement;
public class AbapSql {
private Map<String, AbapSqlPart> parts;
private List<String> order;
private boolean isOldSyntax = true;
private List<String> comments = new ArrayList<String>();
private String startWhite = "";
public AbapSql(String sql, int diff) {
startWhite = Utility.getWhiteChars(diff);
parts = new HashMap<String, AbapSqlPart>();
// get order
isOldSyntax = checkIfOldSyntax(sql);
if (isOldSyntax) {
setOrder(buildOrder(PreferenceConstants.ORDER_OLD_SYNTAX));
} else {
setOrder(buildOrder(PreferenceConstants.ORDER_NEW_SYNTAX));
}
appendSecWords();
sql = filterComments(sql);
sql = Utility.cleanString(sql);
setFromString(sql);
resetFormat();
}
private void appendSecWords() {
// append keywords, which are introducing the same part
int index;
// INTO ~ APPENDING
index = order.indexOf(Abap.INTO);
if (index != -1) {
order.add(index, Abap.APPENDING);
}
// UPTO ~ OFFSET
index = order.indexOf(Abap.UPTO);
if (index != -1) {
order.add(index, Abap.OFFSET);
}
// INTO ~ INTO CORRESPONDING FIELDS OF
index = order.indexOf(Abap.INTO);
if (index != -1) {
order.add(index, Abap.INTO_COR_FI_OF);
}
}
private String filterComments(String sql) {
String returnSql = "";
String asterisks = "*";
String apostrophes = "\"";
if (sql.contains(asterisks) || sql.contains(apostrophes)) {
List<String> lines = Arrays.asList(sql.split("\r\n"));
for (String line : lines) {
if (line.contains(asterisks) || line.contains(apostrophes)) {
int pos = line.indexOf(asterisks);
// check if asterisks is first char --> full line comment
if (pos == 0) {
comments.add(line.trim());
continue;
}
// asterisks was not a comment --> check apostrophes
pos = line.indexOf(apostrophes);
if (pos == -1) {
returnSql = returnSql + line + "\r\n";
} else {
comments.add(line.substring(pos).trim());
returnSql = returnSql + line.substring(0, pos) + "\r\n";
}
} else {
returnSql = returnSql + line + "\r\n";
}
}
return returnSql;
} else {
// does not contain any comments, return original
return sql;
}
}
private List<String> buildOrder(String syntaxType) {
List<String> returnOrder = new ArrayList<>();
| String curOrderString = Activator.getDefault().getPreferenceStore().getString(syntaxType); | 1 | 2023-10-10 18:56:27+00:00 | 8k |
Spider-Admin/Frost | src/main/java/frost/fileTransfer/NewUploadFilesManager.java | [
{
"identifier": "GenerateShaThread",
"path": "src/main/java/frost/fileTransfer/upload/GenerateShaThread.java",
"snippet": "public class GenerateShaThread extends Thread {\r\n\r\n\tprivate static final Logger logger = LoggerFactory.getLogger(GenerateShaThread.class);\r\n\r\n private NewUploadFilesManager newUploadFilesManager;\r\n \r\n private static final int wait1minute = 1 * 60 * 1000;\r\n FileQueue fileQueue;\r\n\r\n /**\r\n * @param newUploadFilesManager\r\n */\r\n public GenerateShaThread(NewUploadFilesManager newUploadFilesManager) {\r\n this.newUploadFilesManager = newUploadFilesManager;\r\n fileQueue = new FileQueue();\r\n }\r\n\r\n /**\r\n * @param f\r\n */\r\n public void addToFileQueue(final NewUploadFile f) {\r\n // awakes thread\r\n fileQueue.appendFileToQueue(f);\r\n }\r\n\r\n /**\r\n * @return\r\n */\r\n public int getQueueSize() {\r\n return fileQueue.getQueueSize();\r\n }\r\n\r\n /* (non-Javadoc)\r\n * @see java.lang.Thread#run()\r\n */\r\n @Override\r\n public void run() {\r\n\r\n final int maxAllowedExceptions = 5;\r\n int occuredExceptions = 0;\r\n\r\n while(true) {\r\n try {\r\n // if now work is in queue this call waits for a new queueitem\r\n final NewUploadFile newUploadFile = fileQueue.getFileFromQueue();\r\n\r\n if( newUploadFile == null ) {\r\n // paranoia\r\n Mixed.wait(wait1minute);\r\n continue;\r\n }\r\n\r\n final File newFile = new File(newUploadFile.getFilePath());\r\n\r\n final String sha = Core.getCrypto().computeChecksumSHA256(newFile);\r\n\r\n if( sha != null ) {\r\n\r\n // create new item\r\n final FrostSharedFileItem sfi = new FrostSharedFileItem(\r\n newFile,\r\n newUploadFile.getFrom(),\r\n sha);\r\n\r\n // add to shared files\r\n FileTransferManager.inst().getSharedFilesManager().getModel().addNewSharedFile(sfi, newUploadFile.isReplacePathIfFileExists());\r\n\r\n // delete from newuploadfiles database\r\n newUploadFilesManager.deleteNewUploadFile(newUploadFile);\r\n }\r\n\r\n } catch(final Throwable t) {\r\n logger.error(\"Exception catched\", t);\r\n occuredExceptions++;\r\n }\r\n\r\n if( occuredExceptions > maxAllowedExceptions ) {\r\n logger.error(\"Stopping GenerateShaThread because of too much exceptions\");\r\n break;\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * \r\n * @author $Author: $\r\n * @version $Revision: $\r\n */\r\n private class FileQueue {\r\n\r\n private final LinkedList<NewUploadFile> queue = new LinkedList<NewUploadFile>();\r\n\r\n /**\r\n * @return\r\n */\r\n public synchronized NewUploadFile getFileFromQueue() {\r\n try {\r\n // let dequeueing threads wait for work\r\n while( queue.isEmpty() ) {\r\n wait();\r\n }\r\n } catch (final InterruptedException e) {\r\n return null; // waiting abandoned\r\n }\r\n\r\n if( queue.isEmpty() == false ) {\r\n final NewUploadFile key = queue.removeFirst();\r\n return key;\r\n }\r\n return null;\r\n }\r\n\r\n /**\r\n * @param f\r\n */\r\n public synchronized void appendFileToQueue(final NewUploadFile f) {\r\n queue.addLast(f);\r\n notifyAll(); // notify all waiters (if any) of new record\r\n }\r\n\r\n /**\r\n * @return\r\n */\r\n public synchronized int getQueueSize() {\r\n return queue.size();\r\n }\r\n }\r\n}\r"
},
{
"identifier": "ExitSavable",
"path": "src/main/java/frost/storage/ExitSavable.java",
"snippet": "public interface ExitSavable {\r\n\r\n public void exitSave() throws StorageException;\r\n}\r"
},
{
"identifier": "StorageException",
"path": "src/main/java/frost/storage/StorageException.java",
"snippet": "@SuppressWarnings(\"serial\")\r\npublic class StorageException extends Exception {\r\n\r\n\t/**\r\n\t * \r\n\t */\r\n\tpublic StorageException() {\r\n\t\tsuper();\r\n\t}\r\n\t/**\r\n\t * @param message\r\n\t */\r\n\tpublic StorageException(String message) {\r\n\t\tsuper(message);\r\n\t}\r\n\t/**\r\n\t * @param message\r\n\t * @param cause\r\n\t */\r\n\tpublic StorageException(String message, Throwable cause) {\r\n\t\tsuper(message, cause);\r\n\t}\r\n\t/**\r\n\t * @param cause\r\n\t */\r\n\tpublic StorageException(Throwable cause) {\r\n\t\tsuper(cause);\r\n\t}\r\n}\r"
},
{
"identifier": "FrostFilesStorage",
"path": "src/main/java/frost/storage/perst/FrostFilesStorage.java",
"snippet": "public class FrostFilesStorage extends AbstractFrostStorage implements ExitSavable {\r\n\r\n\tprivate static final Logger logger = LoggerFactory.getLogger(FrostFilesStorage.class);\r\n\r\n private static final String STORAGE_FILENAME = \"filesStore.dbs\";\r\n\r\n private FrostFilesStorageRoot storageRoot = null;\r\n\r\n private static FrostFilesStorage instance = new FrostFilesStorage();\r\n\r\n protected FrostFilesStorage() {\r\n super();\r\n }\r\n\r\n public static FrostFilesStorage inst() {\r\n return instance;\r\n }\r\n\r\n @Override\r\n public String getStorageFilename() {\r\n return STORAGE_FILENAME;\r\n }\r\n\r\n @Override\r\n public boolean initStorage() {\r\n final String databaseFilePath = buildStoragePath(getStorageFilename()); // path to the database file\r\n final long pagePoolSize = getPagePoolSize(SettingsClass.PERST_PAGEPOOLSIZE_FILES);\r\n\r\n open(databaseFilePath, pagePoolSize, true, true, false);\r\n\r\n storageRoot = (FrostFilesStorageRoot)getStorage().getRoot();\r\n if (storageRoot == null) {\r\n // Storage was not initialized yet\r\n storageRoot = new FrostFilesStorageRoot();\r\n\r\n storageRoot.downloadFiles = getStorage().createScalableList();\r\n storageRoot.uploadFiles = getStorage().createScalableList();\r\n storageRoot.sharedFiles = getStorage().createScalableList();\r\n storageRoot.newUploadFiles = getStorage().createScalableList();\r\n\r\n storageRoot.hiddenBoardNames = getStorage().createScalableList();\r\n storageRoot.knownBoards = getStorage().createIndex(String.class, true);\r\n\r\n getStorage().setRoot(storageRoot);\r\n commit(); // commit transaction\r\n } else if( storageRoot.hiddenBoardNames == null ) {\r\n // add new root items\r\n storageRoot.hiddenBoardNames = getStorage().createScalableList();\r\n storageRoot.knownBoards = getStorage().createIndex(String.class, true);\r\n storageRoot.modify();\r\n commit(); // commit transaction\r\n }\r\n return true;\r\n }\r\n\r\n public void exitSave() throws StorageException {\r\n close();\r\n storageRoot = null;\r\n logger.info(\"FrostFilesStorage closed.\");\r\n }\r\n\r\n // only used for migration\r\n public void savePerstFrostDownloadFiles(final List<PerstFrostDownloadItem> downloadFiles) {\r\n beginExclusiveThreadTransaction();\r\n try {\r\n for( final PerstFrostDownloadItem pi : downloadFiles ) {\r\n pi.makePersistent(getStorage());\r\n storageRoot.downloadFiles.add(pi);\r\n }\r\n storageRoot.downloadFiles.modify();\r\n } finally {\r\n endThreadTransaction();\r\n }\r\n }\r\n\r\n /**\r\n * Removes all items from the given List and deallocates each item from Storage.\r\n * @param plst IPersistentList of persistent items\r\n */\r\n private void removeAllFromStorage(final IPersistentList<? extends Persistent> plst) {\r\n for(final Iterator<? extends Persistent> i=plst.iterator(); i.hasNext(); ) {\r\n final Persistent pi = i.next();\r\n i.remove(); // remove from List\r\n pi.deallocate(); // remove from Storage\r\n }\r\n plst.clear(); // paranoia\r\n }\r\n\r\n public void saveDownloadFiles(final List<FrostDownloadItem> downloadFiles) {\r\n beginExclusiveThreadTransaction();\r\n try {\r\n removeAllFromStorage(storageRoot.downloadFiles); // delete all old items\r\n for( final FrostDownloadItem dlItem : downloadFiles ) {\r\n if( dlItem.isExternal() ) {\r\n continue;\r\n }\r\n final PerstFrostDownloadItem pi = new PerstFrostDownloadItem(dlItem);\r\n storageRoot.downloadFiles.add(pi);\r\n }\r\n } finally {\r\n endThreadTransaction();\r\n }\r\n }\r\n\r\n public List<FrostDownloadItem> loadDownloadFiles() {\r\n final LinkedList<FrostDownloadItem> downloadItems = new LinkedList<FrostDownloadItem>();\r\n beginCooperativeThreadTransaction();\r\n try {\r\n for( final PerstFrostDownloadItem pi : storageRoot.downloadFiles ) {\r\n final FrostDownloadItem dlItem = pi.toFrostDownloadItem(logger);\r\n if( dlItem != null ) {\r\n downloadItems.add(dlItem);\r\n }\r\n }\r\n } finally {\r\n endThreadTransaction();\r\n }\r\n return downloadItems;\r\n }\r\n\r\n // only used for migration\r\n public void savePerstFrostUploadFiles(final List<PerstFrostUploadItem> uploadFiles) {\r\n beginExclusiveThreadTransaction();\r\n try {\r\n for( final PerstFrostUploadItem pi : uploadFiles ) {\r\n storageRoot.uploadFiles.add(pi);\r\n }\r\n } finally {\r\n endThreadTransaction();\r\n }\r\n }\r\n\r\n public void saveUploadFiles(final List<FrostUploadItem> uploadFiles) {\r\n beginExclusiveThreadTransaction();\r\n try {\r\n removeAllFromStorage(storageRoot.uploadFiles); // delete all old items\r\n for( final FrostUploadItem ulItem : uploadFiles ) {\r\n if( ulItem.isExternal() ) {\r\n continue;\r\n }\r\n final PerstFrostUploadItem pi = new PerstFrostUploadItem(ulItem);\r\n storageRoot.uploadFiles.add(pi);\r\n }\r\n } finally {\r\n endThreadTransaction();\r\n }\r\n }\r\n\r\n public List<FrostUploadItem> loadUploadFiles(final List<FrostSharedFileItem> sharedFiles) {\r\n final LinkedList<FrostUploadItem> uploadItems = new LinkedList<FrostUploadItem>();\r\n final Language language = Language.getInstance();\r\n beginCooperativeThreadTransaction();\r\n try {\r\n for( final PerstFrostUploadItem pi : storageRoot.uploadFiles ) {\r\n final FrostUploadItem ulItem = pi.toFrostUploadItem(sharedFiles, logger, language);\r\n if( ulItem != null ) {\r\n uploadItems.add(ulItem);\r\n }\r\n }\r\n } finally {\r\n endThreadTransaction();\r\n }\r\n return uploadItems;\r\n }\r\n\r\n // only used for migration\r\n public void savePerstFrostSharedFiles(final List<PerstFrostSharedFileItem> sfFiles) {\r\n beginExclusiveThreadTransaction();\r\n try {\r\n for( final PerstFrostSharedFileItem pi : sfFiles ) {\r\n pi.makePersistent(getStorage());\r\n storageRoot.sharedFiles.add(pi);\r\n }\r\n storageRoot.sharedFiles.modify();\r\n } finally {\r\n endThreadTransaction();\r\n }\r\n }\r\n\r\n public void saveSharedFiles(final List<FrostSharedFileItem> sfFiles) {\r\n beginExclusiveThreadTransaction();\r\n try {\r\n removeAllFromStorage(storageRoot.sharedFiles);\r\n for( final FrostSharedFileItem sfItem : sfFiles ) {\r\n final PerstFrostSharedFileItem pi = new PerstFrostSharedFileItem(sfItem);\r\n storageRoot.sharedFiles.add(pi);\r\n }\r\n } finally {\r\n endThreadTransaction();\r\n }\r\n }\r\n\r\n public List<FrostSharedFileItem> loadSharedFiles() {\r\n final LinkedList<FrostSharedFileItem> sfItems = new LinkedList<FrostSharedFileItem>();\r\n final Language language = Language.getInstance();\r\n beginCooperativeThreadTransaction();\r\n try {\r\n for( final PerstFrostSharedFileItem pi : storageRoot.sharedFiles ) {\r\n final FrostSharedFileItem sfItem = pi.toFrostSharedFileItem(logger, language);\r\n if( sfItem != null ) {\r\n sfItems.add(sfItem);\r\n }\r\n }\r\n } finally {\r\n endThreadTransaction();\r\n }\r\n return sfItems;\r\n }\r\n\r\n public void saveNewUploadFiles(final List<NewUploadFile> newUploadFiles) {\r\n beginExclusiveThreadTransaction();\r\n try {\r\n removeAllFromStorage(storageRoot.newUploadFiles);\r\n for( final NewUploadFile nuf : newUploadFiles ) {\r\n nuf.makePersistent(getStorage());\r\n nuf.modify(); // for already persistent items\r\n\r\n storageRoot.newUploadFiles.add(nuf);\r\n }\r\n } finally {\r\n endThreadTransaction();\r\n }\r\n }\r\n\r\n public LinkedList<NewUploadFile> loadNewUploadFiles() {\r\n\r\n final LinkedList<NewUploadFile> newUploadFiles = new LinkedList<NewUploadFile>();\r\n beginCooperativeThreadTransaction();\r\n try {\r\n for( final NewUploadFile nuf : storageRoot.newUploadFiles ) {\r\n final File f = new File(nuf.getFilePath());\r\n if( !f.isFile() ) {\r\n logger.warn(\"File ({}) is missing. File removed.\", nuf.getFilePath());\r\n continue;\r\n }\r\n newUploadFiles.add(nuf);\r\n }\r\n } finally {\r\n endThreadTransaction();\r\n }\r\n return newUploadFiles;\r\n }\r\n\r\n /**\r\n * Load all hidden board names.\r\n */\r\n public HashSet<String> loadHiddenBoardNames() {\r\n final HashSet<String> result = new HashSet<String>();\r\n beginCooperativeThreadTransaction();\r\n try {\r\n for( final PerstHiddenBoardName hbn : storageRoot.hiddenBoardNames ) {\r\n result.add(hbn.getHiddenBoardName());\r\n }\r\n } finally {\r\n endThreadTransaction();\r\n }\r\n return result;\r\n }\r\n\r\n /**\r\n * Clear table and save all hidden board names.\r\n */\r\n public void saveHiddenBoardNames(final HashSet<String> names) {\r\n beginExclusiveThreadTransaction();\r\n try {\r\n removeAllFromStorage(storageRoot.hiddenBoardNames);\r\n for( final String s : names ) {\r\n final PerstHiddenBoardName h = new PerstHiddenBoardName(s);\r\n storageRoot.hiddenBoardNames.add(h);\r\n }\r\n } finally {\r\n endThreadTransaction();\r\n }\r\n }\r\n\r\n private String buildBoardIndex(final Board b) {\r\n final StringBuilder sb = new StringBuilder();\r\n sb.append(b.getNameLowerCase());\r\n if( b.getPublicKey() != null ) {\r\n sb.append(b.getPublicKey());\r\n }\r\n if( b.getPrivateKey() != null ) {\r\n sb.append(b.getPrivateKey());\r\n }\r\n return sb.toString();\r\n }\r\n\r\n /**\r\n * @return List of KnownBoard\r\n */\r\n public List<KnownBoard> getKnownBoards() {\r\n beginCooperativeThreadTransaction();\r\n final List<KnownBoard> lst;\r\n try {\r\n lst = new ArrayList<KnownBoard>();\r\n for( final PerstKnownBoard pkb : storageRoot.knownBoards ) {\r\n final KnownBoard kb = new KnownBoard(pkb.getBoardName(), pkb.getPublicKey(), pkb.getPrivateKey(), pkb\r\n .getDescription());\r\n lst.add(kb);\r\n }\r\n } finally {\r\n endThreadTransaction();\r\n }\r\n return lst;\r\n }\r\n\r\n public synchronized boolean deleteKnownBoard(final Board b) {\r\n final String newIx = buildBoardIndex(b);\r\n beginExclusiveThreadTransaction();\r\n final boolean retval;\r\n try {\r\n final PerstKnownBoard pkb = storageRoot.knownBoards.get(newIx);\r\n if( pkb != null ) {\r\n storageRoot.knownBoards.remove(newIx, pkb);\r\n pkb.deallocate();\r\n retval = true;\r\n } else {\r\n retval = false;\r\n }\r\n } finally {\r\n endThreadTransaction();\r\n }\r\n return retval;\r\n }\r\n\r\n /**\r\n * Called with a list of Board, should add all boards that are not contained already\r\n * @param lst List of Board\r\n * @return number of added boards\r\n */\r\n public synchronized int addNewKnownBoards( final List<? extends Board> lst ) {\r\n if( lst == null || lst.size() == 0 ) {\r\n return 0;\r\n }\r\n beginExclusiveThreadTransaction();\r\n int added = 0;\r\n try {\r\n for( final Board b : lst ) {\r\n final String newIx = buildBoardIndex(b);\r\n final PerstKnownBoard pkb = new PerstKnownBoard(b.getName(), b.getPublicKey(), b.getPrivateKey(), b\r\n .getDescription());\r\n if( storageRoot.knownBoards.put(newIx, pkb) ) {\r\n added++;\r\n }\r\n }\r\n } finally {\r\n endThreadTransaction();\r\n }\r\n return added;\r\n }\r\n}\r"
},
{
"identifier": "NewUploadFile",
"path": "src/main/java/frost/storage/perst/NewUploadFile.java",
"snippet": "public class NewUploadFile extends Persistent {\r\n\r\n protected String filePath;\r\n protected String from;\r\n protected boolean replacePathIfFileExists;\r\n\r\n public NewUploadFile() {\r\n }\r\n\r\n public NewUploadFile(final File f, final String fromName, final boolean replacePath) {\r\n filePath = f.getPath();\r\n from = fromName;\r\n replacePathIfFileExists = replacePath;\r\n }\r\n\r\n public String getFilePath() {\r\n return filePath;\r\n }\r\n\r\n public String getFrom() {\r\n return from;\r\n }\r\n\r\n public boolean isReplacePathIfFileExists() {\r\n return replacePathIfFileExists;\r\n }\r\n}\r"
}
] | import java.util.LinkedList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import frost.fileTransfer.upload.GenerateShaThread;
import frost.storage.ExitSavable;
import frost.storage.StorageException;
import frost.storage.perst.FrostFilesStorage;
import frost.storage.perst.NewUploadFile;
| 4,417 | /*
NewUploadFilesManager.java / Frost
Copyright (C) 2006 Frost Project <jtcfrost.sourceforge.net>
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 2 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, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package frost.fileTransfer;
/**
*
* @author $Author: $
* @version $Revision: $
*/
public class NewUploadFilesManager implements ExitSavable {
private static final Logger logger = LoggerFactory.getLogger(NewUploadFilesManager.class);
| /*
NewUploadFilesManager.java / Frost
Copyright (C) 2006 Frost Project <jtcfrost.sourceforge.net>
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 2 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, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package frost.fileTransfer;
/**
*
* @author $Author: $
* @version $Revision: $
*/
public class NewUploadFilesManager implements ExitSavable {
private static final Logger logger = LoggerFactory.getLogger(NewUploadFilesManager.class);
| private LinkedList<NewUploadFile> newUploadFiles;
| 4 | 2023-10-07 22:25:20+00:00 | 8k |
Milosz08/screen-sharing-system | host/src/main/java/pl/polsl/screensharing/host/net/ClientThread.java | [
{
"identifier": "SessionDetails",
"path": "host/src/main/java/pl/polsl/screensharing/host/model/SessionDetails.java",
"snippet": "@Data\n@Builder\n@AllArgsConstructor\npublic class SessionDetails {\n @JsonProperty(\"ipAddress\")\n private String ipAddress;\n\n @JsonProperty(\"isMachineIp\")\n private Boolean isMachineIp;\n\n @JsonProperty(\"port\")\n private int port;\n\n @JsonProperty(\"hasPassword\")\n private Boolean hasPassword;\n\n @JsonProperty(\"password\")\n private String password;\n\n public SessionDetails() {\n ipAddress = Utils.getMachineAddress();\n isMachineIp = true;\n port = SharedConstants.DEFAULT_PORT;\n hasPassword = false;\n password = StringUtils.EMPTY;\n }\n\n @JsonIgnore\n public void setSessionDetails(SessionDetails o) {\n ipAddress = o.ipAddress;\n isMachineIp = o.isMachineIp;\n port = o.port;\n hasPassword = o.hasPassword;\n password = Base64.getEncoder().encodeToString(o.password.getBytes());\n }\n\n @JsonIgnore\n public String getPortAsStr() {\n return String.valueOf(port);\n }\n\n @Override\n public String toString() {\n return \"{\" +\n \"ipAddress=\" + ipAddress +\n \", isMachineIp=\" + isMachineIp +\n \", port=\" + port +\n \", hasPassword=\" + hasPassword +\n \", password=******\" +\n '}';\n }\n}"
},
{
"identifier": "HostState",
"path": "host/src/main/java/pl/polsl/screensharing/host/state/HostState.java",
"snippet": "public class HostState extends AbstractDisposableProvider {\n private final BehaviorSubject<StreamingState> streamingState$;\n private final BehaviorSubject<Long> streamingTime$;\n private final BehaviorSubject<SessionState> sessionState$;\n private final BehaviorSubject<Long> sessionTime$;\n private final BehaviorSubject<Integer> realFpsBuffer$;\n private final BehaviorSubject<Long> sentBytesPerSec$;\n private final BehaviorSubject<GraphicsDevice> selectedGraphicsDevice$;\n private final BehaviorSubject<QualityLevel> streamingQuality$;\n private final BehaviorSubject<Color> frameColor$;\n private final BehaviorSubject<Boolean> isScreenShowForParticipants$;\n private final BehaviorSubject<Boolean> isShowingFrameSelector$;\n private final BehaviorSubject<Boolean> isCursorShowing$;\n private final BehaviorSubject<CaptureMode> captureMode$;\n private final BehaviorSubject<SessionDetails> sessionDetails$;\n private final BehaviorSubject<ConcurrentMap<Long, ConnectedClientInfo>> connectedClients$;\n\n @Getter\n private final PersistedStateLoader persistedStateLoader;\n\n public HostState() {\n persistedStateLoader = new PersistedStateLoader(this);\n persistedStateLoader.initPersistor(new PersistedState());\n\n streamingState$ = BehaviorSubject.createDefault(StreamingState.STOPPED);\n streamingTime$ = BehaviorSubject.createDefault(0L);\n sessionState$ = BehaviorSubject.createDefault(SessionState.INACTIVE);\n sessionTime$ = BehaviorSubject.createDefault(0L);\n realFpsBuffer$ = BehaviorSubject.createDefault(30);\n sentBytesPerSec$ = BehaviorSubject.createDefault(0L);\n selectedGraphicsDevice$ = BehaviorSubject.create();\n streamingQuality$ = BehaviorSubject.createDefault(QualityLevel.GOOD);\n frameColor$ = BehaviorSubject.createDefault(Color.RED);\n isScreenShowForParticipants$ = BehaviorSubject.createDefault(true);\n isShowingFrameSelector$ = BehaviorSubject.createDefault(false);\n isCursorShowing$ = BehaviorSubject.createDefault(true);\n captureMode$ = BehaviorSubject.createDefault(CaptureMode.FULL_FRAME);\n sessionDetails$ = BehaviorSubject.createDefault(new SessionDetails());\n connectedClients$ = BehaviorSubject.createDefault(new ConcurrentHashMap<>());\n\n persistedStateLoader.loadApplicationSavedState();\n }\n\n public void updateStreamingState(StreamingState streamingState) {\n streamingState$.onNext(streamingState);\n }\n\n public void updateStreamingTime(long seconds) {\n streamingTime$.onNext(seconds);\n }\n\n public void updateSessionState(SessionState sessionState) {\n sessionState$.onNext(sessionState);\n }\n\n public void updateSessionTime(long seconds) {\n sessionTime$.onNext(seconds);\n }\n\n public void updateRealFpsBuffer(Integer fps) {\n realFpsBuffer$.onNext(fps);\n }\n\n public void updateSentBytesPerSec(Long bytesPerSec) {\n sentBytesPerSec$.onNext(bytesPerSec);\n }\n\n public void updateSelectedGraphicsDevice(GraphicsDevice graphicsDevice) {\n selectedGraphicsDevice$.onNext(graphicsDevice);\n }\n\n public void updateStreamingQuality(QualityLevel qualityLevel) {\n streamingQuality$.onNext(qualityLevel);\n }\n\n public void updateFrameColor(Color color) {\n frameColor$.onNext(color);\n }\n\n public void updateShowingScreenForParticipants(boolean isShowing) {\n isScreenShowForParticipants$.onNext(isShowing);\n }\n\n public void updateShowingFrameSelectorState(boolean isShowing) {\n isShowingFrameSelector$.onNext(isShowing);\n }\n\n public void updateShowingCursorState(boolean isShowing) {\n isCursorShowing$.onNext(isShowing);\n }\n\n public void updateCaptureMode(CaptureMode captureMode) {\n captureMode$.onNext(captureMode);\n }\n\n public void updateSessionDetails(SessionDetails sessionDetails) {\n sessionDetails$.onNext(sessionDetails);\n }\n\n public void updateConnectedClients(ConcurrentMap<Long, ConnectedClientInfo> connectedClients) {\n connectedClients$.onNext(connectedClients);\n }\n\n public Observable<StreamingState> getStreamingState$() {\n return streamingState$.hide();\n }\n\n public Observable<Long> getStreamingTime$() {\n return streamingTime$.hide();\n }\n\n public Observable<SessionState> getSessionState$() {\n return sessionState$.hide();\n }\n\n public Observable<Long> getSessionTime$() {\n return sessionTime$.hide();\n }\n\n public Observable<Integer> getRealFpsBuffer$() {\n return realFpsBuffer$.hide();\n }\n\n public Observable<Long> getSentBytesPerSec$() {\n return sentBytesPerSec$.hide();\n }\n\n public Observable<GraphicsDevice> getSelectedGraphicsDevice$() {\n return selectedGraphicsDevice$.hide();\n }\n\n public Observable<QualityLevel> getStreamingQualityLevel$() {\n return streamingQuality$.hide();\n }\n\n public Observable<Color> getFrameColor$() {\n return frameColor$.hide();\n }\n\n public Observable<Boolean> isScreenIsShowForParticipants$() {\n return isScreenShowForParticipants$.hide();\n }\n\n public Observable<Boolean> isFrameSelectorShowing$() {\n return isShowingFrameSelector$.hide();\n }\n\n public Observable<Boolean> isCursorShowing$() {\n return isCursorShowing$.hide();\n }\n\n public Observable<CaptureMode> getCaptureMode$() {\n return captureMode$.hide();\n }\n\n public Observable<SessionDetails> getSessionDetails$() {\n return sessionDetails$.hide();\n }\n\n public Observable<ConcurrentMap<Long, ConnectedClientInfo>> getConnectedClientsInfo$() {\n return connectedClients$.hide();\n }\n\n public Color getLastEmittedFrameColor() {\n return frameColor$.getValue();\n }\n\n public CaptureMode getLastEmittedCapturedMode() {\n return captureMode$.getValue();\n }\n\n public SessionDetails getLastEmittedSessionDetails() {\n return sessionDetails$.getValue();\n }\n\n public ConcurrentMap<Long, ConnectedClientInfo> getLastEmittedConnectedClients() {\n return connectedClients$.getValue();\n }\n\n public StreamingState getLastEmittedStreamingState() {\n return streamingState$.getValue();\n }\n\n public Boolean getLastEmittedIsScreenIsShowForParticipants() {\n return isScreenShowForParticipants$.getValue();\n }\n\n public Boolean getLastEmittedIsCursorShowing() {\n return isCursorShowing$.getValue();\n }\n\n public QualityLevel getLastEmittedQualityLevel() {\n return streamingQuality$.getValue();\n }\n}"
},
{
"identifier": "StreamingState",
"path": "host/src/main/java/pl/polsl/screensharing/host/state/StreamingState.java",
"snippet": "@Getter\n@RequiredArgsConstructor\npublic enum StreamingState implements ColoredLabelState {\n STREAMING(\"streaming\", Color.RED),\n STOPPED(\"stopped\", Color.GRAY),\n ;\n\n private final String state;\n private final Color color;\n}"
},
{
"identifier": "HostWindow",
"path": "host/src/main/java/pl/polsl/screensharing/host/view/HostWindow.java",
"snippet": "@Getter\npublic class HostWindow extends AbstractRootFrame {\n private final HostState hostState;\n private final Optional<Image> streamingImageIconOptional;\n\n private final TopMenuBar topMenuBar;\n private final TopToolbar topToolbar;\n private final TabbedPaneWindow tabbedPaneWindow;\n private final BottomInfobar bottomInfobar;\n\n private final AboutDialogWindow aboutDialogWindow;\n private final LicenseDialogWindow licenseDialogWindow;\n private final SessionDetailsDialogWindow sessionDetailsDialogWindow;\n private final ParticipantsDialogWindow participantsDialogWindow;\n private final SessionInfoDialogWindow sessionInfoDialogWindow;\n\n @Setter\n private ServerDatagramSocket serverDatagramSocket;\n @Setter\n private ServerTcpSocket serverTcpSocket;\n @Setter\n private DatagramKey datagramKey;\n\n public HostWindow(HostState hostState) {\n super(AppType.HOST, hostState, HostWindow.class);\n this.hostState = hostState;\n streamingImageIconOptional = FileUtils.getImageFileFromResources(getClass(), \"HostIconStreaming.png\");\n\n topMenuBar = new TopMenuBar(this);\n topToolbar = new TopToolbar(this);\n tabbedPaneWindow = new TabbedPaneWindow(this);\n bottomInfobar = new BottomInfobar(this);\n\n aboutDialogWindow = new AboutDialogWindow(this);\n licenseDialogWindow = new LicenseDialogWindow(this);\n sessionDetailsDialogWindow = new SessionDetailsDialogWindow(this);\n participantsDialogWindow = new ParticipantsDialogWindow(this);\n sessionInfoDialogWindow = new SessionInfoDialogWindow(this);\n\n initObservables();\n\n setResizable(false);\n setMaximumSize(AppType.HOST.getRootWindowSize());\n }\n\n @Override\n protected void extendsFrame(JFrame frame, JPanel rootPanel) {\n frame.setJMenuBar(topMenuBar);\n frame.add(topToolbar, BorderLayout.NORTH);\n frame.add(tabbedPaneWindow, BorderLayout.CENTER);\n frame.add(bottomInfobar, BorderLayout.SOUTH);\n }\n\n public void initObservables() {\n hostState.wrapAsDisposable(hostState.getStreamingState$(), streamingState -> {\n if (streamingState.equals(StreamingState.STREAMING)) {\n streamingImageIconOptional.ifPresent(this::setIconImage);\n } else {\n imageIconOptional.ifPresent(this::setIconImage);\n }\n });\n }\n\n public BottomInfobarController getBottomInfobarController() {\n return bottomInfobar.getBottomInfobarController();\n }\n\n public VideoCanvas getVideoCanvas() {\n return tabbedPaneWindow.getTabbedScreenFramePanel().getVideoCanvas();\n }\n}"
},
{
"identifier": "Utils",
"path": "lib/src/main/java/pl/polsl/screensharing/lib/Utils.java",
"snippet": "@Slf4j\n@NoArgsConstructor(access = AccessLevel.PRIVATE)\npublic class Utils {\n public static String parseBytes(long bytes, String prefix, boolean isPerSec) {\n String formattedBytes;\n try {\n formattedBytes = String.format(\"%s%s\", FileUtils.byteCountToDisplaySize(bytes),\n isPerSec ? \"/s\" : StringUtils.EMPTY);\n } catch (IllegalArgumentException ex) {\n formattedBytes = \"unknow\";\n }\n return String.format(\"%s: %s\", prefix, formattedBytes);\n }\n\n public static String parseBytesPerSecToMegaBytes(long bytes, String prefix) {\n return String.format(\"%s: %.3f Mb/s\", prefix, (double) bytes / (1024 * 1024));\n }\n\n public static String parseTime(long seconds, String prefix) {\n final String time = DurationFormatUtils.formatDuration(seconds * 1000, \"HH:mm:ss\");\n return String.format(\"%s time: %s\", prefix, time);\n }\n\n public static Dimension calcSizeBaseAspectRatio(JComponent component, double aspectRatio) {\n int containerWidth = component.getWidth() - 10;\n int containerHeight = component.getHeight() - 10;\n\n int width, height;\n\n if ((double) containerWidth / containerHeight > aspectRatio) {\n height = containerHeight;\n width = (int) (height * aspectRatio);\n } else {\n width = containerWidth;\n height = (int) (width / aspectRatio);\n }\n return new Dimension(width, height);\n }\n\n public static Dimension calcHeightBaseWidthAndAR(int width, Rectangle bounds) {\n final double aspectRatio = bounds.getWidth() / bounds.getHeight();\n final int height = (int) (width / aspectRatio);\n return new Dimension(width, height);\n }\n\n public static boolean checkIfSizeNotExact(Rectangle first, Rectangle second) {\n return first.width != second.width || first.height != second.height;\n }\n\n public static Rectangle scaleElementUp(int width, int height, Rectangle bounds, Rectangle scale) {\n final double xS = ((double) scale.x / width) * bounds.getWidth();\n final double yS = ((double) scale.y / height) * (int) bounds.getHeight();\n final double widthS = ((double) scale.width / width) * (int) bounds.getWidth();\n final double heightS = ((double) scale.height / height) * (int) bounds.getHeight();\n return new Rectangle((int) xS, (int) yS, (int) widthS, (int) heightS);\n }\n\n public static double calcAspectRatio(BufferedImage bufferedImage) {\n double aspectRatio = (double) bufferedImage.getWidth() / bufferedImage.getHeight();\n return Math.round(aspectRatio * 100) / 100.0;\n }\n\n public static String getMachineAddress() {\n try {\n return InetAddress.getLocalHost().getHostAddress();\n } catch (UnknownHostException ex) {\n throw new UnoperableException(ex);\n }\n }\n\n public static int getRandomPortOrDefault(int defaultPort) {\n int selectedPort = defaultPort;\n for (int port = 1024; port <= 65535; port++) {\n try (\n final ServerSocket ignored = new ServerSocket(port);\n final DatagramSocket ignored1 = new DatagramSocket(port)\n ) {\n selectedPort = port;\n break;\n } catch (IOException ignore) {\n }\n }\n return selectedPort;\n }\n\n public static InetSocketAddress extractAddrDetails(String merged) {\n final int separatorPos = merged.indexOf(':');\n return new InetSocketAddress(\n merged.substring(0, separatorPos),\n Integer.parseInt(merged.substring(separatorPos + 1))\n );\n }\n\n public static void generateThreadUsagePerTick() {\n final AtomicInteger previousCount = new AtomicInteger(0);\n final Timer timer = new Timer(12_000, e -> {\n if (previousCount.get() != Thread.activeCount() || previousCount.get() == 0) {\n log.info(\"All current active threads: {}\", Thread.activeCount());\n }\n previousCount.set(Thread.activeCount());\n });\n timer.start();\n }\n}"
},
{
"identifier": "CryptoAsymmetricHelper",
"path": "lib/src/main/java/pl/polsl/screensharing/lib/net/CryptoAsymmetricHelper.java",
"snippet": "@Slf4j\n@Getter\npublic class CryptoAsymmetricHelper {\n private KeyPair keyPair;\n\n public void generateRsaKeypair() throws GeneralSecurityException {\n // Generacja zestawu kluczy publiczny, prywatny typu RSA o długości 2048 bitów.\n final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(\"RSA\");\n keyPairGenerator.initialize(2048);\n keyPair = keyPairGenerator.generateKeyPair();\n log.info(\"Successfully generated public and private RSA keys\");\n }\n\n public PublicKey base64ToPublicKey(String base64Key) throws Exception {\n // Konwersja klucza przesyłanego przez sieć z Base64 do tablicy bajtów\n // oraz na jej podstawie zainicjalizowanie instancji PublicKey\n final byte[] keyBytes = Base64.getDecoder().decode(base64Key);\n final KeyFactory keyFactory = KeyFactory.getInstance(\"RSA\");\n final X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);\n return keyFactory.generatePublic(keySpec);\n }\n\n public String publicKeyToBase64() {\n // Konwersja klucza publicznego do formatu Base64 aby można go było przesłać przez sieć.\n return Base64.getEncoder().encodeToString(keyPair.getPublic().getEncoded());\n }\n\n public String encrypt(String data, PublicKey publicKey) throws Exception {\n // Szyfrowanie danych przychodzących kluczem publiczny oraz zakodowanie w Base64\n final Cipher encryptCipher = Cipher.getInstance(\"RSA\");\n encryptCipher.init(Cipher.ENCRYPT_MODE, publicKey);\n return Base64.getEncoder().encodeToString(encryptCipher.doFinal(data.getBytes()));\n }\n\n public String decrypt(String data) throws Exception {\n // Deszyfrowanie danych przychodzących kluczem prywatnym oraz odkodowanie z Base64\n final Cipher decryptCipher = Cipher.getInstance(\"RSA\");\n decryptCipher.init(Cipher.DECRYPT_MODE, keyPair.getPrivate());\n return new String(decryptCipher.doFinal(Base64.getDecoder().decode(data)));\n }\n}"
},
{
"identifier": "SocketState",
"path": "lib/src/main/java/pl/polsl/screensharing/lib/net/SocketState.java",
"snippet": "public enum SocketState {\n WAITING,\n EXHANGE_KEYS_REQ,\n EXHANGE_KEYS_RES,\n CHECK_PASSWORD_REQ,\n CHECK_PASSWORD_RES,\n SEND_CLIENT_DATA_REQ,\n SEND_CLIENT_DATA_RES,\n EVENT_START_STREAMING,\n EVENT_STOP_STREAMING,\n EVENT_TOGGLE_SCREEN_VISIBILITY,\n KICK_FROM_SESSION,\n END_UP_SESSION,\n ;\n\n private static final char SEPARATOR = '%';\n\n public String generateBody(String content) {\n return name() + SEPARATOR + content;\n }\n\n public static SocketState extractHeader(String merged) {\n return valueOf(merged.substring(0, merged.indexOf(SEPARATOR)));\n }\n\n public static String extractContent(String merged) {\n return merged.substring(merged.indexOf(SEPARATOR) + 1);\n }\n}"
},
{
"identifier": "StreamingSignalState",
"path": "lib/src/main/java/pl/polsl/screensharing/lib/net/StreamingSignalState.java",
"snippet": "public enum StreamingSignalState {\n STREAMING,\n STOPPED,\n SCREEN_HIDDEN,\n}"
},
{
"identifier": "AuthPasswordReq",
"path": "lib/src/main/java/pl/polsl/screensharing/lib/net/payload/AuthPasswordReq.java",
"snippet": "@Data\n@Builder\n@NoArgsConstructor\n@AllArgsConstructor\npublic class AuthPasswordReq {\n @JsonProperty(\"password\")\n private String password;\n\n @Override\n public String toString() {\n return \"{\" +\n \"password=\" + password +\n '}';\n }\n}"
},
{
"identifier": "AuthPasswordRes",
"path": "lib/src/main/java/pl/polsl/screensharing/lib/net/payload/AuthPasswordRes.java",
"snippet": "@Data\n@Builder\n@NoArgsConstructor\n@AllArgsConstructor\npublic class AuthPasswordRes {\n @JsonProperty(\"validStatus\")\n private boolean validStatus;\n\n @JsonProperty(\"secretKeyUdp\")\n private byte[] secretKeyUdp;\n\n @Override\n public String toString() {\n return \"{\" +\n \"validStatus=\" + validStatus +\n \", secretKeyUdp=******\" +\n '}';\n }\n}"
},
{
"identifier": "ConnectionData",
"path": "lib/src/main/java/pl/polsl/screensharing/lib/net/payload/ConnectionData.java",
"snippet": "@Data\n@Builder\n@NoArgsConstructor\n@AllArgsConstructor\npublic class ConnectionData {\n @JsonProperty(\"username\")\n private String username;\n\n @JsonProperty(\"ipAddress\")\n private String ipAddress;\n\n @JsonProperty(\"udpPort\")\n private int udpPort;\n\n @Override\n public String toString() {\n return \"{\" +\n \"username=\" + username +\n \", ipAddress=\" + ipAddress +\n \", udpPort=\" + udpPort +\n '}';\n }\n}"
},
{
"identifier": "VideoFrameDetails",
"path": "lib/src/main/java/pl/polsl/screensharing/lib/net/payload/VideoFrameDetails.java",
"snippet": "@Data\n@Builder\n@NoArgsConstructor\n@AllArgsConstructor\npublic class VideoFrameDetails {\n @JsonProperty(\"aspectRatio\")\n private double aspectRatio;\n\n @JsonProperty(\"streamingSignalState\")\n private StreamingSignalState streamingSignalState;\n\n @Override\n public String toString() {\n return \"{\" +\n \"aspectRatio=\" + aspectRatio +\n \", streamingSignalState=\" + streamingSignalState +\n '}';\n }\n}"
}
] | import at.favre.lib.crypto.bcrypt.BCrypt;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import pl.polsl.screensharing.host.model.SessionDetails;
import pl.polsl.screensharing.host.state.HostState;
import pl.polsl.screensharing.host.state.StreamingState;
import pl.polsl.screensharing.host.view.HostWindow;
import pl.polsl.screensharing.lib.Utils;
import pl.polsl.screensharing.lib.net.CryptoAsymmetricHelper;
import pl.polsl.screensharing.lib.net.SocketState;
import pl.polsl.screensharing.lib.net.StreamingSignalState;
import pl.polsl.screensharing.lib.net.payload.AuthPasswordReq;
import pl.polsl.screensharing.lib.net.payload.AuthPasswordRes;
import pl.polsl.screensharing.lib.net.payload.ConnectionData;
import pl.polsl.screensharing.lib.net.payload.VideoFrameDetails;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.SocketException;
import java.security.PublicKey;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.function.Consumer;
import java.util.function.Function; | 5,287 | /*
* Copyright (c) 2023 by MULTIPLE AUTHORS
* Part of the CS study course project.
*/
package pl.polsl.screensharing.host.net;
@Slf4j
public class ClientThread extends Thread {
@Getter
private final Socket socket; | /*
* Copyright (c) 2023 by MULTIPLE AUTHORS
* Part of the CS study course project.
*/
package pl.polsl.screensharing.host.net;
@Slf4j
public class ClientThread extends Thread {
@Getter
private final Socket socket; | private final HostWindow hostWindow; | 3 | 2023-10-11 16:12:02+00:00 | 8k |
Bawnorton/Potters | src/main/java/com/bawnorton/potters/registry/PottersBlocks.java | [
{
"identifier": "Potters",
"path": "src/main/java/com/bawnorton/potters/Potters.java",
"snippet": "public class Potters implements ModInitializer {\n public static final String MOD_ID = \"potters\";\n public static final Logger LOGGER = LoggerFactory.getLogger(MOD_ID);\n\n public static Identifier id(String path) {\n return new Identifier(MOD_ID, path);\n }\n\n @Override\n public void onInitialize() {\n LOGGER.debug(\"Potters Initialized.\");\n ConfigManager.loadConfigs();\n Networking.init();\n PottersRegistryKeys.init();\n PottersRegistries.init();\n PottersBlocks.init();\n PottersItems.init();\n PottersBlockEntityType.init();\n PottersRecipeSerializer.init();\n }\n}"
},
{
"identifier": "BottomlessDecoratedPotBlock",
"path": "src/main/java/com/bawnorton/potters/block/BottomlessDecoratedPotBlock.java",
"snippet": "public class BottomlessDecoratedPotBlock extends PottersDecoratedPotBlockBase {\n public static final Identifier WITH_CONTENT = Potters.id(\"with_content\");\n public static final BooleanProperty EMTPY = BooleanProperty.of(\"empty\");\n private static final DirectionProperty FACING = Properties.HORIZONTAL_FACING;\n private static final BooleanProperty WATERLOGGED = Properties.WATERLOGGED;\n\n public BottomlessDecoratedPotBlock(Supplier<Item> materialSupplier) {\n super(materialSupplier, FabricBlockSettings.copy(Blocks.DECORATED_POT));\n this.setDefaultState(this.stateManager.getDefaultState()\n .with(FACING, Direction.NORTH)\n .with(WATERLOGGED, Boolean.FALSE)\n .with(EMTPY, Boolean.TRUE));\n }\n\n @Override\n public BlockState getPlacementState(ItemPlacementContext ctx) {\n FluidState fluidState = ctx.getWorld().getFluidState(ctx.getBlockPos());\n BlockState state = this.getDefaultState()\n .with(FACING, ctx.getHorizontalPlayerFacing())\n .with(WATERLOGGED, fluidState.getFluid() == Fluids.WATER)\n .with(EMTPY, Boolean.TRUE);\n\n ItemStack stack = ctx.getStack();\n NbtCompound nbt = stack.getNbt();\n if (nbt == null) return state;\n\n NbtCompound blockEntityTag = nbt.getCompound(\"BlockEntityTag\");\n if (blockEntityTag.isEmpty()) return state;\n\n String count = blockEntityTag.getString(\"count\");\n try {\n int amount = Integer.parseInt(count);\n if (amount > 0) {\n state = state.with(EMTPY, Boolean.FALSE);\n }\n } catch (NumberFormatException ignored) {}\n\n return state;\n }\n\n @Override\n protected void appendProperties(StateManager.Builder<Block, BlockState> builder) {\n builder.add(FACING, WATERLOGGED, EMTPY);\n }\n\n @Override\n public BlockEntity createBlockEntity(BlockPos pos, BlockState state) {\n return new BottomlessDecoratedPotBlockEntity(pos, state);\n }\n\n @Override\n public BlockSoundGroup getSoundGroup(BlockState state) {\n return BlockSoundGroup.DECORATED_POT;\n }\n\n @Override\n protected BlockEntityType<? extends PottersDecoratedPotBlockEntityBase> getBlockEntityType() {\n return PottersBlockEntityType.BOTTOMLESS_DECORATED_POT;\n }\n\n @Override\n public List<ItemStack> getDroppedStacks(BlockState state, LootContextParameterSet.Builder builder) {\n BlockEntity blockEntity = builder.getOptional(LootContextParameters.BLOCK_ENTITY);\n if (blockEntity instanceof BottomlessDecoratedPotBlockEntity bottomlessDecoratedPotBlockEntity) {\n builder.addDynamicDrop(WITH_CONTENT, lootConsumer -> {\n ItemStack stack = bottomlessDecoratedPotBlockEntity.asStack(PottersBlockEntityType.BOTTOMLESS_DECORATED_POT, this.asItem());\n NbtCompound blockEntityTag = stack.getOrCreateNbt().getCompound(\"BlockEntityTag\");\n bottomlessDecoratedPotBlockEntity.getStorage().writeNbt(blockEntityTag);\n stack.getOrCreateNbt().put(\"BlockEntityTag\", blockEntityTag);\n lootConsumer.accept(stack);\n });\n }\n\n List<ItemStack> droppedStacks = super.getDroppedStacks(state, builder);\n // correct nbt for bottomless decorated pot with sherds\n for(ItemStack stack: droppedStacks) {\n if (!(Block.getBlockFromItem(stack.getItem()) instanceof BottomlessDecoratedPotBlock)) continue;\n\n NbtCompound nbt = stack.getNbt();\n if(nbt == null) continue;\n\n NbtCompound blockEntityTag = nbt.getCompound(\"BlockEntityTag\");\n if(blockEntityTag.isEmpty()) continue;\n\n if(blockEntityTag.contains(\"sherds\")) {\n if (blockEntityTag.contains(\"id\")) continue;\n\n Identifier id = Registries.BLOCK_ENTITY_TYPE.getId(PottersBlockEntityType.BOTTOMLESS_DECORATED_POT);\n if(id == null) continue;\n\n blockEntityTag.putString(\"id\", id.toString());\n }\n }\n return droppedStacks;\n }\n\n @Override\n public boolean isFinite() {\n return false;\n }\n}"
},
{
"identifier": "FiniteDecoratedPotBlock",
"path": "src/main/java/com/bawnorton/potters/block/FiniteDecoratedPotBlock.java",
"snippet": "public class FiniteDecoratedPotBlock extends PottersDecoratedPotBlockBase {\n public static final Identifier MATERIAL_AND_SHERDS = Potters.id(\"material_and_sherds\");\n public static final BooleanProperty CRACKED = Properties.CRACKED;\n private static final DirectionProperty FACING = Properties.HORIZONTAL_FACING;\n private static final BooleanProperty WATERLOGGED = Properties.WATERLOGGED;\n private final Supplier<Integer> stackCountSupplier;\n private final Supplier<Item> upgradeCore;\n private final int materialDropCount;\n\n public FiniteDecoratedPotBlock(Supplier<Item> materialSupplier, Supplier<Item> upgradeCore, Supplier<Integer> stackCountSupplier, int materialDropCount) {\n super(materialSupplier, FabricBlockSettings.copy(Blocks.DECORATED_POT));\n this.upgradeCore = upgradeCore;\n this.stackCountSupplier = stackCountSupplier;\n this.materialDropCount = materialDropCount;\n this.setDefaultState(this.stateManager.getDefaultState()\n .with(FACING, Direction.NORTH)\n .with(WATERLOGGED, Boolean.FALSE)\n .with(CRACKED, Boolean.FALSE));\n }\n\n public FiniteDecoratedPotBlock(Supplier<Item> materialSupplier, Supplier<Item> upgradeCore, Supplier<Integer> stackCountSupplier) {\n this(materialSupplier, upgradeCore, stackCountSupplier, 4);\n }\n\n public Supplier<Integer> getStackCountSupplier() {\n return stackCountSupplier;\n }\n\n public Item getUpgradeCore() {\n return upgradeCore.get();\n }\n\n @Override\n public BlockEntity createBlockEntity(BlockPos pos, BlockState state) {\n return new FiniteDecoratedPotBlockEntity(pos, state, getStackCountSupplier());\n }\n\n @Override\n protected BlockEntityType<? extends PottersDecoratedPotBlockEntityBase> getBlockEntityType() {\n return PottersBlockEntityType.FINITE_DECORATED_POT;\n }\n\n @Override\n public void onStateReplaced(BlockState state, World world, BlockPos pos, BlockState newState, boolean moved) {\n BlockEntity blockEntity = world.getBlockEntity(pos);\n if(blockEntity instanceof FiniteDecoratedPotBlockEntity finiteDecoratedPotBlockEntity) {\n DefaultedList<ItemStack> stacks = finiteDecoratedPotBlockEntity.getAndClearStacks();\n ItemScatterer.spawn(world, pos, stacks);\n world.updateComparators(pos, this);\n }\n super.onStateReplaced(state, world, pos, newState, moved);\n }\n\n @Override\n public List<ItemStack> getDroppedStacks(BlockState state, LootContextParameterSet.Builder builder) {\n BlockEntity blockEntity = builder.getOptional(LootContextParameters.BLOCK_ENTITY);\n if (blockEntity instanceof FiniteDecoratedPotBlockEntity finiteDecoratedPotBlockEntity) {\n builder.addDynamicDrop(MATERIAL_AND_SHERDS, lootConsumer -> {\n finiteDecoratedPotBlockEntity.getSherds().stream().map(Item::getDefaultStack).forEach(lootConsumer);\n for (int i = 0; i < materialDropCount; i++) {\n lootConsumer.accept(getMaterial().getDefaultStack());\n }\n });\n }\n\n return super.getDroppedStacks(state, builder);\n }\n\n @Override\n public boolean isFinite() {\n return true;\n }\n}"
},
{
"identifier": "PottersDecoratedPotBlockBase",
"path": "src/main/java/com/bawnorton/potters/block/base/PottersDecoratedPotBlockBase.java",
"snippet": "public abstract class PottersDecoratedPotBlockBase extends DecoratedPotBlock {\n private final Supplier<Item> materialSupplier;\n\n protected PottersDecoratedPotBlockBase(Supplier<Item> materialSupplier, Settings settings) {\n super(settings);\n this.materialSupplier = materialSupplier;\n }\n\n public Item getMaterial() {\n return materialSupplier.get();\n }\n\n public abstract boolean isFinite();\n\n @Override\n public ActionResult onUse(BlockState state, World world, BlockPos pos, PlayerEntity player, Hand hand, BlockHitResult hit) {\n BlockEntity blockEntity = world.getBlockEntity(pos);\n if (!(blockEntity instanceof PottersDecoratedPotBlockEntityBase pottersBlockEntity)) return ActionResult.PASS;\n\n ItemStack playerStack = player.getStackInHand(hand);\n PottersDecoratedPotStorageBase storage = pottersBlockEntity.getStorage();\n if (player.isSneaking() && !storage.isResourceBlank() && playerStack.isEmpty()) {\n ItemStack extracted = storage.extract();\n if (!extracted.isEmpty() && !player.giveItemStack(extracted)) {\n player.dropItem(extracted, false);\n }\n pottersBlockEntity.wobble(DecoratedPotBlockEntity.WobbleType.POSITIVE);\n world.playSound(null, pos, SoundEvents.BLOCK_DECORATED_POT_INSERT_FAIL, SoundCategory.BLOCKS, 1.0F, 1.0F);\n world.updateComparators(pos, this);\n } else if (!playerStack.isEmpty() && storage.canInsert(playerStack)) {\n pottersBlockEntity.wobble(DecoratedPotBlockEntity.WobbleType.POSITIVE);\n player.incrementStat(Stats.USED.getOrCreateStat(playerStack.getItem()));\n ItemStack toInsert = player.isCreative() ? playerStack.copyWithCount(1) : playerStack.split(1);\n storage.insert(toInsert);\n world.playSound(null, pos, SoundEvents.BLOCK_DECORATED_POT_INSERT, SoundCategory.BLOCKS, 1.0F, storage.getPitch());\n\n if (world instanceof ServerWorld serverWorld) {\n serverWorld.spawnParticles(ParticleTypes.DUST_PLUME, pos.getX() + 0.5, pos.getY() + 1.2, pos.getZ() + 0.5, 7, 0.0, 0.0, 0.0, 0.0);\n }\n world.updateComparators(pos, this);\n } else {\n world.playSound(null, pos, SoundEvents.BLOCK_DECORATED_POT_INSERT_FAIL, SoundCategory.BLOCKS, 1.0F, 1.0F);\n pottersBlockEntity.wobble(DecoratedPotBlockEntity.WobbleType.NEGATIVE);\n }\n\n world.emitGameEvent(player, GameEvent.BLOCK_CHANGE, pos);\n return ActionResult.SUCCESS;\n }\n\n @Override\n public void onPlaced(World world, BlockPos pos, BlockState state, @Nullable LivingEntity placer, ItemStack itemStack) {\n if (world.isClient) {\n world.getBlockEntity(pos, getBlockEntityType())\n .ifPresent(blockEntity -> blockEntity.readNbtFromStack(itemStack));\n }\n }\n\n public abstract BlockEntity createBlockEntity(BlockPos pos, BlockState state);\n\n @Override\n public void onProjectileHit(World world, BlockState state, BlockHitResult hit, ProjectileEntity projectile) {\n }\n\n @Override\n public ItemStack getPickStack(WorldView world, BlockPos pos, BlockState state) {\n return world.getBlockEntity(pos) instanceof PottersDecoratedPotBlockEntityBase pottersBlockEntity ? pottersBlockEntity.asStack(getBlockEntityType(), asItem()) : super.getPickStack(world, pos, state);\n }\n\n protected abstract BlockEntityType<? extends PottersDecoratedPotBlockEntityBase> getBlockEntityType();\n}"
},
{
"identifier": "ConfigManager",
"path": "src/main/java/com/bawnorton/potters/config/ConfigManager.java",
"snippet": "public class ConfigManager {\n private static final Gson GSON = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)\n .setPrettyPrinting()\n .create();\n private static final Path localConfigPath = FabricLoader.getInstance()\n .getConfigDir()\n .resolve(Potters.MOD_ID + \".json\");\n private static final Path serverConfigPath = FabricLoader.getInstance()\n .getConfigDir()\n .resolve(Potters.MOD_ID + \"-server.json\");\n\n private static boolean loaded = false;\n\n public static Config getConfig() {\n if (!loaded) {\n Potters.LOGGER.warn(\"Attempted to access configs before they were loaded, loading configs now\");\n loadConfigs();\n }\n if (Networking.isDedicated()) return Config.getServerInstance();\n return Config.getLocalInstance();\n }\n\n public static void loadConfigs() {\n loadLocalConfig();\n loadServerConfig();\n loaded = true;\n }\n\n private static void loadLocalConfig() {\n Config config = loadLocal();\n validateFields(config);\n Config.updateLocal(config);\n saveLocalConfig();\n Potters.LOGGER.info(\"Loaded local config\");\n }\n\n private static void loadServerConfig() {\n Config config = loadServer();\n validateFields(config);\n Config.updateServer(config);\n saveServerConfig();\n Potters.LOGGER.info(\"Loaded server config\");\n }\n\n private static void validateFields(Object instance) {\n validateFloatFields(instance);\n validateIntFields(instance);\n validateLongFields(instance);\n validateBooleanFields(instance);\n validateNestedFields(instance);\n }\n\n private static void validateFloatFields(Object instance) {\n Reflection.forEachFieldByAnnotation(instance, FloatOption.class, (field, annotation) -> {\n setIfNull(instance, field, annotation.value());\n ConfigOptionReference reference = ConfigOptionReference.of(instance, field);\n if (reference.floatValue() < annotation.min()) reference.floatValue(annotation.min());\n if (reference.floatValue() > annotation.max()) reference.floatValue(annotation.max());\n });\n }\n\n private static void validateIntFields(Object instance) {\n Reflection.forEachFieldByAnnotation(instance, IntOption.class, (field, annotation) -> {\n setIfNull(instance, field, annotation.value());\n ConfigOptionReference reference = ConfigOptionReference.of(instance, field);\n if (reference.intValue() < annotation.min()) reference.intValue(annotation.min());\n if (reference.intValue() > annotation.max()) reference.intValue(annotation.max());\n });\n }\n\n private static void validateLongFields(Object instance) {\n Reflection.forEachFieldByAnnotation(instance, LongOption.class, (field, annotation) -> {\n setIfNull(instance, field, annotation.value());\n ConfigOptionReference reference = ConfigOptionReference.of(instance, field);\n if (reference.longValue() < annotation.min()) reference.longValue(annotation.min());\n if (reference.longValue() > annotation.max()) reference.longValue(annotation.max());\n });\n }\n\n private static void validateBooleanFields(Object instance) {\n Reflection.forEachFieldByAnnotation(instance, BooleanOption.class, (field, annotation) -> setIfNull(instance, field, annotation.value()));\n }\n\n private static void validateNestedFields(Object instance) {\n Reflection.forEachFieldByAnnotation(instance, NestedOption.class, (field, annotation) -> {\n setIfNull(instance, field, Reflection.newInstance(field.getType()));\n\n NestedConfigOption nestedOption = Reflection.accessField(field, instance, NestedConfigOption.class);\n validateFields(nestedOption);\n });\n }\n\n private static void setIfNull(Object instance, Field field, Object fallback) {\n if (Reflection.accessField(field, instance) != null) return;\n\n Reflection.setField(field, instance, fallback);\n }\n\n public static String serializeConfig() {\n return GSON.toJson(Config.getServerInstance());\n }\n\n public static void deserializeConfig(String serialized) {\n Config.updateServer(GSON.fromJson(serialized, Config.class));\n saveServerConfig();\n }\n\n private static Config loadLocal() {\n return load(Config.getLocalInstance(), localConfigPath);\n }\n\n private static Config loadServer() {\n return load(Config.getServerInstance(), serverConfigPath);\n }\n\n private static Config load(Config config, Path path) {\n try {\n if (!Files.exists(path)) {\n Files.createDirectories(path.getParent());\n Files.createFile(path);\n return config;\n }\n try {\n return GSON.fromJson(Files.newBufferedReader(path), Config.class);\n } catch (JsonSyntaxException e) {\n Potters.LOGGER.error(\"Failed to parse config file, using default config\");\n }\n } catch (IOException e) {\n Potters.LOGGER.error(\"Failed to load config\", e);\n }\n return config;\n }\n\n public static boolean loaded() {\n return loaded;\n }\n\n public static void saveLocalConfig() {\n save(Config.getLocalInstance(), localConfigPath);\n }\n\n public static void saveServerConfig() {\n save(Config.getServerInstance(), serverConfigPath);\n }\n\n private static void save(Config config, Path path) {\n try {\n Files.write(path, GSON.toJson(config).getBytes());\n } catch (IOException e) {\n Potters.LOGGER.error(\"Failed to save config\", e);\n }\n }\n}"
}
] | import com.bawnorton.potters.Potters;
import com.bawnorton.potters.block.BottomlessDecoratedPotBlock;
import com.bawnorton.potters.block.FiniteDecoratedPotBlock;
import com.bawnorton.potters.block.base.PottersDecoratedPotBlockBase;
import com.bawnorton.potters.config.ConfigManager;
import net.minecraft.block.Block;
import net.minecraft.item.Items;
import net.minecraft.registry.Registries;
import net.minecraft.registry.Registry;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.stream.Stream; | 6,266 | package com.bawnorton.potters.registry;
public class PottersBlocks {
public static final FiniteDecoratedPotBlock REDSTONE_DECORATED_POT;
public static final FiniteDecoratedPotBlock COPPER_DECORATED_POT;
public static final FiniteDecoratedPotBlock IRON_DECORATED_POT;
public static final FiniteDecoratedPotBlock LAPIS_DECORATED_POT;
public static final FiniteDecoratedPotBlock GOLD_DECORATED_POT;
public static final FiniteDecoratedPotBlock AMETHYST_DECORATED_POT;
public static final FiniteDecoratedPotBlock DIAMOND_DECORATED_POT;
public static final FiniteDecoratedPotBlock EMERALD_DECORATED_POT;
public static final FiniteDecoratedPotBlock NETHERITE_DECORATED_POT;
public static final BottomlessDecoratedPotBlock BOTTOMLESS_DECORATED_POT;
private static final List<PottersDecoratedPotBlockBase> ALL;
private static final List<FiniteDecoratedPotBlock> FINITE_DECORATED_POTS;
private static final Map<Block, String> BLOCK_TO_NAME;
static {
ALL = new ArrayList<>();
FINITE_DECORATED_POTS = new ArrayList<>();
BLOCK_TO_NAME = new HashMap<>();
COPPER_DECORATED_POT = register("copper", new FiniteDecoratedPotBlock(() -> Items.COPPER_INGOT, () -> Items.DECORATED_POT, () -> ConfigManager.getConfig().copperStackCount));
LAPIS_DECORATED_POT = register("lapis", new FiniteDecoratedPotBlock(() -> Items.LAPIS_LAZULI, COPPER_DECORATED_POT::asItem, () -> ConfigManager.getConfig().lapisStackCount));
REDSTONE_DECORATED_POT = register("redstone", new FiniteDecoratedPotBlock(() -> Items.REDSTONE, LAPIS_DECORATED_POT::asItem, () -> ConfigManager.getConfig().redstoneStackCount));
EMERALD_DECORATED_POT = register("emerald", new FiniteDecoratedPotBlock(() -> Items.EMERALD, REDSTONE_DECORATED_POT::asItem, () -> ConfigManager.getConfig().emeraldStackCount));
AMETHYST_DECORATED_POT = register("amethyst", new FiniteDecoratedPotBlock(() -> Items.AMETHYST_SHARD, EMERALD_DECORATED_POT::asItem, () -> ConfigManager.getConfig().amethystStackCount));
IRON_DECORATED_POT = register("iron", new FiniteDecoratedPotBlock(() -> Items.IRON_INGOT, () -> Items.DECORATED_POT, () -> ConfigManager.getConfig().ironStackCount));
GOLD_DECORATED_POT = register("gold", new FiniteDecoratedPotBlock(() -> Items.GOLD_INGOT, IRON_DECORATED_POT::asItem, () -> ConfigManager.getConfig().goldStackCount));
DIAMOND_DECORATED_POT = register("diamond", new FiniteDecoratedPotBlock(() -> Items.DIAMOND, GOLD_DECORATED_POT::asItem, () -> ConfigManager.getConfig().diamondStackCount));
NETHERITE_DECORATED_POT = register("netherite", new FiniteDecoratedPotBlock(() -> Items.NETHERITE_INGOT, DIAMOND_DECORATED_POT::asItem, () -> ConfigManager.getConfig().netheriteStackCount, 1));
BOTTOMLESS_DECORATED_POT = register("bottomless", new BottomlessDecoratedPotBlock(() -> Items.ENDER_PEARL));
/* Progression:
* copper => lapis => redstone => emerald => amethyst
* iron => gold => diamond => netherite => bottomless
* normal + 4 copper => copper
* copper + 4 lapis => lapis
* lapis + 4 redstone => redstone
* redstone + 4 emerald => emerald
* emerald + 4 amethyst => amethyst
* normal + 4 iron => iron
* iron + 4 gold => gold
* gold + 4 diamond => diamond
* diamond + netherite => netherite
* netherite + 2 ender pearl + nether star/dragon egg => bottomless
* copper + 2 iron => iron
* lapis + 2 gold => gold
* redstone + 2 diamond => diamond
* emerald + netherite => netherite
* amethyst + 4 ender pearl + nether star/dragon egg => bottomless
*/
/* Costs:
* Copper: 4 copper ingot + 4 bricks
* Lapis: 4 lapis lazuli + 4 copper ingot + 4 bricks
* Redstone: 4 redstone + 4 lapis lazuli + 4 copper ingot + 4 bricks
* Emerald: 4 emerald + 4 redstone + 4 lapis lazuli + 4 copper ingot + 4 bricks
* Amethyst: 4 amethyst + 4 emerald + 4 redstone + 4 lapis lazuli + 4 copper ingot + 4 bricks
* Iron: 4 iron ingot + 4 bricks
* 2 iron ingot + 4 copper ingot + 4 bricks
* Gold: 4 gold ingot + 4 iron ingot + 4 bricks
* 2 gold ingot + 4 lapis lazuli + 4 copper ingot + 4 bricks
* 4 gold ingot + 2 iron ingot + 4 copper ingot + 4 bricks
* Diamond: 4 diamond + 4 gold ingot + 4 iron ingot + 4 bricks
* 2 diamond + 4 redstone + 4 lapis lazuli + 4 copper ingot + 4 bricks
* 4 diamond + 2 gold ingot + 4 lapis lazuli + 4 copper ingot + 4 bricks
* 4 diamond + 4 gold ingot + 2 iron ingot + 4 copper ingot + 4 bricks
* Netherite: netherite ingot + 4 diamond + 4 gold ingot + 4 iron ingot + 4 bricks
* nehterite ingot + 4 emerald + 4 redstone + 4 lapis lazuli + 4 copper ingot + 4 bricks
* netherite ingot + 2 diamond + 4 redstone + 4 lapis lazuli + 4 copper ingot + 4 bricks
* netherite ingot + 4 diamond + 2 gold ingot + 4 lapis lazuli + 4 copper ingot + 4 bricks
* netherite ingot + 4 diamond + 4 gold ingot + 2 iron ingot + 4 copper ingot + 4 bricks
* Bottomless: 2 ender pearl + nether star + netherite ingot + 4 diamond + 4 gold ingot + 4 iron ingot + 4 bricks
* 2 ender pearl + nether star + netherite ingot + 4 emerald + 4 redstone + 4 lapis lazuli + 4 copper ingot + 4 bricks
* 2 ender pearl + nether star + netherite ingot + 2 diamond + 4 redstone + 4 lapis lazuli + 4 copper ingot + 4 bricks
* 2 ender pearl + nether star + netherite ingot + 4 diamond + 2 gold ingot + 4 lapis lazuli + 4 copper ingot + 4 bricks
* 2 ender pearl + nether star + netherite ingot + 4 diamond + 4 gold ingot + 2 iron ingot + 4 copper ingot + 4 bricks
* 4 ender pearl + nether star + 4 amethyst + 4 emerald + 4 redstone + 4 lapis lazuli + 4 copper ingot + 4 bricks
*/
}
public static void init() {
// no-op
}
public static String getName(Block block) {
return BLOCK_TO_NAME.get(block);
}
public static Stream<PottersDecoratedPotBlockBase> stream() {
return ALL.stream();
}
public static void forEach(Consumer<PottersDecoratedPotBlockBase> blockConsumer) {
ALL.forEach(blockConsumer);
}
public static void forEachFinite(Consumer<FiniteDecoratedPotBlock> blockConsumer) {
FINITE_DECORATED_POTS.forEach(blockConsumer);
}
private static <T extends PottersDecoratedPotBlockBase> T register(String name, T block) { | package com.bawnorton.potters.registry;
public class PottersBlocks {
public static final FiniteDecoratedPotBlock REDSTONE_DECORATED_POT;
public static final FiniteDecoratedPotBlock COPPER_DECORATED_POT;
public static final FiniteDecoratedPotBlock IRON_DECORATED_POT;
public static final FiniteDecoratedPotBlock LAPIS_DECORATED_POT;
public static final FiniteDecoratedPotBlock GOLD_DECORATED_POT;
public static final FiniteDecoratedPotBlock AMETHYST_DECORATED_POT;
public static final FiniteDecoratedPotBlock DIAMOND_DECORATED_POT;
public static final FiniteDecoratedPotBlock EMERALD_DECORATED_POT;
public static final FiniteDecoratedPotBlock NETHERITE_DECORATED_POT;
public static final BottomlessDecoratedPotBlock BOTTOMLESS_DECORATED_POT;
private static final List<PottersDecoratedPotBlockBase> ALL;
private static final List<FiniteDecoratedPotBlock> FINITE_DECORATED_POTS;
private static final Map<Block, String> BLOCK_TO_NAME;
static {
ALL = new ArrayList<>();
FINITE_DECORATED_POTS = new ArrayList<>();
BLOCK_TO_NAME = new HashMap<>();
COPPER_DECORATED_POT = register("copper", new FiniteDecoratedPotBlock(() -> Items.COPPER_INGOT, () -> Items.DECORATED_POT, () -> ConfigManager.getConfig().copperStackCount));
LAPIS_DECORATED_POT = register("lapis", new FiniteDecoratedPotBlock(() -> Items.LAPIS_LAZULI, COPPER_DECORATED_POT::asItem, () -> ConfigManager.getConfig().lapisStackCount));
REDSTONE_DECORATED_POT = register("redstone", new FiniteDecoratedPotBlock(() -> Items.REDSTONE, LAPIS_DECORATED_POT::asItem, () -> ConfigManager.getConfig().redstoneStackCount));
EMERALD_DECORATED_POT = register("emerald", new FiniteDecoratedPotBlock(() -> Items.EMERALD, REDSTONE_DECORATED_POT::asItem, () -> ConfigManager.getConfig().emeraldStackCount));
AMETHYST_DECORATED_POT = register("amethyst", new FiniteDecoratedPotBlock(() -> Items.AMETHYST_SHARD, EMERALD_DECORATED_POT::asItem, () -> ConfigManager.getConfig().amethystStackCount));
IRON_DECORATED_POT = register("iron", new FiniteDecoratedPotBlock(() -> Items.IRON_INGOT, () -> Items.DECORATED_POT, () -> ConfigManager.getConfig().ironStackCount));
GOLD_DECORATED_POT = register("gold", new FiniteDecoratedPotBlock(() -> Items.GOLD_INGOT, IRON_DECORATED_POT::asItem, () -> ConfigManager.getConfig().goldStackCount));
DIAMOND_DECORATED_POT = register("diamond", new FiniteDecoratedPotBlock(() -> Items.DIAMOND, GOLD_DECORATED_POT::asItem, () -> ConfigManager.getConfig().diamondStackCount));
NETHERITE_DECORATED_POT = register("netherite", new FiniteDecoratedPotBlock(() -> Items.NETHERITE_INGOT, DIAMOND_DECORATED_POT::asItem, () -> ConfigManager.getConfig().netheriteStackCount, 1));
BOTTOMLESS_DECORATED_POT = register("bottomless", new BottomlessDecoratedPotBlock(() -> Items.ENDER_PEARL));
/* Progression:
* copper => lapis => redstone => emerald => amethyst
* iron => gold => diamond => netherite => bottomless
* normal + 4 copper => copper
* copper + 4 lapis => lapis
* lapis + 4 redstone => redstone
* redstone + 4 emerald => emerald
* emerald + 4 amethyst => amethyst
* normal + 4 iron => iron
* iron + 4 gold => gold
* gold + 4 diamond => diamond
* diamond + netherite => netherite
* netherite + 2 ender pearl + nether star/dragon egg => bottomless
* copper + 2 iron => iron
* lapis + 2 gold => gold
* redstone + 2 diamond => diamond
* emerald + netherite => netherite
* amethyst + 4 ender pearl + nether star/dragon egg => bottomless
*/
/* Costs:
* Copper: 4 copper ingot + 4 bricks
* Lapis: 4 lapis lazuli + 4 copper ingot + 4 bricks
* Redstone: 4 redstone + 4 lapis lazuli + 4 copper ingot + 4 bricks
* Emerald: 4 emerald + 4 redstone + 4 lapis lazuli + 4 copper ingot + 4 bricks
* Amethyst: 4 amethyst + 4 emerald + 4 redstone + 4 lapis lazuli + 4 copper ingot + 4 bricks
* Iron: 4 iron ingot + 4 bricks
* 2 iron ingot + 4 copper ingot + 4 bricks
* Gold: 4 gold ingot + 4 iron ingot + 4 bricks
* 2 gold ingot + 4 lapis lazuli + 4 copper ingot + 4 bricks
* 4 gold ingot + 2 iron ingot + 4 copper ingot + 4 bricks
* Diamond: 4 diamond + 4 gold ingot + 4 iron ingot + 4 bricks
* 2 diamond + 4 redstone + 4 lapis lazuli + 4 copper ingot + 4 bricks
* 4 diamond + 2 gold ingot + 4 lapis lazuli + 4 copper ingot + 4 bricks
* 4 diamond + 4 gold ingot + 2 iron ingot + 4 copper ingot + 4 bricks
* Netherite: netherite ingot + 4 diamond + 4 gold ingot + 4 iron ingot + 4 bricks
* nehterite ingot + 4 emerald + 4 redstone + 4 lapis lazuli + 4 copper ingot + 4 bricks
* netherite ingot + 2 diamond + 4 redstone + 4 lapis lazuli + 4 copper ingot + 4 bricks
* netherite ingot + 4 diamond + 2 gold ingot + 4 lapis lazuli + 4 copper ingot + 4 bricks
* netherite ingot + 4 diamond + 4 gold ingot + 2 iron ingot + 4 copper ingot + 4 bricks
* Bottomless: 2 ender pearl + nether star + netherite ingot + 4 diamond + 4 gold ingot + 4 iron ingot + 4 bricks
* 2 ender pearl + nether star + netherite ingot + 4 emerald + 4 redstone + 4 lapis lazuli + 4 copper ingot + 4 bricks
* 2 ender pearl + nether star + netherite ingot + 2 diamond + 4 redstone + 4 lapis lazuli + 4 copper ingot + 4 bricks
* 2 ender pearl + nether star + netherite ingot + 4 diamond + 2 gold ingot + 4 lapis lazuli + 4 copper ingot + 4 bricks
* 2 ender pearl + nether star + netherite ingot + 4 diamond + 4 gold ingot + 2 iron ingot + 4 copper ingot + 4 bricks
* 4 ender pearl + nether star + 4 amethyst + 4 emerald + 4 redstone + 4 lapis lazuli + 4 copper ingot + 4 bricks
*/
}
public static void init() {
// no-op
}
public static String getName(Block block) {
return BLOCK_TO_NAME.get(block);
}
public static Stream<PottersDecoratedPotBlockBase> stream() {
return ALL.stream();
}
public static void forEach(Consumer<PottersDecoratedPotBlockBase> blockConsumer) {
ALL.forEach(blockConsumer);
}
public static void forEachFinite(Consumer<FiniteDecoratedPotBlock> blockConsumer) {
FINITE_DECORATED_POTS.forEach(blockConsumer);
}
private static <T extends PottersDecoratedPotBlockBase> T register(String name, T block) { | T value = Registry.register(Registries.BLOCK, Potters.id(name + "_decorated_pot"), block); | 0 | 2023-10-13 19:14:56+00:00 | 8k |
YinQin257/mqs-adapter | mqs-starter/src/main/java/org/yinqin/mqs/kafka/consumer/factory/KafkaBatchConsumerFactory.java | [
{
"identifier": "Constants",
"path": "mqs-starter/src/main/java/org/yinqin/mqs/common/Constants.java",
"snippet": "public interface Constants {\n int SUCCESS = 1;\n int ERROR = 0;\n String TRAN = \"TRAN\";\n String BATCH = \"BATCH\";\n String BROADCAST = \"BROADCAST\";\n String TRUE = \"true\";\n String EMPTY = \"\";\n String HYPHEN = \"-\";\n String UNDER_SCORE = \"_\";\n String BROADCAST_CONNECTOR = \"_BROADCAST_\";\n String BROADCAST_SUFFIX = \"_BROADCAST\";\n String BATCH_SUFFIX = \"_BATCH\";\n String WILDCARD =\"*\";\n}"
},
{
"identifier": "MqsProperties",
"path": "mqs-starter/src/main/java/org/yinqin/mqs/common/config/MqsProperties.java",
"snippet": "@ConfigurationProperties(MqsProperties.PREFIX)\n@Data\n@ToString\n@NoArgsConstructor\n@AllArgsConstructor\npublic class MqsProperties {\n\n /**\n * 配置项前缀\n */\n public static final String PREFIX = \"mqs\";\n\n /**\n * 配置集合\n */\n private Map<String, AdapterProperties> adapter = new LinkedHashMap<>();\n\n /**\n * 消息中间件实例配置类\n *\n * @author YinQin\n * @version 1.0.3\n * @createDate 2023年10月13日\n * @since 1.0.0\n */\n @Data\n public static class AdapterProperties {\n\n /**\n * 消息中间件厂商名称\n */\n private String vendorName;\n\n /**\n * 生产组或消费组名称\n * 批量消费组(groupName)、单条消费组(groupName + ‘_TRAN’)、广播消费组(groupName + ‘BROADCAST’)\n */\n private String groupName;\n\n /**\n * 消费者启动开关\n */\n private boolean consumerEnabled = false;\n\n /**\n * 生产者启动开关\n */\n private boolean producerEnabled = false;\n\n /**\n * 消费组配置类\n */\n private ConvertProperties group = new ConvertProperties();\n\n /**\n * topic配置类\n */\n private ConvertProperties topic = new ConvertProperties();\n\n /**\n * rocketmq配置类\n */\n private CustomRocketmqProperties rocketmq = new CustomRocketmqProperties();\n\n /**\n * kafka配置类\n */\n private CustomKafkaProperties kafka = new CustomKafkaProperties();\n\n /**\n * 转换配置类\n *\n * @author YinQin\n * @version 1.0.4\n * @createDate 2023年11月20日\n * @since 1.0.0\n */\n @Data\n public static class ConvertProperties {\n\n /**\n * 前缀\n */\n private String prefix;\n\n /**\n * 后缀\n */\n private String suffix;\n\n /**\n * 是否小写转大写\n */\n private boolean isLowerToUpper = false;\n\n /**\n * 是否大写转小写\n */\n private boolean isUpperToLower = false;\n\n /**\n * 是否下划线转中划线\n */\n private boolean isUnderScoreToHyphen = false;\n\n /**\n * 是否中划线转下划线\n */\n private boolean isHyphenToUnderScore = false;\n }\n\n /**\n * rocketmq配置类\n *\n * @author YinQin\n * @version 1.0.3\n * @createDate 2023年10月13日\n * @since 1.0.0\n */\n @Data\n public static class CustomRocketmqProperties {\n\n /**\n * rocketmq acl访问控制\n * 可配置acl开关、accessKey、secretKey\n */\n private Acl acl = new Acl();\n\n /**\n * 批量消费最大数量,建议不超过32\n */\n private int consumeMessageBatchMaxSize = 1;\n\n /**\n * 消费线程最大数量\n */\n private int consumeThreadMax = 1;\n\n /**\n * 消费线程最小数量\n */\n private int consumeThreadMin = 1;\n\n /**\n * 流量控制\n * 消费者本地缓存消息数超过pullThresholdForQueue时,降低拉取消息频率\n */\n private int pullThresholdForQueue = 1000;\n\n /**\n * 流量控制\n * 消费者本地缓存消息跨度超过consumeConcurrentlyMaxSpan时,降低拉取消息频率\n */\n private int consumeConcurrentlyMaxSpan = 500;\n\n /**\n * rocketmq其他源生配置项,可自行参考官网配置\n *\n * @see ClientConfig\n */\n private ClientConfig clientConfig;\n\n /**\n * acl访问控制类,继承SessionCredentials\n *\n * @author YinQin\n * @version 1.0.3\n * @createDate 2023年10月13日\n * @see org.apache.rocketmq.acl.common.SessionCredentials\n * @since 1.0.0\n */\n @EqualsAndHashCode(callSuper = true)\n @Data\n public static class Acl extends SessionCredentials {\n\n /**\n * acl访问控制开关\n */\n private boolean enabled;\n }\n }\n\n /**\n * kafka配置类\n *\n * @author YinQin\n * @version 1.0.3\n * @createDate 2023年10月13日\n * @since 1.0.0\n */\n @Data\n public static class CustomKafkaProperties {\n\n /**\n * kafka其他源生配置项,可自行参考官网配置\n *\n * @see org.apache.kafka.clients.consumer.ConsumerConfig\n */\n private Properties clientConfig;\n\n /**\n * 拉取消息间隔时间,单位:毫秒\n */\n private int interval = 100;\n }\n }\n\n}"
},
{
"identifier": "ConsumerFactory",
"path": "mqs-starter/src/main/java/org/yinqin/mqs/common/factory/ConsumerFactory.java",
"snippet": "public abstract class ConsumerFactory {\n\n /**\n * 启动消费者方法,消费者具体是什么类型由子类控制\n * @param instanceId 实例ID\n * @param properties 配置类\n * @param messageHandlers 消费者集合\n * @return 消费者实例\n */\n public MessageConsumer startConsumer(String instanceId, MqsProperties.AdapterProperties properties, Map<String, MessageHandler> messageHandlers) {\n MessageConsumer consumer = createConsumer(instanceId, properties, messageHandlers);\n consumer.start();\n return consumer;\n }\n\n /**\n * 工厂方法\n *\n * @param instanceId 实例ID\n * @param properties 配置\n * @param messageHandlers 消息处理器\n * @return 单条消费者\n */\n public abstract MessageConsumer createConsumer(String instanceId, MqsProperties.AdapterProperties properties, Map<String, MessageHandler> messageHandlers);\n\n}"
},
{
"identifier": "MessageHandler",
"path": "mqs-starter/src/main/java/org/yinqin/mqs/common/handler/MessageHandler.java",
"snippet": "public interface MessageHandler {\n\n /**\n * 单条或广播消息处理方法\n *\n * @param message 消息\n * @throws Exception 异常\n */\n void process(AdapterMessage message) throws Exception;\n\n /**\n * 批量消息处理方法\n *\n * @param messages 消息\n * @throws Exception 异常\n */\n void process(List<AdapterMessage> messages) throws Exception;\n}"
},
{
"identifier": "MessageConsumer",
"path": "mqs-starter/src/main/java/org/yinqin/mqs/common/service/MessageConsumer.java",
"snippet": "public interface MessageConsumer extends DisposableBean {\n\n /**\n * 消费组启动方法\n */\n void start();\n}"
},
{
"identifier": "PollWorker",
"path": "mqs-starter/src/main/java/org/yinqin/mqs/kafka/PollWorker.java",
"snippet": "public class PollWorker implements Runnable {\n\n private final Logger logger = LoggerFactory.getLogger(PollWorker.class);\n\n /**\n * 线程停止标记\n */\n private final AtomicBoolean closed = new AtomicBoolean(false);\n\n /**\n * kafka源生消费者\n */\n private final KafkaConsumer<String, byte[]> kafkaConsumer;\n\n /**\n * 消息处理器集合\n */\n private final Map<String, MessageHandler> messageHandlers;\n\n /**\n * 拉取消息间隔\n */\n private final int interval;\n\n public PollWorker(KafkaConsumer<String, byte[]> kafkaConsumer, Map<String, MessageHandler> messageHandlers, int interval) {\n this.kafkaConsumer = kafkaConsumer;\n this.messageHandlers = messageHandlers;\n this.interval = interval;\n }\n\n @Override\n public void run() {\n try {\n while (!closed.get()) {\n try {\n List<AdapterMessage> messages = fetchMessages();\n if (messages.isEmpty()) {\n ThreadUtil.sleep(interval);\n continue;\n }\n\n consumeMessage(messages);\n } catch (Exception e) {\n logger.error(\"拉取消息异常:\", e);\n }\n }\n } finally {\n // 关闭消费者,必须在当前线程关闭,否则会有线程安全问题\n kafkaConsumer.close();\n }\n\n }\n\n public void shutdown() {\n closed.set(true);\n }\n\n /**\n * 拉取消息\n *\n * @return 消息集合\n */\n private List<AdapterMessage> fetchMessages() {\n ConsumerRecords<String, byte[]> records = kafkaConsumer.poll(Duration.ofMillis(100));\n Iterator<ConsumerRecord<String, byte[]>> iterator = records.iterator();\n List<AdapterMessage> messages = new ArrayList<>(records.count());\n ConsumerRecord<String, byte[]> item;\n while (iterator.hasNext()) {\n item = iterator.next();\n AdapterMessage message = AdapterMessage.builder()\n .topic(item.topic())\n .body(item.value())\n .bizKey(item.key())\n .build();\n message.setOriginMessage(item);\n messages.add(message);\n }\n return messages;\n }\n\n /**\n * 按照topic分组批量消费消息\n *\n * @param messages 消息集合\n */\n private void consumeMessage(List<AdapterMessage> messages) {\n Map<String, List<AdapterMessage>> collect = messages.stream().collect(Collectors.groupingBy(AdapterMessage::getTopic, Collectors.toList()));\n try {\n for (Map.Entry<String, List<AdapterMessage>> entry : collect.entrySet()) {\n String topic = entry.getKey();\n List<AdapterMessage> messageObjectList = entry.getValue();\n logger.debug(\"kafka批量消息,topic:{},消息数量为:{}\", topic, messageObjectList.size());\n MessageAdapter messageAdapter = messageHandlers.get(messageObjectList.get(0).getTopic()).getClass().getAnnotation(MessageAdapter.class);\n if (messageAdapter.isBatch()) {\n messageHandlers.get(messageObjectList.get(0).getTopic()).process(messages);\n } else {\n for (AdapterMessage msg : messages)\n messageHandlers.get(messageObjectList.get(0).getTopic()).process(msg);\n }\n }\n } catch (Exception e) {\n logger.error(\"kafka消费异常:\", e);\n }\n }\n}"
},
{
"identifier": "CustomKafkaConsumer",
"path": "mqs-starter/src/main/java/org/yinqin/mqs/kafka/consumer/CustomKafkaConsumer.java",
"snippet": "public class CustomKafkaConsumer implements MessageConsumer {\n\n private final Logger logger = LoggerFactory.getLogger(CustomKafkaConsumer.class);\n\n /**\n * 实例ID\n */\n private final String instanceId;\n\n /**\n * 消费类型\n */\n private final String consumerType;\n\n /**\n * 拉取消息工作线程\n */\n @Getter\n private final PollWorker pollWorker;\n\n public CustomKafkaConsumer(String instanceId, String consumerType, PollWorker pollWorker) {\n this.instanceId = instanceId;\n this.consumerType = consumerType;\n this.pollWorker = pollWorker;\n }\n\n /**\n * 异步启动拉取消息工作线程\n */\n @Override\n public void start() {\n ThreadUtil.newThread(pollWorker, instanceId + Constants.HYPHEN + consumerType + \"-poll-worker\").start();\n }\n\n /**\n * 停止拉取消息工作线程\n */\n @Override\n public void destroy() {\n pollWorker.shutdown();\n logger.info(\"实例:{},消费类型:{}, 消费者停止成功,\", instanceId, consumerType);\n }\n\n}"
}
] | import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.yinqin.mqs.common.Constants;
import org.yinqin.mqs.common.config.MqsProperties;
import org.yinqin.mqs.common.factory.ConsumerFactory;
import org.yinqin.mqs.common.handler.MessageHandler;
import org.yinqin.mqs.common.service.MessageConsumer;
import org.yinqin.mqs.kafka.PollWorker;
import org.yinqin.mqs.kafka.consumer.CustomKafkaConsumer;
import java.util.Map;
import java.util.Properties; | 3,683 | package org.yinqin.mqs.kafka.consumer.factory;
/**
* kafka批量消费者工厂类
*
* @author YinQin
* @createDate 2023年11月27日
* @since 1.0.6
* @see ConsumerFactory
* @version 1.0.6
*/
public class KafkaBatchConsumerFactory extends ConsumerFactory implements CreateKafkaConsumer {
@Override
public MessageConsumer createConsumer(String instanceId, MqsProperties.AdapterProperties properties, Map<String, MessageHandler> messageHandlers) {
// 初始化配置
Properties kafkaProperties = new Properties();
init(kafkaProperties, properties);
// 设置消费组名称
String groupName = properties.getGroupName() + Constants.BATCH_SUFFIX;
// 创建kafka原生消费者
KafkaConsumer<String, byte[]> kafkaConsumer = createKafkaConsumer(groupName, properties, kafkaProperties);
// 订阅topic
subscribe(kafkaConsumer, instanceId, groupName, messageHandlers);
// 创建拉取消息工作线程
PollWorker pollWorker = new PollWorker(kafkaConsumer, messageHandlers, properties.getKafka().getInterval());
// 创建自定义消费者 | package org.yinqin.mqs.kafka.consumer.factory;
/**
* kafka批量消费者工厂类
*
* @author YinQin
* @createDate 2023年11月27日
* @since 1.0.6
* @see ConsumerFactory
* @version 1.0.6
*/
public class KafkaBatchConsumerFactory extends ConsumerFactory implements CreateKafkaConsumer {
@Override
public MessageConsumer createConsumer(String instanceId, MqsProperties.AdapterProperties properties, Map<String, MessageHandler> messageHandlers) {
// 初始化配置
Properties kafkaProperties = new Properties();
init(kafkaProperties, properties);
// 设置消费组名称
String groupName = properties.getGroupName() + Constants.BATCH_SUFFIX;
// 创建kafka原生消费者
KafkaConsumer<String, byte[]> kafkaConsumer = createKafkaConsumer(groupName, properties, kafkaProperties);
// 订阅topic
subscribe(kafkaConsumer, instanceId, groupName, messageHandlers);
// 创建拉取消息工作线程
PollWorker pollWorker = new PollWorker(kafkaConsumer, messageHandlers, properties.getKafka().getInterval());
// 创建自定义消费者 | return new CustomKafkaConsumer(instanceId, Constants.BATCH, pollWorker); | 6 | 2023-10-11 03:23:43+00:00 | 8k |
Feniksovich/RxPubSub | src/main/java/io/github/feniksovich/rxpubsub/event/EventBusImpl.java | [
{
"identifier": "MessagingService",
"path": "src/main/java/io/github/feniksovich/rxpubsub/MessagingService.java",
"snippet": "public final class MessagingService {\n\n private MessagingServiceConfig config;\n private RedisClient redisClient;\n private StatefulRedisPubSubConnection<String, String> subConnection;\n private StatefulRedisPubSubConnection<String, String> pubConnection;\n\n private final Logger logger;\n private final EventBusImpl eventBus;\n\n private final ConcurrentHashMap<String, Class<? extends PubSubMessage>> registeredMessages = new ConcurrentHashMap<>();\n private final ConcurrentHashMap<String, CallbackHandlerWrapper<? extends PubSubMessage>> awaitingCallbacks = new ConcurrentHashMap<>();\n\n private final ScheduledThreadPoolExecutor timeoutsScheduler = new ScheduledThreadPoolExecutor(20);\n\n private final ConcurrentHashMap<String, PubSubChannel> registeredIncomingChannels = new ConcurrentHashMap<>();\n private final ConcurrentHashMap<String, PubSubChannel> registeredOutgoingChannels = new ConcurrentHashMap<>();\n\n private static final Gson GSON = new GsonBuilder()\n .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)\n .disableHtmlEscaping()\n .create();\n\n public MessagingService(MessagingServiceConfig config) {\n this(config, LoggerFactory.getLogger(MessagingService.class.getName()));\n }\n \n public MessagingService(MessagingServiceConfig config, Logger logger) {\n this.config = config;\n this.eventBus = new EventBusImpl(this);\n this.logger = logger;\n timeoutsScheduler.setRemoveOnCancelPolicy(true);\n timeoutsScheduler.setKeepAliveTime(1, TimeUnit.SECONDS);\n init();\n }\n\n private boolean init() {\n redisClient = RedisClient.create(config.connectionUri());\n try {\n subConnection = redisClient.connectPubSub();\n pubConnection = redisClient.connectPubSub();\n subConnection.addListener(new RedisPubSubAdapter<>() {\n @Override\n public void message(String channel, String message) {\n handleMessage(channel, message);\n }\n });\n } catch (RedisConnectionException ex) {\n logger.error(\"Failed to connect to the Redis server\", ex);\n return false;\n }\n return true;\n }\n\n private void handleMessage(String channel, String message) {\n // Don't handle if channel isn't registered as incoming\n if (!registeredIncomingChannels.containsKey(channel)) return;\n\n logger.debug(\"Received message: \" + channel + \" @ \" + message);\n\n // Check whether any message is registered with the obtained class ID\n getMessageClass(message).ifPresentOrElse(clazz -> {\n // Deserialize raw JSON message to pubsub message POJO\n var pubSubMessage = GSON.fromJson(message, clazz);\n if (pubSubMessage.getResponseTo().isPresent()) {\n var awaitingCallback = awaitingCallbacks.get(pubSubMessage.getResponseTo().get());\n if (awaitingCallback != null) {\n awaitingCallbacks.remove(pubSubMessage.getMessageId());\n awaitingCallback.accept(clazz, pubSubMessage);\n }\n return;\n }\n // There is no awaiting callbacks, pass pubsub message to the event bus\n eventBus.handleMessage(clazz, pubSubMessage);\n }, () -> logger.debug(\"Received message is unregistered. Rejected.\"));\n }\n\n /**\n * Determines the class based on the raw string representation of the message.\n *\n * @param message a string representation of the message\n * @return the class of the message if registered, otherwise nothing\n */\n private Optional<Class<? extends PubSubMessage>> getMessageClass(String message) {\n var id = GSON.fromJson(message, JsonObject.class).get(ReservedFields.MESSAGE_CLASS_IDENTIFIER_FIELD);\n if (id == null) return Optional.empty();\n return Optional.ofNullable(registeredMessages.get(id.getAsString()));\n }\n\n /**\n * Sets the class id for the message.\n *\n * @param jsonMessage target message {@link JsonObject} representation\n * @param classId id to set\n * @return {@link JsonObject} message representation with set class id\n */\n private JsonObject setMessageClass(JsonObject jsonMessage, String classId) {\n jsonMessage.addProperty(ReservedFields.MESSAGE_CLASS_IDENTIFIER_FIELD, classId);\n return jsonMessage;\n }\n\n private void subscribe(PubSubChannel channel) {\n Objects.requireNonNull(channel, \"channel is null\");\n subConnection.sync().subscribe(channel.getId());\n }\n\n private void subscribe(String... channelsId) {\n Objects.requireNonNull(channelsId, \"channelsId is null\");\n subConnection.sync().subscribe(channelsId);\n }\n\n private void unsubscribe(PubSubChannel channel) {\n Objects.requireNonNull(channel, \"channel is null\");\n subConnection.sync().unsubscribe(channel.getId());\n }\n\n private void unsubscribe(String... channelsId) {\n Objects.requireNonNull(channelsId, \"channelsId is null\");\n subConnection.sync().unsubscribe(channelsId);\n }\n\n /**\n * Reloads the messaging service by completely destroying the current client\n * and constructing a new one using the assigned {@link MessagingServiceConfig}.\n * This operation resubscribes to all registered channels.\n *\n * @return {@code true} if the reload is successful, {@code false} otherwise\n */\n public boolean reload() {\n redisClient.shutdown();\n\n final boolean state = init();\n // Resubscribe to the registered incoming channels\n if (state && !registeredIncomingChannels.isEmpty())\n subscribe(registeredIncomingChannels.keySet().toArray(new String[0]));\n\n return state;\n }\n\n /**\n * Reloads the messaging service by completely destroying the current client\n * and constructing a new one using the provided {@link MessagingServiceConfig}.\n * This operation resubscribes to all registered channels.\n *\n * @param config a new config to use\n * @return {@code true} if the reload is successful, {@code false} otherwise\n */\n public boolean reload(MessagingServiceConfig config) {\n this.config = config;\n return reload();\n }\n\n /**\n * Completely shutdowns the service and destroys all\n * related thread pools.\n */\n public void shutdown() {\n eventBus.shutdown();\n redisClient.shutdown();\n timeoutsScheduler.shutdownNow();\n }\n\n /**\n * Gets RxPubSub {@link EventBus} used for listening\n * to the reception of pubsub messages.\n * @return the event bus\n */\n public EventBus getEventBus() {\n return eventBus;\n }\n\n /**\n * Registers {@link PubSubMessage} to handle sending and receiving it.\n *\n * @param clazz pubsub message class to register\n * @return {@link MessagingService} instance for chaining purposes\n */\n public MessagingService registerMessageClass(Class<? extends PubSubMessage> clazz) {\n final var classId = AnnotationUtils.getPubSubClassId(clazz);\n final var registeredClass = registeredMessages.get(classId);\n\n if (registeredClass == null) {\n registeredMessages.put(classId, clazz);\n return this;\n }\n\n if (clazz == registeredClass) {\n logger.warn(\"Message class \" + clazz.getSimpleName() + \" already registered!\");\n return this;\n }\n\n logger.warn(\"Unable to register message class \" + clazz.getSimpleName() + \". Message ID \"\n + classId + \" is already taken by \" + registeredClass.getSimpleName() + \" class!\");\n return this;\n }\n\n /**\n * Registers {@link PubSubMessage}s to handle sending and receiving it.\n *\n * @param classes pubsub messages classes to register\n * @return {@link MessagingService} instance for chaining purposes\n */\n @SafeVarargs\n public final MessagingService registerMessageClass(Class<? extends PubSubMessage>... classes) {\n for (var clazz : classes) registerMessageClass(clazz);\n return this;\n }\n\n /**\n * Registers {@link PubSubChannel} as incoming channel to receive messages from it.\n *\n * @param channel pubsub channel to register\n * @return {@link MessagingService} instance for chaining purposes\n */\n public MessagingService registerIncomingChannel(PubSubChannel channel) {\n Objects.requireNonNull(channel , \"channel is null\");\n if (registeredIncomingChannels.get(channel.getId()) != null) {\n logger.warn(\"Channel \" + channel.getId() + \" already registered as incoming channel!\");\n return this;\n }\n registeredIncomingChannels.put(channel.getId(), channel);\n subscribe(channel);\n return this;\n }\n\n /**\n * Registers {@link PubSubChannel} as outgoing channel to publish messages in it.\n *\n * @param channel pubsub channel to register\n * @return {@link MessagingService} instance for chaining purposes\n */\n public MessagingService registerOutgoingChannel(PubSubChannel channel) {\n Objects.requireNonNull(channel , \"channel is null\");\n if (registeredOutgoingChannels.get(channel.getId()) != null) {\n logger.warn(\"Channel \" + channel.getId() + \" already registered as outgoing channel!\");\n return this;\n }\n registeredOutgoingChannels.put(channel.getId(), channel);\n return this;\n }\n\n /**\n * Registers {@link PubSubChannel} as duplex (incoming & outgoing) channel\n * to receive and publish messages with it.\n *\n * @param channel pubsub channel to register\n * @return {@link MessagingService} instance for chaining purposes\n */\n public MessagingService registerDuplexChannel(PubSubChannel channel) {\n return registerIncomingChannel(channel).registerOutgoingChannel(channel);\n }\n\n /**\n * Publishes {@link PubSubMessage} in {@link PubSubChannel}.\n * @param channel channel to publish the message to\n * @param message message to publish\n * @param error returns error state\n */\n public void publishMessage(PubSubChannel channel, PubSubMessage message, Consumer<Boolean> error) {\n if (!registeredOutgoingChannels.containsKey(channel.getId())) {\n if (error != null) {\n error.accept(true);\n }\n throw new IllegalArgumentException(\"Cannot send message\" + message + \" in channel \" + channel.getId()\n + \" since it isn't registered as outgoing channel!\");\n }\n\n ForkJoinPool.commonPool().execute(() -> {\n var classId = registeredMessages.entrySet().stream()\n .filter(e -> e.getValue() == message.getClass())\n .findAny();\n\n if (classId.isEmpty()) {\n if (error != null) {\n error.accept(true);\n }\n throw new IllegalArgumentException(\"Cannot send message \" + message + \" since provided message class \"\n + message.getClass() + \" isn't registered!\");\n }\n\n JsonObject jsonMessage = setMessageClass(\n GSON.toJsonTree(message).getAsJsonObject(),\n classId.get().getKey()\n );\n\n pubConnection.async()\n .publish(channel.getId(), GSON.toJson(jsonMessage))\n .whenComplete((reached, ex) -> {\n if (ex != null) {\n logger.error(\"Failed to publish message \" + message, ex);\n if (error != null) {\n error.accept(true);\n }\n return;\n }\n if (error != null) {\n error.accept(false);\n }\n });\n });\n }\n\n /**\n * Publishes {@link PubSubMessage} in {@link PubSubChannel}.\n *\n * @param channel channel to publish the message to\n * @param message message to publish\n */\n public void publishMessage(PubSubChannel channel, PubSubMessage message) {\n publishMessage(channel, message, (Consumer<Boolean>) null);\n }\n\n /**\n * Publishes {@link PubSubMessage} in {@link PubSubChannel} and waits for callback.\n *\n * @param channel channel to publish the message to\n * @param message message to publish\n * @param handler callback message handler\n */\n public <T extends PubSubMessage> void publishMessage(\n PubSubChannel channel, PubSubMessage message, CallbackHandler<T> handler\n ) {\n var wrapper = new CallbackHandlerWrapper<>(handler, timeoutsScheduler);\n awaitingCallbacks.put(message.getMessageId(), wrapper);\n publishMessage(channel, message, error -> {\n if (!error) return;\n awaitingCallbacks.remove(message.getMessageId());\n wrapper.exceptionally(new ConnectException());\n });\n }\n}"
},
{
"identifier": "PubSubChannel",
"path": "src/main/java/io/github/feniksovich/rxpubsub/model/PubSubChannel.java",
"snippet": "public class PubSubChannel {\n\n private static final Pattern VALID_IDENTIFIER_REGEX = Pattern.compile(\"[a-z0-9/\\\\-_]*\");\n\n private final String namespace;\n private final String name;\n\n private PubSubChannel(String namespace, String name) {\n this.namespace = namespace;\n this.name = name;\n }\n\n /**\n * Creates a new PubSubChannel instance with the specified namespace and name.\n *\n * @param namespace the namespace of the channel\n * @param name the name of the channel\n * @return a new PubSubChannel instance\n * @throws IllegalArgumentException if the namespace or name is null or empty, or if they are not valid\n */\n public static PubSubChannel from(String namespace, String name) {\n Preconditions.checkArgument(!Strings.isNullOrEmpty(namespace), \"namespace is null or empty\");\n Preconditions.checkArgument(!Strings.isNullOrEmpty(name), \"name is null or empty\");\n Preconditions.checkArgument(\n VALID_IDENTIFIER_REGEX.matcher(namespace).matches(),\n \"namespace is not valid\"\n );\n Preconditions.checkArgument(\n VALID_IDENTIFIER_REGEX.matcher(name).matches(),\n \"name is not valid\"\n );\n return new PubSubChannel(namespace, name);\n }\n\n /**\n * Gets the ID of the pubsub channel.\n *\n * @return the ID of the channel in the format \"namespace:name\"\n */\n public String getId() {\n return namespace + \":\" + name;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n PubSubChannel that = (PubSubChannel) o;\n return Objects.equals(namespace, that.namespace) && Objects.equals(name, that.name);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(namespace, name);\n }\n\n @Override\n public String toString() {\n return \"PubSubChannel{\" +\n \"namespace='\" + namespace + '\\'' +\n \", name='\" + name + '\\'' +\n '}';\n }\n}"
},
{
"identifier": "PubSubMessage",
"path": "src/main/java/io/github/feniksovich/rxpubsub/model/PubSubMessage.java",
"snippet": "public abstract class PubSubMessage {\n\n @SerializedName(ReservedFields.MESSAGE_ID_FIELD)\n private String messageId = UUID.randomUUID().toString();\n\n @SerializedName(ReservedFields.MESSAGE_RESPONSE_TO_ID_FIELD)\n protected String responseTo;\n\n public String getMessageId() {\n return messageId;\n }\n\n /**\n * Sets a custom message ID of pre-generated one instead.\n * @param messageId ID to set\n */\n public void setMessageId(String messageId) {\n this.messageId = messageId;\n }\n\n /**\n * Returns the source message ID that this message responds to.\n * @return source message ID if present\n */\n public Optional<String> getResponseTo() {\n return Optional.ofNullable(responseTo);\n }\n\n /**\n * Sets the source message ID that this message responds to.\n * @param responseTo source message ID\n */\n public void setResponseTo(String responseTo) {\n this.responseTo = responseTo;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n PubSubMessage that = (PubSubMessage) o;\n return Objects.equals(messageId, that.messageId) && Objects.equals(responseTo, that.responseTo);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(messageId, responseTo);\n }\n}"
}
] | import io.github.feniksovich.rxpubsub.MessagingService;
import io.github.feniksovich.rxpubsub.model.PubSubChannel;
import io.github.feniksovich.rxpubsub.model.PubSubMessage;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.Consumer;
import java.util.function.Function; | 4,101 | package io.github.feniksovich.rxpubsub.event;
public class EventBusImpl implements EventBus {
private final MessagingService messagingService;
private final ConcurrentHashMap<Class<? extends PubSubMessage>, List<ReceiptListener>> handlers = new ConcurrentHashMap<>();
private final ConcurrentHashMap<Class<? extends PubSubMessage>, List<ReceiptListener>> respondingHandlers = new ConcurrentHashMap<>();
private final ExecutorService listenersExecutor = Executors.newCachedThreadPool();
public EventBusImpl(MessagingService messagingService) {
this.messagingService = messagingService;
}
public <T extends PubSubMessage> EventBus registerReceiptListener(Class<T> messageClass, Consumer<T> handler) {
// Create new listener object
final var listener = new ReceiptListener() {
@Override
public void execute(PubSubMessage message) {
handler.accept(messageClass.cast(message));
}
};
registerListener(messageClass, listener, handlers);
return this;
}
public <T extends PubSubMessage> EventBus registerRespondingListener( | package io.github.feniksovich.rxpubsub.event;
public class EventBusImpl implements EventBus {
private final MessagingService messagingService;
private final ConcurrentHashMap<Class<? extends PubSubMessage>, List<ReceiptListener>> handlers = new ConcurrentHashMap<>();
private final ConcurrentHashMap<Class<? extends PubSubMessage>, List<ReceiptListener>> respondingHandlers = new ConcurrentHashMap<>();
private final ExecutorService listenersExecutor = Executors.newCachedThreadPool();
public EventBusImpl(MessagingService messagingService) {
this.messagingService = messagingService;
}
public <T extends PubSubMessage> EventBus registerReceiptListener(Class<T> messageClass, Consumer<T> handler) {
// Create new listener object
final var listener = new ReceiptListener() {
@Override
public void execute(PubSubMessage message) {
handler.accept(messageClass.cast(message));
}
};
registerListener(messageClass, listener, handlers);
return this;
}
public <T extends PubSubMessage> EventBus registerRespondingListener( | Class<T> messageClass, PubSubChannel channel, Function<T, PubSubMessage> handler | 1 | 2023-10-09 19:05:31+00:00 | 8k |
openpilot-hub/devpilot-intellij | src/main/java/com/zhongan/devpilot/gui/toolwindows/chat/DevPilotChatToolWindowService.java | [
{
"identifier": "BasicEditorAction",
"path": "src/main/java/com/zhongan/devpilot/actions/editor/popupmenu/BasicEditorAction.java",
"snippet": "public abstract class BasicEditorAction extends AnAction {\n\n BasicEditorAction(\n @Nullable @NlsActions.ActionText String text,\n @Nullable @NlsActions.ActionDescription String description,\n @Nullable Icon icon) {\n super(text, description, icon);\n PopupMenuEditorActionGroupUtil.registerOrReplaceAction(this);\n }\n\n protected abstract void actionPerformed(Project project, Editor editor, String selectedText);\n\n public void actionPerformed(@NotNull AnActionEvent event) {\n var project = event.getProject();\n var editor = event.getData(PlatformDataKeys.EDITOR);\n if (editor != null && project != null) {\n actionPerformed(project, editor, editor.getSelectionModel().getSelectedText());\n }\n }\n\n public void fastAction(Project project, Editor editor, String selectedText) {\n actionPerformed(project, editor, selectedText);\n }\n\n public void update(AnActionEvent event) {\n Project project = event.getProject();\n Editor editor = event.getData(PlatformDataKeys.EDITOR);\n boolean menuAllowed = false;\n if (editor != null && project != null) {\n menuAllowed = editor.getSelectionModel().getSelectedText() != null;\n }\n event.getPresentation().setEnabled(menuAllowed);\n }\n\n}"
},
{
"identifier": "PromptConst",
"path": "src/main/java/com/zhongan/devpilot/constant/PromptConst.java",
"snippet": "public class PromptConst {\n\n private PromptConst() {\n }\n\n public static final String RESPONSE_FORMAT = \"You are a coding expert.\\n\" +\n \"You must obey ALL of the following rules:\\n\\n\" +\n \"- quote variable name with single backtick such as `name`.\\n\" +\n \"- quote code block with triple backticks such as ```...```\";\n\n public static final String ANSWER_IN_CHINESE = \"\\nPlease answer in Chinese.\";\n\n public static final String GENERATE_COMMIT = \"Summarize the git diff with a concise and descriptive commit message. Adopt the imperative mood, present tense, active voice, and include relevant verbs. Remember that your entire response will be directly used as the git commit message.\";\n \n public final static String MOCK_WEB_MVC = \"please use MockMvc to mock web requests, \";\n\n}"
},
{
"identifier": "EditorActionEnum",
"path": "src/main/java/com/zhongan/devpilot/enums/EditorActionEnum.java",
"snippet": "public enum EditorActionEnum {\n PERFORMANCE_CHECK(\"devpilot.action.performance.check\", \"Performance check in the following code\",\n \"{{selectedCode}}\\nGiving the code above, please fix any performance issues.\" +\n \"\\nRemember you are very familiar with performance optimization.\\n\"),\n\n GENERATE_COMMENTS(\"devpilot.action.generate.comments\", \"Generate comments in the following code\",\n \"{{selectedCode}}\\nGiving the code above, please generate code comments, return code with comments.\"),\n\n GENERATE_TESTS(\"devpilot.action.generate.tests\", \"Generate Tests in the following code\",\n \"{{selectedCode}}\\nGiving the {{language:unknown}} code above, \" +\n \"please help to generate {{testFramework:suitable}} test cases for it, \" +\n \"mocking test data with {{mockFramework:suitable mock framework}} if necessary, \" +\n \"{{additionalMockPrompt:}}\" +\n \"be aware that if the code is untestable, \" +\n \"please state it and give suggestions instead.\"),\n\n FIX_THIS(\"devpilot.action.fix\", \"Fix This in the following code\",\n \"{{selectedCode}}\\nGiving the code above, please help to fix it:\\n\\n\" +\n \"- Fix any typos or grammar issues.\\n\" +\n \"- Use better names as replacement to magic numbers or arbitrary acronyms.\\n\" +\n \"- Simplify the code so that it's more strait forward and easy to understand.\\n\" +\n \"- Optimize it for performance reasons.\\n\" +\n \"- Refactor it using best practice in software engineering.\\n\" + \"\\nMust only provide the code to be fixed and explain why it should be fixed.\\n\"),\n\n REVIEW_CODE(\"devpilot.action.review\", \"Review code in the following code\",\n \"{{selectedCode}}\\nGiving the code above, please review the code line by line:\\n\\n\" +\n \"- Think carefully, you should be extremely careful.\\n\" +\n \"- Find out if any bugs exists.\\n\" +\n \"- Reveal any bad smell in the code.\\n\" +\n \"- Give optimization or best practice suggestion.\\n\"),\n\n EXPLAIN_THIS(\"devpilot.action.explain\", \"Explain this in the following code\",\n \"{{selectedCode}}\\nGiving the code above, please explain it in detail, line by line.\\n\");\n\n private final String label;\n\n private final String userMessage;\n\n private final String prompt;\n\n EditorActionEnum(String label, String userMessage, String prompt) {\n this.label = label;\n this.userMessage = userMessage;\n this.prompt = prompt;\n }\n\n public static EditorActionEnum getEnumByLabel(String label) {\n if (Objects.isNull(label)) {\n return null;\n }\n for (EditorActionEnum type : EditorActionEnum.values()) {\n if (type.getLabel().equals(label)) {\n return type;\n }\n }\n return null;\n }\n\n public String getLabel() {\n return label;\n }\n\n public String getPrompt() {\n return prompt;\n }\n\n public String getUserMessage() {\n return userMessage;\n }\n}"
},
{
"identifier": "SessionTypeEnum",
"path": "src/main/java/com/zhongan/devpilot/enums/SessionTypeEnum.java",
"snippet": "public enum SessionTypeEnum {\n\n INDEPENDENT(0, \"independent session\"),\n MULTI_TURN(1, \"multi-turn session \");\n\n private final Integer code;\n\n private final String desc;\n\n SessionTypeEnum(Integer code, String desc) {\n this.code = code;\n this.desc = desc;\n }\n\n public Integer getCode() {\n return code;\n }\n\n public String getDesc() {\n return desc;\n }\n\n public static SessionTypeEnum getEnumByCode(Integer code) {\n if (Objects.isNull(code)) {\n return MULTI_TURN;\n }\n for (SessionTypeEnum type : SessionTypeEnum.values()) {\n if (type.getCode().equals(code)) {\n return type;\n }\n }\n return MULTI_TURN;\n }\n}"
},
{
"identifier": "LlmProvider",
"path": "src/main/java/com/zhongan/devpilot/integrations/llms/LlmProvider.java",
"snippet": "public interface LlmProvider {\n\n String chatCompletion(Project project, DevPilotChatCompletionRequest chatCompletionRequest, Consumer<String> callback);\n\n DevPilotChatCompletionResponse chatCompletionSync(DevPilotChatCompletionRequest chatCompletionRequest);\n\n void interruptSend();\n\n default void restoreMessage(MessageModel messageModel) {\n // default not restore message\n }\n\n default EventSource buildEventSource(Request request,\n DevPilotChatToolWindowService service, Consumer<String> callback) {\n var time = System.currentTimeMillis();\n var result = new StringBuilder();\n var client = OkhttpUtils.getClient();\n\n return EventSources.createFactory(client).newEventSource(request, new EventSourceListener() {\n @Override\n public void onEvent(@NotNull EventSource eventSource, @Nullable String id, @Nullable String type, @NotNull String data) {\n if (data.equals(\"[DONE]\")) {\n return;\n }\n\n var response = JsonUtils.fromJson(data, DevPilotSuccessStreamingResponse.class);\n\n if (response == null) {\n interruptSend();\n return;\n }\n\n var choice = response.getChoices().get(0);\n var finishReason = choice.getFinishReason();\n\n if (choice.getDelta().getContent() != null) {\n result.append(choice.getDelta().getContent());\n }\n\n var streaming = !\"stop\".equals(finishReason);\n\n var assistantMessage = MessageModel\n .buildAssistantMessage(response.getId(), time, result.toString(), streaming);\n\n restoreMessage(assistantMessage);\n service.callWebView(assistantMessage);\n\n if (!streaming) {\n service.addMessage(assistantMessage);\n var devPilotMessage = new DevPilotMessage();\n devPilotMessage.setId(response.getId());\n devPilotMessage.setRole(\"assistant\");\n devPilotMessage.setContent(result.toString());\n service.addRequestMessage(devPilotMessage);\n if (callback != null) {\n callback.accept(result.toString());\n }\n }\n }\n\n @Override\n public void onFailure(@NotNull EventSource eventSource, @Nullable Throwable t, @Nullable Response response) {\n var message = \"Chat completion failed\";\n\n if (response != null && response.code() == 401) {\n message = \"Chat completion failed: Unauthorized\";\n }\n\n if (t != null) {\n if (t.getMessage().contains(\"Socket closed\")) {\n return;\n }\n\n message = \"Chat completion failed: \" + t.getMessage();\n }\n\n var assistantMessage = MessageModel\n .buildAssistantMessage(UUID.randomUUID().toString(), time, message, false);\n\n service.callWebView(assistantMessage);\n service.addMessage(assistantMessage);\n }\n });\n }\n}"
},
{
"identifier": "LlmProviderFactory",
"path": "src/main/java/com/zhongan/devpilot/integrations/llms/LlmProviderFactory.java",
"snippet": "@Service\npublic final class LlmProviderFactory {\n\n public LlmProvider getLlmProvider(Project project) {\n var settings = DevPilotLlmSettingsState.getInstance();\n String selectedModel = settings.getSelectedModel();\n ModelServiceEnum modelServiceEnum = ModelServiceEnum.fromName(selectedModel);\n\n switch (modelServiceEnum) {\n case OPENAI:\n return project.getService(OpenAIServiceProvider.class);\n case LLAMA:\n return project.getService(LlamaServiceProvider.class);\n case AIGATEWAY:\n return project.getService(AIGatewayServiceProvider.class);\n }\n\n return project.getService(AIGatewayServiceProvider.class);\n }\n\n}"
},
{
"identifier": "DevPilotChatCompletionRequest",
"path": "src/main/java/com/zhongan/devpilot/integrations/llms/entity/DevPilotChatCompletionRequest.java",
"snippet": "public class DevPilotChatCompletionRequest {\n\n String model;\n\n List<DevPilotMessage> messages = new ArrayList<>();\n\n boolean stream = Boolean.FALSE;\n\n public String getModel() {\n return model;\n }\n\n public void setModel(String model) {\n this.model = model;\n }\n\n public List<DevPilotMessage> getMessages() {\n return messages;\n }\n\n public void setMessages(List<DevPilotMessage> messages) {\n this.messages = messages;\n }\n\n public boolean isStream() {\n return stream;\n }\n\n public void setStream(boolean stream) {\n this.stream = stream;\n }\n\n}"
},
{
"identifier": "DevPilotMessage",
"path": "src/main/java/com/zhongan/devpilot/integrations/llms/entity/DevPilotMessage.java",
"snippet": "public class DevPilotMessage {\n @JsonIgnore\n private String id;\n\n private String role;\n\n private String content;\n\n public String getId() {\n return id;\n }\n\n public void setId(String id) {\n this.id = id;\n }\n\n public String getRole() {\n return role;\n }\n\n public void setRole(String role) {\n this.role = role;\n }\n\n public String getContent() {\n return content;\n }\n\n public void setContent(String content) {\n this.content = content;\n }\n\n}"
},
{
"identifier": "DevPilotMessageBundle",
"path": "src/main/java/com/zhongan/devpilot/util/DevPilotMessageBundle.java",
"snippet": "public class DevPilotMessageBundle extends DynamicBundle {\n\n private static final DevPilotMessageBundle INSTANCE = new DevPilotMessageBundle();\n\n private static ResourceBundle bundleEn;\n\n private static ResourceBundle bundleCN;\n\n private static final String pathToBundle = \"messages.devpilot\";\n\n private DevPilotMessageBundle() {\n super(pathToBundle);\n }\n\n static {\n bundleEn = ResourceBundle.getBundle(pathToBundle, Locale.ENGLISH);\n bundleCN = ResourceBundle.getBundle(pathToBundle, Locale.CHINA);\n }\n\n public static String get(@NotNull @PropertyKey(resourceBundle = \"messages.devpilot\") String key) {\n Integer languageIndex = LanguageSettingsState.getInstance().getLanguageIndex();\n if (languageIndex == 1) {\n return bundleCN.getString(key);\n }\n return bundleEn.getString(key);\n }\n\n public static String get(@NotNull @PropertyKey(resourceBundle = \"messages.devpilot\") String key, Object... params) {\n return INSTANCE.getMessage(key, params);\n }\n\n public static String getFromBundleEn(@NotNull @PropertyKey(resourceBundle = \"messages.devpilot\") String key) {\n return bundleEn.getString(key);\n }\n\n}"
},
{
"identifier": "JsonUtils",
"path": "src/main/java/com/zhongan/devpilot/util/JsonUtils.java",
"snippet": "public class JsonUtils {\n private final static ObjectMapper objectMapper = new ObjectMapper();\n\n public static String toJson(Object object) {\n try {\n return objectMapper.writeValueAsString(object);\n } catch (Exception e) {\n return null;\n }\n }\n\n public static <T> T fromJson(String json, Class<T> clazz) {\n try {\n return objectMapper.readValue(json, clazz);\n } catch (Exception e) {\n return null;\n }\n }\n}"
},
{
"identifier": "MessageUtil",
"path": "src/main/java/com/zhongan/devpilot/util/MessageUtil.java",
"snippet": "public class MessageUtil {\n\n public static DevPilotMessage createMessage(String id, String role, String content) {\n DevPilotMessage message = new DevPilotMessage();\n message.setId(id);\n message.setRole(role);\n message.setContent(content);\n return message;\n }\n\n public static DevPilotMessage createUserMessage(String content, String id) {\n return createMessage(id, \"user\", content);\n }\n\n public static DevPilotMessage createSystemMessage(String content) {\n return createMessage(\"-1\", \"system\", content);\n }\n\n}"
},
{
"identifier": "JavaCallModel",
"path": "src/main/java/com/zhongan/devpilot/webview/model/JavaCallModel.java",
"snippet": "public class JavaCallModel {\n private String command;\n\n private Object payload;\n\n public String getCommand() {\n return command;\n }\n\n public void setCommand(String command) {\n this.command = command;\n }\n\n public Object getPayload() {\n return payload;\n }\n\n public void setPayload(Object payload) {\n this.payload = payload;\n }\n}"
},
{
"identifier": "LocaleModel",
"path": "src/main/java/com/zhongan/devpilot/webview/model/LocaleModel.java",
"snippet": "public class LocaleModel {\n private String locale;\n\n public LocaleModel(String locale) {\n this.locale = locale;\n }\n\n public String getLocale() {\n return locale;\n }\n\n public void setLocale(String locale) {\n this.locale = locale;\n }\n}"
},
{
"identifier": "MessageModel",
"path": "src/main/java/com/zhongan/devpilot/webview/model/MessageModel.java",
"snippet": "@JsonIgnoreProperties(ignoreUnknown = true)\npublic class MessageModel {\n private String id;\n\n private Long time;\n\n private String role;\n\n private String content;\n\n private String username;\n\n private String avatar;\n\n private Boolean streaming;\n\n private CodeReferenceModel codeRef;\n\n public static MessageModel buildCodeMessage(String id, Long time, String content,\n String username, CodeReferenceModel codeReference) {\n MessageModel messageModel = new MessageModel();\n messageModel.setId(id);\n messageModel.setTime(time);\n messageModel.setRole(\"user\");\n messageModel.setContent(content);\n messageModel.setUsername(username);\n messageModel.setAvatar(null);\n messageModel.setStreaming(false);\n messageModel.setCodeRef(codeReference);\n return messageModel;\n }\n\n public static MessageModel buildUserMessage(String id, Long time, String content, String username) {\n return buildCodeMessage(id, time, content, username, null);\n }\n\n public static MessageModel buildErrorMessage(String content) {\n return buildAssistantMessage(UUID.randomUUID().toString(), System.currentTimeMillis(), content, false);\n }\n\n public static MessageModel buildAssistantMessage(String id, Long time, String content, boolean streaming) {\n MessageModel messageModel = new MessageModel();\n messageModel.setId(id);\n messageModel.setTime(time);\n messageModel.setRole(\"assistant\");\n messageModel.setContent(content);\n messageModel.setUsername(null);\n messageModel.setAvatar(null);\n messageModel.setStreaming(streaming);\n messageModel.setCodeRef(null);\n return messageModel;\n }\n\n public static MessageModel buildDividerMessage() {\n MessageModel messageModel = new MessageModel();\n messageModel.setId(\"-1\");\n messageModel.setTime(System.currentTimeMillis());\n messageModel.setRole(\"divider\");\n messageModel.setContent(null);\n messageModel.setUsername(null);\n messageModel.setAvatar(null);\n messageModel.setStreaming(false);\n return messageModel;\n }\n\n public static MessageModel buildLoadingMessage() {\n MessageModel messageModel = new MessageModel();\n messageModel.setId(\"-1\");\n messageModel.setTime(System.currentTimeMillis());\n messageModel.setRole(\"assistant\");\n messageModel.setContent(\"...\");\n messageModel.setUsername(null);\n messageModel.setAvatar(null);\n messageModel.setStreaming(true);\n return messageModel;\n }\n\n public String getId() {\n return id;\n }\n\n public void setId(String id) {\n this.id = id;\n }\n\n public Long getTime() {\n return time;\n }\n\n public void setTime(Long time) {\n this.time = time;\n }\n\n public String getRole() {\n return role;\n }\n\n public void setRole(String role) {\n this.role = role;\n }\n\n public String getContent() {\n return content;\n }\n\n public void setContent(String content) {\n this.content = content;\n }\n\n public String getUsername() {\n return username;\n }\n\n public void setUsername(String username) {\n this.username = username;\n }\n\n public String getAvatar() {\n return avatar;\n }\n\n public void setAvatar(String avatar) {\n this.avatar = avatar;\n }\n\n public Boolean getStreaming() {\n return streaming;\n }\n\n public void setStreaming(Boolean streaming) {\n this.streaming = streaming;\n }\n\n public CodeReferenceModel getCodeRef() {\n return codeRef;\n }\n\n public void setCodeRef(CodeReferenceModel codeRef) {\n this.codeRef = codeRef;\n }\n}"
},
{
"identifier": "ThemeModel",
"path": "src/main/java/com/zhongan/devpilot/webview/model/ThemeModel.java",
"snippet": "public class ThemeModel {\n private String theme;\n\n public ThemeModel(String theme) {\n this.theme = theme;\n }\n\n public String getTheme() {\n return theme;\n }\n\n public void setTheme(String theme) {\n this.theme = theme;\n }\n}"
}
] | import com.intellij.openapi.actionSystem.ActionManager;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.components.Service;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.project.Project;
import com.zhongan.devpilot.actions.editor.popupmenu.BasicEditorAction;
import com.zhongan.devpilot.constant.PromptConst;
import com.zhongan.devpilot.enums.EditorActionEnum;
import com.zhongan.devpilot.enums.SessionTypeEnum;
import com.zhongan.devpilot.integrations.llms.LlmProvider;
import com.zhongan.devpilot.integrations.llms.LlmProviderFactory;
import com.zhongan.devpilot.integrations.llms.entity.DevPilotChatCompletionRequest;
import com.zhongan.devpilot.integrations.llms.entity.DevPilotMessage;
import com.zhongan.devpilot.util.DevPilotMessageBundle;
import com.zhongan.devpilot.util.JsonUtils;
import com.zhongan.devpilot.util.MessageUtil;
import com.zhongan.devpilot.webview.model.JavaCallModel;
import com.zhongan.devpilot.webview.model.LocaleModel;
import com.zhongan.devpilot.webview.model.MessageModel;
import com.zhongan.devpilot.webview.model.ThemeModel;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer; | 4,958 | package com.zhongan.devpilot.gui.toolwindows.chat;
@Service
public final class DevPilotChatToolWindowService {
private final Project project;
private final DevPilotChatToolWindow devPilotChatToolWindow;
private LlmProvider llmProvider;
private final List<MessageModel> historyMessageList = new ArrayList<>();
| package com.zhongan.devpilot.gui.toolwindows.chat;
@Service
public final class DevPilotChatToolWindowService {
private final Project project;
private final DevPilotChatToolWindow devPilotChatToolWindow;
private LlmProvider llmProvider;
private final List<MessageModel> historyMessageList = new ArrayList<>();
| private final List<DevPilotMessage> historyRequestMessageList = new ArrayList<>(); | 7 | 2023-11-29 06:37:51+00:00 | 8k |
Gaia3D/mago-3d-tiler | tiler/src/main/java/com/gaia3d/command/PointCloudProcessModel.java | [
{
"identifier": "FormatType",
"path": "core/src/main/java/com/gaia3d/basic/types/FormatType.java",
"snippet": "@Getter\npublic enum FormatType {\n // 3D Formats\n FBX(\"fbx\", true),\n GLTF(\"gltf\", true),\n GLB(\"glb\", true),\n KML(\"kml\", false),\n COLLADA(\"dae\", false),\n MAX_3DS(\"3ds\", false),\n MAX_ASE(\"ase\", false),\n OBJ(\"obj\", false),\n IFC(\"ifc\", false),\n CITY_GML(\"gml\", false),\n MODO(\"lxo\", false),\n LWO(\"lwo\", false),\n LWS(\"lws\", false),\n DirectX(\"x\", false),\n // 2D Formats,\n SHP(\"shp\", false),\n GEOJSON(\"geojson\", false),\n JSON(\"json\", false),\n LAS(\"las\", false),\n LAZ(\"laz\", false),\n // OUTPUT Formats\n B3DM(\"b3dm\", true),\n I3DM(\"i3dm\", true),\n PNTS(\"pnts\", true),\n TEMP(\"mgb\", false);\n\n final String extension;\n final boolean yUpAxis;\n\n FormatType(String extension, boolean yUpAxis) {\n this.extension = extension;\n this.yUpAxis = yUpAxis;\n }\n\n public static FormatType fromExtension(String extension) {\n return Arrays.stream(FormatType.values())\n .filter(type -> type.getExtension().equals(extension.toLowerCase()))\n .findFirst()\n .orElse(null);\n }\n}"
},
{
"identifier": "PointCloudFileLoader",
"path": "tiler/src/main/java/com/gaia3d/converter/PointCloudFileLoader.java",
"snippet": "@Slf4j\npublic class PointCloudFileLoader implements FileLoader {\n private final LasConverter converter;\n private final CommandLine command;\n\n public PointCloudFileLoader(CommandLine command, LasConverter converter) {\n this.command = command;\n this.converter = converter;\n }\n\n public List<GaiaPointCloud> loadPointCloud(File input) {\n return converter.load(input);\n }\n\n public List<File> loadFiles() {\n File inputFile = new File(command.getOptionValue(ProcessOptions.INPUT.getArgName()));\n String inputExtension = command.getOptionValue(ProcessOptions.INPUT_TYPE.getArgName());\n boolean recursive = command.hasOption(ProcessOptions.RECURSIVE.getArgName());\n FormatType formatType = FormatType.fromExtension(inputExtension);\n String[] extensions = getExtensions(formatType);\n return (ArrayList<File>) FileUtils.listFiles(inputFile, extensions, recursive);\n }\n\n public List<TileInfo> loadTileInfo(File file) {\n Path outputPath = new File(command.getOptionValue(ProcessOptions.OUTPUT.getArgName())).toPath();\n List<TileInfo> tileInfos = new ArrayList<>();\n file = new File(file.getParent(), file.getName());\n List<GaiaPointCloud> pointClouds = loadPointCloud(file);\n for (GaiaPointCloud pointCloud : pointClouds) {\n if (pointCloud == null) {\n log.error(\"Failed to load scene: {}\", file.getAbsolutePath());\n return null;\n } else {\n TileInfo tileInfo = TileInfo.builder()\n .pointCloud(pointCloud)\n .outputPath(outputPath)\n .build();\n tileInfos.add(tileInfo);\n }\n }\n return tileInfos;\n }\n\n private String[] getExtensions(FormatType formatType) {\n return new String[]{formatType.getExtension().toLowerCase(), formatType.getExtension().toUpperCase()};\n }\n}"
},
{
"identifier": "LasConverter",
"path": "tiler/src/main/java/com/gaia3d/converter/pointcloud/LasConverter.java",
"snippet": "@Slf4j\npublic class LasConverter {\n private final CommandLine command;\n private final CoordinateReferenceSystem crs;\n\n public LasConverter(CommandLine command, CoordinateReferenceSystem crs) {\n this.command = command;\n this.crs = crs;\n }\n\n public List<GaiaPointCloud> load(String path) {\n return convert(new File(path));\n }\n\n public List<GaiaPointCloud> load(File file) {\n return convert(file);\n }\n\n public List<GaiaPointCloud> load(Path path) {\n return convert(path.toFile());\n }\n\n private List<GaiaPointCloud> convert(File file) {\n List<GaiaPointCloud> pointClouds = new ArrayList<>();\n GaiaPointCloud pointCloud = new GaiaPointCloud();\n List<GaiaVertex> vertices = pointCloud.getVertices();\n\n LASReader reader = new LASReader(file);\n LASHeader header = reader.getHeader();\n\n log.info(\"[LoadFile] Loading a pointcloud file. : {}\", file.getAbsolutePath());\n\n Iterable<LASPoint> pointIterable = reader.getPoints();\n GaiaBoundingBox boundingBox = pointCloud.getGaiaBoundingBox();\n\n double xScaleFactor = header.getXScaleFactor();\n double xOffset = header.getXOffset();\n double yScaleFactor = header.getYScaleFactor();\n double yOffset = header.getYOffset();\n double zScaleFactor = header.getZScaleFactor();\n double zOffset = header.getZOffset();\n\n pointIterable.forEach(point -> {\n double x = point.getX() * xScaleFactor + xOffset;\n double y = point.getY() * yScaleFactor + yOffset;\n double z = point.getZ() * zScaleFactor + zOffset;\n //Vector3d position = new Vector3d(x, y, z);\n\n ProjCoordinate coordinate = new ProjCoordinate(x, y, z);\n ProjCoordinate transformedCoordinate = GlobeUtils.transform(crs, coordinate);\n\n Vector3d position = new Vector3d(transformedCoordinate.x, transformedCoordinate.y, z);\n\n double red = (double) point.getRed() / 65535;\n double green = (double) point.getGreen() / 65535;\n double blue = (double) point.getBlue() / 65535;\n\n byte[] rgb = new byte[3];\n rgb[0] = (byte) (red * 255);\n rgb[1] = (byte) (green * 255);\n rgb[2] = (byte) (blue * 255);\n\n GaiaVertex vertex = new GaiaVertex();\n //vertex.setPosition(new Vector3d(x, y, z));\n vertex.setPosition(position);\n vertex.setColor(rgb);\n vertex.setBatchId(0);\n vertices.add(vertex);\n boundingBox.addPoint(position);\n });\n\n // BatchId setting\n /*for (int i = 0; i < vertices.size(); i++) {\n vertices.get(i).setBatchId(i);\n }*/\n\n // randomize arrays\n Collections.shuffle(vertices);\n //var divided = pointCloud.divide();\n //pointClouds.add(divided.get(0));\n\n pointClouds.add(pointCloud);\n return pointClouds;\n }\n}"
},
{
"identifier": "PointCloudProcessFlow",
"path": "tiler/src/main/java/com/gaia3d/process/PointCloudProcessFlow.java",
"snippet": "@Slf4j\n@AllArgsConstructor\npublic class PointCloudProcessFlow implements Process {\n private List<PreProcess> preProcesses;\n private TileProcess tileProcess;\n private List<PostProcess> postProcesses;\n\n public void process(FileLoader fileLoader) throws IOException {\n List<TileInfo> tileInfos = new ArrayList<>();\n log.info(\"[process] Start loading tile infos.\");\n preprocess(fileLoader, tileInfos);\n Tileset tileset = tileprocess(tileInfos);\n postprocess(tileset);\n if (!tileInfos.isEmpty()) {\n tileInfos.get(0).deleteTemp();\n }\n }\n\n private void preprocess(FileLoader fileLoader, List<TileInfo> tileInfos) {\n List<File> fileList = fileLoader.loadFiles();\n log.info(\"[pre-process] Total file counts : {}\", fileList.size());\n int count = 0;\n int size = fileList.size();\n for (File file : fileList) {\n count++;\n log.info(\"[load] : {}/{} : {}\", count, size, file);\n List<TileInfo> tileInfoResult = fileLoader.loadTileInfo(file);\n int serial = 0;\n for (TileInfo tileInfo : tileInfoResult) {\n if (tileInfo != null) {\n log.info(\"[{}/{}][{}/{}] load tile...\", count, size, serial, tileInfoResult.size());\n for (PreProcess preProcessors : preProcesses) {\n preProcessors.run(tileInfo);\n }\n serial++;\n tileInfos.add(tileInfo);\n }\n }\n }\n }\n\n private Tileset tileprocess(List<TileInfo> tileInfos) {\n Tiler tiler = (Tiler) tileProcess;\n Tileset tileset = tiler.run(tileInfos);\n tiler.writeTileset(tileset);\n return tileset;\n }\n\n private void postprocess(Tileset tileset) {\n List<ContentInfo> contentInfos = tileset.findAllContentInfo();\n int count = 0;\n int size = contentInfos.size();\n for (ContentInfo contentInfo : contentInfos) {\n count++;\n log.info(\"[post-process][{}/{}] content-info : {}\", count, size, contentInfo.getName());\n for (PostProcess postProcessor : postProcesses) {\n postProcessor.run(contentInfo);\n }\n }\n }\n}"
},
{
"identifier": "ProcessOptions",
"path": "tiler/src/main/java/com/gaia3d/process/ProcessOptions.java",
"snippet": "@AllArgsConstructor\n@Getter\npublic enum ProcessOptions {\n HELP(\"help\", \"h\", \"help\", false, \"print this message\"),\n VERSION(\"version\", \"v\", \"version\", false, \"print version\"),\n QUIET(\"quiet\", \"q\", \"quiet\", false, \"quiet mode\"),\n LOG(\"log\", \"l\", \"log\", true, \"output log file path\"),\n INPUT(\"input\", \"i\", \"input\", true, \"input file path\"),\n OUTPUT(\"output\", \"o\", \"output\", true, \"output file path\"),\n INPUT_TYPE(\"inputType\", \"it\", \"inputType\", true, \"input file type (kml, 3ds, obj, gltf, etc...)\"),\n OUTPUT_TYPE(\"outputType\", \"ot\", \"outputType\", true, \"output file type\"),\n CRS(\"crs\", \"c\", \"crs\", true,\"Coordinate Reference Systems, only epsg code (4326, 3857, etc...)\"),\n PROJ4(\"proj\", \"p\", \"proj\", true, \"proj4 parameters (ex: +proj=tmerc +la...)\"),\n\n // 3D Options\n RECURSIVE(\"recursive\", \"r\", \"recursive\", false, \"deep directory exploration\"),\n //SWAP_YZ(\"swapYZ\", \"yz\", \"swapYZ\", false, \"swap vertices axis YZ\"),\n REVERSE_TEXCOORD(\"reverseTexCoord\", \"rt\", \"reverseTexCoord\", false, \"texture y-axis coordinate reverse\"),\n MULTI_THREAD(\"multiThread\", \"mt\", \"multiThread\", false, \"multi thread mode\"),\n MULTI_THREAD_COUNT(\"multiThreadCount\", \"mc\", \"multiThreadCount\", true, \"multi thread count (Default: 8)\"),\n PNG_TEXTURE(\"pngTexture\", \"pt\", \"pngTexture\", false, \"png texture mode\"),\n Y_UP_AXIS(\"yUpAxis\", \"ya\", \"yAxis\", false, \"Assign 3D root transformed matrix Y-UP axis\"),\n\n // 3D Tiles Options\n REFINE_ADD(\"refineAdd\", \"ra\", \"refineAdd\", false, \"refine addd mode\"),\n MAX_COUNT(\"maxCount\", \"mx\", \"maxCount\", true, \"max count of nodes (Default: 1024)\"),\n MAX_LOD(\"maxLod\", \"xl\", \"maxLod\", true, \"max level of detail (Default: 3)\"),\n MIN_LOD(\"minLod\", \"nl\", \"minLod\", true, \"min level of detail (Default: 0)\"),\n MAX_POINTS(\"maxPoints\", \"mp\", \"maxPoints\", true, \"max points of pointcloud data (Default: 20000)\"),\n\n // 2D Options\n FLIP_COORDINATE(\"flipCoordinate\", \"fc\", \"flipCoordinate\", false, \"flip x,y Coordinate.\"),\n NAME_COLUMN(\"nameColumn\", \"nc\", \"nameColumn\", true, \"name column setting. (Default: name)\"),\n HEIGHT_COLUMN(\"heightColumn\", \"hc\", \"heightColumn\", true, \"height column setting. (Default: height)\"),\n ALTITUDE_COLUMN(\"altitudeColumn\", \"ac\", \"altitudeColumn\", true, \"altitude Column setting.\"),\n MINIMUM_HEIGHT(\"minimumHeight\", \"mh\", \"minimumHeight\", true, \"minimum height setting.\"),\n ABSOLUTE_ALTITUDE(\"absoluteAltitude\", \"aa\", \"absoluteAltitude\", true, \"absolute altitude mode.\"),\n\n //Experimental,\n ZERO_ORIGIN(\"zeroOrigin\", \"zo\", \"zeroOrigin\", false, \"[Experimental] fix 3d root transformed matrix origin to zero point.\"),\n AUTO_UP_AXIS(\"autoUpAxis\", \"aa\", \"autoUpAxis\", false, \"[Experimental] automatically Assign 3D Matrix Axes\"),\n //Z_UP_AXIS(\"zAxis\", \"ya\", \"zAxis\", false, \"[Experimental] Assign 3D root transformed matrix Z-UP axis\"),\n //GENERATE_NORMALS(\"genNormals\", \"gn\", \"genNormals\", false, \"generate normals\"),\n //SCALE(\"scale\", \"sc\", \"scale\", false, \"scale factor\"),\n //STRICT(\"strict\", \"st\", \"strict\", false, \"strict mode\"),\n\n DEBUG(\"debug\", \"d\", \"debug\", false,\"debug mode\"),\n DEBUG_ALL_DRAWING(\"debugAllDrawing\", \"dad\", \"debugAllDrawing\", false,\"debug all drawing\"),\n DEBUG_IGNORE_TEXTURES(\"debugIgnoreTextures\", \"dit\", \"debugIgnoreTextures\", false,\"debug ignore textures\"),\n DEBUG_GLTF(\"gltf\", \"gltf\", \"gltf\", false, \"create gltf file.\"),\n DEBUG_GLB(\"glb\", \"glb\", \"glb\", false, \"create glb file.\");\n\n private final String longName;\n private final String shortName;\n private final String argName;\n private final boolean argRequired;\n private final String description;\n}"
},
{
"identifier": "TilerOptions",
"path": "tiler/src/main/java/com/gaia3d/process/TilerOptions.java",
"snippet": "@Getter\n@Builder\npublic class TilerOptions {\n private final Path inputPath;\n private final Path outputPath;\n private final FormatType inputFormatType;\n private final CoordinateReferenceSystem source;\n}"
},
{
"identifier": "PostProcess",
"path": "tiler/src/main/java/com/gaia3d/process/postprocess/PostProcess.java",
"snippet": "public interface PostProcess {\n ContentInfo run(ContentInfo contentInfo);\n}"
},
{
"identifier": "PreProcess",
"path": "tiler/src/main/java/com/gaia3d/process/preprocess/PreProcess.java",
"snippet": "public interface PreProcess {\n TileInfo run(TileInfo tileInfo);\n}"
},
{
"identifier": "TileProcess",
"path": "tiler/src/main/java/com/gaia3d/process/tileprocess/TileProcess.java",
"snippet": "public interface TileProcess {\n Tileset run(List<TileInfo> tileInfo);\n\n public void writeTileset(Tileset tileset);\n}"
},
{
"identifier": "PointCloudTiler",
"path": "tiler/src/main/java/com/gaia3d/process/tileprocess/tile/PointCloudTiler.java",
"snippet": "@Slf4j\npublic class PointCloudTiler implements Tiler {\n private static final int DEFUALT_MAX_COUNT = 20000;\n\n private final CommandLine command;\n private final TilerOptions options;\n\n public PointCloudTiler(TilerOptions tilerOptions, CommandLine command) {\n this.options = tilerOptions;\n this.command = command;\n }\n\n @Override\n public Tileset run(List<TileInfo> tileInfos) {\n double geometricError = calcGeometricError(tileInfos);\n\n GaiaBoundingBox globalBoundingBox = calcBoundingBox(tileInfos);\n\n double minX = globalBoundingBox.getMinX();\n double maxX = globalBoundingBox.getMaxX();\n double minY = globalBoundingBox.getMinY();\n double maxY = globalBoundingBox.getMaxY();\n double minZ = globalBoundingBox.getMinZ();\n double maxZ = globalBoundingBox.getMaxZ();\n\n double x = (maxX - minX);\n double y = (maxY - minY);\n double maxLength = Math.max(x, y);\n\n double xoffset = maxLength - x;\n double yoffset = maxLength - y;\n\n maxX += xoffset;\n maxY += yoffset;\n GaiaBoundingBox cubeBoundingBox = new GaiaBoundingBox();\n cubeBoundingBox.addPoint(new Vector3d(minX, minY, minZ));\n cubeBoundingBox.addPoint(new Vector3d(maxX, maxY, maxZ));\n\n globalBoundingBox = cubeBoundingBox;\n\n\n Matrix4d transformMatrix = getTransformMatrix(globalBoundingBox);\n rotateX90(transformMatrix);\n\n Node root = createRoot();\n root.setBoundingBox(globalBoundingBox);\n // root만 큐브로\n root.setBoundingVolume(new BoundingVolume(globalBoundingBox));\n root.setTransformMatrix(transformMatrix);\n root.setGeometricError(geometricError);\n\n try {\n createRootNode(root, tileInfos);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n\n Asset asset = createAsset();\n Tileset tileset = new Tileset();\n tileset.setGeometricError(geometricError);\n tileset.setAsset(asset);\n tileset.setRoot(root);\n return tileset;\n }\n\n public void writeTileset(Tileset tileset) {\n File tilesetFile = this.options.getOutputPath().resolve(\"tileset.json\").toFile();\n ObjectMapper objectMapper = new ObjectMapper();\n objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);\n objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);\n objectMapper.setSerializationInclusion(JsonInclude.Include.NON_DEFAULT);\n try (BufferedWriter writer = new BufferedWriter(new FileWriter(tilesetFile))) {\n String result = objectMapper.writeValueAsString(tileset);\n writer.write(result);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n private double calcGeometricError(List<TileInfo> tileInfos) {\n return tileInfos.stream().mapToDouble(tileInfo -> {\n GaiaBoundingBox boundingBox = tileInfo.getPointCloud().getGaiaBoundingBox();\n return boundingBox.getLongestDistance();\n }).max().orElse(0.0d);\n }\n\n private double calcGeometricError(GaiaPointCloud pointCloud) {\n GaiaBoundingBox boundingBox = pointCloud.getGaiaBoundingBox();\n return boundingBox.getLongestDistance();\n }\n\n private GaiaBoundingBox calcBoundingBox(List<TileInfo> tileInfos) {\n GaiaBoundingBox boundingBox = new GaiaBoundingBox();\n tileInfos.forEach(tileInfo -> {\n GaiaBoundingBox localBoundingBox = tileInfo.getPointCloud().getGaiaBoundingBox();\n boundingBox.addBoundingBox(localBoundingBox);\n });\n return boundingBox;\n }\n\n private void createRootNode(Node parentNode, List<TileInfo> tileInfos) throws IOException {\n BoundingVolume parentBoundingVolume = parentNode.getBoundingVolume();\n parentNode.setBoundingVolume(parentBoundingVolume);\n parentNode.setRefine(Node.RefineType.ADD);\n\n List<GaiaPointCloud> pointClouds = tileInfos.stream()\n .map(TileInfo::getPointCloud)\n .toList();\n int index = 0;\n for (GaiaPointCloud pointCloud : pointClouds) {\n pointCloud.setCode((index++) + \"\");\n createNode(parentNode, pointCloud, 16.0d);\n }\n }\n\n private void createNode(Node parentNode, GaiaPointCloud pointCloud, double geometricError) {\n int vertexLength = pointCloud.getVertices().size();\n\n int maxPoints = command.hasOption(ProcessOptions.MAX_POINTS.getArgName()) ? Integer.parseInt(command.getOptionValue(ProcessOptions.MAX_POINTS.getArgName())) : DEFUALT_MAX_COUNT;\n\n List<GaiaPointCloud> divided = pointCloud.divideChunkSize(maxPoints);\n GaiaPointCloud selfPointCloud = divided.get(0);\n GaiaPointCloud remainPointCloud = divided.get(1);\n\n GaiaBoundingBox childBoundingBox = selfPointCloud.getGaiaBoundingBox();\n Matrix4d transformMatrix = getTransformMatrix(childBoundingBox);\n\n //Matrix4d transformMatrix = new Matrix4d();\n //transformMatrix.identity();\n rotateX90(transformMatrix);\n BoundingVolume boundingVolume = new BoundingVolume(childBoundingBox);\n\n double geometricErrorCalc = calcGeometricError(selfPointCloud);\n\n Node childNode = new Node();\n childNode.setParent(parentNode);\n childNode.setTransformMatrix(transformMatrix);\n childNode.setBoundingBox(childBoundingBox);\n childNode.setBoundingVolume(boundingVolume);\n childNode.setRefine(Node.RefineType.ADD);\n childNode.setChildren(new ArrayList<>());\n childNode.setNodeCode(parentNode.getNodeCode() + pointCloud.getCode());\n childNode.setGeometricError(geometricErrorCalc/2);\n childNode.setGeometricError(geometricError);\n\n TileInfo selfTileInfo = TileInfo.builder()\n .pointCloud(selfPointCloud)\n .boundingBox(childBoundingBox)\n .build();\n List<TileInfo> tileInfos = new ArrayList<>();\n tileInfos.add(selfTileInfo);\n\n ContentInfo contentInfo = new ContentInfo();\n contentInfo.setName(\"gaiaPointcloud\");\n contentInfo.setLod(LevelOfDetail.LOD0);\n contentInfo.setBoundingBox(childBoundingBox);\n contentInfo.setNodeCode(childNode.getNodeCode());\n contentInfo.setTileInfos(tileInfos);\n\n Content content = new Content();\n content.setUri(\"data/\" + childNode.getNodeCode() + \".pnts\");\n content.setContentInfo(contentInfo);\n childNode.setContent(content);\n\n parentNode.getChildren().add(childNode);\n log.info(\"[ContentNode][{}] Point cloud nodes calculated.\",childNode.getNodeCode());\n\n if (vertexLength > 0) { // vertexLength > DEFUALT_MAX_COUNT\n List<GaiaPointCloud> distributes = remainPointCloud.distributeOct();\n distributes.forEach(distribute -> {\n if (!distribute.getVertices().isEmpty()) {\n createNode(childNode, distribute, geometricError/2);\n }\n });\n } else {\n return;\n }\n }\n\n private void rotateX90(Matrix4d matrix) {\n Matrix4d rotationMatrix = new Matrix4d();\n rotationMatrix.identity();\n rotationMatrix.rotateX(Math.toRadians(-90));\n matrix.mul(rotationMatrix, matrix);\n }\n\n private Matrix4d getTransformMatrix(GaiaBoundingBox boundingBox) {\n Vector3d center = boundingBox.getCenter();\n double[] cartesian = GlobeUtils.geographicToCartesianWgs84(center.x, center.y, center.z);\n return GlobeUtils.normalAtCartesianPointWgs84(cartesian[0], cartesian[1], cartesian[2]);\n }\n\n private Asset createAsset() {\n Asset asset = new Asset();\n Extras extras = new Extras();\n Cesium cesium = new Cesium();\n Ion ion = new Ion();\n List<Credit> credits = new ArrayList<>();\n Credit credit = new Credit();\n credit.setHtml(\"<html>Gaia3D</html>\");\n credits.add(credit);\n cesium.setCredits(credits);\n extras.setIon(ion);\n extras.setCesium(cesium);\n asset.setExtras(extras);\n return asset;\n }\n\n private Node createRoot() {\n Node root = new Node();\n root.setParent(root);\n root.setNodeCode(\"R\");\n root.setRefine(Node.RefineType.ADD);\n root.setChildren(new ArrayList<>());\n return root;\n }\n}"
}
] | import com.gaia3d.basic.types.FormatType;
import com.gaia3d.converter.PointCloudFileLoader;
import com.gaia3d.converter.pointcloud.LasConverter;
import com.gaia3d.process.PointCloudProcessFlow;
import com.gaia3d.process.ProcessOptions;
import com.gaia3d.process.TilerOptions;
import com.gaia3d.process.postprocess.PostProcess;
import com.gaia3d.process.preprocess.PreProcess;
import com.gaia3d.process.tileprocess.TileProcess;
import com.gaia3d.process.tileprocess.tile.PointCloudTiler;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.io.FileExistsException;
import org.locationtech.proj4j.CRSFactory;
import org.locationtech.proj4j.CoordinateReferenceSystem;
import java.io.File;
import java.io.IOException;
import java.nio.file.NotDirectoryException;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List; | 6,091 | package com.gaia3d.command;
@Slf4j
public class PointCloudProcessModel implements ProcessFlowModel{
public void run(CommandLine command) throws IOException {
File inputFile = new File(command.getOptionValue(ProcessOptions.INPUT.getArgName()));
File outputFile = new File(command.getOptionValue(ProcessOptions.OUTPUT.getArgName()));
String crs = command.getOptionValue(ProcessOptions.CRS.getArgName());
String proj = command.getOptionValue(ProcessOptions.PROJ4.getArgName());
String inputExtension = command.getOptionValue(ProcessOptions.INPUT_TYPE.getArgName());
Path inputPath = createPath(inputFile);
Path outputPath = createPath(outputFile);
if (!validate(outputPath)) {
return;
}
FormatType formatType = FormatType.fromExtension(inputExtension);
CRSFactory factory = new CRSFactory();
CoordinateReferenceSystem source = null;
if (proj != null && !proj.isEmpty()) {
source = factory.createFromParameters("CUSTOM", proj);
} else {
source = (crs != null && !crs.isEmpty()) ? factory.createFromName("EPSG:" + crs) : null;
}
LasConverter converter = new LasConverter(command, source);
PointCloudFileLoader fileLoader = new PointCloudFileLoader(command, converter);
List<PreProcess> preProcessors = new ArrayList<>();
TilerOptions tilerOptions = TilerOptions.builder()
.inputPath(inputPath)
.outputPath(outputPath)
.inputFormatType(formatType)
.source(source)
.build();
TileProcess tileProcess = new PointCloudTiler(tilerOptions, command); | package com.gaia3d.command;
@Slf4j
public class PointCloudProcessModel implements ProcessFlowModel{
public void run(CommandLine command) throws IOException {
File inputFile = new File(command.getOptionValue(ProcessOptions.INPUT.getArgName()));
File outputFile = new File(command.getOptionValue(ProcessOptions.OUTPUT.getArgName()));
String crs = command.getOptionValue(ProcessOptions.CRS.getArgName());
String proj = command.getOptionValue(ProcessOptions.PROJ4.getArgName());
String inputExtension = command.getOptionValue(ProcessOptions.INPUT_TYPE.getArgName());
Path inputPath = createPath(inputFile);
Path outputPath = createPath(outputFile);
if (!validate(outputPath)) {
return;
}
FormatType formatType = FormatType.fromExtension(inputExtension);
CRSFactory factory = new CRSFactory();
CoordinateReferenceSystem source = null;
if (proj != null && !proj.isEmpty()) {
source = factory.createFromParameters("CUSTOM", proj);
} else {
source = (crs != null && !crs.isEmpty()) ? factory.createFromName("EPSG:" + crs) : null;
}
LasConverter converter = new LasConverter(command, source);
PointCloudFileLoader fileLoader = new PointCloudFileLoader(command, converter);
List<PreProcess> preProcessors = new ArrayList<>();
TilerOptions tilerOptions = TilerOptions.builder()
.inputPath(inputPath)
.outputPath(outputPath)
.inputFormatType(formatType)
.source(source)
.build();
TileProcess tileProcess = new PointCloudTiler(tilerOptions, command); | List<PostProcess> postProcessors = new ArrayList<>(); | 6 | 2023-11-30 01:59:44+00:00 | 8k |
xuemingqi/x-cloud | x-config/src/main/java/com/x/config/redis/conf/RedissonConfig.java | [
{
"identifier": "RedisCommonConstant",
"path": "x-config/src/main/java/com/x/config/redis/constants/RedisCommonConstant.java",
"snippet": "public interface RedisCommonConstant {\n\n String CACHE_MANAGER_NAME = \"selfCacheManager\";\n}"
},
{
"identifier": "RedissonClusterProperty",
"path": "x-config/src/main/java/com/x/config/redis/property/RedissonClusterProperty.java",
"snippet": "@Data\n@Component\n@RefreshScope\n@ConditionalOnClass(RedissonClient.class)\n@ConfigurationProperties(prefix = \"spring.redis.redisson.cluster\")\npublic class RedissonClusterProperty {\n\n private String[] nodeAddresses;\n\n private String password;\n\n private int connectTimeout = 10000;\n\n private int idleConnectionTimeout = 10000;\n\n private int timeout = 3000;\n\n private int masterConnectionMinimumIdleSize = 2;\n\n private int masterConnectionPoolSize = 10;\n\n private int slaveConnectionMinimumIdleSize = 2;\n\n private int slaveConnectionPoolSize = 10;\n\n private int retryAttempts = 3;\n\n private int retryInterval = 15;\n\n private int subscriptionsPerConnection = 6;\n\n private int scanInterval = 1000;\n\n}"
},
{
"identifier": "RedissonMasterSlaveProperty",
"path": "x-config/src/main/java/com/x/config/redis/property/RedissonMasterSlaveProperty.java",
"snippet": "@Data\n@Component\n@RefreshScope\n@ConditionalOnClass(RedissonClient.class)\n@ConfigurationProperties(prefix = \"spring.redis.redisson.master-salve\")\npublic class RedissonMasterSlaveProperty {\n\n private String masterAddress;\n\n private Set<String> slaveAddress;\n\n private String password;\n\n private int connectTimeout = 10000;\n\n private int idleConnectionTimeout = 10000;\n\n private int masterConnectionPoolSize = 100;\n\n private int masterConnectionMinimumIdleSize = 20;\n\n private int slaveConnectionPoolSize = 50;\n\n private int slaveConnectionMinimumIdleSize = 10;\n\n private int timeout = 3000;\n\n}"
},
{
"identifier": "RedissonSingleProperty",
"path": "x-config/src/main/java/com/x/config/redis/property/RedissonSingleProperty.java",
"snippet": "@Data\n@Component\n@RefreshScope\n@ConditionalOnClass(RedissonClient.class)\n@ConfigurationProperties(prefix = \"spring.redis.redisson.single\")\npublic class RedissonSingleProperty {\n\n private String address;\n\n private String password;\n\n private int connectTimeout = 10000;\n\n private int connectionPoolSize = 50;\n\n private int idleConnectionTimeout = 10000;\n\n private int connectionMinimumIdleSize = 20;\n\n private int timeout = 3000;\n\n}"
},
{
"identifier": "TtlRedisCacheManager",
"path": "x-config/src/main/java/com/x/config/redis/property/TtlRedisCacheManager.java",
"snippet": "public class TtlRedisCacheManager extends RedisCacheManager {\n\n public TtlRedisCacheManager(RedisCacheWriter cacheWriter, RedisCacheConfiguration defaultCacheConfiguration) {\n super(cacheWriter, defaultCacheConfiguration);\n }\n\n @Override\n protected RedisCache createRedisCache(@Nonnull String name, @Nullable RedisCacheConfiguration cacheConfig) {\n String[] cells = StringUtils.delimitedListToStringArray(name, \"=\");\n name = cells[0];\n if (cells.length > 1 && null != cacheConfig) {\n long ttl = Long.parseLong(cells[1]);\n cacheConfig = cacheConfig.entryTtl(Duration.ofSeconds(ttl));\n }\n return super.createRedisCache(name, cacheConfig);\n }\n\n}"
},
{
"identifier": "RedissonType",
"path": "x-config/src/main/java/com/x/config/redis/type/RedissonType.java",
"snippet": "@Data\n@Component\n@ConfigurationProperties(prefix = \"spring.redis.redisson\")\npublic class RedissonType {\n\n public Type type;\n\n @Getter\n @RequiredArgsConstructor\n public enum Type {\n\n SINGLE(\"SINGLE\", \"单机\"),\n\n MASTER_SLAVE(\"MASTER_SLAVE\", \"主从\"),\n\n CLUSTER(\"CLUSTER\", \"集群\");\n\n private final String type;\n private final String memo;\n\n static Type fromType(String key) {\n return Arrays.stream(values())\n .filter(o -> key.equals(o.getType()))\n .findAny().orElse(null);\n }\n }\n}"
},
{
"identifier": "RedisUtil",
"path": "x-config/src/main/java/com/x/config/redis/util/RedisUtil.java",
"snippet": "@SuppressWarnings({\"unused\", \"UnusedReturnValue\"})\n@Slf4j\npublic class RedisUtil {\n\n private final RedissonClient redissonClient;\n\n public RedisUtil(RedissonClient redissonClient) {\n this.redissonClient = redissonClient;\n }\n\n /**\n * 普通缓存获取\n *\n * @param key 键\n * @return 值\n */\n public <T> T get(String key) {\n RBucket<T> rBucket = getRBucket(key);\n return rBucket.get();\n }\n\n\n /**\n * 普通缓存放入\n *\n * @param key 键\n * @param value 值\n */\n public <T> void set(String key, T value) {\n getRBucket(key).set(value);\n }\n\n\n /**\n * 普通缓存放入并设置时间\n *\n * @param key 键\n * @param value 值\n * @param timeoutSec 时间(秒) time要大于0 如果time小于等于0 将设置无限期\n */\n public <T> void set(String key, T value, long timeoutSec, TimeUnit timeUnit) {\n getRBucket(key).set(value, timeoutSec, timeUnit);\n }\n\n /**\n * 设置指定 key 的值,并返回 key 的旧值\n */\n public <T> T getAndSet(String key, T value) {\n RBucket<T> rBucket = getRBucket(key);\n return rBucket.getAndSet(value);\n }\n\n /**\n * 设置指定 key 的值,并返回 key 的旧值,并设置键的有效期\n */\n public <T> T getAndSet(String key, T value, long timeToLive, TimeUnit timeUnit) {\n RBucket<T> rBucket = getRBucket(key);\n return rBucket.getAndSet(value, timeToLive, timeUnit);\n }\n\n\n /**\n * 根据key 获取过期时间\n *\n * @param key 键 不能为null\n * @return 时间(秒) 返回0代表为永久有效\n */\n public long getExpire(String key) {\n return getRBucket(key).remainTimeToLive() / 1000;\n }\n\n\n /**\n * 指定缓存失效时间\n *\n * @param key 键\n * @param timeoutSec 时间(秒)\n */\n public void expired(String key, long timeoutSec) {\n expired(key, timeoutSec, TimeUnit.SECONDS);\n }\n\n\n /**\n * 指定缓存失效时间\n *\n * @param key 键\n * @param timeoutSec 时间(秒)\n */\n public void expired(String key, long timeoutSec, TimeUnit unit) {\n getRBucket(key).expire(timeoutSec, unit);\n }\n\n\n /**\n * 判断key是否存在\n *\n * @param key 键\n * @return true 存在 false不存在\n */\n public boolean exists(String key) {\n return getRBucket(key).isExists();\n }\n\n\n /**\n * 删除缓存\n *\n * @param key 可以传一个值 或多个\n * @return 数量\n */\n public boolean del(String key) {\n return getRBucket(key).delete();\n }\n\n\n /**\n * 删除缓存\n *\n * @param keys 可以传一个值 或多个\n * @return 数量\n */\n public long del(String... keys) {\n return getRKeys().delete(keys);\n }\n\n\n /**\n * 递增\n *\n * @param key 键\n * @param delta 要增加几(大于0)\n */\n public long incr(String key, long delta) {\n return getRAtomicLong(key).addAndGet(delta);\n }\n\n\n /**\n * HashGet\n *\n * @param key 键 不能为null\n * @param hashKey 项 不能为null\n */\n public <K, V> V hGet(String key, K hashKey) {\n RMapCache<K, V> rMapCache = getRMapCache(key);\n return rMapCache.get(hashKey);\n }\n\n\n /**\n * 向一张hash表中放入数据,如果不存在将创建\n *\n * @param key 键\n * @param hashKey 项\n * @param value 值\n */\n public <k, v> void hSet(String key, k hashKey, v value) {\n getRMapCache(key).put(hashKey, value);\n }\n\n\n /**\n * 向一张hash表中放入数据,如果不存在将创建\n *\n * @param key 键\n * @param hashKey 项\n * @param value 值\n * @param timeoutSec 时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间\n */\n public <k, v> void hSet(String key, k hashKey, v value, long timeoutSec) {\n getRMapCache(key).put(hashKey, value, timeoutSec, TimeUnit.SECONDS);\n }\n\n\n /**\n * 获取hashKey对应的所有键值\n *\n * @param key 键\n * @return 对应的多个键值\n */\n public <K, V> Map<K, V> hMGet(String key) {\n RMapCache<K, V> rMapCache = getRMapCache(key);\n return rMapCache.readAllMap();\n }\n\n\n /**\n * HashSet\n *\n * @param key 键\n * @param map 对应多个键值\n */\n public <K, V> void hMSet(String key, Map<? extends K, ? extends V> map) {\n getRMapCache(key).putAll(map);\n }\n\n\n /**\n * HashSet 并设置时间\n *\n * @param key 键\n * @param map 对应多个键值\n * @param timeoutSec 时间(秒)\n */\n public <K, V> void hMSet(String key, Map<? extends K, ? extends V> map, long timeoutSec) {\n RMapCache<K, V> rMapCache = getRMapCache(key);\n rMapCache.putAll(map, timeoutSec, TimeUnit.SECONDS);\n }\n\n\n /**\n * 删除hash表中的值\n *\n * @param key 键 不能为null\n * @param hashKeys 项 可以使多个 不能为null\n */\n public long hDel(String key, Object... hashKeys) {\n return getRMapCache(key).fastRemove(hashKeys);\n }\n\n\n /**\n * 判断hash表中是否有该项的值\n *\n * @param key 键 不能为null\n * @param hashKey 项 不能为null\n * @return true 存在 false不存在\n */\n public boolean hExists(String key, String hashKey) {\n return getRMapCache(key).containsKey(hashKey);\n }\n\n\n /**\n * hash递增 如果不存在,就会创建一个 并把新增后的值返回\n *\n * @param key 键\n * @param hashKey 项\n * @param delta 要增加几(大于0)\n */\n public long hIncr(String key, String hashKey, long delta) {\n return (long) getRMapCache(key).addAndGet(hashKey, delta);\n }\n\n\n /**\n * hash递增 如果不存在,就会创建一个 并把新增后的值返回\n *\n * @param key 键\n * @param hashKey 项\n * @param delta 要增加几(大于0)\n */\n public double hIncr(String key, String hashKey, double delta) {\n return (double) getRMapCache(key).addAndGet(hashKey, delta);\n }\n\n\n /**\n * 根据key获取Set中的所有值\n *\n * @param key 键\n */\n public <V> Set<V> sGet(String key) {\n RSet<V> rSet = getRSet(key);\n return rSet.readAll();\n }\n\n\n /**\n * 根据key获取Set中的值\n *\n * @param key 键\n */\n public <V> V sPop(String key) {\n RSet<V> rSet = getRSet(key);\n return rSet.removeRandom();\n }\n\n\n /**\n * 根据key获取Set中的值\n *\n * @param key 键\n * @param count 数量\n */\n public <V> Set<V> sPop(String key, int count) {\n RSet<V> rSet = getRSet(key);\n return rSet.removeRandom(count);\n }\n\n\n /**\n * 根据key获取Set中的值\n *\n * @param key 键\n */\n public <V> V sRandom(String key) {\n RSet<V> rSet = getRSet(key);\n return rSet.random();\n }\n\n\n /**\n * 根据key获取Set中的值\n *\n * @param key 键\n * @param count 数量\n */\n public <V> Set<V> sRandom(String key, int count) {\n RSet<V> rSet = getRSet(key);\n return rSet.random(count);\n }\n\n\n /**\n * 将数据放入set缓存\n *\n * @param key 键\n * @param values 值 可以是多个\n * @return 成功个数\n */\n public <E> boolean sAdd(String key, E values) {\n RSet<E> rSet = getRSet(key);\n return rSet.add(values);\n }\n\n\n /**\n * 将set数据放入缓存\n *\n * @param key 键\n * @param timeoutSec 时间(秒)\n * @param values 值 可以是多个\n * @return 成功个数\n */\n public <E> boolean sAddExpire(String key, long timeoutSec, E values) {\n RSet<E> rSet = getRSet(key);\n rSet.add(values);\n return getRSet(key).expire(timeoutSec, TimeUnit.SECONDS);\n }\n\n\n /**\n * 移除值为value的\n *\n * @param key 键\n * @param values 值 可以是多个\n * @return 移除的个数\n */\n\n public boolean sDel(String key, Object values) {\n return getRSet(key).remove(values);\n }\n\n\n /**\n * 根据value从一个set中查询,是否存在\n *\n * @param key 键\n * @param value 值\n * @return true 存在 false不存在\n */\n public boolean sExists(String key, Object value) {\n return getRSet(key).contains(value);\n }\n\n\n /**\n * 获取set缓存的长度\n *\n * @param key 键\n */\n public int sSize(String key) {\n return getRSet(key).size();\n }\n\n\n /**\n * 获取list缓存的内容\n *\n * @param key 键\n * @param start 开始\n * @param end 结束 0 到 -1 代表所有值\n */\n public <T> List<T> lRange(String key, int start, int end) {\n RList<T> rList = getRList(key);\n return rList.range(start, end);\n }\n\n\n /**\n * 通过索引 获取list中的值\n *\n * @param key 键\n * @param index 索引 index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推\n */\n public <T> T lIndex(String key, int index) {\n RList<T> rList = getRList(key);\n return rList.get(index);\n }\n\n\n /**\n * 将list放入缓存\n *\n * @param key 键\n * @param index 索引 index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推\n * @param value 值\n */\n public <T> void lSet(String key, int index, T value) {\n RList<T> rList = getRList(key);\n rList.add(index, value);\n }\n\n\n /**\n * 将list放入缓存\n *\n * @param key 键\n * @param index 索引 index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推\n * @param value 值\n */\n public <T> void lSet(String key, int index, T value, long timeoutSec) {\n RList<T> rList = getRList(key);\n rList.add(index, value);\n rList.expire(timeoutSec, TimeUnit.SECONDS);\n }\n\n\n /**\n * trim list缓存的内容\n *\n * @param key 键\n * @param start 开始\n * @param end 结束 0 到 -1 代表所有值\n */\n public void ltrim(String key, int start, int end) {\n getRList(key).trim(start, end);\n }\n\n\n public <T> T lPopLeft(String key) {\n RDeque<T> rDeque = getRRDeque(key);\n return rDeque.removeFirst();\n }\n\n\n /**\n * 将list放入缓存\n *\n * @param key 键\n * @param value 值\n */\n public <T> boolean lPushLeft(String key, T value) {\n RDeque<T> rDeque = getRRDeque(key);\n return rDeque.add(value);\n }\n\n\n public <T> void lPushLeft(String key, T value, long timeoutSec) {\n RDeque<T> rDeque = getRRDeque(key);\n rDeque.addFirst(value);\n rDeque.expire(timeoutSec, TimeUnit.SECONDS);\n }\n\n\n /**\n * 将list放入缓存\n *\n * @param key 键\n * @param values 值\n */\n public <T> boolean lPushLeftAll(String key, List<T> values) {\n RDeque<T> rDeque = getRRDeque(key);\n return rDeque.addAll(values);\n }\n\n\n public <T> T lPopRight(String key) {\n RDeque<T> rDeque = getRRDeque(key);\n return rDeque.removeLast();\n }\n\n\n /**\n * 将list放入缓存\n *\n * @param key 键\n * @param value 值\n */\n public <T> void lPushRight(String key, T value) {\n RDeque<T> rDeque = getRRDeque(key);\n rDeque.addLast(value);\n }\n\n\n /**\n * 移除N个值为value\n *\n * @param key 键\n * @param count 移除多少个\n * @param value 值\n * @return 移除的个数\n */\n\n public <V> boolean lDel(String key, int count, V value) {\n RList<V> rList = getRList(key);\n return rList.remove(value, count);\n }\n\n\n /**\n * 获取list缓存的长度\n *\n * @param key 键\n */\n public long lSize(String key) {\n return getRList(key).size();\n }\n\n\n /**\n * 同步锁\n *\n * @param key key\n * @param timeoutSec 锁超时时间\n * @param waitTime 加锁等待时间\n */\n public boolean lock(String key, long timeoutSec, long waitTime) {\n RLock lock = getRlock(key);\n try {\n return lock.tryLock(waitTime, timeoutSec, TimeUnit.SECONDS);\n } catch (InterruptedException e) {\n log.error(\"redisson lock error\", e);\n return false;\n }\n }\n\n\n /**\n * 同步锁\n *\n * @param key key\n * @param timeoutSec 锁超时时间\n */\n public boolean lock(String key, long timeoutSec) {\n RLock lock = getRlock(key);\n try {\n return lock.tryLock(timeoutSec, TimeUnit.SECONDS);\n } catch (InterruptedException e) {\n log.error(\"redisson lock error\", e);\n return false;\n }\n }\n\n\n /**\n * 释放同步锁\n *\n * @param key key\n */\n public void unLock(String key) {\n RLock lock = getRlock(key);\n if (lock.isLocked()) {\n lock.unlock();\n }\n }\n\n /**\n * 添加定时任务\n *\n * @param key 任务key\n * @param runnable 执行方法\n * @param delay 延迟时间\n * @param period 调度周期\n */\n public RScheduledFuture<?> schedule(String key, Runnable runnable, long delay, long period) {\n return getRScheduledExecutorService(key).scheduleAtFixedRate(runnable, delay, period, TimeUnit.SECONDS);\n }\n\n /**\n * 添加任务\n *\n * @param key 任务key\n * @param callable 执行方法\n * @param delay 延迟时间\n */\n public <T> RScheduledFuture<T> schedule(String key, Callable<T> callable, long delay) {\n return getRScheduledExecutorService(key).schedule(callable, delay, TimeUnit.SECONDS);\n }\n\n /**\n * 添加任务\n *\n * @param key 任务key\n * @param runnable 执行方法\n */\n public Future<?> submit(String key, Runnable runnable) {\n return getRExecutorService(key).submit(runnable);\n }\n\n /**\n * 限流\n *\n * @param key 限流key\n * @param counts 令牌数\n * @param unit 计数时间单位\n */\n public boolean tryAcquire(String key, long counts, RateIntervalUnit unit) {\n RRateLimiter limiter = getRRateLimiter(key);\n limiter.trySetRate(RateType.OVERALL, counts, 1, unit);\n return limiter.tryAcquire();\n }\n\n /**\n * 通用对象桶\n */\n private <T> RBucket<T> getRBucket(String key) {\n return redissonClient.getBucket(key);\n }\n\n /**\n * 原子整长形\n */\n private RAtomicLong getRAtomicLong(String key) {\n return redissonClient.getAtomicLong(key);\n }\n\n /**\n * 对象\n */\n private RKeys getRKeys() {\n return redissonClient.getKeys();\n }\n\n /**\n * 批量\n */\n private RBatch getRBatch() {\n return redissonClient.createBatch();\n }\n\n /**\n * 映射\n */\n private <K, V> RMap<K, V> getRMap(String key) {\n return redissonClient.getMap(key);\n }\n\n /**\n * 集\n */\n private <V> RSet<V> getRSet(String key) {\n return redissonClient.getSet(key);\n }\n\n /**\n * 列表\n */\n private <V> RList<V> getRList(String key) {\n return redissonClient.getList(key);\n }\n\n /**\n * 分布式淘汰机制map\n */\n private <K, V> RMapCache<K, V> getRMapCache(String key) {\n return redissonClient.getMapCache(key);\n }\n\n /**\n * 分布式淘汰机制set\n */\n private <V> RSetCache<V> getRSetCache(String key) {\n return redissonClient.getSetCache(key);\n }\n\n /**\n * 双端队列\n */\n private <V> RDeque<V> getRRDeque(String key) {\n return redissonClient.getDeque(key);\n }\n\n /**\n * 锁\n */\n private RLock getRlock(String key) {\n return redissonClient.getLock(key);\n }\n\n /**\n * 限流\n */\n private RRateLimiter getRRateLimiter(String key) {\n return redissonClient.getRateLimiter(key);\n }\n\n /**\n * 定时任务\n */\n private RScheduledExecutorService getRScheduledExecutorService(String key) {\n return redissonClient.getExecutorService(key);\n }\n\n /**\n * 定时任务\n */\n private RExecutorService getRExecutorService(String key) {\n return redissonClient.getExecutorService(key);\n }\n\n}"
}
] | import com.x.config.redis.constants.RedisCommonConstant;
import com.x.config.redis.property.RedissonClusterProperty;
import com.x.config.redis.property.RedissonMasterSlaveProperty;
import com.x.config.redis.property.RedissonSingleProperty;
import com.x.config.redis.property.TtlRedisCacheManager;
import com.x.config.redis.type.RedissonType;
import com.x.config.redis.util.RedisUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.codec.JsonJacksonCodec;
import org.redisson.config.Config;
import org.redisson.config.ReadMode;
import org.redisson.connection.balancer.RoundRobinLoadBalancer;
import org.redisson.spring.data.connection.RedissonConnectionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter; | 7,064 | package com.x.config.redis.conf;
/**
* @author : xuemingqi
* @since : 2023/1/7 16:38
*/
@Slf4j
@Configuration
@ConditionalOnClass(RedissonClient.class)
@RequiredArgsConstructor(onConstructor = @__({@Autowired}))
public class RedissonConfig {
private final RedissonSingleProperty singleProperty;
private final RedissonMasterSlaveProperty masterSlaveProperty;
private final RedissonClusterProperty clusterProperty;
private final RedissonType redissonType;
@Bean
public RedissonClient redissonClient() {
Config config = new Config();
switch (redissonType.getType()) {
case SINGLE:
createSingleConfig(config);
break;
case MASTER_SLAVE:
createMasterSlaveConfig(config);
break;
case CLUSTER:
createClusterConfig(config);
break;
}
return Redisson.create(config);
}
/**
* redisUtil bean
*/
@Bean | package com.x.config.redis.conf;
/**
* @author : xuemingqi
* @since : 2023/1/7 16:38
*/
@Slf4j
@Configuration
@ConditionalOnClass(RedissonClient.class)
@RequiredArgsConstructor(onConstructor = @__({@Autowired}))
public class RedissonConfig {
private final RedissonSingleProperty singleProperty;
private final RedissonMasterSlaveProperty masterSlaveProperty;
private final RedissonClusterProperty clusterProperty;
private final RedissonType redissonType;
@Bean
public RedissonClient redissonClient() {
Config config = new Config();
switch (redissonType.getType()) {
case SINGLE:
createSingleConfig(config);
break;
case MASTER_SLAVE:
createMasterSlaveConfig(config);
break;
case CLUSTER:
createClusterConfig(config);
break;
}
return Redisson.create(config);
}
/**
* redisUtil bean
*/
@Bean | public RedisUtil redisUtil(RedissonClient redissonClient) { | 6 | 2023-11-27 08:23:38+00:00 | 8k |
okx/OKBund | aa-rest/src/main/java/com/okcoin/dapp/bundler/rest/test/NewTestController.java | [
{
"identifier": "AccountUtil",
"path": "aa-infra/src/main/java/com/okcoin/dapp/bundler/infra/chain/AccountUtil.java",
"snippet": "public class AccountUtil {\n\n @SneakyThrows\n public static BigInteger getNonce(String address, boolean isLatest, IChain chain) {\n EthGetTransactionCount ethGetTransactionCount = chain.getWeb3j().ethGetTransactionCount(address, isLatest ? DefaultBlockParameterName.LATEST : DefaultBlockParameterName.PENDING).send();\n ChainErrorUtil.throwChainError(ethGetTransactionCount);\n return ethGetTransactionCount.getTransactionCount();\n }\n\n @SneakyThrows\n public static BigInteger getBalance(String address, IChain chain) {\n EthGetBalance ethGetBalance = chain.getWeb3j().ethGetBalance(address, DefaultBlockParameterName.LATEST).send();\n ChainErrorUtil.throwChainError(ethGetBalance);\n return ethGetBalance.getBalance();\n }\n\n public static BigDecimal getBalance(String address, Convert.Unit unit, IChain chain) {\n BigInteger balance = getBalance(address, chain);\n return Convert.fromWei(new BigDecimal(balance), unit);\n }\n\n @SneakyThrows\n public static String getCode(String address, IChain chain) {\n EthGetCode ethGetCode = chain.getWeb3j().ethGetCode(address, DefaultBlockParameterName.LATEST).send();\n ChainErrorUtil.throwChainError(ethGetCode);\n return ethGetCode.getCode();\n }\n}"
},
{
"identifier": "Web3Constant",
"path": "aa-infra/src/main/java/com/okcoin/dapp/bundler/infra/chain/constant/Web3Constant.java",
"snippet": "public interface Web3Constant {\n\n String HEX_PREFIX = \"0x\";\n\n String HEX_ZERO = \"0x0\";\n\n int METHOD_ID_LENGTH = 10;\n\n int BYTE_LENGTH = 32;\n\n long UINT48_MAX = 281474976710655L;\n\n double FEE_HISTORY_COMMON_REWARD_PERCENTILE = 50D;\n\n int ADDRESS_WITH_HEX_PREFIX = 42;\n\n}"
},
{
"identifier": "ChainConfig",
"path": "aa-pool/src/main/java/com/okcoin/dapp/bundler/pool/config/ChainConfig.java",
"snippet": "@Component\n@Getter\npublic class ChainConfig implements IChain {\n\n private static final int DEFAULT_BLOCK_TIME_MS = 1000;\n\n private final long chainId;\n\n private final boolean eip1559;\n\n private final int blockTime;\n\n @Setter\n private Web3jDebug web3j;\n\n public ChainConfig(PoolConfig poolConfig) {\n this.chainId = poolConfig.getChainId();\n this.eip1559 = poolConfig.isEip1559();\n this.blockTime = poolConfig.getBlockTime() == null ? DEFAULT_BLOCK_TIME_MS : poolConfig.getBlockTime();\n HttpService web3jService = new HttpService(poolConfig.getRpc(), true);\n this.web3j = Web3jDebug.build(web3jService);\n }\n\n}"
},
{
"identifier": "PoolConfig",
"path": "aa-pool/src/main/java/com/okcoin/dapp/bundler/pool/config/PoolConfig.java",
"snippet": "@Configuration\n@ConfigurationProperties(prefix = \"pool.core\")\n@Data\npublic class PoolConfig {\n\n private boolean safeMode;\n\n private Long chainId;\n\n private boolean eip1559;\n\n private String rpc;\n\n private String entrypoint;\n\n private long maxMempoolSize;\n\n private int autoBundleInterval;\n\n private String entrypointRuntimeCodeV6;\n\n private Integer blockTime;\n\n public void setEntrypoint(String entrypoint) {\n this.entrypoint = entrypoint.toLowerCase();\n }\n\n}"
},
{
"identifier": "Entrypoint",
"path": "aa-pool/src/main/java/com/okcoin/dapp/bundler/pool/entrypoint/Entrypoint.java",
"snippet": "public class Entrypoint {\n\n private static final String FAKE_BENEFICIARY = \"0x1234567890abcdeffedcba098765432113579ace\";\n\n public static String getSenderAddress(String entrypoint, String initCode, IChain chain) {\n Function function = new Function(\"getSenderAddress\", Lists.newArrayList(new DynamicBytes(Numeric.hexStringToByteArray(initCode))), Lists.newArrayList());\n String data = FunctionEncoder.encode(function);\n EthCall call = TransactionUtil.call(null, entrypoint, data, chain);\n ChainErrorMsg chainErrorMsg = ChainErrorUtil.parseChainError(call);\n if (chainErrorMsg.isMethodId(SenderAddressResult.ERROR_METHOD_ID)) {\n return new SenderAddressResult(chainErrorMsg).getAddress();\n } else {\n return Address.DEFAULT.getValue();\n }\n }\n\n public static BigInteger getNonce(String entrypoint, String sender, BigInteger key, IChain chain) {\n Function function = new Function(\"getNonce\", Lists.newArrayList(new Address(sender), new Uint192(key)), Lists.newArrayList(TypeReference.create(Uint256.class)));\n String data = FunctionEncoder.encode(function);\n EthCall call = TransactionUtil.call(null, entrypoint, data, chain);\n ChainErrorUtil.throwChainError(call);\n return ((Uint256) FunctionReturnDecoder.decode(call.getValue(), function.getOutputParameters()).get(0)).getValue();\n }\n\n\n public static String getHandleOpsCallData(List<UserOperationDO> ops) {\n return getHandleOpsCallData(ops, FAKE_BENEFICIARY);\n }\n\n public static String handleOps(List<UserOperationDO> uopList, String beneficiary, String from,\n BigInteger gasLimit, BigInteger maxFeePerGas, BigInteger maxPriorityFeePerGas) {\n UserOperationDO uop = uopList.get(0);\n BigInteger verificationGasLimitMax = uopList.stream().map(UserOperationDO::getVerificationGasLimit).max(Comparator.comparing(x -> x)).orElse(BigInteger.ZERO);\n IChain chain = uop.getChain();\n String entryPoint = uop.getEntryPoint();\n String data = getHandleOpsCallData(uopList, beneficiary);\n EthSendTransaction transaction = TransactionUtil.execute(chain, from,\n gasLimit.add(verificationGasLimitMax).add(ENTRYPOINT_EXT_GAS), entryPoint, null, data,\n false, maxFeePerGas, maxPriorityFeePerGas);\n ChainErrorUtil.throwChainError(transaction);\n\n return transaction.getTransactionHash();\n }\n\n public static String getHandleOpsCallData(List<UserOperationDO> ops, String beneficiary) {\n DynamicArray<DynamicStruct> userOps = new DynamicArray<>(DynamicStruct.class, ops.stream().map(UserOperationDO::toDynamicStruct).collect(Collectors.toList()));\n Function function = new Function(\"handleOps\", Lists.newArrayList(userOps, new Address(beneficiary)), Lists.newArrayList());\n return FunctionEncoder.encode(function);\n }\n\n public static BigInteger balanceOf(IChain chain, String entrypoint, String accountAddress) {\n List<Type> inputParameters = Lists.newArrayList(new Address(accountAddress));\n List<TypeReference<?>> outputParameters = Lists.newArrayList(TypeReference.create(Uint256.class));\n Function function = new Function(\"balanceOf\", inputParameters, outputParameters);\n EthCall call = TransactionUtil.call(null, entrypoint, FunctionEncoder.encode(function), chain);\n return (BigInteger) FunctionReturnDecoder.decode(call.getValue(), function.getOutputParameters()).get(0).getValue();\n }\n\n public static DepositInfo getDepositInfo(IChain chain, String entrypoint, String accountAddress) {\n List<Type> inputParameters = Lists.newArrayList(new Address(accountAddress));\n List<TypeReference<?>> outputParameters = Lists.newArrayList(TypeReference.create(DepositInfo.class));\n Function function = new Function(\"getDepositInfo\", inputParameters, outputParameters);\n EthCall call = TransactionUtil.call(null, entrypoint, FunctionEncoder.encode(function), chain);\n return (DepositInfo) FunctionReturnDecoder.decode(call.getValue(), function.getOutputParameters()).get(0);\n }\n}"
},
{
"identifier": "GasPriceInfo",
"path": "aa-pool/src/main/java/com/okcoin/dapp/bundler/pool/gasprice/GasPriceInfo.java",
"snippet": "@Data\n@NoArgsConstructor\npublic class GasPriceInfo {\n\n private BigInteger baseFee;\n\n private BigInteger maxPriorityFeePerGas;\n\n private long timestamp;\n\n public BigInteger resolveMaxFeePerGas() {\n // TODO YUKINO 2023/10/26: 优化price\n return MathUtil.multiply(baseFee, BigDecimal.valueOf(1.5)).add(maxPriorityFeePerGas);\n }\n\n public GasPriceInfo(BigInteger baseFee, BigInteger maxPriorityFeePerGas, long timestamp) {\n this.baseFee = baseFee;\n this.maxPriorityFeePerGas = maxPriorityFeePerGas;\n this.timestamp = timestamp;\n }\n}"
},
{
"identifier": "GasService",
"path": "aa-pool/src/main/java/com/okcoin/dapp/bundler/pool/gasprice/GasService.java",
"snippet": "@Component\npublic class GasService {\n\n private final Map<Long, GasPriceInfo> gasClientPriceInfoMap = Maps.newConcurrentMap();\n\n private final Map<Long, L1GasInfo> l1GasInfoMap = Maps.newConcurrentMap();\n\n @Autowired\n private ArbGasInfoContract arbGasInfoContract;\n\n @Autowired\n private OpL1BlockContract opL1BlockContract;\n\n @Autowired\n private GasConfig gasConfig;\n\n public GasPriceInfo getGasPriceInfoWithCache(IChain chain) {\n Map<Long, GasPriceInfo> gasPriceInfoMap = gasClientPriceInfoMap;\n GasPriceInfo gasPriceInfo = gasPriceInfoMap.get(chain.getChainId());\n long current = System.currentTimeMillis();\n\n if (gasPriceInfo != null && gasPriceInfo.getTimestamp() + TimeUnit.SECONDS.toMillis(gasConfig.getGasPriceCacheTimeSecond()) > current) {\n return gasPriceInfo;\n }\n\n gasPriceInfo = getGasPriceInfo(chain);\n gasPriceInfoMap.put(chain.getChainId(), gasPriceInfo);\n\n return gasPriceInfo;\n\n }\n\n public L1GasInfo getL1GasInfoWithCache(IChain chain) {\n L1GasInfo l1GasInfo = l1GasInfoMap.get(chain.getChainId());\n long current = System.currentTimeMillis();\n\n if (l1GasInfo != null && l1GasInfo.getTimestamp() + TimeUnit.SECONDS.toMillis(gasConfig.getGasPriceCacheTimeSecond()) > current) {\n return l1GasInfo;\n }\n\n l1GasInfo = getL1GasInfo(chain);\n l1GasInfoMap.put(chain.getChainId(), l1GasInfo);\n\n return l1GasInfo;\n\n }\n\n\n private GasPriceInfo getGasPriceInfo(IChain chain) {\n long timestamp = System.currentTimeMillis();\n BigInteger maxPriorityFeePerGas;\n BigInteger baseFee;\n if (chain.isEip1559()) {\n TransactionUtil.ChainFee chainFee = TransactionUtil.get1559GasPrice(chain, gasConfig.getRewardPercentile());\n maxPriorityFeePerGas = chainFee.getMaxPriorityFeePerGas();\n baseFee = chainFee.getBaseFee();\n } else {\n maxPriorityFeePerGas = TransactionUtil.getGasPrice(chain);\n baseFee = BigInteger.ZERO;\n }\n\n return new GasPriceInfo(baseFee, maxPriorityFeePerGas, timestamp);\n }\n\n private L1GasInfo getL1GasInfo(IChain chain) {\n L1GasInfo l1GasInfo;\n long timestamp = System.currentTimeMillis();\n if (chain.getChainId() == ChainIdConstant.ARB_MAIN) {\n BigInteger l1BaseFee = arbGasInfoContract.getL1BaseFeeEstimate(chain);\n l1GasInfo = new L1GasInfo(l1BaseFee, timestamp);\n } else {\n OpL1BlockInfo opL1BlockInfo = opL1BlockContract.getOpL1BlockInfo(chain);\n l1GasInfo = new L1GasInfo(opL1BlockInfo.getL1BaseFee(), timestamp);\n l1GasInfo.setL1FeeOverhead(opL1BlockInfo.getL1FeeOverhead());\n l1GasInfo.setL1FeeScalar(opL1BlockInfo.getL1FeeScalar());\n }\n\n return l1GasInfo;\n }\n}"
},
{
"identifier": "AccountFactory",
"path": "aa-rest/src/main/java/com/okcoin/dapp/bundler/rest/account/AccountFactory.java",
"snippet": "@Component\npublic class AccountFactory {\n\n @Autowired\n private Map<String, IAccount> accountMap;\n\n public IAccount get(String account) {\n return accountMap.get(AccountSimple.VERSION);\n\n }\n}"
},
{
"identifier": "AccountSignContext",
"path": "aa-rest/src/main/java/com/okcoin/dapp/bundler/rest/account/AccountSignContext.java",
"snippet": "@Getter\n@AllArgsConstructor\npublic class AccountSignContext {\n\n private final UserOperationDO uop;\n\n private final Credentials credentials;\n\n}"
},
{
"identifier": "IAccount",
"path": "aa-rest/src/main/java/com/okcoin/dapp/bundler/rest/account/IAccount.java",
"snippet": "public interface IAccount {\n\n String getInitFunc(String owner);\n\n String getCallData(List<SingleCallDataContext> context);\n\n String sign(AccountSignContext context);\n}"
},
{
"identifier": "SingleCallDataContext",
"path": "aa-rest/src/main/java/com/okcoin/dapp/bundler/rest/account/SingleCallDataContext.java",
"snippet": "@Getter\npublic class SingleCallDataContext {\n\n private final String to;\n\n private final BigInteger value;\n\n private final byte[] data;\n\n public SingleCallDataContext(String to, BigInteger value, byte[] data) {\n this.to = to;\n this.value = value;\n this.data = data;\n }\n}"
},
{
"identifier": "AAController",
"path": "aa-rest/src/main/java/com/okcoin/dapp/bundler/rest/api/AAController.java",
"snippet": "@RestController\n@RequestMapping(\"rpc\")\n@Slf4j\npublic class AAController {\n\n @Autowired\n private AAMethodProcessorFactory aaMethodProcessorFactory;\n\n @Autowired\n private ChainConfig chainConfig;\n\n @MultiChainRestLog\n @PostMapping\n public AAResp chain(@RequestBody AAReq request) {\n AAResp<Object> response = new AAResp<>();\n response.setId(request.getId());\n response.setJsonrpc(request.getJsonrpc());\n String method = request.getMethod();\n List<Object> params = request.getParams();\n try {\n AAMethodProcessor processor = aaMethodProcessorFactory.get(method);\n Object result = processor.process(chainConfig, params);\n response.setResult(result);\n } catch (AAException e) {\n log.error(\"{}, aa error\", method, e);\n response.setError(new AAError(e.getCode(), e.getMsg(), e.getData()));\n return response;\n } catch (Exception e) {\n log.error(\"{} error\", method, e);\n response.setError(new AAError(0, e.getMessage(), null));\n return response;\n }\n\n return response;\n }\n\n}"
},
{
"identifier": "AAReq",
"path": "aa-rest/src/main/java/com/okcoin/dapp/bundler/rest/api/req/AAReq.java",
"snippet": "@Data\npublic class AAReq {\n\n private String jsonrpc;\n\n private String method;\n\n private List<Object> params;\n\n private Long id;\n}"
},
{
"identifier": "UserOperationParam",
"path": "aa-rest/src/main/java/com/okcoin/dapp/bundler/rest/api/req/UserOperationParam.java",
"snippet": "@Data\npublic class UserOperationParam {\n\n protected String callData;\n private String sender;\n private String nonce;\n private String initCode;\n\n private String paymasterAndData;\n\n private String signature;\n\n private String callGasLimit = Web3Constant.HEX_ZERO;\n\n private String verificationGasLimit = Web3Constant.HEX_ZERO;\n\n private String preVerificationGas = Web3Constant.HEX_ZERO;\n\n private String maxFeePerGas = Web3Constant.HEX_ZERO;\n\n private String maxPriorityFeePerGas = Web3Constant.HEX_ZERO;\n\n @Override\n public String toString() {\n return JSON.toJSONString(this);\n }\n\n public void setSender(String sender) {\n this.sender = StringUtils.lowerCase(sender);\n }\n\n public void setNonce(String nonce) {\n this.nonce = StringUtils.lowerCase(nonce);\n }\n\n public void setInitCode(String initCode) {\n this.initCode = StringUtils.lowerCase(initCode);\n }\n\n public void setCallData(String callData) {\n this.callData = StringUtils.lowerCase(callData);\n }\n\n public void setCallGasLimit(String callGasLimit) {\n this.callGasLimit = StringUtils.lowerCase(callGasLimit);\n }\n\n public void setVerificationGasLimit(String verificationGasLimit) {\n this.verificationGasLimit = StringUtils.lowerCase(verificationGasLimit);\n }\n\n public void setPreVerificationGas(String preVerificationGas) {\n this.preVerificationGas = StringUtils.lowerCase(preVerificationGas);\n }\n\n public void setMaxFeePerGas(String maxFeePerGas) {\n this.maxFeePerGas = StringUtils.lowerCase(maxFeePerGas);\n }\n\n public void setMaxPriorityFeePerGas(String maxPriorityFeePerGas) {\n this.maxPriorityFeePerGas = StringUtils.lowerCase(maxPriorityFeePerGas);\n }\n\n public void setPaymasterAndData(String paymasterAndData) {\n this.paymasterAndData = StringUtils.lowerCase(paymasterAndData);\n }\n\n public void setSignature(String signature) {\n this.signature = StringUtils.lowerCase(signature);\n }\n}"
},
{
"identifier": "AAResp",
"path": "aa-rest/src/main/java/com/okcoin/dapp/bundler/rest/api/resp/AAResp.java",
"snippet": "@Data\npublic class AAResp<E> {\n\n private long id;\n\n private String jsonrpc;\n\n private E result;\n\n private AAError error;\n}"
},
{
"identifier": "EstimateUserOperationGasVO",
"path": "aa-rest/src/main/java/com/okcoin/dapp/bundler/rest/api/resp/EstimateUserOperationGasVO.java",
"snippet": "@Data\npublic class EstimateUserOperationGasVO {\n\n private String preVerificationGas;\n\n private String verificationGasLimit;\n\n private String callGasLimit;\n\n private String validAfter;\n\n private String validUntil;\n\n public EstimateUserOperationGasVO(BigInteger preVerificationGas, BigInteger verificationGasLimit, BigInteger callGasLimit, long validAfter, long validUntil) {\n this.preVerificationGas = Numeric.encodeQuantity(preVerificationGas);\n this.verificationGasLimit = Numeric.encodeQuantity(verificationGasLimit);\n this.callGasLimit = Numeric.encodeQuantity(callGasLimit);\n this.validAfter = Numeric.encodeQuantity(BigInteger.valueOf(validAfter));\n this.validUntil = Numeric.encodeQuantity(BigInteger.valueOf(validUntil));\n }\n}"
},
{
"identifier": "AaMethodConstant",
"path": "aa-rest/src/main/java/com/okcoin/dapp/bundler/rest/constant/AaMethodConstant.java",
"snippet": "public interface AaMethodConstant {\n\n String ETH_SUPPORTED_ENTRY_POINTS = \"eth_supportedEntryPoints\";\n\n String ETH_GET_USER_OPERATION_BY_HASH = \"eth_getUserOperationByHash\";\n\n String ETH_GET_USER_OPERATION_RECEIPT = \"eth_getUserOperationReceipt\";\n\n String ETH_ESTIMATE_USER_OPERATION_GAS = \"eth_estimateUserOperationGas\";\n\n String ETH_SEND_USER_OPERATION = \"eth_sendUserOperation\";\n\n String ETH_CHAIN_ID = \"eth_chainId\";\n\n String WEB3_CLIENT_VERSION = \"web3_clientVersion\";\n\n String DEBUG_BUNDLER_CLEAR_STATE = \"debug_bundler_clearState\";\n\n String DEBUG_BUNDLER_CLEAR_MEMPOOL = \"debug_bundler_clearMempool\";\n\n String DEBUG_BUNDLER_DUMP_MEMPOOL = \"debug_bundler_dumpMempool\";\n\n String DEBUG_BUNDLER_SEND_BUNDLE_NOW = \"debug_bundler_sendBundleNow\";\n\n String DEBUG_BUNDLER_SET_BUNDLING_MODE = \"debug_bundler_setBundlingMode\";\n\n String DEBUG_BUNDLER_SET_BUNDLE_INTERVAL = \"debug_bundler_setBundleInterval\";\n\n String DEBUG_BUNDLER_SET_REPUTATION = \"debug_bundler_setReputation\";\n\n String DEBUG_BUNDLER_DUMP_REPUTATION = \"debug_bundler_dumpReputation\";\n\n String DEBUG_BUNDLER_CLEAR_REPUTATION = \"debug_bundler_clearReputation\";\n\n String DEBUG_BUNDLER_GET_STAKE_STATUS = \"debug_bundler_getStakeStatus\";\n}"
},
{
"identifier": "AccountFactoryFactory",
"path": "aa-rest/src/main/java/com/okcoin/dapp/bundler/rest/factory/AccountFactoryFactory.java",
"snippet": "@Component\npublic class AccountFactoryFactory {\n\n @Autowired\n private Map<String, IAccountFactory> accountFactoryMap;\n\n public IAccountFactory get(String accountFactory) {\n return accountFactoryMap.get(AccountFactorySimple.VERSION);\n }\n}"
},
{
"identifier": "IAccountFactory",
"path": "aa-rest/src/main/java/com/okcoin/dapp/bundler/rest/factory/IAccountFactory.java",
"snippet": "public abstract class IAccountFactory {\n\n public abstract String getInitCode(InitCodeContext context);\n\n public abstract String getSenderAddress(SenderAddressContext context, IChain chain);\n}"
},
{
"identifier": "InitCodeContext",
"path": "aa-rest/src/main/java/com/okcoin/dapp/bundler/rest/factory/InitCodeContext.java",
"snippet": "@Getter\npublic class InitCodeContext {\n\n private final String factory;\n\n private final String owner;\n\n private final BigInteger salt;\n\n public InitCodeContext(String factory, String owner, BigInteger salt) {\n this.factory = factory;\n this.owner = owner;\n this.salt = salt;\n }\n}"
},
{
"identifier": "SenderAddressContext",
"path": "aa-rest/src/main/java/com/okcoin/dapp/bundler/rest/factory/SenderAddressContext.java",
"snippet": "@Getter\npublic class SenderAddressContext {\n\n private final String initCode;\n\n private final String entrypoint;\n\n\n public SenderAddressContext(String initCode, String entrypoint) {\n this.initCode = initCode;\n this.entrypoint = entrypoint;\n }\n}"
},
{
"identifier": "UopUtil",
"path": "aa-rest/src/main/java/com/okcoin/dapp/bundler/rest/util/UopUtil.java",
"snippet": "@Slf4j\npublic class UopUtil {\n\n public static UserOperationDO toUserOperationDO(UserOperationParam param, IChain chain, String entryPointAddress) {\n UserOperationDO uop = UserOperationDO.newUserOperationDO();\n uop.setOpStatus(UserOperationStatusEnum.WAITING);\n uop.setChain(chain);\n uop.setEntryPoint(entryPointAddress);\n uop.setSender(param.getSender());\n uop.setNonce(Numeric.decodeQuantity(param.getNonce()));\n uop.setInitCode(param.getInitCode());\n uop.setCallData(param.getCallData());\n uop.setPaymasterAndData(param.getPaymasterAndData());\n uop.setSignature(param.getSignature());\n\n uop.setCallGasLimit(Numeric.decodeQuantity(param.getCallGasLimit()));\n uop.setVerificationGasLimit(Numeric.decodeQuantity(param.getVerificationGasLimit()));\n uop.setPreVerificationGas(Numeric.decodeQuantity(param.getPreVerificationGas()));\n uop.setMaxFeePerGas(Numeric.decodeQuantity(param.getMaxFeePerGas()));\n uop.setMaxPriorityFeePerGas(Numeric.decodeQuantity(param.getMaxPriorityFeePerGas()));\n return uop;\n }\n\n public static UserOperationDO copy(UserOperationDO oldUop) {\n UserOperationDO uop = UserOperationDO.newUserOperationDO();\n uop.setChain(oldUop.getChain());\n uop.setEntryPoint(oldUop.getEntryPoint());\n uop.setOpStatus(oldUop.getOpStatus());\n uop.setSender(oldUop.getSender());\n uop.setNonce(oldUop.getNonce());\n uop.setInitCode(oldUop.getInitCode());\n uop.setCallData(oldUop.getCallData());\n uop.setCallGasLimit(oldUop.getCallGasLimit());\n uop.setVerificationGasLimit(oldUop.getVerificationGasLimit());\n uop.setPreVerificationGas(oldUop.getPreVerificationGas());\n uop.setMaxFeePerGas(oldUop.getMaxFeePerGas());\n uop.setMaxPriorityFeePerGas(oldUop.getMaxPriorityFeePerGas());\n uop.setPaymasterAndData(oldUop.getPaymasterAndData());\n uop.setSignature(oldUop.getSignature());\n return uop;\n }\n\n public static UserOperationDO toUserOperationDO(IChain chain, String entryPoint, Tuple tuple) {\n UserOperationDO uop = UserOperationDO.newUserOperationDO();\n uop.setChain(chain);\n uop.setEntryPoint(entryPoint.toLowerCase());\n uop.setOpStatus(UserOperationStatusEnum.SUCCEED);\n uop.setSender(tuple.get(0).toString().toLowerCase());\n uop.setNonce(tuple.get(1));\n uop.setInitCode(Numeric.toHexString(tuple.get(2)));\n uop.setCallData(Numeric.toHexString(tuple.get(3)));\n uop.setCallGasLimit(tuple.get(4));\n uop.setVerificationGasLimit(tuple.get(5));\n uop.setPreVerificationGas(tuple.get(6));\n uop.setMaxFeePerGas(tuple.get(7));\n uop.setMaxPriorityFeePerGas(tuple.get(8));\n uop.setPaymasterAndData(Numeric.toHexString(tuple.get(9)));\n uop.setSignature(Numeric.toHexString(tuple.get(10)));\n return uop;\n }\n\n public static UserOperationOnChainVO toUserOperationVo(Transaction transaction, UserOperationDO uop) {\n UserOperationOnChainVO resultVO = new UserOperationOnChainVO();\n resultVO.setUserOperation(toUserOperationVO(uop));\n resultVO.setEntryPoint(CodecUtil.toChecksumAddress(uop.getEntryPoint()));\n resultVO.setBlockHash(transaction.getBlockHash());\n resultVO.setBlockNumber(Numeric.encodeQuantity(transaction.getBlockNumber()));\n resultVO.setTransactionHash(transaction.getHash());\n return resultVO;\n }\n\n public static List<UserOperationVO> convertDoToUserOperationVO(List<UserOperationDO> userOperationDOs) {\n List<UserOperationVO> userOperationOnChainVOS = new ArrayList<>();\n for (UserOperationDO userOperationDO : userOperationDOs) {\n userOperationOnChainVOS.add(toUserOperationVO(userOperationDO));\n }\n return userOperationOnChainVOS;\n }\n\n private static UserOperationVO toUserOperationVO(UserOperationDO uop) {\n UserOperationVO uopVO = new UserOperationVO();\n uopVO.setSender(CodecUtil.toChecksumAddress(uop.getSender()));\n uopVO.setNonce(Numeric.toHexStringWithPrefix(uop.getNonce()));\n uopVO.setInitCode(uop.getInitCode());\n // TODO YUKINO 2023/10/30: 不应该有大小写区分\n if (!uop.getFactory().equals(Web3Constant.HEX_PREFIX)) {\n uopVO.setInitCode(CodecUtil.toChecksumAddress(uop.getFactory()) + uop.getInitCode().substring(Web3Constant.ADDRESS_WITH_HEX_PREFIX));\n }\n uopVO.setCallData(uop.getCallData());\n uopVO.setCallGasLimit(Numeric.toHexStringWithPrefix(uop.getCallGasLimit()));\n uopVO.setVerificationGasLimit(Numeric.toHexStringWithPrefix(uop.getVerificationGasLimit()));\n uopVO.setPreVerificationGas(Numeric.toHexStringWithPrefix(uop.getPreVerificationGas()));\n uopVO.setMaxFeePerGas(Numeric.toHexStringWithPrefix(uop.getMaxFeePerGas()));\n uopVO.setMaxPriorityFeePerGas(Numeric.toHexStringWithPrefix(uop.getMaxPriorityFeePerGas()));\n uopVO.setPaymasterAndData(uop.getPaymasterAndData());\n uopVO.setSignature(uop.getSignature());\n\n return uopVO;\n }\n}"
}
] | import com.alibaba.fastjson2.JSON;
import com.google.common.collect.Lists;
import com.okcoin.dapp.bundler.infra.chain.AccountUtil;
import com.okcoin.dapp.bundler.infra.chain.constant.Web3Constant;
import com.okcoin.dapp.bundler.pool.config.ChainConfig;
import com.okcoin.dapp.bundler.pool.config.PoolConfig;
import com.okcoin.dapp.bundler.pool.entrypoint.Entrypoint;
import com.okcoin.dapp.bundler.pool.gasprice.GasPriceInfo;
import com.okcoin.dapp.bundler.pool.gasprice.GasService;
import com.okcoin.dapp.bundler.rest.account.AccountFactory;
import com.okcoin.dapp.bundler.rest.account.AccountSignContext;
import com.okcoin.dapp.bundler.rest.account.IAccount;
import com.okcoin.dapp.bundler.rest.account.SingleCallDataContext;
import com.okcoin.dapp.bundler.rest.api.AAController;
import com.okcoin.dapp.bundler.rest.api.req.AAReq;
import com.okcoin.dapp.bundler.rest.api.req.UserOperationParam;
import com.okcoin.dapp.bundler.rest.api.resp.AAResp;
import com.okcoin.dapp.bundler.rest.api.resp.EstimateUserOperationGasVO;
import com.okcoin.dapp.bundler.rest.constant.AaMethodConstant;
import com.okcoin.dapp.bundler.rest.factory.AccountFactoryFactory;
import com.okcoin.dapp.bundler.rest.factory.IAccountFactory;
import com.okcoin.dapp.bundler.rest.factory.InitCodeContext;
import com.okcoin.dapp.bundler.rest.factory.SenderAddressContext;
import com.okcoin.dapp.bundler.rest.util.UopUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.web3j.abi.datatypes.DynamicBytes;
import org.web3j.crypto.Credentials;
import org.web3j.utils.Numeric;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.List; | 6,946 | package com.okcoin.dapp.bundler.rest.test;
@RestController
@RequestMapping
@Slf4j
public class NewTestController {
private static final String FAKE_SIGN_FOR_EVM = "0x7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a07fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a01b";
@Autowired
private AAController aaController;
@Autowired
private AccountFactory accountFactory;
@Autowired | package com.okcoin.dapp.bundler.rest.test;
@RestController
@RequestMapping
@Slf4j
public class NewTestController {
private static final String FAKE_SIGN_FOR_EVM = "0x7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a07fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a01b";
@Autowired
private AAController aaController;
@Autowired
private AccountFactory accountFactory;
@Autowired | private AccountFactoryFactory accountFactoryFactory; | 17 | 2023-11-27 10:54:49+00:00 | 8k |
lidaofu-hub/j_media_server | src/main/java/com/ldf/media/api/service/impl/ApiServiceImpl.java | [
{
"identifier": "MediaInfoResult",
"path": "src/main/java/com/ldf/media/api/model/result/MediaInfoResult.java",
"snippet": "@Data\n@ApiModel(value = \"GetMediaListParam对象\", description = \"流信息\")\npublic class MediaInfoResult implements Serializable {\n\n private static final long serialVersionUID = 1;\n\n @ApiModelProperty(value = \"app\")\n private String app;\n\n @ApiModelProperty(value = \"流id\")\n private String stream;\n\n @ApiModelProperty(value = \"本协议观看人数\")\n private Integer readerCount;\n\n @ApiModelProperty(value = \"产生源类型,包括 unknown = 0,rtmp_push=1,rtsp_push=2,rtp_push=3,pull=4,ffmpeg_pull=5,mp4_vod=6,device_chn=7\")\n private Integer originType;\n\n @ApiModelProperty(value = \"产生源的url\")\n private String originUrl;\n\n @ApiModelProperty(value = \"产生源的url的类型\")\n private String originTypeStr;\n\n @ApiModelProperty(value = \"观看总数 包括hls/rtsp/rtmp/http-flv/ws-flv\")\n private Integer totalReaderCount;\n\n @ApiModelProperty(value = \"schema\")\n private String schema;\n\n @ApiModelProperty(value = \"存活时间,单位秒\")\n private Integer aliveSecond;\n\n @ApiModelProperty(value = \"数据产生速度,单位byte/s\")\n private Long bytesSpeed;\n\n @ApiModelProperty(value = \"GMT unix系统时间戳,单位秒\")\n private Long createStamp;\n\n @ApiModelProperty(value = \"是否录制Hls\")\n private Boolean isRecordingHLS;\n\n @ApiModelProperty(value = \"是否录制mp4\")\n private Boolean isRecordingMP4;\n\n @ApiModelProperty(value = \"虚拟地址\")\n private String vhost;\n\n private List<Track> tracks;\n\n\n}"
},
{
"identifier": "Track",
"path": "src/main/java/com/ldf/media/api/model/result/Track.java",
"snippet": "@Data\npublic class Track implements Serializable {\n private static final long serialVersionUID = 1;\n\n private Integer is_video;\n private Integer codec_id;\n private String codec_id_name;\n private Integer codec_type;\n private Integer fps;\n private Integer frames;\n private Integer bit_rate;\n private Integer gop_interval_ms;\n private Integer gop_size;\n private Integer height;\n private Integer key_frames;\n private Integer loss;\n private Boolean ready;\n private Integer width;\n private Integer sample_rate;\n private Integer audio_channel;\n private Integer audio_sample_bit;\n\n}"
},
{
"identifier": "IApiService",
"path": "src/main/java/com/ldf/media/api/service/IApiService.java",
"snippet": "public interface IApiService {\n\n void addStreamProxy(StreamProxyParam param);\n\n Integer closeStream(CloseStreamParam param);\n\n Integer closeStreams(CloseStreamsParam param);\n List<MediaInfoResult> getMediaList(GetMediaListParam param);\n\n Boolean startRecord(StartRecordParam param);\n\n Boolean stopRecord(StopRecordParam param);\n\n Boolean isRecording(RecordStatusParam param);\n}"
},
{
"identifier": "MKSourceFindCallBack",
"path": "src/main/java/com/ldf/media/callback/MKSourceFindCallBack.java",
"snippet": "public class MKSourceFindCallBack implements IMKSourceFindCallBack {\n private IMKSourceHandleCallBack imkSourceHandleCallBack;\n\n public MKSourceFindCallBack(IMKSourceHandleCallBack imkSourceHandleCallBack) {\n this.imkSourceHandleCallBack = imkSourceHandleCallBack;\n //回调使用同一个线程\n Native.setCallbackThreadInitializer(this, new CallbackThreadInitializer(true, false, \"MediaSourceFindThread\"));\n }\n\n public void invoke(Pointer user_data, MK_MEDIA_SOURCE ctx) {\n imkSourceHandleCallBack.invoke(ctx);\n }\n}"
},
{
"identifier": "MediaServerConstants",
"path": "src/main/java/com/ldf/media/constants/MediaServerConstants.java",
"snippet": "public interface MediaServerConstants {\n\n /**\n * 默认vhost\n */\n String DEFAULT_VHOST=\"__defaultVhost__\";\n\n /**\n * 默认app\n */\n String DEFAULT_APP=\"live\";\n}"
},
{
"identifier": "MediaServerContext",
"path": "src/main/java/com/ldf/media/context/MediaServerContext.java",
"snippet": "@Slf4j\n@Component\npublic class MediaServerContext {\n @Autowired\n private MediaServerConfig config;\n public static ZLMApi ZLM_API = null;\n private static MK_EVENTS MK_EVENTS = null;\n\n @PostConstruct\n public void initMediaServer() {\n ZLM_API = Native.load(\"mk_api\", ZLMApi.class);\n log.info(\"【MediaServer】初始化MediaServer程序成功\");\n this.initServerConf();\n }\n\n\n public void initServerConf() {\n //初始化环境配置\n MK_INI mkIni = ZLM_API.mk_ini_default();\n ZLM_API.mk_ini_set_option(mkIni, \"general.mediaServerId\", \"JMediaServer\");\n ZLM_API.mk_ini_set_option(mkIni, \"http.notFound\", \"<h1 style=\\\"text-align:center;\\\">Media Server V1.0 By LiDaoFu</h1>\");\n ZLM_API.mk_ini_set_option_int(mkIni, \"protocol.auto_close\", config.getAuto_close());\n ZLM_API.mk_ini_set_option_int(mkIni, \"general.streamNoneReaderDelayMS\", config.getStreamNoneReaderDelayMS());\n ZLM_API.mk_ini_set_option_int(mkIni, \"general.maxStreamWaitMS\", config.getMaxStreamWaitMS());\n ZLM_API.mk_ini_set_option_int(mkIni, \"protocol.enable_ts\", config.getEnable_ts());\n ZLM_API.mk_ini_set_option_int(mkIni, \"protocol.enable_hls\", config.getEnable_hls());\n ZLM_API.mk_ini_set_option_int(mkIni, \"protocol.enable_fmp4\", config.getEnable_fmp4());\n ZLM_API.mk_ini_set_option_int(mkIni, \"protocol.enable_rtsp\", config.getEnable_rtsp());\n ZLM_API.mk_ini_set_option_int(mkIni, \"protocol.enable_rtmp\", config.getEnable_rtmp());\n ZLM_API.mk_ini_set_option_int(mkIni, \"protocol.enable_mp4\", config.getEnable_mp4());\n ZLM_API.mk_ini_set_option_int(mkIni, \"protocol.enable_hls_fmp4\", config.getEnable_hls_fmp4());\n ZLM_API.mk_ini_set_option_int(mkIni, \"protocol.enable_audio\", config.getEnable_audio());\n ZLM_API.mk_ini_set_option_int(mkIni, \"protocol.mp4_as_player\", config.getMp4_as_player());\n ZLM_API.mk_ini_set_option_int(mkIni, \"protocol.mp4_max_second\", config.getMp4_max_second());\n ZLM_API.mk_ini_set_option(mkIni, \"http.rootPath\", config.getRootPath());\n ZLM_API.mk_ini_set_option(mkIni, \"protocol.mp4_save_path\", config.getMp4_save_path());\n ZLM_API.mk_ini_set_option(mkIni, \"protocol.hls_save_path\", config.getHls_save_path());\n ZLM_API.mk_ini_set_option_int(mkIni, \"protocol.hls_demand\", config.getHls_demand());\n ZLM_API.mk_ini_set_option_int(mkIni, \"protocol.rtsp_demand\", config.getRtsp_demand());\n ZLM_API.mk_ini_set_option_int(mkIni, \"protocol.rtmp_demand\", config.getRtmp_demand());\n ZLM_API.mk_ini_set_option_int(mkIni, \"protocol.ts_demand\", config.getTs_demand());\n ZLM_API.mk_ini_set_option_int(mkIni, \"protocol.fmp4_demand\", config.getFmp4_demand());\n //全局回调\n MK_EVENTS = new MK_EVENTS();\n MK_EVENTS.on_mk_media_changed = new MKStreamChangeCallBack();\n MK_EVENTS.on_mk_media_no_reader = new MKNoReaderCallBack();\n MK_EVENTS.on_mk_media_publish = new MKPublishCallBack();\n MK_EVENTS.on_mk_media_not_found = new MKNoFoundCallBack();\n MK_EVENTS.on_mk_flow_report = new MKHttpFlowReportCallBack();\n MK_EVENTS.on_mk_media_play = new MKPlayCallBack();\n /* MK_EVENTS.on_mk_http_access = new MKHttpAccessCallBack();\n MK_EVENTS.on_mk_http_request = new MKHttpRequestCallBack();\n MK_EVENTS.on_mk_http_access = new MKHttpAccessCallBack();\n MK_EVENTS.on_mk_http_before_access = new MKHttpBeforeAccessCallBack();*/\n MK_EVENTS.on_mk_record_mp4 = new MKRecordMp4CallBack();\n MK_EVENTS.on_mk_log = new MKLogCallBack();\n //添加全局回调\n ZLM_API.mk_events_listen(MK_EVENTS);\n //初始化zmk服务器\n ZLM_API.mk_env_init1(config.getThread_num(), config.getLog_level(), config.getLog_mask(), config.getLog_path(), config.getLog_file_days(), 0, null, 0, null, null);\n //创建http服务器 0:失败,非0:端口号\n short http_server_port = ZLM_API.mk_http_server_start(config.getHttp_port().shortValue(), 0);\n log.info(\"【MediaServer】HTTP流媒体服务启动:{}\", http_server_port == 0 ? \"失败\" : \"成功,端口:\" + http_server_port);\n //创建rtsp服务器 0:失败,非0:端口号\n short rtsp_server_port = ZLM_API.mk_rtsp_server_start(config.getRtsp_port().shortValue(), 0);\n log.info(\"【MediaServer】RTSP流媒体服务启动:{}\", rtsp_server_port == 0 ? \"失败\" : \"成功,端口:\" + rtsp_server_port);\n //创建rtmp服务器 0:失败,非0:端口号\n short rtmp_server_port = ZLM_API.mk_rtmp_server_start(config.getRtmp_port().shortValue(), 0);\n log.info(\"【MediaServer】RTMP流媒体服务启动:{}\", rtmp_server_port == 0 ? \"失败\" : \"成功,端口:\" + rtmp_server_port);\n }\n\n @PreDestroy\n public void release() {\n ZLM_API.mk_stop_all_server();\n log.info(\"【MediaServer】关闭所有流媒体服务\");\n }\n}"
},
{
"identifier": "IMKProxyPlayCloseCallBack",
"path": "src/main/java/com/ldf/media/sdk/callback/IMKProxyPlayCloseCallBack.java",
"snippet": "public interface IMKProxyPlayCloseCallBack extends Callback {\n /**\n * MediaSource.close()回调事件\n * 在选择关闭一个关联的MediaSource时,将会最终触发到该回调\n * 你应该通过该事件调用mk_proxy_player_release函数并且释放其他资源\n * 如果你不调用mk_proxy_player_release函数,那么MediaSource.close()操作将无效\n *\n * @param pUser 用户数据指针,通过mk_proxy_player_set_on_close函数设置\n */\n public void invoke(Pointer pUser, int err, String what, int sys_err);\n}"
},
{
"identifier": "MK_MEDIA_SOURCE",
"path": "src/main/java/com/ldf/media/sdk/structure/MK_MEDIA_SOURCE.java",
"snippet": "public class MK_MEDIA_SOURCE extends SdkStructure {\n public int dwSize;\n public MK_MEDIA_SOURCE(Pointer pointer) {\n super(pointer);\n }\n public MK_MEDIA_SOURCE() {\n }\n}"
},
{
"identifier": "MK_PROXY_PLAYER",
"path": "src/main/java/com/ldf/media/sdk/structure/MK_PROXY_PLAYER.java",
"snippet": "public class MK_PROXY_PLAYER extends SdkStructure {\n public int dwSize;\n public MK_PROXY_PLAYER(Pointer pointer) {\n super(pointer);\n }\n public MK_PROXY_PLAYER() {\n }\n\n}"
},
{
"identifier": "MK_TRACK",
"path": "src/main/java/com/ldf/media/sdk/structure/MK_TRACK.java",
"snippet": "public class MK_TRACK extends SdkStructure {\n public int dwSize;\n\n public MK_TRACK(Pointer pointer){\n super(pointer);\n }\n public MK_TRACK() {\n }\n}"
}
] | import cn.hutool.core.lang.Assert;
import com.ldf.media.api.model.param.*;
import com.ldf.media.api.model.result.MediaInfoResult;
import com.ldf.media.api.model.result.Track;
import com.ldf.media.api.service.IApiService;
import com.ldf.media.callback.MKSourceFindCallBack;
import com.ldf.media.constants.MediaServerConstants;
import com.ldf.media.context.MediaServerContext;
import com.ldf.media.sdk.callback.IMKProxyPlayCloseCallBack;
import com.ldf.media.sdk.structure.MK_MEDIA_SOURCE;
import com.ldf.media.sdk.structure.MK_PROXY_PLAYER;
import com.ldf.media.sdk.structure.MK_TRACK;
import com.sun.jna.Pointer;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference; | 3,836 | package com.ldf.media.api.service.impl;
/**
* 接口服务
*
* @author lidaofu
* @since 2023/11/29
**/
@Service
public class ApiServiceImpl implements IApiService {
@Override
public void addStreamProxy(StreamProxyParam param) {
//查询流是是否存在
MK_MEDIA_SOURCE mkMediaSource = MediaServerContext.ZLM_API.mk_media_source_find2(param.getEnableRtmp() == 1 ? "rtmp" : "rtsp", MediaServerConstants.DEFAULT_VHOST, param.getApp(), param.getStream(), 0);
Assert.isNull(mkMediaSource, "当前流信息已被使用");
//创建拉流代理
MK_PROXY_PLAYER mk_proxy = MediaServerContext.ZLM_API.mk_proxy_player_create(MediaServerConstants.DEFAULT_VHOST, param.getApp(), param.getStream(), param.getEnableHls(), param.getEnableMp4(), param.getEnableFmp4(), param.getEnableTs(), param.getEnableRtmp(), param.getEnableRtsp());
//回调关闭时间
IMKProxyPlayCloseCallBack imkProxyPlayCloseCallBack = (pUser, err, what, sys_err) -> {
//这里Pointer是ZLM维护的不需要我们释放 遵循谁申请谁释放原则
MediaServerContext.ZLM_API.mk_proxy_player_release(new MK_PROXY_PLAYER(pUser));
};
MediaServerContext.ZLM_API.mk_proxy_player_set_option(mk_proxy, "rtp_type", param.getRtpType().toString());
//开始播放
MediaServerContext.ZLM_API.mk_proxy_player_play(mk_proxy, param.getUrl());
//添加代理关闭回调 并把代理客户端传过去释放
MediaServerContext.ZLM_API.mk_proxy_player_set_on_close(mk_proxy, imkProxyPlayCloseCallBack, mk_proxy.getPointer());
}
@Override
public Integer closeStream(CloseStreamParam param) {
//查询流是是否存在
MK_MEDIA_SOURCE mkMediaSource = MediaServerContext.ZLM_API.mk_media_source_find2(param.getSchema(), MediaServerConstants.DEFAULT_VHOST, param.getApp(), param.getStream(), 0);
Assert.notNull(mkMediaSource, "当前流不在线");
return MediaServerContext.ZLM_API.mk_media_source_close(mkMediaSource, param.getForce());
}
@Override
public Integer closeStreams(CloseStreamsParam param) {
AtomicReference<Integer> count = new AtomicReference<>(0);
MediaServerContext.ZLM_API.mk_media_source_for_each(Pointer.NULL, new MKSourceFindCallBack((MK_MEDIA_SOURCE ctx) -> {
int status = MediaServerContext.ZLM_API.mk_media_source_close(ctx, param.getForce());
count.set(count.get() + status);
}), param.getSchema(), MediaServerConstants.DEFAULT_VHOST, param.getApp(), param.getStream());
try {
Thread.sleep(200L);
} catch (InterruptedException ignored) {
}
return count.get();
}
@Override
public List<MediaInfoResult> getMediaList(GetMediaListParam param) {
List<MediaInfoResult> list = new ArrayList<>();
MediaServerContext.ZLM_API.mk_media_source_for_each(Pointer.NULL, new MKSourceFindCallBack((MK_MEDIA_SOURCE ctx) -> {
String app = MediaServerContext.ZLM_API.mk_media_source_get_app(ctx);
String stream = MediaServerContext.ZLM_API.mk_media_source_get_stream(ctx);
String schema = MediaServerContext.ZLM_API.mk_media_source_get_schema(ctx);
int readerCount = MediaServerContext.ZLM_API.mk_media_source_get_reader_count(ctx);
int totalReaderCount = MediaServerContext.ZLM_API.mk_media_source_get_total_reader_count(ctx);
int trackSize = MediaServerContext.ZLM_API.mk_media_source_get_track_count(ctx);
MediaInfoResult mediaInfoResult = new MediaInfoResult();
mediaInfoResult.setApp(app);
mediaInfoResult.setStream(stream);
mediaInfoResult.setSchema(schema);
mediaInfoResult.setReaderCount(readerCount);
mediaInfoResult.setTotalReaderCount(totalReaderCount);
List<Track> tracks = new ArrayList<>();
for (int i = 0; i < trackSize; i++) { | package com.ldf.media.api.service.impl;
/**
* 接口服务
*
* @author lidaofu
* @since 2023/11/29
**/
@Service
public class ApiServiceImpl implements IApiService {
@Override
public void addStreamProxy(StreamProxyParam param) {
//查询流是是否存在
MK_MEDIA_SOURCE mkMediaSource = MediaServerContext.ZLM_API.mk_media_source_find2(param.getEnableRtmp() == 1 ? "rtmp" : "rtsp", MediaServerConstants.DEFAULT_VHOST, param.getApp(), param.getStream(), 0);
Assert.isNull(mkMediaSource, "当前流信息已被使用");
//创建拉流代理
MK_PROXY_PLAYER mk_proxy = MediaServerContext.ZLM_API.mk_proxy_player_create(MediaServerConstants.DEFAULT_VHOST, param.getApp(), param.getStream(), param.getEnableHls(), param.getEnableMp4(), param.getEnableFmp4(), param.getEnableTs(), param.getEnableRtmp(), param.getEnableRtsp());
//回调关闭时间
IMKProxyPlayCloseCallBack imkProxyPlayCloseCallBack = (pUser, err, what, sys_err) -> {
//这里Pointer是ZLM维护的不需要我们释放 遵循谁申请谁释放原则
MediaServerContext.ZLM_API.mk_proxy_player_release(new MK_PROXY_PLAYER(pUser));
};
MediaServerContext.ZLM_API.mk_proxy_player_set_option(mk_proxy, "rtp_type", param.getRtpType().toString());
//开始播放
MediaServerContext.ZLM_API.mk_proxy_player_play(mk_proxy, param.getUrl());
//添加代理关闭回调 并把代理客户端传过去释放
MediaServerContext.ZLM_API.mk_proxy_player_set_on_close(mk_proxy, imkProxyPlayCloseCallBack, mk_proxy.getPointer());
}
@Override
public Integer closeStream(CloseStreamParam param) {
//查询流是是否存在
MK_MEDIA_SOURCE mkMediaSource = MediaServerContext.ZLM_API.mk_media_source_find2(param.getSchema(), MediaServerConstants.DEFAULT_VHOST, param.getApp(), param.getStream(), 0);
Assert.notNull(mkMediaSource, "当前流不在线");
return MediaServerContext.ZLM_API.mk_media_source_close(mkMediaSource, param.getForce());
}
@Override
public Integer closeStreams(CloseStreamsParam param) {
AtomicReference<Integer> count = new AtomicReference<>(0);
MediaServerContext.ZLM_API.mk_media_source_for_each(Pointer.NULL, new MKSourceFindCallBack((MK_MEDIA_SOURCE ctx) -> {
int status = MediaServerContext.ZLM_API.mk_media_source_close(ctx, param.getForce());
count.set(count.get() + status);
}), param.getSchema(), MediaServerConstants.DEFAULT_VHOST, param.getApp(), param.getStream());
try {
Thread.sleep(200L);
} catch (InterruptedException ignored) {
}
return count.get();
}
@Override
public List<MediaInfoResult> getMediaList(GetMediaListParam param) {
List<MediaInfoResult> list = new ArrayList<>();
MediaServerContext.ZLM_API.mk_media_source_for_each(Pointer.NULL, new MKSourceFindCallBack((MK_MEDIA_SOURCE ctx) -> {
String app = MediaServerContext.ZLM_API.mk_media_source_get_app(ctx);
String stream = MediaServerContext.ZLM_API.mk_media_source_get_stream(ctx);
String schema = MediaServerContext.ZLM_API.mk_media_source_get_schema(ctx);
int readerCount = MediaServerContext.ZLM_API.mk_media_source_get_reader_count(ctx);
int totalReaderCount = MediaServerContext.ZLM_API.mk_media_source_get_total_reader_count(ctx);
int trackSize = MediaServerContext.ZLM_API.mk_media_source_get_track_count(ctx);
MediaInfoResult mediaInfoResult = new MediaInfoResult();
mediaInfoResult.setApp(app);
mediaInfoResult.setStream(stream);
mediaInfoResult.setSchema(schema);
mediaInfoResult.setReaderCount(readerCount);
mediaInfoResult.setTotalReaderCount(totalReaderCount);
List<Track> tracks = new ArrayList<>();
for (int i = 0; i < trackSize; i++) { | MK_TRACK mkTrack = MediaServerContext.ZLM_API.mk_media_source_get_track(ctx, i); | 9 | 2023-11-29 07:47:56+00:00 | 8k |
seraxis/lr2oraja-endlessdream | core/src/bms/player/beatoraja/skin/json/JsonSelectSkinObjectLoader.java | [
{
"identifier": "MusicSelectSkin",
"path": "core/src/bms/player/beatoraja/select/MusicSelectSkin.java",
"snippet": "public class MusicSelectSkin extends Skin {\n\n\t/**\n\t * カーソルが合っているBarのindex\n\t */\n\tprivate int centerBar;\n\t/**\n\t * クリック可能なBarのindex\n\t */\n\tprivate int[] clickableBar = new int[0];\n\n\tpublic SkinText searchText;\n\tprivate Rectangle search;\n\n\tpublic MusicSelectSkin(SkinHeader header) {\n\t\tsuper(header);\n\t}\n\n\tpublic int[] getClickableBar() {\n\t\treturn clickableBar;\n\t}\n\n\tpublic void setClickableBar(int[] clickableBar) {\n\t\tthis.clickableBar = clickableBar;\n\t}\n\n\tpublic int getCenterBar() {\n\t\treturn centerBar;\n\t}\n\n\tpublic void setCenterBar(int centerBar) {\n\t\tthis.centerBar = centerBar;\n\t}\n\t\n\tpublic Rectangle getSearchTextRegion() {\n\t\treturn search;\n\t}\n\n\tpublic void setSearchTextRegion(Rectangle r) {\n\t\tsearch = r;\n\t}\n\n}"
},
{
"identifier": "SkinBar",
"path": "core/src/bms/player/beatoraja/select/SkinBar.java",
"snippet": "public class SkinBar extends SkinObject {\n\n /**\n * 選択時のBarのSkinImage\n */\n private SkinImage[] barimageon = new SkinImage[BAR_COUNT];\n /**\n * 非選択時のBarのSkinImage\n */\n private SkinImage[] barimageoff = new SkinImage[BAR_COUNT];\n \n public static final int BAR_COUNT = 60;\n\n /**\n * トロフィーのSkinImage。描画位置はBarの相対座標\n */\n private SkinImage[] trophy = new SkinImage[BARTROPHY_COUNT];\n \n public static final int BARTROPHY_COUNT = 3;\n\n /**\n * BarのSkinText。描画位置はBarの相対座標。\n * Indexは0:通常 1:新規 2:SongBar(通常) 3:SongBar(新規) 4:FolderBar(通常) 5:FolderBar(新規) 6:TableBar or HashBar\n * 7:GradeBar(曲所持) 8:(SongBar or GradeBar)(曲未所持) 9:CommandBar or ContainerBar 10:SearchWordBar\n * 3以降で定義されてなければ0か1を用いる\n */\n private SkinText[] text = new SkinText[BARTEXT_COUNT];\n\n public static final int BARTEXT_NORMAL = 0;\n public static final int BARTEXT_NEW = 1;\n public static final int BARTEXT_SONG_NORMAL = 2;\n public static final int BARTEXT_SONG_NEW = 3;\n public static final int BARTEXT_FOLDER_NORMAL = 4;\n public static final int BARTEXT_FOLDER_NEW = 5;\n public static final int BARTEXT_TABLE = 6;\n public static final int BARTEXT_GRADE = 7;\n public static final int BARTEXT_NO_SONGS = 8;\n public static final int BARTEXT_COMMAND = 9;\n public static final int BARTEXT_SEARCH = 10;\n public static final int BARTEXT_COUNT = 11;\n /**\n * レベルのSkinNumber。描画位置はBarの相対座標\n */\n private SkinNumber[] barlevel = new SkinNumber[BARLEVEL_COUNT];\n \n public static final int BARLEVEL_COUNT = 7;\n\n /**\n * 譜面ラベルのSkinImage。描画位置はBarの相対座標\n */\n private SkinImage[] label = new SkinImage[BARLABEL_COUNT];\n \n public static final int BARLABEL_COUNT = 5;\n\n private SkinDistributionGraph graph;\n\n private int position = 0;\n\n /**\n * ランプ画像\n */\n private SkinImage[] lamp = new SkinImage[BARLAMP_COUNT];\n /**\n * ライバルランプ表示時のプレイヤーランプ画像\n */\n private SkinImage[] mylamp = new SkinImage[BARLAMP_COUNT];\n /**\n * ライバルランプ表示時のライバルランプ画像\n */\n private SkinImage[] rivallamp = new SkinImage[BARLAMP_COUNT];\n\n public static final int BARLAMP_COUNT = 11;\n \n private MusicSelector selector;\n /**\n * 描画不可スキンオブジェクト\n */\n private Array<SkinObject> removes = new Array();\n\n public SkinBar(int position) {\n this.position = position;\n this.setDestination(0, 0, 0, 0, 0, 0, 0, 255, 255, 255, 0, 0, 0, 0, 0, 0, new int[0]);\n }\n\n public void setBarImage(SkinImage[] onimage, SkinImage[] offimage) {\n \tbarimageon = onimage;\n \tbarimageoff = offimage;\n }\n\n public SkinImage getBarImages(boolean on, int index) {\n \tif(index >= 0 && index < barimageoff.length) {\n return on ? barimageon[index] : barimageoff[index]; \t\t\n \t}\n \treturn null;\n }\n\n public SkinImage getLamp(int id) {\n if(id >= 0 && id < this.lamp.length) {\n return this.lamp[id];\n }\n return null;\n }\n\n public SkinImage getPlayerLamp(int id) {\n if(id >= 0 && id < this.mylamp.length) {\n return this.mylamp[id];\n }\n return null;\n }\n\n public SkinImage getRivalLamp(int id) {\n if(id >= 0 && id < this.rivallamp.length) {\n return this.rivallamp[id];\n }\n return null;\n }\n\n public SkinImage getTrophy(int id) {\n if(id >= 0 && id < this.trophy.length) {\n return this.trophy[id];\n }\n return null;\n }\n\n public SkinText getText(int id) {\n if(id >= 0 && id < this.text.length) {\n return this.text[id];\n }\n return null;\n }\n\n public void setTrophy(int id, SkinImage trophy) {\n if(id >= 0 && id < this.trophy.length) {\n this.trophy[id] = trophy;\n }\n }\n\n public void setLamp(int id, SkinImage lamp) {\n if(id >= 0 && id < this.lamp.length) {\n this.lamp[id] = lamp;\n }\n }\n\n public void setPlayerLamp(int id, SkinImage mylamp) {\n if(id >= 0 && id < this.mylamp.length) {\n this.mylamp[id] = mylamp;\n }\n }\n\n public void setText(int id, SkinText text) {\n if(id >= 0 && id < this.text.length) {\n this.text[id] = text;\n }\n }\n\n public void setRivalLamp(int id, SkinImage rivallamp) {\n if(id >= 0 && id < this.rivallamp.length) {\n this.rivallamp[id] = rivallamp;\n }\n }\n\n public boolean validate() {\n \tfor(int i = 0;i < barimageon.length;i++) {\n \t\tif(barimageon[i] != null && !barimageon[i].validate()) {\n \t\t\tremoves.add(barimageon[i]);\n \t\t\tbarimageon[i] = null;\n \t\t}\n \t}\n \tfor(int i = 0;i < barimageoff.length;i++) {\n \t\tif(barimageoff[i] != null && !barimageoff[i].validate()) {\n \t\t\tremoves.add(barimageoff[i]);\n \t\t\tbarimageoff[i] = null;\n \t\t}\n \t}\n \tfor(int i = 0;i < trophy.length;i++) {\n \t\tif(trophy[i] != null && !trophy[i].validate()) {\n \t\t\tremoves.add(trophy[i]);\n \t\t\ttrophy[i] = null;\n \t\t}\n \t}\n \tfor(int i = 0;i < label.length;i++) {\n \t\tif(label[i] != null && !label[i].validate()) {\n \t\t\tremoves.add(label[i]);\n \t\t\tlabel[i] = null;\n \t\t}\n \t}\n \tfor(int i = 0;i < lamp.length;i++) {\n \t\tif(lamp[i] != null && !lamp[i].validate()) {\n \t\t\tremoves.add(lamp[i]);\n \t\t\tlamp[i] = null;\n \t\t}\n \t}\n \tfor(int i = 0;i < mylamp.length;i++) {\n \t\tif(mylamp[i] != null && !mylamp[i].validate()) {\n \t\t\tremoves.add(mylamp[i]);\n \t\t\tmylamp[i] = null;\n \t\t}\n \t}\n \tfor(int i = 0;i < rivallamp.length;i++) {\n \t\tif(rivallamp[i] != null && !rivallamp[i].validate()) {\n \t\t\tremoves.add(rivallamp[i]);\n \t\t\trivallamp[i] = null;\n \t\t}\n \t}\n \tfor(int i = 0;i < text.length;i++) {\n \t\tif(text[i] != null && !text[i].validate()) {\n \t\t\tremoves.add(text[i]);\n \t\t\ttext[i] = null;\n \t\t}\n \t}\n \treturn super.validate();\n }\n \n @Override\n public void prepare(long time, MainState state) {\n \tif(selector == null) {\n \t\tselector = ((MusicSelector) state);\n \t\tif(selector == null) {\n \t\t\tdraw = false;\n \t\t\treturn;\n \t\t}\n \t}\n \tsuper.prepare(time, state);\n \tfor(SkinImage bar : barimageon) {\n \t\tif(bar != null) {\n \t\t\tbar.prepare(time, state);\n \t\t}\n \t}\n \tfor(SkinImage bar : barimageoff) {\n \t\tif(bar != null) {\n \t\t\tbar.prepare(time, state);\n \t\t}\n \t}\n \tfor(SkinImage trophy : trophy) {\n \t\tif(trophy != null) {\n \t\t\ttrophy.prepare(time, state);\n \t\t}\n \t}\n \tfor(SkinText text : text) {\n \t\tif(text != null) {\n \t\t\ttext.prepare(time, state);\n \t\t}\n \t}\n \tfor(SkinNumber barlevel : barlevel) {\n \t\tif(barlevel != null) {\n \t\t\tbarlevel.prepare(time, state);\n \t\t}\n \t}\n \tfor(SkinImage label : label) {\n \t\tif(label != null) {\n \t\t\tlabel.prepare(time, state);\n \t\t}\n \t}\n \tfor(SkinImage lamp : lamp) {\n \t\tif(lamp != null) {\n \t\t\tlamp.prepare(time, state);\n \t\t}\n \t}\n \tfor(SkinImage mylamp : mylamp) {\n \t\tif(mylamp != null) {\n \t\t\tmylamp.prepare(time, state);\n \t\t}\n \t}\n \tfor(SkinImage rivallamp : rivallamp) {\n \t\tif(rivallamp != null) {\n \t\t\trivallamp.prepare(time, state);\n \t\t}\n \t}\n \t\n \tif(graph != null) {\n \t\tgraph.prepare(time, state);\n \t}\n\n selector.getBarRender().prepare((MusicSelectSkin) selector.getSkin(), this, time);\n\n }\n\n public void draw(SkinObjectRenderer sprite) {\n selector.getBarRender().render(sprite, (MusicSelectSkin) selector.getSkin(), this);\n }\n\n @Override\n public void dispose() {\n \tdisposeAll(removes.toArray(SkinObject.class));\n \tdisposeAll(barimageon);\n \tdisposeAll(barimageoff);\n \tdisposeAll(trophy);\n \tdisposeAll(text);\n \tdisposeAll(barlevel);\n \tdisposeAll(label);\n disposeAll(lamp);\n disposeAll(mylamp);\n disposeAll(rivallamp);\n \tif(graph != null) {\n \t\tgraph.dispose();\n \t\tgraph = null;\n \t}\n }\n\n public SkinNumber getBarlevel(int id) {\n if(id >= 0 && id < this.barlevel.length) {\n return this.barlevel[id];\n }\n return null;\n }\n\n public void setBarlevel(int id, SkinNumber barlevel) {\n if(id >= 0 && id < this.barlevel.length) {\n this.barlevel[id] = barlevel;\n }\n }\n\n public int getPosition() {\n return position;\n }\n \n @Override\n\tprotected boolean mousePressed(MainState state, int button, int x, int y) {\n return ((MusicSelector) state).getBarRender().mousePressed(this, button, x, y);\n\t}\n\n public SkinImage getLabel(int id) {\n if(id >= 0 && id < this.label.length) {\n return this.label[id];\n }\n return null;\n }\n\n public void setLabel(int id, SkinImage label) {\n if(id >= 0 && id < this.label.length) {\n this.label[id] = label;\n }\n }\n\n\tpublic SkinDistributionGraph getGraph() {\n\t\treturn graph;\n\t}\n\n\tpublic void setGraph(SkinDistributionGraph graph) {\n\t\tthis.graph = graph;\n\t}\n}"
},
{
"identifier": "SkinDistributionGraph",
"path": "core/src/bms/player/beatoraja/select/SkinDistributionGraph.java",
"snippet": "public class SkinDistributionGraph extends SkinObject {\n\n\t/**\n\t * グラフの各イメージソース\n\t */\n private final SkinSource[] lampimage;\n /**\n * グラフタイプ。0:クリアランプ、1:スコアランク\n */\n private final int type;\n /**\n * 現在のグラフイメージ\n */\n private TextureRegion[] currentImage;\n /**\n * 対象のDirectoryBar\n */\n private DirectoryBar currentBar;\n\n private static final String[] LAMP = { \"ff404040\", \"ff000080\", \"ff800080\", \"ffff00ff\", \"ff40ff40\", \"ff00c0f0\", \"ffffffff\",\n \"ff88ffff\", \"ffffff88\", \"ff8888ff\", \"ff0000ff\" };\n\n private static final String[] RANK = { \"ff404040\", \"ff400040\", \"ff400040\", \"ff400040\", \"ff400040\", \"ff400040\", \"ff000040\",\n \"ff000040\", \"ff000040\", \"ff004040\", \"ff004040\", \"ff004040\", \"ff00c000\", \"ff00c000\", \"ff00c000\", \"ff80c000\", \"ff80c000\",\n \"ff80c000\", \"ff0080f0\", \"ff0080f0\", \"ff0080f0\", \"ffe0e0e0\", \"ffe0e0e0\", \"ffe0e0e0\", \"ff44ffff\", \"ff44ffff\", \"ff44ffff\",\n \"ffccffff\" };\n\n\n public SkinDistributionGraph(int type) {\n \tthis(type, createDefaultImages(type), 0, 0);\n }\n \n private static TextureRegion[][] createDefaultImages(int type) {\n if(type == 0) {\n Pixmap lampp = new Pixmap(11,1, Pixmap.Format.RGBA8888);\n for(int i = 0;i < LAMP.length;i++) {\n lampp.drawPixel(i,0, Color.valueOf(LAMP[i]).toIntBits());\n }\n Texture lampt = new Texture(lampp);\n TextureRegion[][] result = new TextureRegion[11][1];\n for(int i = 0;i < LAMP.length;i++) {\n \tresult[i] = new TextureRegion[]{new TextureRegion(lampt,i,0,1,1)};\n }\n lampp.dispose();\n return result;\n } else {\n Pixmap rankp = new Pixmap(28,1, Pixmap.Format.RGBA8888);\n for(int i = 0;i < RANK.length;i++) {\n rankp.drawPixel(i,0, Color.valueOf(RANK[i]).toIntBits());\n }\n Texture rankt = new Texture(rankp);\n TextureRegion[][] result = new TextureRegion[28][1];\n for(int i = 0;i < RANK.length;i++) {\n \tresult[i] = new TextureRegion[]{new TextureRegion(rankt,i,0,1,1)};\n }\n rankp.dispose();\n return result;\n }\n }\n\n public SkinDistributionGraph(int type, TextureRegion[][] image, int timer, int cycle) {\n this.type = type;\n if(type == 0) {\n lampimage = new SkinSource[11];\n for(int i = 0;i < lampimage.length;i++) {\n lampimage[i] = new SkinSourceImage(image[i],timer,cycle);\n }\n } else {\n lampimage = new SkinSource[28];\n for(int i = 0;i < lampimage.length;i++) {\n lampimage[i] = new SkinSourceImage(image[i],timer,cycle);\n }\n }\n currentImage = new TextureRegion[lampimage.length];\n }\n\n public SkinDistributionGraph(int type, TextureRegion[][] image, TimerProperty timer, int cycle) {\n this.type = type;\n if(type == 0) {\n lampimage = new SkinSource[11];\n for(int i = 0;i < lampimage.length;i++) {\n lampimage[i] = new SkinSourceImage(image[i],timer,cycle);\n }\n } else {\n lampimage = new SkinSource[28];\n for(int i = 0;i < lampimage.length;i++) {\n lampimage[i] = new SkinSourceImage(image[i],timer,cycle);\n }\n }\n currentImage = new TextureRegion[lampimage.length];\n }\n\n\tpublic void prepare(long time, MainState state) {\n \tfinal Bar bar = ((MusicSelector)state).getSelectedBar();\n this.currentBar = (bar instanceof DirectoryBar) ? (DirectoryBar)bar : null;\n if (!state.resource.getConfig().isFolderlamp()) {\n draw = false;\n return;\n }\n super.prepare(time, state);\n for(int i = 0;i < currentImage.length;i++) {\n currentImage[i] = lampimage[i].getImage(time,state);\n }\n\t}\n\t\n public void draw(SkinObjectRenderer sprite) {\n draw(sprite, currentBar, 0, 0);\n }\n\n public void draw(SkinObjectRenderer sprite, DirectoryBar current, float offsetx, float offsety) {\n \tif(current == null) {\n \t\treturn;\n \t}\n // TODO 分布計算はフォルダ選択時にのみ行う場合、同一DirectoryBarでbackgroundでのLAMP更新があった場合は?\n int[] lamps = current.getLamps();\n int[] ranks = current.getRanks();\n int count = 0;\n for (int lamp : lamps) {\n count += lamp;\n }\n\n if (count != 0) {\n if(type == 0) {\n for (int i = 10, x = 0; i >= 0; i--) {\n sprite.draw(currentImage[i], region.x + x * region.width / count + offsetx, region.y + offsety, lamps[i] * region.width / count, region.height);\n x += lamps[i];\n }\n } else {\n for (int i = 27, x = 0; i >= 0; i--) {\n sprite.draw(currentImage[i], region.x + x * region.width / count + offsetx, region.y + offsety, ranks[i] * region.width / count, region.height);\n x += ranks[i];\n }\n }\n }\n }\n\n @Override\n public void dispose() {\n \tdisposeAll(lampimage);\n }\n}"
},
{
"identifier": "TimerProperty",
"path": "core/src/bms/player/beatoraja/skin/property/TimerProperty.java",
"snippet": "public interface TimerProperty {\n\tlong getMicro(MainState state);\n\n\tdefault long get(MainState state) {\n\t\treturn getMicro(state) / 1000;\n\t}\n\n\tdefault long getNowTime(MainState state) {\n\t\tlong time = getMicro(state);\n\t\treturn time == Long.MIN_VALUE ? 0 : state.timer.getNowTime() - time / 1000;\n\t}\n\n\tdefault boolean isOn(MainState state) {\n\t\treturn getMicro(state) != Long.MIN_VALUE;\n\t}\n\n\tdefault boolean isOff(MainState state) {\n\t\treturn getMicro(state) == Long.MIN_VALUE;\n\t}\n\n\t/**\n\t * タイマーIDに依存した処理のためのバックドア\n\t * @return タイマーID (スクリプトによるタイマー定義の場合は {@code Integer.MIN_VALUE})\n\t */\n\tdefault int getTimerId() {\n\t\treturn Integer.MIN_VALUE;\n\t}\n}"
}
] | import java.nio.file.Path;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import bms.player.beatoraja.select.MusicSelectSkin;
import bms.player.beatoraja.select.SkinBar;
import bms.player.beatoraja.select.SkinDistributionGraph;
import bms.player.beatoraja.skin.*;
import bms.player.beatoraja.skin.property.TimerProperty; | 5,475 | package bms.player.beatoraja.skin.json;
/**
* JSONセレクトスキンオブジェクトローダー
*
* @author exch
*/
public class JsonSelectSkinObjectLoader extends JsonSkinObjectLoader<MusicSelectSkin> {
public JsonSelectSkinObjectLoader(JSONSkinLoader loader) {
super(loader);
}
@Override
public MusicSelectSkin getSkin(SkinHeader header) {
return new MusicSelectSkin(header);
}
@Override
public SkinObject loadSkinObject(MusicSelectSkin skin, JsonSkin.Skin sk, JsonSkin.Destination dst, Path p) {
SkinObject obj =super.loadSkinObject(skin, sk, dst, p);
if(obj != null) {
return obj;
}
if (sk.songlist != null && dst.id.equals(sk.songlist.id)) { | package bms.player.beatoraja.skin.json;
/**
* JSONセレクトスキンオブジェクトローダー
*
* @author exch
*/
public class JsonSelectSkinObjectLoader extends JsonSkinObjectLoader<MusicSelectSkin> {
public JsonSelectSkinObjectLoader(JSONSkinLoader loader) {
super(loader);
}
@Override
public MusicSelectSkin getSkin(SkinHeader header) {
return new MusicSelectSkin(header);
}
@Override
public SkinObject loadSkinObject(MusicSelectSkin skin, JsonSkin.Skin sk, JsonSkin.Destination dst, Path p) {
SkinObject obj =super.loadSkinObject(skin, sk, dst, p);
if(obj != null) {
return obj;
}
if (sk.songlist != null && dst.id.equals(sk.songlist.id)) { | SkinBar barobj = new SkinBar(0); | 1 | 2023-12-02 23:41:17+00:00 | 8k |
Elb1to/FFA | src/main/java/me/elb1to/ffa/command/manager/CommandManager.java | [
{
"identifier": "FfaPlugin",
"path": "src/main/java/me/elb1to/ffa/FfaPlugin.java",
"snippet": "@Getter\npublic class FfaPlugin extends JavaPlugin {\n\n\tprivate MongoSrv mongoSrv;\n\n\tprivate MapManager mapManager;\n\tprivate KitManager kitManager;\n\tprivate FfaManager ffaManager;\n\n\tprivate UserProfileManager userProfileManager;\n\tprivate LeaderboardManager leaderboardManager;\n\n\tprivate CommandManager commandManager;\n\n\t@Override\n\tpublic void onEnable() {\n\t\tsaveDefaultConfig();\n\n\t\tmongoSrv = new MongoSrv(this, getConfig().getConfigurationSection(\"mongo\"));\n\n\t\tmapManager = new MapManager(this, getConfig().getConfigurationSection(\"maps\"));\n\t\tkitManager = new KitManager(this, getConfig().getConfigurationSection(\"kits\"));\n\t\tffaManager = new FfaManager(this);\n\n\t\tuserProfileManager = new UserProfileManager(this);\n\t\tleaderboardManager = new LeaderboardManager(this);\n\t\tcommandManager = new CommandManager(this);\n\n\t\tgetServer().getPluginManager().registerEvents(new FfaListener(this), this);\n\t\tgetServer().getPluginManager().registerEvents(new ButtonListener(this), this);\n\t\tgetServer().getPluginManager().registerEvents(new UserProfileListener(this), this);\n\n\t\tgetServer().getScheduler().runTaskLater(this, () -> {\n\t\t\tfor (FfaMap ffaMap : mapManager.getMaps()) {\n\t\t\t\tffaMap.setWorld(Bukkit.getWorld(ffaMap.getName()));\n\t\t\t\tCuboid cuboid = new Cuboid(ffaMap.getMin().toBukkitLocation(), ffaMap.getMax().toBukkitLocation());\n\t\t\t\tffaMap.setCuboid(cuboid);\n\t\t\t}\n\n\t\t\tleaderboardManager.updateLeaderboards();\n\t\t}, 100L);\n\n\t\tgetServer().getScheduler().runTaskTimerAsynchronously(this, new ItemRemovalTask(this), 1L, 1L);\n\n\t\tAssemble assemble = new Assemble(this, new ScoreboardLayout(this));\n\t\tassemble.setAssembleStyle(AssembleStyle.CUSTOM);\n\t\tassemble.setTicks(20);\n\t}\n\n\t@Override\n\tpublic void onDisable() {\n\t\tkitManager.save();\n\t\tmapManager.save();\n\n\t\tfor (UserProfile userProfile : userProfileManager.getAllProfiles()) {\n\t\t\tuserProfileManager.save(userProfile);\n\t\t}\n\n\t\tfor (World world : Bukkit.getWorlds()) {\n\t\t\tfor (Entity entity : world.getEntities()) {\n\t\t\t\tif (!(entity.getType() == EntityType.PAINTING || entity.getType() == EntityType.ITEM_FRAME)) {\n\t\t\t\t\tentity.remove();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tmongoSrv.disconnect();\n\t}\n}"
},
{
"identifier": "FfaCommand",
"path": "src/main/java/me/elb1to/ffa/command/FfaCommand.java",
"snippet": "@CommandAlias(\"ffa\")\npublic class FfaCommand extends BaseCommand {\n\n\t@Dependency\n\tprivate FfaPlugin plugin;\n\n\t@Default\n\tpublic void getHelp(Player player) {\n\t\tnew MapSelectionMenu(plugin).openMenu(player);\n\n\t\tplayer.sendMessage(\" \");\n\t\tplayer.sendMessage(CC.color(\"&b&lFFA Commands &8- &7Information\"));\n\t\tplayer.sendMessage(CC.color(\"&3 ● &b/ffa join <kit> &8- &7Join a FFA\"));\n\t\tplayer.sendMessage(CC.color(\"&3 ● &b/ffa leave &8- &7Leave a FFA\"));\n\t\tplayer.sendMessage(\" \");\n\t}\n\n\t@Subcommand(\"join\")\n\t@CommandCompletion(\"@kits\")\n\tpublic void join(Player player, Kit kit) {\n\t\tif (kit == null) {\n\t\t\tplayer.sendMessage(CC.color(\"&cThat kit does not exist.\"));\n\t\t\treturn;\n\t\t}\n\n\t\tUserProfile profile\t= plugin.getUserProfileManager().getByUuid(player.getUniqueId());\n\t\tif (profile.getFfa() != null || profile.getState() == UserProfile.State.PLAYING) {\n\t\t\tplayer.sendMessage(CC.color(\"&cYou are already in a FFA.\"));\n\t\t\treturn;\n\t\t}\n\n\t\tFfaInstance instance = plugin.getFfaManager().getByKitName(kit.getName());\n\t\tif (instance == null) {\n\t\t\tplayer.sendMessage(CC.color(\"&cThere is no FFA with that kit.\"));\n\t\t\treturn;\n\t\t}\n\n\t\tplugin.getFfaManager().addPlayer(player, instance, plugin.getMapManager().getRandom().getName());\n\t}\n\n\t@Subcommand(\"leave\")\n\tpublic void leave(Player player) {\n\t\tUserProfile profile\t= plugin.getUserProfileManager().getByUuid(player.getUniqueId());\n\t\tFfaInstance instance = profile.getFfa();\n\t\tif (instance == null) {\n\t\t\tplayer.sendMessage(CC.color(\"&cYou are not in a FFA.\"));\n\t\t\treturn;\n\t\t}\n\n\t\tplugin.getFfaManager().removePlayer(player, instance);\n\t}\n}"
},
{
"identifier": "Kit",
"path": "src/main/java/me/elb1to/ffa/kit/Kit.java",
"snippet": "@Getter\n@Setter\n@RequiredArgsConstructor\npublic class Kit {\n\n\tprivate final String name;\n\n\tprivate ItemStack icon;\n\tprivate ItemStack[] armor;\n\tprivate ItemStack[] contents;\n\n\tpublic void equip(Player player) {\n\t\tplayer.getInventory().setArmorContents(armor);\n\t\tplayer.getInventory().setContents(contents);\n\n\t\tfor (PotionEffect potionEffect : player.getActivePotionEffects()) {\n\t\t\tplayer.removePotionEffect(potionEffect.getType());\n\t\t}\n\t}\n}"
},
{
"identifier": "KitCommand",
"path": "src/main/java/me/elb1to/ffa/kit/command/KitCommand.java",
"snippet": "@CommandAlias(\"kit\")\n@CommandPermission(\"ffa.admin\")\npublic class KitCommand extends BaseCommand {\n\n\t@Dependency\n\tprivate FfaPlugin plugin;\n\n\t@Default\n\tpublic void getHelp(Player player) {\n\t\tplayer.sendMessage(\" \");\n\t\tplayer.sendMessage(CC.color(\"&b&lKit Commands &8- &7Information\"));\n\t\tplayer.sendMessage(CC.color(\"&3 ● &b/kit list &8- &7List all existing kits\"));\n\t\tplayer.sendMessage(CC.color(\"&3 ● &b/kit create <name> &8- &7Create a new kit\"));\n\t\tplayer.sendMessage(CC.color(\"&3 ● &b/kit delete <name> &8- &7Delete an existing kit\"));\n\t\tplayer.sendMessage(CC.color(\"&3 ● &b/kit icon <name> &8- &7Change the icon of the kit\"));\n\t\tplayer.sendMessage(CC.color(\"&3 ● &b/kit update <name> &8- &7Update the kit inventory\"));\n\t\tplayer.sendMessage(CC.color(\"&3 ● &b/kit give <name> <player> &8- &7Give a kit to a player\"));\n\t\tplayer.sendMessage(\" \");\n\t}\n\n\t@Subcommand(\"list\")\n\tpublic void list(Player player) {\n\t\tplayer.sendMessage(\" \");\n\t\tplayer.sendMessage(CC.color(\"&b&lKit List &8- &7Information\"));\n\t\tfor (Kit kit : plugin.getKitManager().getKits().values()) {\n\t\t\tplayer.sendMessage(CC.color(\"&3 ● &b\" + kit.getName()));\n\t\t}\n\t\tplayer.sendMessage(\" \");\n\t}\n\n\t@Subcommand(\"create\")\n\tpublic void create(Player player, String name) {\n\t\tif (plugin.getKitManager().exists(name)) {\n\t\t\tplayer.sendMessage(CC.color(\"&cA kit with that name already exists.\"));\n\t\t\treturn;\n\t\t}\n\n\t\tplugin.getKitManager().create(name);\n\t\tplayer.sendMessage(CC.color(\"&aYou have created a new kit with the name &b\" + name + \"&a.\"));\n\t}\n\n\t@Subcommand(\"delete\")\n\t@CommandCompletion(\"@kits\")\n\tpublic void delete(Player player, Kit kit) {\n\t\tif (!plugin.getKitManager().exists(kit.getName())) {\n\t\t\tplayer.sendMessage(CC.color(\"&cA kit with that name does not exist.\"));\n\t\t\treturn;\n\t\t}\n\n\t\tplugin.getKitManager().delete(kit.getName());\n\t\tplayer.sendMessage(CC.color(\"&aYou have deleted the &b\" + kit.getName() + \" &akit.\"));\n\t}\n\n\t@Subcommand(\"icon\")\n\t@CommandCompletion(\"@kits\")\n\tpublic void updateIcon(Player player, Kit kit) {\n\t\tif (!plugin.getKitManager().exists(kit.getName())) {\n\t\t\tplayer.sendMessage(CC.color(\"&cA kit with that name does not exist.\"));\n\t\t\treturn;\n\t\t}\n\n\t\tkit.setIcon(player.getItemInHand());\n\t\tplayer.sendMessage(CC.color(\"&aYou have updated the icon of the &b\" + kit.getName() + \" &akit.\"));\n\t}\n\n\t@Subcommand(\"update\")\n\t@CommandCompletion(\"@kits\")\n\tpublic void updateInventory(Player player, Kit kit) {\n\t\tif (!plugin.getKitManager().exists(kit.getName())) {\n\t\t\tplayer.sendMessage(CC.color(\"&cA kit with that name does not exist.\"));\n\t\t\treturn;\n\t\t}\n\n\t\tplayer.updateInventory();\n\t\tkit.setArmor(player.getInventory().getArmorContents());\n\t\tkit.setContents(player.getInventory().getContents());\n\t\tplayer.sendMessage(CC.color(\"&aYou have updated the inventory of the &b\" + kit.getName() + \" &akit.\"));\n\n\t\tplugin.getKitManager().save();\n\t}\n\n\t@Subcommand(\"give\")\n\t@CommandCompletion(\"@kits\")\n\tpublic void getInventory(Player player, Kit kit, OnlinePlayer target) {\n\t\tif (!plugin.getKitManager().exists(kit.getName())) {\n\t\t\tplayer.sendMessage(CC.color(\"&cA kit with that name does not exist.\"));\n\t\t\treturn;\n\t\t}\n\n\t\tkit.equip(target.getPlayer());\n\t\tplayer.sendMessage(CC.color(\"&aYou have given the &b\" + kit.getName() + \" &akit to &b\" + target.getPlayer().getName() + \"&a.\"));\n\t}\n}"
},
{
"identifier": "FfaMap",
"path": "src/main/java/me/elb1to/ffa/map/FfaMap.java",
"snippet": "@Data\npublic class FfaMap {\n\n\tprivate final String name;\n\tprivate final Type type;\n\n\tprivate CustomLocation spawn;\n\tprivate CustomLocation min;\n\tprivate CustomLocation max;\n\n\tprivate World world;\n\tprivate Cuboid cuboid;\n\n\tpublic enum Type {\n\t\tLOBBY, ARENA\n\t}\n\n\tpublic boolean has(Player player) {\n\t\treturn this.cuboid.contains(player.getLocation());\n\t}\n\n\tpublic boolean denyDamageInSafeZone(Player player) {\n\t\treturn this.type == Type.ARENA && has(player);\n\t}\n}"
},
{
"identifier": "BuildModeCommand",
"path": "src/main/java/me/elb1to/ffa/map/command/BuildModeCommand.java",
"snippet": "public class BuildModeCommand extends BaseCommand {\n\n\t@Dependency\n\tprivate FfaPlugin plugin;\n\n\t@CommandAlias(\"buildmode|build\")\n\t@CommandPermission(\"ffa.admin\")\n\tpublic void onExecute(Player player) {\n\t\tif (plugin.getUserProfileManager().getBuilders().contains(player.getUniqueId())) {\n\t\t\tplugin.getUserProfileManager().getBuilders().remove(player.getUniqueId());\n\t\t} else {\n\t\t\tplugin.getUserProfileManager().getBuilders().add(player.getUniqueId());\n\t\t}\n\n\t\tplayer.sendMessage(CC.color(\"&7You are now in &b\" + (plugin.getUserProfileManager().getBuilders().contains(player.getUniqueId()) ? \"build\" : \"play\") + \" &7mode.\"));\n\t}\n}"
},
{
"identifier": "MapCommand",
"path": "src/main/java/me/elb1to/ffa/map/command/MapCommand.java",
"snippet": "@CommandAlias(\"map\")\n@CommandPermission(\"ffa.admin\")\npublic class MapCommand extends BaseCommand {\n\n\t@Dependency\n\tprivate FfaPlugin plugin;\n\n\t@Default\n\tpublic void getHelp(Player player) {\n\t\tplayer.sendMessage(\" \");\n\t\tplayer.sendMessage(CC.color(\"&b&lMap Commands &8- &7Information\"));\n\t\tplayer.sendMessage(CC.color(\"&3 ● &b/map list &8- &7List all existing maps\"));\n\t\tplayer.sendMessage(CC.color(\"&3 ● &b/map debug <name> &8- &7Debug a map\"));\n\t\tplayer.sendMessage(CC.color(\"&3 ● &b/map create <name> &8- &7Create a new map\"));\n\t\tplayer.sendMessage(CC.color(\"&3 ● &b/map delete <name> &8- &7Delete an existing map\"));\n\t\tplayer.sendMessage(CC.color(\"&3 ● &b/map teleport <name> &8- &7Teleport to the map\"));\n\t\tplayer.sendMessage(CC.color(\"&3 ● &b/map nofall <name> &8- &7Disable fall damage in the map\"));\n\t\tplayer.sendMessage(CC.color(\"&3 ● &b/map setlocation <name> <spawn|min|max> &8- &7Set the location of the map\"));\n\t\tplayer.sendMessage(CC.color(\"&3 ● &b/map slot <name> <number> &8- &7Set the slot of the map in the map selection menu\"));\n\t\tplayer.sendMessage(\" \");\n\t}\n\n\t@Subcommand(\"debug\")\n\t@CommandCompletion(\"@maps\")\n\tpublic void debug(Player player, FfaMap ffaMap) {\n\t\tif (!plugin.getMapManager().exists(ffaMap.getName())) {\n\t\t\tplayer.sendMessage(CC.color(\"&cA map with that name does not exist.\"));\n\t\t\treturn;\n\t\t}\n\n\t\tplayer.sendMessage(\" \");\n\t\tplayer.sendMessage(CC.color(\"&b&lMap Debug &8- &7Information\"));\n\t\tplayer.sendMessage(CC.color(\"&3 ● &bName: &f\" + ffaMap.getName()));\n\t\tplayer.sendMessage(CC.color(\"&3 ● &bType: &f\" + ffaMap.getType().name()));\n\t\tplayer.sendMessage(CC.color(\"&3 ● &bSpawn: &f\" + (ffaMap.getSpawn() == null ? \"None\" : ffaMap.getSpawn().toString())));\n\t\tplayer.sendMessage(CC.color(\"&3 ● &bMin: &f\" + (ffaMap.getMin() == null ? \"None\" : ffaMap.getMin().toString())));\n\t\tplayer.sendMessage(CC.color(\"&3 ● &bMax: &f\" + (ffaMap.getMax() == null ? \"None\" : ffaMap.getMax().toString())));\n\t\tplayer.sendMessage(\" \");\n\t}\n\n\t@Subcommand(\"list\")\n\tpublic void list(Player player) {\n\t\tplayer.sendMessage(\" \");\n\t\tplayer.sendMessage(CC.color(\"&b&lMap List &8- &7Information\"));\n\t\tfor (FfaMap map : plugin.getMapManager().getMaps()) {\n\t\t\tplayer.sendMessage(CC.color(\"&3 ● &b\" + map.getName()));\n\t\t}\n\t\tplayer.sendMessage(\" \");\n\t}\n\n\t@Subcommand(\"create\")\n\tpublic void create(Player player, String name, String type) {\n\t\tif (plugin.getMapManager().exists(name)) {\n\t\t\tplayer.sendMessage(CC.color(\"&cA map with that name already exists.\"));\n\t\t\treturn;\n\t\t}\n\t\tif (!(type.equalsIgnoreCase(\"lobby\") || type.equalsIgnoreCase(\"arena\"))) {\n\t\t\tplayer.sendMessage(CC.color(\"&cThat is not a valid map type. Valid types: lobby, arena\"));\n\t\t\treturn;\n\t\t}\n\n\t\tplugin.getMapManager().create(name, FfaMap.Type.valueOf(type.toUpperCase()));\n\t\tplayer.sendMessage(CC.color(\"&aYou have created a new map with the name &b\" + name + \"&a.\"));\n\t}\n\n\t@Subcommand(\"delete\")\n\t@CommandCompletion(\"@maps\")\n\tpublic void delete(Player player, FfaMap ffaMap) {\n\t\tif (!plugin.getMapManager().exists(ffaMap.getName())) {\n\t\t\tplayer.sendMessage(CC.color(\"&cA ffaMap with that name does not exist.\"));\n\t\t\treturn;\n\t\t}\n\n\t\tplugin.getMapManager().delete(ffaMap.getName());\n\t\tplayer.sendMessage(CC.color(\"&aYou have deleted the &b\" + ffaMap.getName() + \" &amap.\"));\n\t}\n\n\t@Subcommand(\"setlocation\")\n\t@CommandCompletion(\"@maps\")\n\tpublic void setLocation(Player player, FfaMap ffaMap, String location) {\n\t\tif (!plugin.getMapManager().exists(ffaMap.getName())) {\n\t\t\tplayer.sendMessage(CC.color(\"&cA ffaMap with that name does not exist.\"));\n\t\t\treturn;\n\t\t}\n\n\t\tswitch (location.toLowerCase()) {\n\t\t\tcase \"spawn\":\n\t\t\t\tffaMap.setSpawn(CustomLocation.fromBukkitLocation(player.getLocation()));\n\t\t\t\tbreak;\n\t\t\tcase \"min\":\n\t\t\t\tffaMap.setMin(CustomLocation.fromBukkitLocation(player.getLocation()));\n\t\t\t\tbreak;\n\t\t\tcase \"max\":\n\t\t\t\tffaMap.setMax(CustomLocation.fromBukkitLocation(player.getLocation()));\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tplayer.sendMessage(CC.color(\"&cThat is not a valid location. Valid locations: spawn, min, max\"));\n\t\t}\n\n\t\tplayer.sendMessage(CC.color(\"&aYou have set the &b\" + location + \" &alocation of the &b\" + ffaMap.getName() + \" &amap.\"));\n\t}\n\n\t@Subcommand(\"teleport\")\n\t@CommandCompletion(\"@maps\")\n\tpublic void sendToLocation(Player player, FfaMap ffaMap) {\n\t\tif (!plugin.getMapManager().exists(ffaMap.getName())) {\n\t\t\tplayer.sendMessage(CC.color(\"&cA map with that name does not exist.\"));\n\t\t\treturn;\n\t\t}\n\n\t\tplayer.teleport(ffaMap.getSpawn().toBukkitLocation());\n\t\tplayer.sendMessage(CC.color(\"&aYou have been teleported to the &b\" + ffaMap.getName() + \" &amap.\"));\n\t}\n\n\t@Subcommand(\"nofall\")\n\t@CommandCompletion(\"@maps\")\n\tpublic void noFall(Player player, FfaMap ffaMap) {\n\t\tif (!plugin.getMapManager().exists(ffaMap.getName())) {\n\t\t\tplayer.sendMessage(CC.color(\"&cA map with that name does not exist.\"));\n\t\t\treturn;\n\t\t}\n\n\t\t//ffaMap.setNoFall(!ffaMap.isNoFall());\n\t\t//player.sendMessage(CC.color(\"&aYou have \" + (ffaMap.isNoFall() ? \"enabled\" : \"disabled\") + \" no fall damage in the &b\" + ffaMap.getName() + \" &amap.\"));\n\t}\n\n\t@Subcommand(\"slot\")\n\t@CommandCompletion(\"@maps\")\n\tpublic void setSlot(Player player, FfaMap ffaMap, int slot) {\n\t\tif (!plugin.getMapManager().exists(ffaMap.getName())) {\n\t\t\tplayer.sendMessage(CC.color(\"&cA map with that name does not exist.\"));\n\t\t\treturn;\n\t\t}\n\n\t\t//ffaMap.setSlot(slot);\n\t\t//player.sendMessage(CC.color(\"&aYou have set the slot of the &b\" + ffaMap.getName() + \" &amap to &b\" + slot + \"&a.\"));\n\t}\n}"
},
{
"identifier": "SettingsCommand",
"path": "src/main/java/me/elb1to/ffa/user/command/SettingsCommand.java",
"snippet": "public class SettingsCommand extends BaseCommand {\n\n\t@Dependency\n\tprivate FfaPlugin plugin;\n\n\t@CommandAlias(\"settings|options|prefs\")\n\tpublic void onExecute(Player player) {\n\t\t\n\t}\n}"
},
{
"identifier": "StatsCommand",
"path": "src/main/java/me/elb1to/ffa/user/command/StatsCommand.java",
"snippet": "public class StatsCommand extends BaseCommand {\n\n\tprivate final List<String> format = Lists.newArrayList(\n\t\t\t\"&b&l<player>'s Stats\",\n\t\t\t\" &bKills: &f<kills>\",\n\t\t\t\" &bDeaths: &f<deaths>\",\n\t\t\t\" &bKDR: &f<kdr>\"\n\t);\n\n\t@Dependency\n\tprivate FfaPlugin plugin;\n\n\t@CommandAlias(\"stats|statistics\")\n\t@CommandCompletion(\"@players\")\n\t@Syntax(\"<player>\")\n\tpublic void getPlayerStats(Player player, String name) {\n\t\ttry {\n\t\t\t//OfflinePlayer target = plugin.getServer().getOfflinePlayer(name);\n\t\t\tUserProfile user = plugin.getMongoSrv().getProfile(name).get();\n\t\t\tif (user == null) {\n\t\t\t\tplayer.sendMessage(CC.color(\"&cNo data found for '\" + name + \"'\"));\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tfor (String message : format) {\n\t\t\t\tplayer.sendMessage(CC.color(message\n\t\t\t\t\t\t.replace(\"<player>\", name)\n\t\t\t\t\t\t.replace(\"<kills>\", String.valueOf(user.getKills()))\n\t\t\t\t\t\t.replace(\"<deaths>\", String.valueOf(user.getDeaths()))\n\t\t\t\t));\n\t\t\t}\n\t\t} catch (Exception e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n}"
},
{
"identifier": "UserProfileDebugCommand",
"path": "src/main/java/me/elb1to/ffa/user/command/UserProfileDebugCommand.java",
"snippet": "public class UserProfileDebugCommand extends BaseCommand {\n\n\t@Dependency\n\tprivate FfaPlugin plugin;\n\n\t@CommandAlias(\"userdebug\") @CommandPermission(\"ffa.admin\")\n\tpublic void onCommand(Player player, OnlinePlayer target) {\n\t\tUserProfile profile = plugin.getUserProfileManager().getByUuid(target.getPlayer().getUniqueId());\n\t\tplayer.sendMessage(\"§aLoading user profile for §e\" + target.getPlayer().getName() + \"§a...\");\n\t\tplayer.sendMessage(\"\");\n\t\tplayer.sendMessage(\"§aName: §f\" + target.getPlayer().getName());\n\t\tplayer.sendMessage(\"§aUUID: §f\" + target.getPlayer().getUniqueId());\n\t\tplayer.sendMessage(\"§aState: §f\" + profile.getState());\n\t\tplayer.sendMessage(\"§aKills: §f\" + profile.getKills());\n\t\tplayer.sendMessage(\"§aDeaths: §f\" + profile.getDeaths());\n\t\tplayer.sendMessage(profile.getMap().getName() == null ? \"§aMap: §fNone\" : \"§aMap: §f\" + profile.getMap().getName());\n\t}\n}"
}
] | import co.aikar.commands.PaperCommandManager;
import me.elb1to.ffa.FfaPlugin;
import me.elb1to.ffa.command.FfaCommand;
import me.elb1to.ffa.kit.Kit;
import me.elb1to.ffa.kit.command.KitCommand;
import me.elb1to.ffa.map.FfaMap;
import me.elb1to.ffa.map.command.BuildModeCommand;
import me.elb1to.ffa.map.command.MapCommand;
import me.elb1to.ffa.user.command.SettingsCommand;
import me.elb1to.ffa.user.command.StatsCommand;
import me.elb1to.ffa.user.command.UserProfileDebugCommand;
import java.util.ArrayList;
import java.util.stream.Collectors; | 5,393 | package me.elb1to.ffa.command.manager;
/**
* @author Elb1to
* @since 11/24/2023
*/
public class CommandManager {
private final FfaPlugin plugin;
private final PaperCommandManager manager;
public CommandManager(FfaPlugin plugin) {
this.plugin = plugin;
this.manager = new PaperCommandManager(plugin);
load();
}
private void load() {
manager.getCommandCompletions().registerCompletion("kits", context -> new ArrayList<>(plugin.getKitManager().getKits().values())
.stream()
.map(Kit::getName)
.collect(Collectors.toList())
);
manager.getCommandCompletions().registerCompletion("maps", context -> plugin.getMapManager().getMaps()
.stream()
.map(FfaMap::getName)
.collect(Collectors.toList())
);
manager.getCommandContexts().registerContext(Kit.class, context -> plugin.getKitManager().get(context.popFirstArg()));
manager.getCommandContexts().registerContext(FfaMap.class, context -> plugin.getMapManager().getByName(context.popFirstArg()));
manager.registerCommand(new FfaCommand());
manager.registerCommand(new KitCommand());
manager.registerCommand(new MapCommand());
manager.registerCommand(new StatsCommand()); // Unfinished command
//manager.registerCommand(new SettingsCommand()); // Not working currently | package me.elb1to.ffa.command.manager;
/**
* @author Elb1to
* @since 11/24/2023
*/
public class CommandManager {
private final FfaPlugin plugin;
private final PaperCommandManager manager;
public CommandManager(FfaPlugin plugin) {
this.plugin = plugin;
this.manager = new PaperCommandManager(plugin);
load();
}
private void load() {
manager.getCommandCompletions().registerCompletion("kits", context -> new ArrayList<>(plugin.getKitManager().getKits().values())
.stream()
.map(Kit::getName)
.collect(Collectors.toList())
);
manager.getCommandCompletions().registerCompletion("maps", context -> plugin.getMapManager().getMaps()
.stream()
.map(FfaMap::getName)
.collect(Collectors.toList())
);
manager.getCommandContexts().registerContext(Kit.class, context -> plugin.getKitManager().get(context.popFirstArg()));
manager.getCommandContexts().registerContext(FfaMap.class, context -> plugin.getMapManager().getByName(context.popFirstArg()));
manager.registerCommand(new FfaCommand());
manager.registerCommand(new KitCommand());
manager.registerCommand(new MapCommand());
manager.registerCommand(new StatsCommand()); // Unfinished command
//manager.registerCommand(new SettingsCommand()); // Not working currently | manager.registerCommand(new BuildModeCommand()); | 5 | 2023-11-28 16:53:29+00:00 | 8k |
daironpf/SocialSeed | Backend/src/test/java/com/social/seed/service/SocialUserServiceTest.java | [
{
"identifier": "SocialUser",
"path": "Backend/src/main/java/com/social/seed/model/SocialUser.java",
"snippet": "@Data\n@Builder\n@NoArgsConstructor\n@AllArgsConstructor\n@Node\npublic class SocialUser {\n\n @Id\n @GeneratedValue(UUIDStringGenerator.class)\n @Property(\"identifier\")\n private String id;\n\n private LocalDateTime dateBorn;\n private LocalDateTime registrationDate;\n\n private String fullName;\n private String userName;\n private String email;\n private String language;\n\n private Boolean onVacation;\n private Boolean isActive;\n private Boolean isDeleted;\n\n private Integer friendCount;\n private Integer followersCount;\n private Integer followingCount;\n private Integer friendRequestCount;\n\n @Relationship(type = \"INTERESTED_IN_HASHTAG\")\n private List<SocialUserInterestInHashTagRelationShip> hashTags;\n}"
},
{
"identifier": "SocialUserRepository",
"path": "Backend/src/main/java/com/social/seed/repository/SocialUserRepository.java",
"snippet": "public interface SocialUserRepository extends Neo4jRepository<SocialUser, String> {\n\n //region existBy\n @Query(\"\"\"\n OPTIONAL MATCH (u:SocialUser {email: $email})\n RETURN CASE WHEN u IS NOT NULL THEN true ELSE false END AS existUser\n \"\"\")\n Boolean existByEmail(String email);\n\n @Query(\"\"\"\n OPTIONAL MATCH (u:SocialUser {userName: $userName})\n RETURN CASE WHEN u IS NOT NULL THEN true ELSE false END AS existUser\n \"\"\")\n Boolean existByUserName(String userName);\n //endregion\n\n //region findBy\n @Query(\"\"\"\n OPTIONAL MATCH (u:SocialUser {email: $email})\n RETURN u\n \"\"\")\n Optional<SocialUser> findByEmail(String email);\n\n @Query(\"\"\"\n OPTIONAL MATCH (u:SocialUser {userName: $userName})\n RETURN u\n \"\"\")\n Optional<SocialUser> findByUserName(String userName);\n //endregion\n\n //region CRUD\n @Override\n @Query(\"\"\"\n OPTIONAL MATCH (u:SocialUser {identifier: $id})\n OPTIONAL MATCH (u)-[rt]->(t:HashTag)\n RETURN u, collect(rt), collect(t)\n \"\"\")\n Optional<SocialUser> findById(String id);\n\n @Query(\"\"\"\n MATCH (u:SocialUser {identifier: $id})\n SET u.fullName = $fullName,\n u.dateBorn = $dateBorn,\n u.language = $language\n \"\"\")\n void update(\n String id,\n String fullName,\n LocalDateTime dateBorn,\n String language\n );\n //endregion\n\n //region Update Special Props\n @Query(\"MATCH (u:SocialUser {identifier: $id}) SET u.userName = $newUserName\")\n void updateSocialUserName(String id, String newUserName);\n\n @Query(\"MATCH (u:SocialUser {identifier: $id}) SET u.email = $newEmail\")\n void updateSocialUserEmail(String id, String newEmail);\n //endregion\n\n //region FOLLOW\n @Query(\"\"\"\n MATCH (b:SocialUser {identifier: $userBId})\n MATCH (a:SocialUser {identifier: $userAId})\n OPTIONAL MATCH(b)<-[r:FOLLOWED_BY]-(a)\n RETURN CASE WHEN r IS NOT NULL THEN true ELSE false END AS following\n \"\"\")\n Boolean isUserBFollowerOfUserA(String userBId, String userAId);\n\n @Query(\"\"\"\n MATCH (b:SocialUser {identifier: $userBId})\n MATCH (a:SocialUser {identifier: $userAId})\n MERGE(b)<-[r:FOLLOWED_BY {followDate:$followDate}]-(a)\n WITH a, b\n SET a.followersCount = a.followersCount + 1,\n b.followingCount = b.followingCount + 1\n \"\"\")\n void createUserBFollowUserA(\n String userBId,\n String userAId,\n LocalDateTime followDate);\n\n @Query(\"\"\"\n MATCH (b:SocialUser {identifier: $userBId})\n MATCH (a:SocialUser {identifier: $userAId})\n MATCH (b)<-[r:FOLLOWED_BY]-(a)\n DELETE r\n WITH a, b\n SET a.followersCount = a.followersCount - 1,\n b.followingCount = b.followingCount - 1\n \"\"\")\n void unFollowTheUserA(String userBId, String userAId);\n //endregion\n\n //region Vacation Mode\n @Query(\"\"\"\n MATCH (u:SocialUser {identifier: $idUserRequest})\n RETURN u.onVacation\n \"\"\")\n Boolean isVacationModeActivated(String idUserRequest);\n @Query(\"\"\"\n MATCH (u:SocialUser {identifier: $idUserRequest})\n SET u.onVacation = true\n \"\"\")\n void activateVacationMode(String idUserRequest);\n @Query(\"\"\"\n MATCH (u:SocialUser {identifier: $idUserRequest})\n SET u.onVacation = false\n \"\"\")\n void deactivateVacationMode(String idUserRequest);\n //endregion\n\n //region Delete\n @Override\n @Query(\"\"\"\n MATCH (u:SocialUser {identifier: $id})\n OPTIONAL MATCH (u)<-[:POSTED_BY]-(p)\n FOREACH (_ IN CASE WHEN u IS NOT NULL THEN [1] ELSE [] END | \n DETACH DELETE u\n )\n FOREACH (_ IN CASE WHEN p IS NOT NULL THEN [1] ELSE [] END |\n DETACH DELETE p\n )\n \"\"\")\n void deleteById(String id);\n //endregion\n\n //region Activated Mode\n @Query(\"\"\"\n MATCH (u:SocialUser {identifier: $id})\n RETURN u.isActive\n \"\"\")\n boolean isSocialUserActivated(String id);\n\n @Query(\"\"\"\n MATCH (u:SocialUser {identifier: $id})\n SET u.isActive= true\n \"\"\")\n void activateSocialUser(String id);\n\n @Query(\"\"\"\n MATCH (u:SocialUser {identifier: $id})\n SET u.isActive= false\n \"\"\")\n void deactivateSocialUser(String id);\n //endregion\n}"
},
{
"identifier": "TestUtils",
"path": "Backend/src/test/java/com/social/seed/utils/TestUtils.java",
"snippet": "public class TestUtils {\n\n /**\n * Creates a SocialUser object with the specified properties.\n *\n * @param userName The username of the social user.\n * @param email The email of the social user.\n * @param dateBorn The date of birth of the social user in the format \"yyyy-MM-dd'T'HH:mm:ss\".\n * @param fullName The full name of the social user.\n * @param language The language preference of the social user.\n * @return A SocialUser object with the specified properties.\n */\n public static SocialUser createSocialUser(String userName, String email, String dateBorn, String fullName, String language) {\n return SocialUser.builder()\n .userName(userName)\n .email(email)\n .dateBorn(LocalDateTime.parse(dateBorn))\n .fullName(fullName)\n .language(language)\n .registrationDate(LocalDateTime.now())\n .isActive(true)\n .isDeleted(false)\n .onVacation(false)\n .followersCount(0)\n .friendCount(0)\n .followingCount(0)\n .friendRequestCount(0)\n .build();\n }\n\n /**\n * Creates a new HashTag instance with the given properties.\n *\n * @param id The unique identifier of the hashtag.\n * @param name The name of the hashtag.\n * @param socialUserInterestIn The count of social users interested in this hashtag.\n * @param postTaggedIn The count of posts tagged with this hashtag.\n * @return A new HashTag instance with the specified properties.\n */\n public static HashTag createHashTag(String id, String name, int socialUserInterestIn, int postTaggedIn) {\n return HashTag.builder()\n .id(id)\n .name(name)\n .socialUserInterestIn(socialUserInterestIn)\n .postTaggedIn(postTaggedIn)\n .build();\n }\n\n /**\n * Asserts that two instances of {@link SocialUser} are equal in terms of their properties.\n *\n * @param actual The actual SocialUser instance obtained during testing.\n * @param expected The expected SocialUser instance with the predefined values for comparison.\n *\n * @throws AssertionError If the actual and expected SocialUser instances are not equal.\n * The error details in the assertions can help identify which properties differ.\n */\n public static void assertSocialUserEquals(SocialUser actual, SocialUser expected) {\n // Ensure that the actual SocialUser instance is not null\n assertThat(actual).as(\"Actual SocialUser instance should not be null\").isNotNull();\n\n // Compare individual properties for equality\n\n // Check for potential errors in the 'id' property comparison\n assertThat(actual.getId())\n .as(\"Error in 'id' property comparison\")\n .isEqualTo(expected.getId());\n\n // Check for potential errors in the 'dateBorn' property comparison\n assertThat(actual.getDateBorn())\n .as(\"Error in 'dateBorn' property comparison\")\n .isEqualTo(expected.getDateBorn());\n\n // Check for potential errors in the 'registrationDate' property comparison\n assertThat(actual.getRegistrationDate())\n .as(\"Error in 'registrationDate' property comparison\")\n .isEqualTo(expected.getRegistrationDate());\n\n // Check for potential errors in the 'fullName' property comparison\n assertThat(actual.getFullName())\n .as(\"Error in 'fullName' property comparison\")\n .isEqualTo(expected.getFullName());\n\n // Check for potential errors in the 'userName' property comparison\n assertThat(actual.getUserName())\n .as(\"Error in 'userName' property comparison\")\n .isEqualTo(expected.getUserName());\n\n // Check for potential errors in the 'email' property comparison\n assertThat(actual.getEmail())\n .as(\"Error in 'email' property comparison\")\n .isEqualTo(expected.getEmail());\n\n // Check for potential errors in the 'language' property comparison\n assertThat(actual.getLanguage())\n .as(\"Error in 'language' property comparison\")\n .isEqualTo(expected.getLanguage());\n\n // Check for potential errors in the 'onVacation' property comparison\n assertThat(actual.getOnVacation())\n .as(\"Error in 'onVacation' property comparison\")\n .isEqualTo(expected.getOnVacation());\n\n // Check for potential errors in the 'isActive' property comparison\n assertThat(actual.getIsActive())\n .as(\"Error in 'isActive' property comparison\")\n .isEqualTo(expected.getIsActive());\n\n // Check for potential errors in the 'isDeleted' property comparison\n assertThat(actual.getIsDeleted())\n .as(\"Error in 'isDeleted' property comparison\")\n .isEqualTo(expected.getIsDeleted());\n\n // Check for potential errors in the 'friendCount' property comparison\n assertThat(actual.getFriendCount())\n .as(\"Error in 'friendCount' property comparison\")\n .isEqualTo(expected.getFriendCount());\n\n // Check for potential errors in the 'followersCount' property comparison\n assertThat(actual.getFollowersCount())\n .as(\"Error in 'followersCount' property comparison\")\n .isEqualTo(expected.getFollowersCount());\n\n // Check for potential errors in the 'followingCount' property comparison\n assertThat(actual.getFollowingCount())\n .as(\"Error in 'followingCount' property comparison\")\n .isEqualTo(expected.getFollowingCount());\n\n // Check for potential errors in the 'friendRequestCount' property comparison\n assertThat(actual.getFriendRequestCount())\n .as(\"Error in 'friendRequestCount' property comparison\")\n .isEqualTo(expected.getFriendRequestCount());\n }\n\n /**\n * Asserts that two instances of {@link HashTag} are equal in terms of their properties.\n *\n * @param actual The actual HashTag instance obtained during testing.\n * @param expected The expected HashTag instance with the predefined values for comparison.\n *\n * @throws AssertionError If the actual and expected HashTag instances are not equal.\n * The error details in the assertions can help identify which properties differ.\n */\n public static void assertHashTagEquals(HashTag actual, HashTag expected) {\n // Ensure that the actual SocialUser instance is not null\n assertThat(actual).as(\"Actual HashTag instance should not be null\").isNotNull();\n\n // Check for potential errors in the 'id' property comparison\n assertThat(actual.getId())\n .as(\"Error in 'id' property comparison\")\n .isEqualTo(expected.getId());\n\n // Check for potential errors in the 'name' property comparison\n assertThat(actual.getName())\n .as(\"Error in 'name' property comparison\")\n .isEqualTo(expected.getName());\n\n // Check for potential errors in the 'socialUserInterestIn' property comparison\n assertThat(actual.getSocialUserInterestIn())\n .as(\"Error in 'socialUserInterestIn' property comparison\")\n .isEqualTo(expected.getSocialUserInterestIn());\n\n // Check for potential errors in the 'postTaggedIn' property comparison\n assertThat(actual.getPostTaggedIn())\n .as(\"Error in 'postTaggedIn' property comparison\")\n .isEqualTo(expected.getPostTaggedIn());\n }\n\n /**\n * Asserts that two instances of {@link com.social.seed.model.Post} are equal in terms of their properties.\n *\n * @param actual The actual Post instance obtained during testing.\n * @param expected The expected Post instance with the predefined values for comparison.\n *\n * @throws AssertionError If the actual and expected Post instances are not equal.\n * The error details in the assertions can help identify which properties differ.\n */\n public static void assertPostEquals(Post actual, Post expected) {\n // Ensure that the actual Post instance is not null\n assertThat(actual).as(\"Actual Post instance should not be null\").isNotNull();\n\n // Check for potential errors in the 'id' property comparison\n assertThat(actual.getId())\n .as(\"Error in 'id' property comparison\")\n .isEqualTo(expected.getId());\n\n // Check for potential errors in the 'content' property comparison\n assertThat(actual.getContent())\n .as(\"Error in 'content' property comparison\")\n .isEqualTo(expected.getContent());\n\n // Check for potential errors in the 'updateDate' property comparison\n assertThat(actual.getUpdateDate())\n .as(\"Error in 'updateDate' property comparison\")\n .isEqualTo(expected.getUpdateDate());\n\n // Check for potential errors in the 'imageUrl' property comparison\n assertThat(actual.getImageUrl())\n .as(\"Error in 'imageUrl' property comparison\")\n .isEqualTo(expected.getImageUrl());\n\n // Check for potential errors in the 'isActive' property comparison\n assertThat(actual.getIsActive())\n .as(\"Error in 'isActive' property comparison\")\n .isEqualTo(expected.getIsActive());\n\n // Check for potential errors in the 'likedCount' property comparison\n assertThat(actual.getLikedCount())\n .as(\"Error in 'likedCount' property comparison\")\n .isEqualTo(expected.getLikedCount());\n }\n}"
},
{
"identifier": "ResponseService",
"path": "Backend/src/main/java/com/social/seed/util/ResponseService.java",
"snippet": "@Component\npublic class ResponseService {\n public ResponseEntity<Object> successResponse(Object data) {\n return new ResponseEntity<>(ResponseDTO.success(data, \"Successful\"), HttpStatus.OK);\n }\n\n public ResponseEntity<Object> successResponseWithMessage(Object data, String message) {\n return new ResponseEntity<>(ResponseDTO.success(data, message), HttpStatus.OK);\n }\n\n public ResponseEntity<Object> successCreatedResponse(Object data) {\n return new ResponseEntity<>(ResponseDTO.success(data, \"Created Successful\"), HttpStatus.CREATED);\n }\n\n public ResponseEntity<Object> conflictResponseWithMessage(String message) {\n return new ResponseEntity<>(ResponseDTO.conflict(message), HttpStatus.CONFLICT);\n }\n\n public ResponseEntity<Object> forbiddenResponseWithMessage(String message) {\n return new ResponseEntity<>(ResponseDTO.forbidden(message), HttpStatus.FORBIDDEN);\n }\n\n public ResponseEntity<Object> forbiddenDuplicateSocialUser() {\n return new ResponseEntity<>(ResponseDTO.forbidden(\"The user cannot be the same.\"), HttpStatus.FORBIDDEN);\n }\n\n public ResponseEntity<Object> userNotFoundResponse(String userId) {\n return new ResponseEntity<>(ResponseDTO.notFound(String.format(\"The user with id: [ %s ] was not found.\", userId)), HttpStatus.NOT_FOUND);\n }\n\n public ResponseEntity<Object> notFoundWithMessageResponse(String message) {\n return new ResponseEntity<>(ResponseDTO.notFound(message), HttpStatus.NOT_FOUND);\n }\n\n public ResponseEntity<Object> dontUnFollow(String userId) {\n return new ResponseEntity<>(ResponseDTO.conflict(String.format(\"User %s is not being followed.\", userId)), HttpStatus.CONFLICT);\n }\n\n public ResponseEntity<Object> postNotFoundResponse(String postId) {\n return new ResponseEntity<>(ResponseDTO.notFound(String.format(\"Post not found with ID: %s\", postId)), HttpStatus.NOT_FOUND);\n }\n\n public ResponseEntity<Object> isNotPostAuthor() {\n return new ResponseEntity<>(ResponseDTO.forbidden(\"The user making the request is not the Author of the Post.\"), HttpStatus.FORBIDDEN);\n }\n\n public ResponseEntity<Object> hashTagNotFoundResponse(String hashTagId) {\n return new ResponseEntity<>(ResponseDTO.notFound(String.format(\"Hashtag not found with ID: %s\", hashTagId)), HttpStatus.NOT_FOUND);\n }\n}"
}
] | import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.*;
import com.social.seed.model.SocialUser;
import com.social.seed.repository.SocialUserRepository;
import com.social.seed.utils.TestUtils;
import com.social.seed.util.ResponseDTO;
import com.social.seed.util.ResponseService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import java.util.Optional; | 4,474 | /*
* Copyright 2011-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 com.social.seed.service;
/**
* Test class for the {@link SocialUserService}, focusing on testing individual methods and functionalities
* for managing { SocialUsers }.
* <p>
* @author Dairon Pérez Frías
* @since 2024-01-08
*/
@ExtendWith(MockitoExtension.class)
class SocialUserServiceTest {
// Class under test
@InjectMocks
private SocialUserService underTest;
// region dependencies
@Mock | /*
* Copyright 2011-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 com.social.seed.service;
/**
* Test class for the {@link SocialUserService}, focusing on testing individual methods and functionalities
* for managing { SocialUsers }.
* <p>
* @author Dairon Pérez Frías
* @since 2024-01-08
*/
@ExtendWith(MockitoExtension.class)
class SocialUserServiceTest {
// Class under test
@InjectMocks
private SocialUserService underTest;
// region dependencies
@Mock | private SocialUserRepository socialUserRepository; | 1 | 2023-12-04 21:47:54+00:00 | 8k |
lunasaw/zlm-spring-boot-starter | src/main/java/io/github/lunasaw/zlm/hook/service/AbstractZlmHookService.java | [
{
"identifier": "ServerNodeConfig",
"path": "src/main/java/io/github/lunasaw/zlm/entity/ServerNodeConfig.java",
"snippet": "@Data\npublic class ServerNodeConfig {\n /**\n * \n * The maximum size of RTP packets.\n */\n @JsonProperty(\"rtp.rtpMaxSize\")\n private String rtpRtpMaxSize;\n /**\n * \n * Whether to enable HLS demand.\n */\n @JsonProperty(\"protocol.hls_demand\")\n private String protocolHlsDemand;\n /**\n * \n * The Opus payload type used by the RTP proxy.\n */\n @JsonProperty(\"rtp_proxy.opus_pt\")\n private String rtpProxyOpusPt;\n /**\n * \n * The timeout value for the RTP proxy in seconds.\n */\n @JsonProperty(\"rtp_proxy.timeoutSec\")\n private String rtpProxyTimeoutSec;\n /**\n * \n * The port used for RTMP.\n */\n @JsonProperty(\"rtmp.port\")\n private String rtmpPort;\n /**\n * \n * The action to take when the IP address is not found.\n */\n @JsonProperty(\"hook.on_ip_not_found\")\n private String hookOnIpNotFound;\n /**\n * \n * Whether to allow file repetition during recording.\n */\n @JsonProperty(\"record.fileRepeat\")\n private String recordFileRepeat;\n /**\n * \n * The threshold for the maximum flow.\n */\n @JsonProperty(\"general.flowThreshold\")\n private String generalFlowThreshold;\n /**\n * \n * The transport type used for RTP in RTSP.\n */\n @JsonProperty(\"rtsp.rtpTransportType\")\n private String rtspRtpTransportType;\n /**\n * \n * The delay time for retrying hooks in seconds.\n */\n @JsonProperty(\"hook.retry_delay\")\n private String hookRetryDelay;\n /**\n * \n * The root path for HTTP requests.\n */\n @JsonProperty(\"http.rootPath\")\n private String httpRootPath;\n /**\n * \n * The time in seconds to keep the RTSP connection alive.\n */\n @JsonProperty(\"rtsp.keepAliveSecond\")\n private String rtspKeepAliveSecond;\n /**\n * \n * The action to take when the server is started.\n */\n @JsonProperty(\"hook.on_server_started\")\n private String hookOnServerStarted;\n /**\n * \n * The default snapshot for the API.\n */\n @JsonProperty(\"api.defaultSnap\")\n private String apiDefaultSnap;\n /**\n * \n * The origin URL for the cluster.\n */\n @JsonProperty(\"cluster.origin_url\")\n private String clusterOriginUrl;\n /**\n * \n * The port used for HTTP.\n */\n @JsonProperty(\"http.port\")\n private String httpPort;\n /**\n * \n * The virtual path for HTTP requests.\n */\n @JsonProperty(\"http.virtualPath\")\n private String httpVirtualPath;\n /**\n * \n * The time in seconds to keep the HTTP connection alive.\n */\n @JsonProperty(\"http.keepAliveSecond\")\n private String httpKeepAliveSecond;\n /**\n * \n * The log file for FFmpeg.\n */\n @JsonProperty(\"ffmpeg.log\")\n private String ffmpegLog;\n /**\n * \n * The action to take when a flow report is received.\n */\n @JsonProperty(\"hook.on_flow_report\")\n private String hookOnFlowReport;\n /**\n * \n * Whether to enable directory listing for HTTP requests.\n */\n @JsonProperty(\"http.dirMenu\")\n private String httpDirMenu;\n /**\n * \n * Whether to use direct proxy for RTSP.\n */\n @JsonProperty(\"rtsp.directProxy\")\n private String rtspDirectProxy;\n /**\n * \n * The command used for FFmpeg.\n */\n @JsonProperty(\"ffmpeg.cmd\")\n private String ffmpegCmd;\n /**\n * \n * Whether to enable low latency for RTP.\n */\n @JsonProperty(\"rtp.lowLatency\")\n private String rtpLowLatency;\n /**\n * \n * Whether to enable RTSP.\n */\n @JsonProperty(\"protocol.enable_rtsp\")\n private String protocolEnableRtsp;\n /**\n * \n * The port used for RTSP.\n */\n @JsonProperty(\"rtsp.port\")\n private String rtspPort;\n /**\n * \n * The SSL port used for RTMP.\n */\n @JsonProperty(\"rtmp.sslport\")\n private String rtmpSslport;\n /**\n * \n * The save path for HLS.\n */\n @JsonProperty(\"protocol.hls_save_path\")\n private String protocolHlsSavePath;\n /**\n * \n * The character set used for HTTP requests.\n */\n @JsonProperty(\"http.charSet\")\n private String httpCharSet;\n /**\n * \n * The size of the send buffer for HTTP requests.\n */\n @JsonProperty(\"http.sendBufSize\")\n private String httpSendBufSize;\n /**\n * \n * Whether to broadcast recorded TS files.\n */\n @JsonProperty(\"hls.broadcastRecordTs\")\n private String hlsBroadcastRecordTs;\n /**\n * \n * Whether to enable API debugging.\n */\n @JsonProperty(\"api.apiDebug\")\n private String apiApiDebug;\n /**\n * \n * The time in milliseconds for merging writes.\n */\n @JsonProperty(\"general.mergeWriteMS\")\n private String generalMergeWriteMS;\n /**\n * \n * The suffixes to forbid caching for HTTP requests.\n */\n @JsonProperty(\"http.forbidCacheSuffix\")\n private String httpForbidCacheSuffix;\n /**\n * \n * The action to take when a resource is not found for HTTP requests.\n */\n @JsonProperty(\"http.notFound\")\n private String httpNotFound;\n /**\n * \n * The number of times to retry hooks.\n */\n @JsonProperty(\"hook.retry\")\n private String hookRetry;\n /**\n * \n * The application name for recording.\n */\n @JsonProperty(\"record.appName\")\n private String recordAppName;\n /**\n * \n * The buffer size for HLS files.\n */\n @JsonProperty(\"hls.fileBufSize\")\n private String hlsFileBufSize;\n /**\n * \n * The timeout value for hooks in seconds.\n */\n @JsonProperty(\"hook.timeoutSec\")\n private String hookTimeoutSec;\n /**\n * \n * The SSL port used for RTSP.\n */\n @JsonProperty(\"rtsp.sslport\")\n private String rtspSslport;\n /**\n * \n * The delay time for deleting HLS files in seconds.\n */\n @JsonProperty(\"hls.deleteDelaySec\")\n private String hlsDeleteDelaySec;\n /**\n * \n * The action to take when the RTP server times out.\n */\n @JsonProperty(\"hook.on_rtp_server_timeout\")\n private String hookOnRtpServerTimeout;\n /**\n * \n * The action to take when sending RTP is stopped.\n */\n @JsonProperty(\"hook.on_send_rtp_stopped\")\n private String hookOnSendRtpStopped;\n /**\n * \n * The action to take when recording MP4 files.\n */\n @JsonProperty(\"hook.on_record_mp4\")\n private String hookOnRecordMp4;\n /**\n * \n * The interval time for sending keepalive messages for hooks in seconds.\n */\n @JsonProperty(\"hook.alive_interval\")\n private String hookAliveInterval;\n /**\n * \n * The time in seconds for the RTMP handshake.\n */\n @JsonProperty(\"rtmp.handshakeSecond\")\n private String rtmpHandshakeSecond;\n /**\n * \n * The schemas to use for stream changes in hooks.\n */\n @JsonProperty(\"hook.stream_changed_schemas\")\n private String hookStreamChangedSchemas;\n /**\n * \n * The external IP address for RTC.\n */\n @JsonProperty(\"rtc.externIP\")\n private String rtcExternIP;\n /**\n * \n * The bit rate for REMB in RTC.\n */\n @JsonProperty(\"rtc.rembBitRate\")\n private String rtcRembBitRate;\n /**\n * \n * The time in milliseconds for waiting for a stream reader.\n */\n @JsonProperty(\"general.streamNoneReaderDelayMS\")\n private String generalStreamNoneReaderDelayMS;\n /**\n * \n * The maximum duration for MP4 files in seconds.\n */\n @JsonProperty(\"protocol.mp4_max_second\")\n private String protocolMp4MaxSecond;\n /**\n * \n * The action to take when publishing a stream.\n */\n @JsonProperty(\"hook.on_publish\")\n private String hookOnPublish;\n /**\n * \n * The port used for the RTP proxy.\n */\n @JsonProperty(\"rtp_proxy.port\")\n private String rtpProxyPort;\n /**\n * \n * The SSL port used for HTTP.\n */\n @JsonProperty(\"http.sslport\")\n private String httpSslport;\n /**\n * \n * The MTU size for audio packets in RTP.\n */\n @JsonProperty(\"rtp.audioMtuSize\")\n private String rtpAudioMtuSize;\n /**\n * \n * Whether to check for NVIDIA devices.\n */\n @JsonProperty(\"general.check_nvidia_dev\")\n private String generalCheckNvidiaDev;\n /**\n * \n * Whether to enable fast start for recording.\n */\n @JsonProperty(\"record.fastStart\")\n private String recordFastStart;\n /**\n * \n * The action to take when a stream is not found in hooks.\n */\n @JsonProperty(\"hook.on_stream_not_found\")\n private String hookOnStreamNotFound;\n /**\n * \n * The port range used for the RTP proxy.\n */\n @JsonProperty(\"rtp_proxy.port_range\")\n private String rtpProxyPortRange;\n /**\n * \n * Whether to enable RTMP.\n */\n @JsonProperty(\"protocol.enable_rtmp\")\n private String protocolEnableRtmp;\n /**\n * \n * The timeout value for SRT in seconds.\n */\n @JsonProperty(\"srt.timeoutSec\")\n private String srtTimeoutSec;\n /**\n * \n * The time in seconds for the RTSP handshake.\n */\n @JsonProperty(\"rtsp.handshakeSecond\")\n private String rtspHandshakeSecond;\n /**\n * \n * The duration for each HLS segment in seconds.\n */\n @JsonProperty(\"hls.segDur\")\n private String hlsSegDur;\n /**\n * \n * Whether to use MP4 as a player for the protocol.\n */\n @JsonProperty(\"protocol.mp4_as_player\")\n private String protocolMp4AsPlayer;\n /**\n * \n * The secret key for the API.\n */\n @JsonProperty(\"api.secret\")\n private String apiSecret;\n /**\n * \n * The number of HLS segments to retain.\n */\n @JsonProperty(\"hls.segRetain\")\n private String hlsSegRetain;\n /**\n * \n * Whether to enable demand for RTSP.\n */\n @JsonProperty(\"protocol.rtsp_demand\")\n private String protocolRtspDemand;\n /**\n * \n * The port used for SRT.\n */\n @JsonProperty(\"srt.port\")\n private String srtPort;\n /**\n * \n * The packet buffer size for SRT.\n */\n @JsonProperty(\"srt.pktBufSize\")\n private String srtPktBufSize;\n /**\n * \n * Whether to enable GOP caching for the RTP proxy.\n */\n @JsonProperty(\"rtp_proxy.gop_cache\")\n private String rtpProxyGopCache;\n /**\n * \n * The maximum size of requests for the shell.\n */\n @JsonProperty(\"shell.maxReqSize\")\n private String shellMaxReqSize;\n /**\n * \n * Whether to enable snapshots for FFmpeg.\n */\n @JsonProperty(\"ffmpeg.snap\")\n private String ffmpegSnap;\n /**\n * \n * The maximum time in milliseconds to wait for a stream reader.\n */\n @JsonProperty(\"general.maxStreamWaitMS\")\n private String generalMaxStreamWaitMS;\n /**\n * \n * The maximum multicast address.\n */\n @JsonProperty(\"multicast.addrMax\")\n private String multicastAddrMax;\n /**\n * \n * The time in milliseconds to wait for adding a track.\n */\n @JsonProperty(\"general.wait_add_track_ms\")\n private String generalWaitAddTrackMs;\n /**\n * \n * Whether to allow cross-domain requests for HTTP.\n */\n @JsonProperty(\"http.allow_cross_domains\")\n private String httpAllowCrossDomains;\n /**\n * \n * Whether to modify the timestamp for the protocol.\n */\n @JsonProperty(\"protocol.modify_stamp\")\n private String protocolModifyStamp;\n /**\n * \n * The MTU size for video packets in RTP.\n */\n @JsonProperty(\"rtp.videoMtuSize\")\n private String rtpVideoMtuSize;\n /**\n * \n * The root directory for snapshots in the API.\n */\n @JsonProperty(\"api.snapRoot\")\n private String apiSnapRoot;\n /**\n * \n * Whether to enable audio for the protocol.\n */\n @JsonProperty(\"protocol.enable_audio\")\n private String protocolEnableAudio;\n /**\n * \n * The action to take when the server keeps alive.\n */\n @JsonProperty(\"hook.on_server_keepalive\")\n private String hookOnServerKeepalive;\n /**\n * \n * The minimum multicast address.\n */\n @JsonProperty(\"multicast.addrMin\")\n private String multicastAddrMin;\n /**\n * \n * Whether to enable demand for TS.\n */\n @JsonProperty(\"protocol.ts_demand\")\n private String protocolTsDemand;\n /**\n * \n * Whether to enable FMP4 for the protocol.\n */\n @JsonProperty(\"protocol.enable_fmp4\")\n private String protocolEnableFmp4;\n /**\n * \n * Whether to enable low latency for RTSP.\n */\n @JsonProperty(\"rtsp.lowLatency\")\n private String rtspLowLatency;\n /**\n * \n * The IP range to allow for HTTP requests.\n */\n @JsonProperty(\"http.allow_ip_range\")\n private String httpAllowIpRange;\n /**\n * \n * The action to take when the RTSP realm is accessed in hooks.\n */\n @JsonProperty(\"hook.on_rtsp_realm\")\n private String hookOnRtspRealm;\n /**\n * \n * The action to take when a stream is changed in hooks.\n */\n @JsonProperty(\"hook.on_stream_changed\")\n private String hookOnStreamChanged;\n /**\n * \n * The header to use for forwarded IP addresses in HTTP requests.\n */\n @JsonProperty(\"http.forwarded_ip_header\")\n private String httpForwardedIpHeader;\n /**\n * \n * The H.265 payload type used by the RTP proxy.\n */\n @JsonProperty(\"rtp_proxy.h265_pt\")\n private String rtpProxyH265Pt;\n /**\n * \n * The action to take when an MP4 file is deleted in hooks.\n */\n @JsonProperty(\"hook.on_del_mp4\")\n private String hookOnDelMp4;\n /**\n * \n * Whether to enable HLS for the protocol.\n */\n @JsonProperty(\"protocol.enable_hls\")\n private String protocolEnableHls;\n /**\n * \n * Whether to enable MP4 for the protocol.\n */\n @JsonProperty(\"protocol.enable_mp4\")\n private String protocolEnableMp4;\n /**\n * \n * The port used for RTC.\n */\n @JsonProperty(\"rtc.port\")\n private String rtcPort;\n /**\n * \n * Whether to enable demand for FMP4.\n */\n @JsonProperty(\"protocol.fmp4_demand\")\n private String protocolFmp4Demand;\n /**\n * \n * The time in milliseconds for each sample during recording.\n */\n @JsonProperty(\"record.sampleMS\")\n private String recordSampleMS;\n /**\n * \n * The port used for the shell.\n */\n @JsonProperty(\"shell.port\")\n private String shellPort;\n /**\n * \n * The action to take when logging in to the shell.\n */\n @JsonProperty(\"hook.on_shell_login\")\n private String hookOnShellLogin;\n /**\n * \n * The number of times to retry connecting to the cluster.\n */\n @JsonProperty(\"cluster.retry_count\")\n private String clusterRetryCount;\n /**\n * \n * Whether to enable virtual hosts.\n */\n @JsonProperty(\"general.enableVhost\")\n private String generalEnableVhost;\n /**\n * \n * The size of the unready frame cache.\n */\n @JsonProperty(\"general.unready_frame_cache\")\n private String generalUnreadyFrameCache;\n /**\n * \n * The preferred video codec for RTC.\n */\n @JsonProperty(\"rtc.preferredCodecV\")\n private String rtcPreferredCodecV;\n /**\n * \n * The H.264 payload type used by the RTP proxy.\n */\n @JsonProperty(\"rtp_proxy.h264_pt\")\n private String rtpProxyH264Pt;\n /**\n * \n * Whether to automatically close connections for the protocol.\n */\n @JsonProperty(\"protocol.auto_close\")\n private String protocolAutoClose;\n /**\n * \n * The latency multiplier for SRT.\n */\n @JsonProperty(\"srt.latencyMul\")\n private String srtLatencyMul;\n /**\n * \n * The action to take when the server is exited.\n */\n @JsonProperty(\"hook.on_server_exited\")\n private String hookOnServerExited;\n /**\n * \n * Whether to reset when replaying.\n */\n @JsonProperty(\"general.resetWhenRePlay\")\n private String generalResetWhenRePlay;\n /**\n * \n * The save path for MP4 files in the protocol.\n */\n @JsonProperty(\"protocol.mp4_save_path\")\n private String protocolMp4SavePath;\n /**\n * \n * The time in milliseconds for continuing to push data for the protocol.\n */\n @JsonProperty(\"protocol.continue_push_ms\")\n private String protocolContinuePushMs;\n /**\n * \n * The dump directory for the RTP proxy.\n */\n @JsonProperty(\"rtp_proxy.dumpDir\")\n private String rtpProxyDumpDir;\n /**\n * \n * The payload type used for PS in the RTP proxy.\n */\n @JsonProperty(\"rtp_proxy.ps_pt\")\n private String rtpProxyPsPt;\n /**\n * \n * Whether to enable hooks.\n */\n @JsonProperty(\"hook.enable\")\n private String hookEnable;\n /**\n * \n * The timeout value for RTC in seconds.\n */\n @JsonProperty(\"rtc.timeoutSec\")\n private String rtcTimeoutSec;\n /**\n * \n * The preferred audio codec for RTC.\n */\n @JsonProperty(\"rtc.preferredCodecA\")\n private String rtcPreferredCodecA;\n /**\n * \n * The number of HLS segments to keep.\n */\n @JsonProperty(\"hls.segKeep\")\n private String hlsSegKeep;\n /**\n * \n * The TTL value for UDP multicast.\n */\n @JsonProperty(\"multicast.udpTTL\")\n private String multicastUdpTTL;\n /**\n * \n * Whether to enable STAP-A for H.264 in RTP.\n */\n @JsonProperty(\"rtp.h264_stap_a\")\n private String rtpH264StapA;\n /**\n * \n * The action to take when there are no stream readers in hooks.\n */\n @JsonProperty(\"hook.on_stream_none_reader\")\n private String hookOnStreamNoneReader;\n /**\n * \n * The action to take when recording TS files in hooks.\n */\n @JsonProperty(\"hook.on_record_ts\")\n private String hookOnRecordTs;\n /**\n * \n * The path to the FFmpeg binary.\n */\n @JsonProperty(\"ffmpeg.bin\")\n private String ffmpegBin;\n /**\n * \n * Whether to enable demand for TS in the protocol.\n */\n @JsonProperty(\"protocol.enable_ts\")\n private String protocolEnableTs;\n /**\n * \n * Whether to enable HLS FMP4 in the protocol.\n */\n @JsonProperty(\"protocol.enable_hls_fmp4\")\n private String protocolEnableHlsFmp4;\n /**\n * \n * The number of HLS segments.\n */\n @JsonProperty(\"hls.segNum\")\n private String hlsSegNum;\n /**\n * \n * The maximum size of requests for HTTP.\n */\n @JsonProperty(\"http.maxReqSize\")\n private String httpMaxReqSize;\n /**\n * \n * The TCP port used for RTC.\n */\n @JsonProperty(\"rtc.tcpPort\")\n private String rtcTcpPort;\n /**\n * \n * The timeout value for the cluster in seconds.\n */\n @JsonProperty(\"cluster.timeout_sec\")\n private String clusterTimeoutSec;\n /**\n * \n * Whether to enable FFmpeg logging.\n */\n @JsonProperty(\"general.enable_ffmpeg_log\")\n private String generalEnableFfmpegLog;\n /**\n * \n * The ID of the media server.\n */\n @JsonProperty(\"general.mediaServerId\")\n private String generalMediaServerId;\n /**\n * \n * The action to take when accessing HTTP in hooks.\n */\n @JsonProperty(\"hook.on_http_access\")\n private String hookOnHttpAccess;\n /**\n * \n * The time in milliseconds to wait for a track to be ready.\n */\n @JsonProperty(\"general.wait_track_ready_ms\")\n private String generalWaitTrackReadyMs;\n /**\n * \n * Whether to enable basic authentication for RTSP.\n */\n @JsonProperty(\"rtsp.authBasic\")\n private String rtspAuthBasic;\n /**\n * \n * The action to take when authenticating RTSP in hooks.\n */\n @JsonProperty(\"hook.on_rtsp_auth\")\n private String hookOnRtspAuth;\n /**\n * \n * Whether to enable demand for RTMP in the protocol.\n */\n @JsonProperty(\"protocol.rtmp_demand\")\n private String protocolRtmpDemand;\n /**\n * \n * Whether to add mute audio for the protocol.\n */\n @JsonProperty(\"protocol.add_mute_audio\")\n private String protocolAddMuteAudio;\n /**\n * \n * The buffer size for recording files.\n */\n @JsonProperty(\"record.fileBufSize\")\n private String recordFileBufSize;\n /**\n * \n * The time in seconds to keep the RTMP connection alive.\n */\n @JsonProperty(\"rtmp.keepAliveSecond\")\n private String rtmpKeepAliveSecond;\n /**\n * \n * The action to take when playing a stream in hooks.\n */\n @JsonProperty(\"hook.on_play\")\n private String hookOnPlay;\n}"
},
{
"identifier": "ZlmHookService",
"path": "src/main/java/io/github/lunasaw/zlm/hook/service/ZlmHookService.java",
"snippet": "public interface ZlmHookService {\n\n void onServerKeepLive(OnServerKeepaliveHookParam param);\n\n HookResult onPlay(OnPlayHookParam param);\n\n HookResultForOnPublish onPublish(OnPublishHookParam param);\n\n void onStreamChanged(OnStreamChangedHookParam param);\n\n HookResultForStreamNoneReader onStreamNoneReader(OnStreamNoneReaderHookParam param);\n\n void onStreamNotFound(OnStreamNotFoundHookParam param);\n\n void onServerStarted(ServerNodeConfig param);\n\n void onSendRtpStopped(OnSendRtpStoppedHookParam param);\n\n void onRtpServerTimeout(OnRtpServerTimeoutHookParam param);\n\n HookResultForOnHttpAccess onHttpAccess(OnHttpAccessParam param);\n\n HookResultForOnRtspRealm onRtspRealm(OnRtspRealmHookParam param);\n\n HookResultForOnRtspAuth onRtspAuth(OnRtspAuthHookParam param);\n\n void onFlowReport(OnFlowReportHookParam param);\n\n void onServerExited(HookParam param);\n\n void onRecordMp4(OnRecordMp4HookParam param);\n}"
}
] | import io.github.lunasaw.zlm.entity.ServerNodeConfig;
import io.github.lunasaw.zlm.hook.param.*;
import io.github.lunasaw.zlm.hook.service.ZlmHookService;
import lombok.extern.slf4j.Slf4j; | 6,323 | package io.github.lunasaw.zlm.hook.service;
/**
* @author luna
* @version 1.0
* @date 2023/12/3
* @description: 默认的钩子服务实现
*/
@Slf4j
public abstract class AbstractZlmHookService implements ZlmHookService {
@Override
public void onServerKeepLive(OnServerKeepaliveHookParam param) {
}
@Override
public HookResult onPlay(OnPlayHookParam param) {
return HookResult.SUCCESS();
}
@Override
public HookResultForOnPublish onPublish(OnPublishHookParam param) {
return HookResultForOnPublish.SUCCESS();
}
@Override
public void onStreamChanged(OnStreamChangedHookParam param) {
}
@Override
public HookResultForStreamNoneReader onStreamNoneReader(OnStreamNoneReaderHookParam param) {
return HookResultForStreamNoneReader.SUCCESS();
}
@Override
public void onStreamNotFound(OnStreamNotFoundHookParam param) {
}
@Override | package io.github.lunasaw.zlm.hook.service;
/**
* @author luna
* @version 1.0
* @date 2023/12/3
* @description: 默认的钩子服务实现
*/
@Slf4j
public abstract class AbstractZlmHookService implements ZlmHookService {
@Override
public void onServerKeepLive(OnServerKeepaliveHookParam param) {
}
@Override
public HookResult onPlay(OnPlayHookParam param) {
return HookResult.SUCCESS();
}
@Override
public HookResultForOnPublish onPublish(OnPublishHookParam param) {
return HookResultForOnPublish.SUCCESS();
}
@Override
public void onStreamChanged(OnStreamChangedHookParam param) {
}
@Override
public HookResultForStreamNoneReader onStreamNoneReader(OnStreamNoneReaderHookParam param) {
return HookResultForStreamNoneReader.SUCCESS();
}
@Override
public void onStreamNotFound(OnStreamNotFoundHookParam param) {
}
@Override | public void onServerStarted(ServerNodeConfig param) { | 0 | 2023-12-02 08:25:38+00:00 | 8k |
Hoto-Mocha/Re-ARranged-Pixel-Dungeon | SPD-classes/src/main/java/com/watabou/noosa/TextInput.java | [
{
"identifier": "Script",
"path": "SPD-classes/src/main/java/com/watabou/glscripts/Script.java",
"snippet": "public class Script extends Program {\n\n\tprivate static final HashMap<Class<? extends Script>,Script> all =\n\t\t\tnew HashMap<>();\n\t\n\tprivate static Script curScript = null;\n\tprivate static Class<? extends Script> curScriptClass = null;\n\t\n\t@SuppressWarnings(\"unchecked\")\n\tpublic synchronized static<T extends Script> T use( Class<T> c ) {\n\n\t\tif (c != curScriptClass) {\n\t\t\t\n\t\t\tScript script = all.get( c );\n\t\t\tif (script == null) {\n\t\t\t\tscript = Reflection.newInstance( c );\n\t\t\t\tall.put( c, script );\n\t\t\t}\n\n\t\t\tcurScript = script;\n\t\t\tcurScriptClass = c;\n\t\t\tcurScript.use();\n\n\t\t}\n\t\t\n\t\treturn (T)curScript;\n\t}\n\n\tpublic synchronized static void unuse(){\n\t\tcurScript = null;\n\t\tcurScriptClass = null;\n\t}\n\t\n\tpublic synchronized static void reset() {\n\t\tfor (Script script:all.values()) {\n\t\t\tscript.delete();\n\t\t}\n\t\tall.clear();\n\t\t\n\t\tcurScript = null;\n\t\tcurScriptClass = null;\n\t}\n\t\n\tpublic void compile( String src ) {\n\n\t\tString[] srcShaders = src.split( \"//\\n\" );\n\t\tattach( Shader.createCompiled( Shader.VERTEX, srcShaders[0] ) );\n\t\tattach( Shader.createCompiled( Shader.FRAGMENT, srcShaders[1] ) );\n\t\tlink();\n\n\t}\n\n}"
},
{
"identifier": "Blending",
"path": "SPD-classes/src/main/java/com/watabou/glwrap/Blending.java",
"snippet": "public class Blending {\n\t\n\tpublic static void useDefault(){\n\t\tenable();\n\t\tsetNormalMode();\n\t}\n\t\n\tpublic static void enable(){\n\t\tGdx.gl.glEnable( Gdx.gl.GL_BLEND );\n\t}\n\t\n\tpublic static void disable(){\n\t\tGdx.gl.glDisable( Gdx.gl.GL_BLEND );\n\t}\n\t\n\t//in this mode colors overwrite eachother, based on alpha value\n\tpublic static void setNormalMode(){\n\t\tGdx.gl.glBlendFunc( Gdx.gl.GL_SRC_ALPHA, Gdx.gl.GL_ONE_MINUS_SRC_ALPHA );\n\t}\n\t\n\t//in this mode colors add to eachother, eventually reaching pure white\n\tpublic static void setLightMode(){\n\t\tGdx.gl.glBlendFunc( Gdx.gl.GL_SRC_ALPHA, Gdx.gl.GL_ONE );\n\t}\n\t\n}"
},
{
"identifier": "Quad",
"path": "SPD-classes/src/main/java/com/watabou/glwrap/Quad.java",
"snippet": "public class Quad {\n\n\t// 0---1\n\t// | \\ |\n\t// 3---2\n\tpublic static final short[] VALUES = {0, 1, 2, 0, 2, 3};\n\t\n\tpublic static final int SIZE = VALUES.length;\n\t\n\tprivate static ShortBuffer indices;\n\tprivate static int indexSize = 0;\n\tprivate static int bufferIndex = -1;\n\t\n\tpublic static FloatBuffer create() {\n\t\treturn ByteBuffer.\n\t\t\tallocateDirect( 16 * Float.SIZE / 8 ).\n\t\t\torder( ByteOrder.nativeOrder() ).\n\t\t\tasFloatBuffer();\n\t}\n\t\n\tpublic static FloatBuffer createSet( int size ) {\n\t\treturn ByteBuffer.\n\t\t\tallocateDirect( size * 16 * Float.SIZE / 8 ).\n\t\t\torder( ByteOrder.nativeOrder() ).\n\t\t\tasFloatBuffer();\n\t}\n\n\t//sets up for drawing up to 32k quads in one command, shouldn't ever need to exceed this\n\tpublic static void setupIndices(){\n\t\tShortBuffer indices = getIndices( Short.MAX_VALUE );\n\t\tif (bufferIndex == -1){\n\t\t\tbufferIndex = Gdx.gl.glGenBuffer();\n\t\t}\n\t\tGdx.gl.glBindBuffer(Gdx.gl.GL_ELEMENT_ARRAY_BUFFER, bufferIndex);\n\t\tGdx.gl.glBufferData(Gdx.gl.GL_ELEMENT_ARRAY_BUFFER, (indices.capacity()*2), indices, Gdx.gl.GL_STATIC_DRAW);\n\t\tGdx.gl.glBindBuffer(Gdx.gl.GL_ELEMENT_ARRAY_BUFFER, 0);\n\t}\n\n\tpublic static void bindIndices(){\n\t\tGdx.gl.glBindBuffer(Gdx.gl.GL_ELEMENT_ARRAY_BUFFER, bufferIndex);\n\t}\n\n\tpublic static void releaseIndices(){\n\t\tGdx.gl.glBindBuffer(Gdx.gl.GL_ELEMENT_ARRAY_BUFFER, 0);\n\t}\n\t\n\tpublic static ShortBuffer getIndices( int size ) {\n\t\t\n\t\tif (size > indexSize) {\n\t\t\t\n\t\t\tindexSize = size;\n\t\t\tindices = ByteBuffer.\n\t\t\t\tallocateDirect( size * SIZE * Short.SIZE / 8 ).\n\t\t\t\torder( ByteOrder.nativeOrder() ).\n\t\t\t\tasShortBuffer();\n\t\t\t\n\t\t\tshort[] values = new short[size * 6];\n\t\t\tint pos = 0;\n\t\t\tint limit = size * 4;\n\t\t\tfor (int ofs=0; ofs < limit; ofs += 4) {\n\t\t\t\tvalues[pos++] = (short)(ofs + 0);\n\t\t\t\tvalues[pos++] = (short)(ofs + 1);\n\t\t\t\tvalues[pos++] = (short)(ofs + 2);\n\t\t\t\tvalues[pos++] = (short)(ofs + 0);\n\t\t\t\tvalues[pos++] = (short)(ofs + 2);\n\t\t\t\tvalues[pos++] = (short)(ofs + 3);\n\t\t\t}\n\t\t\t\n\t\t\tindices.put( values );\n\t\t\t((Buffer)indices).position( 0 );\n\t\t}\n\t\t\n\t\treturn indices;\n\t}\n\t\n\tpublic static void fill( float[] v,\n\t\tfloat x1, float x2, float y1, float y2,\n\t\tfloat u1, float u2, float v1, float v2 ) {\n\t\t\n\t\tv[0] = x1;\n\t\tv[1] = y1;\n\t\tv[2] = u1;\n\t\tv[3] = v1;\n\t\t\n\t\tv[4] = x2;\n\t\tv[5] = y1;\n\t\tv[6] = u2;\n\t\tv[7] = v1;\n\t\t\n\t\tv[8] = x2;\n\t\tv[9] = y2;\n\t\tv[10]= u2;\n\t\tv[11]= v2;\n\t\t\n\t\tv[12]= x1;\n\t\tv[13]= y2;\n\t\tv[14]= u1;\n\t\tv[15]= v2;\n\t}\n\t\n\tpublic static void fillXY( float[] v, float x1, float x2, float y1, float y2 ) {\n\t\t\n\t\tv[0] = x1;\n\t\tv[1] = y1;\n\t\t\n\t\tv[4] = x2;\n\t\tv[5] = y1;\n\t\t\n\t\tv[8] = x2;\n\t\tv[9] = y2;\n\t\t\n\t\tv[12]= x1;\n\t\tv[13]= y2;\n\t}\n\t\n\tpublic static void fillUV( float[] v, float u1, float u2, float v1, float v2 ) {\n\t\t\n\t\tv[2] = u1;\n\t\tv[3] = v1;\n\t\t\n\t\tv[6] = u2;\n\t\tv[7] = v1;\n\t\t\n\t\tv[10]= u2;\n\t\tv[11]= v2;\n\t\t\n\t\tv[14]= u1;\n\t\tv[15]= v2;\n\t}\n}"
},
{
"identifier": "Texture",
"path": "SPD-classes/src/main/java/com/watabou/glwrap/Texture.java",
"snippet": "public class Texture {\n\n\tpublic static final int NEAREST\t= Gdx.gl.GL_NEAREST;\n\tpublic static final int LINEAR\t= Gdx.gl.GL_LINEAR;\n\t\n\tpublic static final int REPEAT\t= Gdx.gl.GL_REPEAT;\n\tpublic static final int MIRROR\t= Gdx.gl.GL_MIRRORED_REPEAT;\n\tpublic static final int CLAMP\t= Gdx.gl.GL_CLAMP_TO_EDGE;\n\t\n\tpublic int id = -1;\n\tprivate static int bound_id = 0; //id of the currently bound texture\n\t\n\tpublic boolean premultiplied = false;\n\n\tprotected void generate(){\n\t\tid = Gdx.gl.glGenTexture();\n\t}\n\t\n\tpublic static void activate( int index ) {\n\t\tGdx.gl.glActiveTexture( Gdx.gl.GL_TEXTURE0 + index );\n\t}\n\t\n\tpublic void bind() {\n\t\tif (id == -1){\n\t\t\tgenerate();\n\t\t}\n\t\tif (id != bound_id) {\n\t\t\tGdx.gl.glBindTexture( Gdx.gl.GL_TEXTURE_2D, id );\n\t\t\tbound_id = id;\n\t\t}\n\t}\n\t\n\tpublic static void clear(){\n\t\tbound_id = 0;\n\t}\n\t\n\tpublic void filter( int minMode, int maxMode ) {\n\t\tbind();\n\t\tGdx.gl.glTexParameterf( Gdx.gl.GL_TEXTURE_2D, Gdx.gl.GL_TEXTURE_MIN_FILTER, minMode );\n\t\tGdx.gl.glTexParameterf( Gdx.gl.GL_TEXTURE_2D, Gdx.gl.GL_TEXTURE_MAG_FILTER, maxMode );\n\t}\n\t\n\tpublic void wrap( int s, int t ) {\n\t\tbind();\n\t\tGdx.gl.glTexParameterf( Gdx.gl.GL_TEXTURE_2D, Gdx.gl.GL_TEXTURE_WRAP_S, s );\n\t\tGdx.gl.glTexParameterf( Gdx.gl.GL_TEXTURE_2D, Gdx.gl.GL_TEXTURE_WRAP_T, t );\n\t}\n\t\n\tpublic void delete() {\n\t\tif (bound_id == id) bound_id = 0;\n\t\tGdx.gl.glDeleteTexture( id );\n\t}\n\t\n\tpublic void bitmap( Pixmap pixmap ) {\n\t\tbind();\n\t\t\n\t\tGdx.gl.glTexImage2D(\n\t\t\t\tGdx.gl.GL_TEXTURE_2D,\n\t\t\t\t0,\n\t\t\t\tpixmap.getGLInternalFormat(),\n\t\t\t\tpixmap.getWidth(),\n\t\t\t\tpixmap.getHeight(),\n\t\t\t\t0,\n\t\t\t\tpixmap.getGLFormat(),\n\t\t\t\tpixmap.getGLType(),\n\t\t\t\tpixmap.getPixels()\n\t\t);\n\t\t\n\t\tpremultiplied = true;\n\t}\n\t\n\tpublic void pixels( int w, int h, int[] pixels ) {\n\t\n\t\tbind();\n\t\t\n\t\tIntBuffer imageBuffer = ByteBuffer.\n\t\t\tallocateDirect( w * h * 4 ).\n\t\t\torder( ByteOrder.nativeOrder() ).\n\t\t\tasIntBuffer();\n\t\timageBuffer.put( pixels );\n\t\t((Buffer)imageBuffer).position( 0 );\n\t\t\n\t\tGdx.gl.glTexImage2D(\n\t\t\tGdx.gl.GL_TEXTURE_2D,\n\t\t\t0,\n\t\t\tGdx.gl.GL_RGBA,\n\t\t\tw,\n\t\t\th,\n\t\t\t0,\n\t\t\tGdx.gl.GL_RGBA,\n\t\t\tGdx.gl.GL_UNSIGNED_BYTE,\n\t\t\timageBuffer );\n\t}\n\t\n\tpublic void pixels( int w, int h, byte[] pixels ) {\n\t\t\n\t\tbind();\n\t\t\n\t\tByteBuffer imageBuffer = ByteBuffer.\n\t\t\tallocateDirect( w * h ).\n\t\t\torder( ByteOrder.nativeOrder() );\n\t\timageBuffer.put( pixels );\n\t\t((Buffer)imageBuffer).position( 0 );\n\t\t\n\t\tGdx.gl.glPixelStorei( Gdx.gl.GL_UNPACK_ALIGNMENT, 1 );\n\n\t\tGdx.gl.glTexImage2D(\n\t\t\tGdx.gl.GL_TEXTURE_2D,\n\t\t\t0,\n\t\t\tGdx.gl.GL_ALPHA,\n\t\t\tw,\n\t\t\th,\n\t\t\t0,\n\t\t\tGdx.gl.GL_ALPHA,\n\t\t\tGdx.gl.GL_UNSIGNED_BYTE,\n\t\t\timageBuffer );\n\t}\n\t\n\tpublic static Texture create( Pixmap pix ) {\n\t\tTexture tex = new Texture();\n\t\ttex.bitmap( pix );\n\t\t\n\t\treturn tex;\n\t}\n\t\n\tpublic static Texture create( int width, int height, int[] pixels ) {\n\t\tTexture tex = new Texture();\n\t\ttex.pixels( width, height, pixels );\n\t\t\n\t\treturn tex;\n\t}\n\t\n\tpublic static Texture create( int width, int height, byte[] pixels ) {\n\t\tTexture tex = new Texture();\n\t\ttex.pixels( width, height, pixels );\n\t\t\n\t\treturn tex;\n\t}\n}"
},
{
"identifier": "Component",
"path": "SPD-classes/src/main/java/com/watabou/noosa/ui/Component.java",
"snippet": "public class Component extends Group {\n\t\n\tprotected float x;\n\tprotected float y;\n\tprotected float width;\n\tprotected float height;\n\t\n\tpublic Component() {\n\t\tsuper();\n\t\tcreateChildren();\n\t}\n\t\n\tpublic Component setPos( float x, float y ) {\n\t\tthis.x = x;\n\t\tthis.y = y;\n\t\tlayout();\n\t\t\n\t\treturn this;\n\t}\n\t\n\tpublic Component setSize( float width, float height ) {\n\t\tthis.width = width;\n\t\tthis.height = height;\n\t\tlayout();\n\t\t\n\t\treturn this;\n\t}\n\t\n\tpublic Component setRect( float x, float y, float width, float height ) {\n\t\tthis.x = x;\n\t\tthis.y = y;\n\t\tthis.width = width;\n\t\tthis.height = height;\n\t\tlayout();\n\t\t\n\t\treturn this;\n\t}\n\t\n\tpublic boolean inside( float x, float y ) {\n\t\treturn x >= this.x && y >= this.y && x < this.x + width && y < this.y + height;\n\t}\n\t\n\tpublic void fill( Component c ) {\n\t\tsetRect( c.x, c.y, c.width, c.height );\n\t}\n\t\n\tpublic float left() {\n\t\treturn x;\n\t}\n\t\n\tpublic float right() {\n\t\treturn x + width;\n\t}\n\t\n\tpublic float centerX() {\n\t\treturn x + width / 2;\n\t}\n\t\n\tpublic float top() {\n\t\treturn y;\n\t}\n\t\n\tpublic float bottom() {\n\t\treturn y + height;\n\t}\n\t\n\tpublic float centerY() {\n\t\treturn y + height / 2;\n\t}\n\t\n\tpublic float width() {\n\t\treturn width;\n\t}\n\t\n\tpublic float height() {\n\t\treturn height;\n\t}\n\t\n\tprotected void createChildren() {\n\t}\n\t\n\tprotected void layout() {\n\t}\n}"
},
{
"identifier": "DeviceCompat",
"path": "SPD-classes/src/main/java/com/watabou/utils/DeviceCompat.java",
"snippet": "public class DeviceCompat {\n\t\n\tpublic static boolean supportsFullScreen(){\n\t\tswitch (Gdx.app.getType()){\n\t\t\tcase Android:\n\t\t\t\t//Android 4.4+ supports hiding UI via immersive mode\n\t\t\t\treturn Gdx.app.getVersion() >= 19;\n\t\t\tcase iOS:\n\t\t\t\t//iOS supports hiding UI via drawing into the gesture safe area\n\t\t\t\treturn Gdx.graphics.getSafeInsetBottom() != 0;\n\t\t\tdefault:\n\t\t\t\t//TODO implement functionality for other platforms here\n\t\t\t\treturn true;\n\t\t}\n\t}\n\n\tpublic static boolean isAndroid(){\n\t\treturn SharedLibraryLoader.isAndroid;\n\t}\n\n\tpublic static boolean isiOS(){\n\t\treturn SharedLibraryLoader.isIos;\n\t}\n\n\tpublic static boolean isDesktop(){\n\t\treturn SharedLibraryLoader.isWindows || SharedLibraryLoader.isMac || SharedLibraryLoader.isLinux;\n\t}\n\n\tpublic static boolean hasHardKeyboard(){\n\t\treturn Gdx.input.isPeripheralAvailable(Input.Peripheral.HardwareKeyboard);\n\t}\n\t\n\tpublic static boolean isDebug(){\n\t\treturn Game.version.contains(\"INDEV\");\n\t}\n\t\n\tpublic static void log( String tag, String message ){\n\t\tGdx.app.log( tag, message );\n\t}\n\n\tpublic static RectF getSafeInsets(){\n\t\tRectF result = new RectF();\n\t\tresult.left = Gdx.graphics.getSafeInsetLeft();\n\t\tresult.top = Gdx.graphics.getSafeInsetTop();\n\t\tresult.right = Gdx.graphics.getSafeInsetRight();\n\t\tresult.bottom = Gdx.graphics.getSafeInsetBottom();\n\t\treturn result;\n\t}\n\n}"
},
{
"identifier": "FileUtils",
"path": "SPD-classes/src/main/java/com/watabou/utils/FileUtils.java",
"snippet": "public class FileUtils {\n\t\n\t// Helper methods for setting/using a default base path and file address mode\n\t\n\tprivate static Files.FileType defaultFileType = null;\n\tprivate static String defaultPath = \"\";\n\t\n\tpublic static void setDefaultFileProperties( Files.FileType type, String path ){\n\t\tdefaultFileType = type;\n\t\tdefaultPath = path;\n\t}\n\t\n\tpublic static FileHandle getFileHandle( String name ){\n\t\treturn getFileHandle( defaultFileType, defaultPath, name );\n\t}\n\t\n\tpublic static FileHandle getFileHandle( Files.FileType type, String name ){\n\t\treturn getFileHandle( type, \"\", name );\n\t}\n\t\n\tpublic static FileHandle getFileHandle( Files.FileType type, String basePath, String name ){\n\t\tswitch (type){\n\t\t\tcase Classpath:\n\t\t\t\treturn Gdx.files.classpath( basePath + name );\n\t\t\tcase Internal:\n\t\t\t\treturn Gdx.files.internal( basePath + name );\n\t\t\tcase External:\n\t\t\t\treturn Gdx.files.external( basePath + name );\n\t\t\tcase Absolute:\n\t\t\t\treturn Gdx.files.absolute( basePath + name );\n\t\t\tcase Local:\n\t\t\t\treturn Gdx.files.local( basePath + name );\n\t\t\tdefault:\n\t\t\t\treturn null;\n\t\t}\n\t}\n\t\n\t// Files\n\n\t//looks to see if there is any evidence of interrupted saving\n\tpublic static boolean cleanTempFiles(){\n\t\treturn cleanTempFiles(\"\");\n\t}\n\n\tpublic static boolean cleanTempFiles( String dirName ){\n\t\tFileHandle dir = getFileHandle(dirName);\n\t\tboolean foundTemp = false;\n\t\tfor (FileHandle file : dir.list()){\n\t\t\tif (file.isDirectory()){\n\t\t\t\tfoundTemp = cleanTempFiles(dirName + file.name()) || foundTemp;\n\t\t\t} else {\n\t\t\t\tif (file.name().endsWith(\".tmp\")){\n\t\t\t\t\tFileHandle temp = file;\n\t\t\t\t\tFileHandle original = getFileHandle( defaultFileType, \"\", temp.path().replace(\".tmp\", \"\") );\n\n\t\t\t\t\t//replace the base file with the temp one if base is invalid or temp is valid and newer\n\t\t\t\t\ttry {\n\t\t\t\t\t\tbundleFromStream(temp.read());\n\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tbundleFromStream(original.read());\n\n\t\t\t\t\t\t\tif (temp.lastModified() > original.lastModified()) {\n\t\t\t\t\t\t\t\ttemp.moveTo(original);\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\ttemp.delete();\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t} catch (Exception e) {\n\t\t\t\t\t\t\ttemp.moveTo(original);\n\t\t\t\t\t\t}\n\n\t\t\t\t\t} catch (Exception e) {\n\t\t\t\t\t\ttemp.delete();\n\t\t\t\t\t}\n\n\t\t\t\t\tfoundTemp = true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn foundTemp;\n\t}\n\t\n\tpublic static boolean fileExists( String name ){\n\t\tFileHandle file = getFileHandle( name );\n\t\treturn file.exists() && !file.isDirectory() && file.length() > 0;\n\t}\n\n\t//returns length of a file in bytes, or 0 if file does not exist\n\tpublic static long fileLength( String name ){\n\t\tFileHandle file = getFileHandle( name );\n\t\tif (!file.exists() || file.isDirectory()){\n\t\t\treturn 0;\n\t\t} else {\n\t\t\treturn file.length();\n\t\t}\n\t}\n\t\n\tpublic static boolean deleteFile( String name ){\n\t\treturn getFileHandle( name ).delete();\n\t}\n\n\t//replaces a file with junk data, for as many bytes as given\n\t//This is helpful as some cloud sync systems do not persist deleted, empty, or zeroed files\n\tpublic static void overwriteFile( String name, int bytes ){\n\t\tbyte[] data = new byte[bytes];\n\t\tArrays.fill(data, (byte)1);\n\t\tgetFileHandle( name ).writeBytes(data, false);\n\t}\n\t\n\t// Directories\n\t\n\tpublic static boolean dirExists( String name ){\n\t\tFileHandle dir = getFileHandle( name );\n\t\treturn dir.exists() && dir.isDirectory();\n\t}\n\t\n\tpublic static boolean deleteDir( String name ){\n\t\tFileHandle dir = getFileHandle( name );\n\t\t\n\t\tif (dir == null || !dir.isDirectory()){\n\t\t\treturn false;\n\t\t} else {\n\t\t\treturn dir.deleteDirectory();\n\t\t}\n\t}\n\n\tpublic static ArrayList<String> filesInDir( String name ){\n\t\tFileHandle dir = getFileHandle( name );\n\t\tArrayList result = new ArrayList();\n\t\tif (dir != null && dir.isDirectory()){\n\t\t\tfor (FileHandle file : dir.list()){\n\t\t\t\tresult.add(file.name());\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\t\n\t// bundle reading\n\t\n\t//only works for base path\n\tpublic static Bundle bundleFromFile( String fileName ) throws IOException{\n\t\ttry {\n\t\t\tFileHandle file = getFileHandle( fileName );\n\t\t\treturn bundleFromStream(file.read());\n\t\t} catch (GdxRuntimeException e){\n\t\t\t//game classes expect an IO exception, so wrap the GDX exception in that\n\t\t\tthrow new IOException(e);\n\t\t}\n\t}\n\t\n\tprivate static Bundle bundleFromStream( InputStream input ) throws IOException{\n\t\tBundle bundle = Bundle.read( input );\n\t\tinput.close();\n\t\treturn bundle;\n\t}\n\t\n\t// bundle writing\n\t\n\t//only works for base path\n\tpublic static void bundleToFile( String fileName, Bundle bundle ) throws IOException{\n\t\ttry {\n\t\t\tFileHandle file = getFileHandle(fileName);\n\n\t\t\t//write to a temp file, then move the files.\n\t\t\t// This helps prevent save corruption if writing is interrupted\n\t\t\tif (file.exists()){\n\t\t\t\tFileHandle temp = getFileHandle(fileName + \".tmp\");\n\t\t\t\tbundleToStream(temp.write(false), bundle);\n\t\t\t\tfile.delete();\n\t\t\t\ttemp.moveTo(file);\n\t\t\t} else {\n\t\t\t\tbundleToStream(file.write(false), bundle);\n\t\t\t}\n\n\t\t} catch (GdxRuntimeException e){\n\t\t\t//game classes expect an IO exception, so wrap the GDX exception in that\n\t\t\tthrow new IOException(e);\n\t\t}\n\t}\n\t\n\tprivate static void bundleToStream( OutputStream output, Bundle bundle ) throws IOException{\n\t\tBundle.write( bundle, output );\n\t\toutput.close();\n\t}\n\n}"
},
{
"identifier": "Point",
"path": "SPD-classes/src/main/java/com/watabou/utils/Point.java",
"snippet": "public class Point {\n\n\tpublic int x;\n\tpublic int y;\n\t\n\tpublic Point() {\n\t}\n\t\n\tpublic Point( int x, int y ) {\n\t\tthis.x = x;\n\t\tthis.y = y;\n\t}\n\t\n\tpublic Point( Point p ) {\n\t\tthis.x = p.x;\n\t\tthis.y = p.y;\n\t}\n\t\n\tpublic Point set( int x, int y ) {\n\t\tthis.x = x;\n\t\tthis.y = y;\n\t\treturn this;\n\t}\n\t\n\tpublic Point set( Point p ) {\n\t\tx = p.x;\n\t\ty = p.y;\n\t\treturn this;\n\t}\n\t\n\tpublic Point clone() {\n\t\treturn new Point( this );\n\t}\n\t\n\tpublic Point scale( float f ) {\n\t\tthis.x *= f;\n\t\tthis.y *= f;\n\t\treturn this;\n\t}\n\t\n\tpublic Point offset( int dx, int dy ) {\n\t\tx += dx;\n\t\ty += dy;\n\t\treturn this;\n\t}\n\t\n\tpublic Point offset( Point d ) {\n\t\tx += d.x;\n\t\ty += d.y;\n\t\treturn this;\n\t}\n\n\tpublic boolean isZero(){\n\t\treturn x == 0 && y == 0;\n\t}\n\n\tpublic float length() {\n\t\treturn (float)Math.sqrt( x * x + y * y );\n\t}\n\n\tpublic static float distance( Point a, Point b ) {\n\t\tfloat dx = a.x - b.x;\n\t\tfloat dy = a.y - b.y;\n\t\treturn (float)Math.sqrt( dx * dx + dy * dy );\n\t}\n\t\n\t@Override\n\tpublic boolean equals( Object obj ) {\n\t\tif (obj instanceof Point) {\n\t\t\tPoint p = (Point)obj;\n\t\t\treturn p.x == x && p.y == y;\n\t\t} else {\n\t\t\treturn false;\n\t\t}\n\t}\n}"
}
] | import com.badlogic.gdx.Files;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Container;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.ui.TextArea;
import com.badlogic.gdx.scenes.scene2d.ui.TextField;
import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener;
import com.badlogic.gdx.utils.Align;
import com.badlogic.gdx.utils.viewport.Viewport;
import com.watabou.glscripts.Script;
import com.watabou.glwrap.Blending;
import com.watabou.glwrap.Quad;
import com.watabou.glwrap.Texture;
import com.watabou.noosa.ui.Component;
import com.watabou.utils.DeviceCompat;
import com.watabou.utils.FileUtils;
import com.watabou.utils.Point; | 7,072 | @Override
public void changed(ChangeEvent event, Actor actor) {
BitmapFont f = Game.platform.getFont(size, textField.getText(), false, false);
TextField.TextFieldStyle style = textField.getStyle();
if (f != style.font){
style.font = f;
textField.setStyle(style);
}
}
});
if (!multiline){
textField.setTextFieldListener(new TextField.TextFieldListener(){
public void keyTyped (TextField textField, char c){
if (c == '\r' || c == '\n'){
enterPressed();
}
}
});
}
textField.setOnscreenKeyboard(new TextField.OnscreenKeyboard() {
@Override
public void show(boolean visible) {
Game.platform.setOnscreenKeyboardVisible(visible);
}
});
container.setActor(textField);
stage.setKeyboardFocus(textField);
Game.platform.setOnscreenKeyboardVisible(true);
}
public void enterPressed(){
//do nothing by default
};
public void setText(String text){
textField.setText(text);
textField.setCursorPosition(textField.getText().length());
}
public void setMaxLength(int maxLength){
textField.setMaxLength(maxLength);
}
public String getText(){
return textField.getText();
}
public void copyToClipboard(){
if (textField.getSelection().isEmpty()) {
textField.selectAll();
}
textField.copy();
}
public void pasteFromClipboard(){
String contents = Gdx.app.getClipboard().getContents();
if (contents == null) return;
if (!textField.getSelection().isEmpty()){
//just use cut, but override clipboard
textField.cut();
Gdx.app.getClipboard().setContents(contents);
}
String existing = textField.getText();
int cursorIdx = textField.getCursorPosition();
textField.setText(existing.substring(0, cursorIdx) + contents + existing.substring(cursorIdx));
textField.setCursorPosition(cursorIdx + contents.length());
}
@Override
protected void layout() {
super.layout();
float contX = x;
float contY = y;
float contW = width;
float contH = height;
if (bg != null){
bg.x = x;
bg.y = y;
bg.size(width, height);
contX += bg.marginLeft();
contY += bg.marginTop();
contW -= bg.marginHor();
contH -= bg.marginVer();
}
float zoom = Camera.main.zoom;
Camera c = camera();
if (c != null){
zoom = c.zoom;
Point p = c.cameraToScreen(contX, contY);
contX = p.x/zoom;
contY = p.y/zoom;
}
container.align(Align.topLeft);
container.setPosition(contX*zoom, (Game.height-(contY*zoom)));
container.size(contW*zoom, contH*zoom);
}
@Override
public void update() {
super.update();
stage.act(Game.elapsed);
}
@Override
public void draw() {
super.draw();
Quad.releaseIndices(); | /*
* Pixel Dungeon
* Copyright (C) 2012-2015 Oleg Dolya
*
* Shattered Pixel Dungeon
* Copyright (C) 2014-2023 Evan Debenham
*
* 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 <http://www.gnu.org/licenses/>
*/
package com.watabou.noosa;
//essentially contains a libGDX text input field, plus a PD-rendered background
public class TextInput extends Component {
private Stage stage;
private Container container;
private TextField textField;
private Skin skin;
private NinePatch bg;
public TextInput( NinePatch bg, boolean multiline, int size ){
super();
this.bg = bg;
add(bg);
//use a custom viewport here to ensure stage camera matches game camera
Viewport viewport = new Viewport() {};
viewport.setWorldSize(Game.width, Game.height);
viewport.setScreenBounds(0, Game.bottomInset, Game.width, Game.height);
viewport.setCamera(new OrthographicCamera());
stage = new Stage(viewport);
Game.inputHandler.addInputProcessor(stage);
container = new Container<TextField>();
stage.addActor(container);
container.setTransform(true);
skin = new Skin(FileUtils.getFileHandle(Files.FileType.Internal, "gdx/textfield.json"));
TextField.TextFieldStyle style = skin.get(TextField.TextFieldStyle.class);
style.font = Game.platform.getFont(size, "", false, false);
style.background = null;
textField = multiline ? new TextArea("", style) : new TextField("", style);
textField.setProgrammaticChangeEvents(true);
if (!multiline) textField.setAlignment(Align.center);
textField.addListener(new ChangeListener() {
@Override
public void changed(ChangeEvent event, Actor actor) {
BitmapFont f = Game.platform.getFont(size, textField.getText(), false, false);
TextField.TextFieldStyle style = textField.getStyle();
if (f != style.font){
style.font = f;
textField.setStyle(style);
}
}
});
if (!multiline){
textField.setTextFieldListener(new TextField.TextFieldListener(){
public void keyTyped (TextField textField, char c){
if (c == '\r' || c == '\n'){
enterPressed();
}
}
});
}
textField.setOnscreenKeyboard(new TextField.OnscreenKeyboard() {
@Override
public void show(boolean visible) {
Game.platform.setOnscreenKeyboardVisible(visible);
}
});
container.setActor(textField);
stage.setKeyboardFocus(textField);
Game.platform.setOnscreenKeyboardVisible(true);
}
public void enterPressed(){
//do nothing by default
};
public void setText(String text){
textField.setText(text);
textField.setCursorPosition(textField.getText().length());
}
public void setMaxLength(int maxLength){
textField.setMaxLength(maxLength);
}
public String getText(){
return textField.getText();
}
public void copyToClipboard(){
if (textField.getSelection().isEmpty()) {
textField.selectAll();
}
textField.copy();
}
public void pasteFromClipboard(){
String contents = Gdx.app.getClipboard().getContents();
if (contents == null) return;
if (!textField.getSelection().isEmpty()){
//just use cut, but override clipboard
textField.cut();
Gdx.app.getClipboard().setContents(contents);
}
String existing = textField.getText();
int cursorIdx = textField.getCursorPosition();
textField.setText(existing.substring(0, cursorIdx) + contents + existing.substring(cursorIdx));
textField.setCursorPosition(cursorIdx + contents.length());
}
@Override
protected void layout() {
super.layout();
float contX = x;
float contY = y;
float contW = width;
float contH = height;
if (bg != null){
bg.x = x;
bg.y = y;
bg.size(width, height);
contX += bg.marginLeft();
contY += bg.marginTop();
contW -= bg.marginHor();
contH -= bg.marginVer();
}
float zoom = Camera.main.zoom;
Camera c = camera();
if (c != null){
zoom = c.zoom;
Point p = c.cameraToScreen(contX, contY);
contX = p.x/zoom;
contY = p.y/zoom;
}
container.align(Align.topLeft);
container.setPosition(contX*zoom, (Game.height-(contY*zoom)));
container.size(contW*zoom, contH*zoom);
}
@Override
public void update() {
super.update();
stage.act(Game.elapsed);
}
@Override
public void draw() {
super.draw();
Quad.releaseIndices(); | Script.unuse(); | 0 | 2023-11-27 05:56:58+00:00 | 8k |
Tofaa2/EntityLib | src/main/java/me/tofaa/entitylib/meta/Metadata.java | [
{
"identifier": "EntityLib",
"path": "src/main/java/me/tofaa/entitylib/EntityLib.java",
"snippet": "public final class EntityLib {\n\n private EntityLib() {}\n private static final HashMap<Integer, EntityMeta> metadata = new HashMap<>();\n private static final Map<UUID, WrapperEntity> entities = new ConcurrentHashMap<>();\n private static final Map<Integer, WrapperEntity> entitiesById = new ConcurrentHashMap<>();\n private static EntityInteractionProcessor interactionProcessor;\n private static boolean initialized = false;\n private static PacketEventsAPI<?> packetEvents;\n private static MetaConverterRegistry metaRegistry;\n private static EntityIdProvider entityIdProvider = EntityIdProvider.simple();\n\n /**\n * Initialize EntityLib.\n * <p>\n * This method should be called after PacketEvents is initialized.\n * Loads the internal metadata converter registry and sets the library usable\n * </p>\n * @param packetEvents PacketEventsAPI instance\n */\n public static void init(@NotNull PacketEventsAPI<?> packetEvents) {\n if (initialized) {\n throw new IllegalStateException(\"EntityLib is already initialized\");\n }\n initialized = true;\n EntityLib.packetEvents = packetEvents;\n if (!packetEvents.isInitialized()) {\n initialized = false;\n throw new IllegalStateException(\"PacketEvents is not initialized\");\n }\n metaRegistry = new MetaConverterRegistry();\n }\n\n /**\n * Enable entity interactions.\n * <p>\n * Enables entity interactions to be handled by EntityLib, rather than the developer.\n * <br>\n * This will register a PacketEvents listener for {@link PacketType.Play.Client#INTERACT_ENTITY} and call {@link EntityInteractionProcessor#process(WrapperEntity, WrapperPlayClientInteractEntity.InteractAction, InteractionHand, User)}.\n * <br>\n * To set the interaction processor, call {@link EntityLib#setInteractionProcessor(EntityInteractionProcessor)}.\n * </p>\n */\n public static void enableEntityInteractions() {\n checkInit();\n packetEvents.getEventManager().registerListener(new PacketListenerAbstract() {\n @Override\n public void onPacketReceive(PacketReceiveEvent event) {\n if (interactionProcessor == null) return;\n if (event.getPacketType() != PacketType.Play.Client.INTERACT_ENTITY) return;\n WrapperPlayClientInteractEntity packet = new WrapperPlayClientInteractEntity(event);\n WrapperEntity entity = getEntity(packet.getEntityId());\n if (entity == null) return;\n interactionProcessor.process(\n entity, packet.getAction(), packet.getHand(), event.getUser()\n );\n }\n });\n }\n\n /**\n * @param entityId the entity id\n * @return the entity with the given id, or null if an entity with that id does not exist\n */\n public static @Nullable WrapperEntity getEntity(int entityId) {\n checkInit();\n return entitiesById.get(entityId);\n }\n\n /**\n * @param uuid the entity uuid\n * @return the entity with the given uuid, or null if an entity with that uuid does not exist\n */\n public static @Nullable WrapperEntity getEntity(UUID uuid) {\n checkInit();\n return entities.get(uuid);\n }\n\n /**\n * Registers a custom entity to EntityLib. This exists to allow developers to extend {@link WrapperEntity} and its subclasses simply and define their own logic.\n * <p>\n * This method DOES NOT create a new entity, it simply registers the entity to EntityLib.\n * To construct a {@link WrapperEntity} you need to call {@link EntityLib#createMeta(int, EntityType)} and pass the created metadata to the constructor of the entity.\n * <br>\n * This method will throw a RuntimeException if an entity with the given uuid or id already exists.\n * <br>\n * The entity is not modified in any way, simply stored internally for it to be accessible thru {@link EntityLib#getEntity(UUID)} and {@link EntityLib#getEntity(int)}.\n * </p>\n * @param entity the entity to register\n * @return the same entity passed.\n * @param <T> instance of WrapperEntity, used to infer its type.\n */\n public static @NotNull <T extends WrapperEntity> T register(@NotNull T entity) {\n checkInit();\n if (entities.containsKey(entity.getUuid())) throw new RuntimeException(\"An entity with that uuid already exists\");\n if (entitiesById.containsKey(entity.getEntityId())) throw new RuntimeException(\"An entity with that id already exists\");\n entities.put(entity.getUuid(), entity);\n entitiesById.put(entity.getEntityId(), entity);\n return entity;\n }\n\n /**\n * Creates a new WrapperEntity with the given UUID and EntityType.\n * This method will automatically create a new EntityMeta for the entity and keeps track of it internally.\n * To get the entity, use {@link EntityLib#getEntity(UUID)} or {@link EntityLib#getEntity(int)}.\n * <p>\n * In theoretically impossible cases, this method may return null.\n * @param uuid the entity uuid\n * @param entityType the entity type\n * @return the created entity, or null if the entity could not be created\n */\n public static @NotNull WrapperEntity createEntity(int entityId, UUID uuid, EntityType entityType) {\n checkInit();\n if (entities.containsKey(uuid)) throw new RuntimeException(\"An entity with that uuid already exists\");\n if (entitiesById.containsKey(entityId)) throw new RuntimeException(\"An entity with that id already exists\");\n EntityMeta meta = createMeta(entityId, entityType);\n WrapperEntity entity;\n if (meta instanceof LivingEntityMeta) {\n entity = new WrapperLivingEntity(entityId, uuid, entityType, meta);\n }\n else if (entityType == EntityTypes.EXPERIENCE_ORB) {\n entity = new WrapperExperienceOrbEntity(entityId, uuid, entityType, meta);\n }\n else {\n entity = new WrapperEntity(entityId, uuid, entityType, meta);\n }\n entities.put(uuid, entity);\n entitiesById.put(entityId, entity);\n return entity;\n }\n\n public static @NotNull WrapperEntity createEntity(@NotNull UUID uuid, EntityType entityType) {\n return createEntity(entityIdProvider.provide(), uuid, entityType);\n }\n\n public static @NotNull WrapperEntityCreature createEntityCreature(int entityId, @NotNull UUID uuid, @NotNull EntityType entityType) {\n checkInit();\n if (entities.containsKey(uuid)) throw new RuntimeException(\"An entity with that uuid already exists\");\n if (entitiesById.containsKey(entityId)) throw new RuntimeException(\"An entity with that id already exists\");\n EntityMeta meta = createMeta(entityId, entityType);\n if (!(meta instanceof LivingEntityMeta)) {\n throw new RuntimeException(\"Entity type \" + entityType + \" is not a living entity, EntityCreature requires a living entity\");\n }\n WrapperEntityCreature entity = new WrapperEntityCreature(entityId, uuid, entityType, meta);\n entities.put(uuid, entity);\n entitiesById.put(entityId, entity);\n return entity;\n }\n\n public static @NotNull WrapperEntityCreature createEntityCreature(@NotNull UUID uuid, @NotNull EntityType entityType) {\n return createEntityCreature(entityIdProvider.provide(), uuid, entityType);\n }\n\n /**\n * @param entityId the entity id\n * @return the metadata of the entity with the given id. If the entity does not exist, this method will return null.\n */\n public static @Nullable EntityMeta getMeta(int entityId) {\n checkInit();\n return metadata.get(entityId);\n }\n\n /**\n * @param entityId the entity id\n * @param metaClass the metadata class to cast to\n * @return the metadata of the entity with the given id, cast to the given class. If the entity does not exist, this method will return null.\n * @param <T> the metadata class\n */\n public static <T extends EntityMeta> @Nullable T getMeta(int entityId, Class<T> metaClass) {\n checkInit();\n EntityMeta meta = metadata.get(entityId);\n if (meta == null) {\n return null;\n }\n if (metaClass.isAssignableFrom(meta.getClass())) {\n return (T) meta;\n }\n return null;\n }\n\n /**\n * Creates a new EntityMeta for the given entity id and type, these are stored internally and can be retrieved using {@link EntityLib#getMeta(int)}.\n * @param entityId the entity id\n * @param entityType the entity type\n * @return the created EntityMeta\n */\n public static @NotNull EntityMeta createMeta(int entityId, EntityType entityType) {\n checkInit();\n Metadata m = new Metadata(entityId);\n BiFunction<Integer, Metadata, EntityMeta> function = metaRegistry.get(entityType);\n EntityMeta meta = function.apply(entityId, m);\n metadata.put(entityId, meta);\n return meta;\n }\n\n /**\n * Creates a new EntityMeta for an entity, these are stored internally and can be retrieved using {@link EntityLib#getMeta(int)}.\n * @param entity the entity\n * @return the created EntityMeta\n */\n public static EntityMeta createMeta(WrapperEntity entity) {\n return createMeta(entity.getEntityId(), entity.getEntityType());\n }\n\n /**\n * @param entityType the entity type\n * @return the metadata class of the given entity type\n * @param <T> gets the appropriate metadata class for the given entity type\n */\n public static <T extends EntityMeta> Class<T> getMetaClassOf(EntityType entityType) {\n return metaRegistry.getMetaClass(entityType);\n }\n\n /**\n * @return the packet events api instance that was used to initialize EntityLib\n */\n public static PacketEventsAPI<?> getPacketEvents() {\n checkInit();\n return packetEvents;\n }\n\n /**\n * @return the specified interaction processor, or null if none is specified\n */\n public static @Nullable EntityInteractionProcessor getInteractionProcessor() {\n return interactionProcessor;\n }\n\n /**\n * Sets the interaction processor to the given one.\n * @param interactionProcessor the interaction processor\n */\n public static void setInteractionProcessor(EntityInteractionProcessor interactionProcessor) {\n EntityLib.interactionProcessor = interactionProcessor;\n }\n\n /**\n * @return the entity id provider\n */\n public static EntityIdProvider getEntityIdProvider() {\n return entityIdProvider;\n }\n\n /**\n * Sets the entity id provider to the given one.\n * @param entityIdProvider the entity id provider. The default implementation can be found at {@link EntityIdProvider#simple()}\n */\n public static void setEntityIdProvider(EntityIdProvider entityIdProvider) {\n EntityLib.entityIdProvider = entityIdProvider;\n }\n\n /**\n * Another internal method to verify the server version is supported. Safe to use externally as its purpose is simple and to avoid code duplication\n */\n @ApiStatus.Internal\n public static void verifyVersion(ServerVersion supported, String msg) {\n if (packetEvents.getServerManager().getVersion().isOlderThan(supported)) {\n throw new InvalidVersionException(msg);\n }\n }\n\n /**\n * A primarily internal method to send a packet wrapper to a User from the users UUID. This is useful for methods in {@link WrapperEntity}. Safe to use externally as its purpose is simple and to avoid code duplication\n * @param user the user uuid\n * @param wrapper the packet wrapper\n */\n @ApiStatus.Internal\n public static void sendPacket(UUID user, PacketWrapper<?> wrapper) {\n checkInit();\n packetEvents.getProtocolManager().sendPacket(packetEvents.getProtocolManager().getChannel(user), wrapper);\n }\n\n private static void checkInit() {\n if (!initialized) {\n throw new IllegalStateException(\"EntityLib is not initialized\");\n }\n }\n}"
},
{
"identifier": "WrapperEntity",
"path": "src/main/java/me/tofaa/entitylib/entity/WrapperEntity.java",
"snippet": "public class WrapperEntity implements Tickable {\n private final EntityType entityType;\n private final int entityId;\n private final Optional<UUID> uuid;\n private final EntityMeta meta;\n private final Set<UUID> viewers = new HashSet<>();\n private Location location;\n private boolean onGround;\n private boolean spawned;\n protected Vector3d velocity = Vector3d.zero();\n\n public WrapperEntity(int entityId, @NotNull UUID uuid, EntityType entityType, EntityMeta meta) {\n this.uuid = Optional.of(uuid);\n this.entityType = entityType;\n this.meta = meta;\n this.entityId = entityId;\n }\n\n public void refresh() {\n if (!spawned) return;\n sendPacketToViewers(meta.createPacket());\n }\n\n public boolean spawn(Location location) {\n if (spawned) return false;\n this.location = location;\n this.spawned = true;\n int data = 0;\n Optional<Vector3d> velocity;\n double veloX = 0, veloY = 0, veloZ = 0;\n if (meta instanceof ObjectData) {\n ObjectData od = (ObjectData) meta;\n data = od.getObjectData();\n if (od.requiresVelocityPacketAtSpawn()) {\n final WrapperPlayServerEntityVelocity veloPacket = getVelocityPacket();\n veloX = veloPacket.getVelocity().getX();\n veloY = veloPacket.getVelocity().getY();\n veloZ = veloPacket.getVelocity().getZ();\n }\n }\n if (veloX == 0 && veloY == 0 && veloZ == 0) {\n velocity = Optional.empty();\n } else {\n velocity = Optional.of(new Vector3d(veloX, veloY, veloZ));\n }\n sendPacketToViewers(\n new WrapperPlayServerSpawnEntity(\n entityId,\n this.uuid,\n entityType,\n location.getPosition(),\n location.getPitch(),\n location.getYaw(),\n location.getYaw(),\n data,\n velocity\n )\n );\n sendPacketToViewers(meta.createPacket());\n return true;\n }\n\n public boolean hasNoGravity() {\n return meta.isHasNoGravity();\n }\n\n public void setHasNoGravity(boolean hasNoGravity) {\n meta.setHasNoGravity(hasNoGravity);\n refresh();\n }\n\n public void rotateHead(float yaw, float pitch) {\n sendPacketToViewers(\n new WrapperPlayServerEntityRotation(entityId, yaw, pitch, onGround)\n );\n }\n\n public void rotateHead(Location location) {\n rotateHead(location.getYaw(), location.getPitch());\n }\n\n public void rotateHead(WrapperEntity entity) {\n rotateHead(entity.getLocation());\n }\n\n public Location getLocation() {\n return new Location(location.getX(), location.getY(), location.getZ(), location.getYaw(), location.getPitch());\n }\n\n public void remove() {\n if (!spawned) return;\n spawned = false;\n sendPacketToViewers(new WrapperPlayServerDestroyEntities(entityId));\n }\n\n public void teleport(Location location, boolean onGround) {\n this.location = location;\n this.onGround = onGround;\n sendPacketToViewers(\n new WrapperPlayServerEntityTeleport(entityId, location, onGround)\n );\n }\n\n public @NotNull Collection<UUID> getViewers() {\n return Collections.unmodifiableCollection(viewers);\n }\n\n public void teleport(Location location) {\n teleport(location, true);\n }\n\n public void sendPacketToViewers(PacketWrapper<?> packet) {\n viewers.forEach(uuid -> EntityLib.sendPacket(uuid, packet));\n }\n\n public void sendPacketsToViewers(PacketWrapper<?>... wrappers) {\n for (PacketWrapper<?> wrapper : wrappers) {\n sendPacketToViewers(wrapper);\n }\n }\n\n public boolean addViewer(UUID uuid) {\n if (!viewers.add(uuid)) {\n return false;\n }\n if (!spawned) return false;\n WrapperPlayServerSpawnEntity packet = new WrapperPlayServerSpawnEntity(\n entityId,\n this.uuid,\n entityType,\n location.getPosition(),\n location.getPitch(),\n location.getYaw(),\n location.getYaw(),\n 0,\n Optional.empty()\n );\n EntityLib.sendPacket(uuid, packet);\n EntityLib.sendPacket(uuid, meta.createPacket());\n return true;\n }\n\n public void addViewer(User user) {\n addViewer(user.getUUID());\n }\n\n public void removeViewer(UUID uuid) {\n if (!viewers.remove(uuid)) {\n return;\n }\n EntityLib.sendPacket(uuid, new WrapperPlayServerDestroyEntities(entityId));\n }\n\n public EntityMeta getMeta() {\n return meta;\n }\n\n public UUID getUuid() {\n return uuid.get();\n }\n\n public EntityType getEntityType() {\n return entityType;\n }\n\n public int getEntityId() {\n return entityId;\n }\n\n public <T extends EntityMeta> Class<T> getMetaClass() {\n return EntityLib.getMetaClassOf(entityType);\n }\n\n public boolean hasSpawned() {\n return spawned;\n }\n\n public boolean hasVelocity() {\n if (isOnGround()) {\n // if the entity is on the ground and only \"moves\" downwards, it does not have a velocity.\n return Double.compare(velocity.x, 0) != 0 || Double.compare(velocity.z, 0) != 0 || velocity.y > 0;\n } else {\n // The entity does not have velocity if the velocity is zero\n return !velocity.equals(Vector3d.zero());\n }\n }\n\n public boolean isOnGround() {\n return onGround;\n }\n\n public Vector3d getVelocity() {\n return velocity;\n }\n\n public void setVelocity(Vector3d velocity) {\n this.velocity = velocity;\n sendPacketToViewers(getVelocityPacket());\n }\n\n public double getX() {\n return location.getX();\n }\n\n public double getY() {\n return location.getY();\n }\n\n public double getZ() {\n return location.getZ();\n }\n\n public float getYaw() {\n return location.getYaw();\n }\n\n public float getPitch() {\n return location.getPitch();\n }\n\n private WrapperPlayServerEntityVelocity getVelocityPacket() {\n Vector3d velocity = this.velocity.multiply(8000.0f / 20.0f);\n return new WrapperPlayServerEntityVelocity(entityId, velocity);\n }\n\n @Override\n public void update(long time) {\n tick(time);\n }\n\n @Override\n public void tick(long time) {\n\n }\n}"
}
] | import com.github.retrooper.packetevents.protocol.entity.data.EntityData;
import com.github.retrooper.packetevents.protocol.entity.data.EntityDataType;
import com.github.retrooper.packetevents.wrapper.play.server.WrapperPlayServerEntityMetadata;
import me.tofaa.entitylib.EntityLib;
import me.tofaa.entitylib.entity.WrapperEntity;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap; | 4,730 | package me.tofaa.entitylib.meta;
@SuppressWarnings("unchecked")
public class Metadata {
private final Map<Byte, EntityData> metadataMap = new ConcurrentHashMap<>();
private final int entityId;
public Metadata(int entityId) {
this.entityId = entityId;
}
public <T> T getIndex(byte index, @Nullable T defaultValue) {
EntityData entityData = metadataMap.get(index);
if (entityData == null) return defaultValue;
if (entityData.getValue() == null) return defaultValue;
return (T) entityData.getValue();
}
public <T> void setIndex(byte index, @NotNull EntityDataType<T> dataType, T value) {
EntityData data = new EntityData(index, dataType, value);
this.metadataMap.put(index, data); | package me.tofaa.entitylib.meta;
@SuppressWarnings("unchecked")
public class Metadata {
private final Map<Byte, EntityData> metadataMap = new ConcurrentHashMap<>();
private final int entityId;
public Metadata(int entityId) {
this.entityId = entityId;
}
public <T> T getIndex(byte index, @Nullable T defaultValue) {
EntityData entityData = metadataMap.get(index);
if (entityData == null) return defaultValue;
if (entityData.getValue() == null) return defaultValue;
return (T) entityData.getValue();
}
public <T> void setIndex(byte index, @NotNull EntityDataType<T> dataType, T value) {
EntityData data = new EntityData(index, dataType, value);
this.metadataMap.put(index, data); | WrapperEntity e = EntityLib.getEntity(entityId); | 1 | 2023-11-27 02:17:41+00:00 | 8k |
minlwin/onestop-batch6 | s02-backend/member-api/src/main/java/com/jdc/shop/model/service/CatalogService.java | [
{
"identifier": "CatalogDetailsDto",
"path": "s02-backend/member-api/src/main/java/com/jdc/shop/api/anonymous/output/CatalogDetailsDto.java",
"snippet": "@Data\npublic class CatalogDetailsDto {\n\n\tprivate CatalogDto baseInfo;\n\tprivate List<String> images;\n\t\n\tpublic static CatalogDetailsDto from(Catalog entity) {\n\t\tvar dto = new CatalogDetailsDto();\n\t\tdto.setBaseInfo(CatalogDto.from(entity));\n\t\tdto.setImages(entity.getImages());\n\t\treturn dto;\n\t}\n\n}"
},
{
"identifier": "CatalogDto",
"path": "s02-backend/member-api/src/main/java/com/jdc/shop/api/anonymous/output/CatalogDto.java",
"snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\npublic class CatalogDto {\n\n\tprivate int id;\n\tprivate String name;\n\tprivate int categoryId;\n\tprivate String categoryName;\n\tprivate String description;\n\tprivate Purity purity;\n\tprivate BigDecimal weight;\n\tprivate BigDecimal lostWeight;\n\tprivate LocalDateTime marketTime;\n\tprivate BigDecimal marketPrice;\n\tprivate BigDecimal salePrice;\n\tprivate BigDecimal netPrice;\n\tprivate BigDecimal lostWeightFee;\n\tprivate BigDecimal goldSmithFees;\n\tprivate String coverImage;\n\tprivate LocalDateTime createAt;\n\tpublic boolean soldOut;\n\t\n\tpublic static void select(CriteriaQuery<CatalogDto> cq, Root<Catalog> root) {\n\t\tvar catagory = root.join(Catalog_.category);\n\t\t\n\t\tcq.multiselect(\n\t\t\troot.get(Catalog_.id),\n\t\t\troot.get(Catalog_.name),\n\t\t\tcatagory.get(Category_.id),\n\t\t\tcatagory.get(Category_.name),\n\t\t\troot.get(Catalog_.description),\n\t\t\troot.get(Catalog_.purity),\n\t\t\troot.get(Catalog_.weight),\n\t\t\troot.get(Catalog_.lostWeight),\n\t\t\troot.get(Catalog_.marketTime),\n\t\t\troot.get(Catalog_.marketPrice),\n\t\t\troot.get(Catalog_.salePrice),\n\t\t\troot.get(Catalog_.netPrice),\n\t\t\troot.get(Catalog_.lostWeightFee),\n\t\t\troot.get(Catalog_.goldSmithFees),\n\t\t\troot.get(Catalog_.coverImage),\n\t\t\troot.get(Catalog_.createAt),\n\t\t\troot.get(Catalog_.soldOut)\n\t\t);\n\t}\n\t\n\tpublic static CatalogDto from(Catalog entity) {\n\t\tvar dto = new CatalogDto();\n\t\tdto.setId(entity.getId());\n\t\tdto.setName(entity.getName());\n\t\tdto.setCategoryId(entity.getCategory().getId());\n\t\tdto.setCategoryName(entity.getCategory().getName());\n\t\tdto.setDescription(entity.getDescription());\n\t\tdto.setPurity(entity.getPurity());\n\t\tdto.setWeight(entity.getWeight());\n\t\tdto.setLostWeight(entity.getLostWeight());\n\t\tdto.setMarketTime(entity.getMarketTime());\n\t\tdto.setMarketPrice(entity.getMarketPrice());\n\t\tdto.setSalePrice(entity.getSalePrice());\n\t\tdto.setNetPrice(entity.getNetPrice());\n\t\tdto.setLostWeightFee(entity.getLostWeightFee());\n\t\tdto.setGoldSmithFees(entity.getGoldSmithFees());\n\t\tdto.setCoverImage(entity.getCoverImage());\n\t\tdto.setCreateAt(entity.getCreateAt());\n\t\tdto.setSoldOut(entity.isSoldOut());\n\t\treturn dto;\n\t}\n\t\n\t\n\tpublic GoldWeight getWeightForDisplay() {\n\t\treturn new GoldWeight(weight.intValue());\n\t}\n\n}"
},
{
"identifier": "CatalogForm",
"path": "s02-backend/member-api/src/main/java/com/jdc/shop/api/employee/input/CatalogForm.java",
"snippet": "@Data\npublic class CatalogForm {\n\n\t@NotBlank(message = \"Please enter catalog name.\")\n\tprivate String name;\n\n\t@NotNull(message = \"Please select category id.\")\n\tprivate Integer categoryId;\n\n\tprivate String description;\n\t\n\t@NotNull(message = \"Please enter based price.\")\n\tprivate BigDecimal basedPrice;\n\n\t@NotNull(message = \"Please enter purity.\")\n\tprivate Purity purity;\n\n\t@NotNull(message = \"Please enter weight.\")\n\tprivate BigDecimal weight;\n\n\t@NotNull(message = \"Please enter lost weight.\")\n\tprivate BigDecimal lostWeight;\n\n\t@NotNull(message = \"Please enter gold smith fees.\")\n\tprivate BigDecimal goldSmithFees;\n\t\n\tprivate boolean soldOut;\n\t\n\tpublic Catalog entity() {\n\t\tvar entity = new Catalog();\n\t\tentity.setName(name);\n\t\tentity.setDescription(description);\n\t\tentity.setBasedPrice(basedPrice);\n\t\tentity.setPurity(purity);\n\t\tentity.setWeight(weight);\n\t\tentity.setLostWeight(lostWeight);\n\t\tentity.setGoldSmithFees(goldSmithFees);\n\t\tentity.setSoldOut(soldOut);\n\t\treturn entity;\n\t}\n\n}"
},
{
"identifier": "CatalogSearch",
"path": "s02-backend/member-api/src/main/java/com/jdc/shop/api/employee/input/CatalogSearch.java",
"snippet": "@Data\npublic class CatalogSearch {\n\n\tprivate Integer categoryId;\n\tprivate String name;\n\tprivate LocalDate createFrom;\n\tprivate BigDecimal priceFrom;\n\tprivate BigDecimal priceTo;\n\tprivate Boolean soldOut;\n\n\tpublic Predicate where(CriteriaBuilder cb, Root<Catalog> root) {\n\t\tvar list = new ArrayList<Predicate>();\n\t\t\n\t\tif(null != categoryId && categoryId > 0) {\n\t\t\tvar category = root.join(Catalog_.category);\n\t\t\tlist.add(cb.equal(category.get(Category_.id), categoryId));\n\t\t}\n\t\t\n\t\tif(StringUtils.hasLength(name)) {\n\t\t\tlist.add(cb.like(cb.lower(root.get(Catalog_.name)), name.toLowerCase().concat(\"%\")));\n\t\t}\n\t\t\n\t\tif(null != createFrom) {\n\t\t\tlist.add(cb.greaterThanOrEqualTo(root.get(Catalog_.createAt), createFrom.atStartOfDay()));\n\t\t}\n\t\t\n\t\tif(null != priceFrom && priceFrom.intValue() > 0) {\n\t\t\tlist.add(cb.ge(root.get(Catalog_.salePrice), priceFrom));\n\t\t}\n\t\t\n\t\tif(null != priceTo && priceTo.intValue() > 0) {\n\t\t\tlist.add(cb.le(root.get(Catalog_.salePrice), priceTo));\n\t\t}\n\t\t\n\t\tif(null != soldOut) {\n\t\t\tlist.add(cb.equal(root.get(Catalog_.soldOut), soldOut));\n\t\t}\n\t\t\n\t\treturn cb.and(list.toArray(i -> new Predicate[i]));\n\t}\n}"
},
{
"identifier": "GoldPriceDto",
"path": "s02-backend/member-api/src/main/java/com/jdc/shop/api/owner/output/GoldPriceDto.java",
"snippet": "@NoArgsConstructor\n@AllArgsConstructor\npublic class GoldPriceDto {\n\n\t@Getter\n\tprivate LocalDateTime id;\n\tprivate BigDecimal basePrice;\n\tprivate BigDecimal diffFor16P;\n\tprivate BigDecimal diffFor15P;\n\t@Getter\n\tprivate Status status;\n\t\n\t\n\tpublic static void select(CriteriaQuery<GoldPriceDto> cq, Root<GoldPrice> root) {\n\t\tcq.multiselect(\n\t\t\troot.get(GoldPrice_.businessTime),\n\t\t\troot.get(GoldPrice_.basePrice),\n\t\t\troot.get(GoldPrice_.diffFor16P),\n\t\t\troot.get(GoldPrice_.diffFor15P),\n\t\t\troot.get(GoldPrice_.status)\t\t\t\n\t\t);\n\t}\n\t\n\tpublic static GoldPriceDto from(GoldPrice entity) {\n\t\treturn new GoldPriceDto(entity.getBusinessTime(), \n\t\t\t\tentity.getBasePrice(), \n\t\t\t\tentity.getDiffFor16P(), \n\t\t\t\tentity.getDiffFor15P(), \n\t\t\t\tentity.getStatus());\n\t}\n\t\n\n\tpublic BigDecimal getSalePriceFor16P() {\n\t\treturn basePrice;\n\t}\n\tpublic BigDecimal getBuyPriceFor16P() {\n\t\treturn basePrice.subtract(diffFor16P);\n\t}\n\tpublic BigDecimal getSalePriceFor15P() {\n\t\treturn basePrice.divide(new BigDecimal(16), 2, RoundingMode.HALF_UP).multiply(new BigDecimal(15));\n\t}\n\tpublic BigDecimal getBuyPriceFor15P() {\n\t\treturn getSalePriceFor15P().subtract(diffFor15P);\n\t}\n\tpublic long getIdValue() {\n\t\treturn id.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();\n\t}\n\t\n}"
},
{
"identifier": "Catalog",
"path": "s02-backend/member-api/src/main/java/com/jdc/shop/model/entity/Catalog.java",
"snippet": "@Data\n@EqualsAndHashCode(callSuper = false)\n@Entity\n@Table(name = \"CATALOG\")\n@SequenceGenerator(name = \"CATALOG_SEQ\", allocationSize = 1)\npublic class Catalog extends AbstractEntity {\n\n\t@Id\n\t@GeneratedValue(generator = \"CATALOG_SEQ\")\n\tprivate int id;\n\n\t@Column(nullable = false)\n\tprivate String name;\n\n\t@ManyToOne(fetch = FetchType.LAZY)\n\tprivate Category category;\n\n\tprivate String description;\n\n\t@Column(nullable = false)\n\tprivate BigDecimal basedPrice = BigDecimal.ZERO;\n\t\n\tprivate LocalDateTime marketTime;\n\tprivate BigDecimal marketPrice = BigDecimal.ZERO;\n\n\tprivate BigDecimal netPrice = BigDecimal.ZERO;\n\tprivate BigDecimal lostWeightFee = BigDecimal.ZERO;\n\n\tprivate BigDecimal salePrice = BigDecimal.ZERO;\n\n\t@Column(nullable = false)\n\tprivate Purity purity;\n\n\t@Column(nullable = false)\n\tprivate BigDecimal weight;\n\n\t@Column(nullable = false)\n\tprivate BigDecimal lostWeight;\n\n\t@Column(nullable = false)\n\tprivate BigDecimal goldSmithFees;\n\n\tprivate boolean soldOut;\n\n\tprivate String coverImage;\n\t\n\t@ElementCollection\n\t@CollectionTable(name = \"CATALOG_IMAGES\")\n\tprivate List<String> images = new ArrayList<String>();\n\n}"
},
{
"identifier": "GoldPrice",
"path": "s02-backend/member-api/src/main/java/com/jdc/shop/model/entity/GoldPrice.java",
"snippet": "@Data\n@Entity\n@Table(name = \"GOLD_PRICE\")\n@EqualsAndHashCode(callSuper = false)\npublic class GoldPrice extends AbstractEntity {\n\n\t@Id\n\tprivate LocalDateTime businessTime;\n\n\t@Column(nullable = false)\n\tprivate BigDecimal basePrice;\n\n\t@Column(nullable = false)\n\tprivate BigDecimal diffFor16P;\n\n\t@Column(nullable = false)\n\tprivate BigDecimal diffFor15P;\n\t\n\tprivate Status status;\n\t\n\tpublic enum Status {\n\t\tCreated, Calculated\n\t}\n\n}"
},
{
"identifier": "CatalogRepo",
"path": "s02-backend/member-api/src/main/java/com/jdc/shop/model/repo/CatalogRepo.java",
"snippet": "public interface CatalogRepo extends BaseRepository<Catalog, Integer>{\n\n\t@Query(\"select t.id from Catalog t where t.deleted = false and t.soldOut = false\")\n\tList<Integer> searchIdForPriceChange();\n}"
},
{
"identifier": "CategoryRepo",
"path": "s02-backend/member-api/src/main/java/com/jdc/shop/model/repo/CategoryRepo.java",
"snippet": "public interface CategoryRepo extends BaseRepository<Category, Integer>{\n\n}"
},
{
"identifier": "GoldPriceRepo",
"path": "s02-backend/member-api/src/main/java/com/jdc/shop/model/repo/GoldPriceRepo.java",
"snippet": "public interface GoldPriceRepo extends BaseRepository<GoldPrice, LocalDateTime>{\n\n}"
},
{
"identifier": "ApiBusinessException",
"path": "s02-backend/member-api/src/main/java/com/jdc/shop/utils/exceptions/ApiBusinessException.java",
"snippet": "public class ApiBusinessException extends ApiBaseException{\n\n\tprivate static final long serialVersionUID = 1L;\n\n\tpublic ApiBusinessException(List<String> messages) {\n\t\tsuper(messages);\n\t}\n\n\tpublic ApiBusinessException(String message) {\n\t\tsuper(List.of(message));\n\t}\n}"
},
{
"identifier": "DataModificationResult",
"path": "s02-backend/member-api/src/main/java/com/jdc/shop/utils/io/DataModificationResult.java",
"snippet": "@Data\n@NoArgsConstructor\n@AllArgsConstructor\npublic class DataModificationResult<T> {\n\n\tprivate T id;\n\n\tprivate String message;\n\n}"
}
] | import java.time.LocalDateTime;
import java.util.List;
import java.util.function.Function;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import com.jdc.shop.api.anonymous.output.CatalogDetailsDto;
import com.jdc.shop.api.anonymous.output.CatalogDto;
import com.jdc.shop.api.employee.input.CatalogForm;
import com.jdc.shop.api.employee.input.CatalogSearch;
import com.jdc.shop.api.owner.output.GoldPriceDto;
import com.jdc.shop.model.entity.Catalog;
import com.jdc.shop.model.entity.Catalog_;
import com.jdc.shop.model.entity.GoldPrice;
import com.jdc.shop.model.entity.GoldPrice_;
import com.jdc.shop.model.repo.CatalogRepo;
import com.jdc.shop.model.repo.CategoryRepo;
import com.jdc.shop.model.repo.GoldPriceRepo;
import com.jdc.shop.utils.exceptions.ApiBusinessException;
import com.jdc.shop.utils.io.DataModificationResult;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.criteria.CriteriaQuery; | 3,640 | package com.jdc.shop.model.service;
@Service
@Transactional
public class CatalogService {
@Autowired
private CatalogRepo catalogRepo;
@Autowired
private CategoryRepo categoryRepo;
@Autowired
private GoldPriceRepo goldPriceRepo;
@Autowired
private CatalogPriceChangeService priceChangeService;
@Autowired
private PhotoUploadService photoUploadService;
@Transactional(readOnly = true)
public Page<CatalogDto> search(CatalogSearch form, int page, int size) {
Function<CriteriaBuilder, CriteriaQuery<Long>> countFunc = cb -> {
var cq = cb.createQuery(Long.class);
var root = cq.from(Catalog.class);
cq.select(cb.count(root.get(Catalog_.id)));
cq.where(form.where(cb, root));
return cq;
};
Function<CriteriaBuilder, CriteriaQuery<CatalogDto>> queryFunc = cb -> {
var cq = cb.createQuery(CatalogDto.class);
var root = cq.from(Catalog.class);
CatalogDto.select(cq, root);
cq.where(form.where(cb, root));
cq.orderBy(cb.asc(root.get(Catalog_.name)));
return cq;
};
return catalogRepo.search(queryFunc, countFunc, page, size);
}
@Transactional(readOnly = true)
public CatalogDetailsDto findById(int id) {
return catalogRepo.findById(id).map(CatalogDetailsDto::from)
.orElseThrow(() -> new ApiBusinessException("Invalid catalog id."));
}
public DataModificationResult<Integer> create(CatalogForm form) {
var goldPrice = findGoldPrice();
var category = categoryRepo.findById(form.getCategoryId())
.orElseThrow(() -> new ApiBusinessException("Invalid category id."));
var entity = form.entity();
entity.setCategory(category);
entity = catalogRepo.saveAndFlush(entity);
priceChangeService.calculate(entity.getId(), goldPrice);
return new DataModificationResult<Integer>(entity.getId(), "Catalog has been created.");
}
public DataModificationResult<Integer> update(int id, CatalogForm form) {
var goldPrice = findGoldPrice();
var entity = catalogRepo.findById(id)
.orElseThrow(() -> new ApiBusinessException("Invalid catalog id."));
var category = categoryRepo.findById(form.getCategoryId())
.orElseThrow(() -> new ApiBusinessException("Invalid category id."));
entity.setCategory(category);
entity.setName(form.getName());
entity.setDescription(form.getDescription());
entity.setBasedPrice(form.getBasedPrice());
entity.setPurity(form.getPurity());
entity.setWeight(form.getWeight());
entity.setLostWeight(form.getLostWeight());
entity.setGoldSmithFees(form.getGoldSmithFees());
entity = catalogRepo.saveAndFlush(entity);
priceChangeService.calculate(entity.getId(), goldPrice);
return new DataModificationResult<Integer>(entity.getId(), "Catalog has been updated.");
}
public DataModificationResult<Integer> uploadPhoto(int id, List<MultipartFile> files) {
var entity = catalogRepo.findById(id)
.orElseThrow(() -> new ApiBusinessException("Invalid catalog id."));
var images = photoUploadService.saveCatalogImages(id, files);
entity.getImages().addAll(images);
if(!StringUtils.hasLength(entity.getCoverImage()) && !entity.getImages().isEmpty()) {
entity.setCoverImage(entity.getImages().get(0));
}
return new DataModificationResult<Integer>(entity.getId(), "Catalog has been updated.");
}
private GoldPriceDto findGoldPrice() {
| package com.jdc.shop.model.service;
@Service
@Transactional
public class CatalogService {
@Autowired
private CatalogRepo catalogRepo;
@Autowired
private CategoryRepo categoryRepo;
@Autowired
private GoldPriceRepo goldPriceRepo;
@Autowired
private CatalogPriceChangeService priceChangeService;
@Autowired
private PhotoUploadService photoUploadService;
@Transactional(readOnly = true)
public Page<CatalogDto> search(CatalogSearch form, int page, int size) {
Function<CriteriaBuilder, CriteriaQuery<Long>> countFunc = cb -> {
var cq = cb.createQuery(Long.class);
var root = cq.from(Catalog.class);
cq.select(cb.count(root.get(Catalog_.id)));
cq.where(form.where(cb, root));
return cq;
};
Function<CriteriaBuilder, CriteriaQuery<CatalogDto>> queryFunc = cb -> {
var cq = cb.createQuery(CatalogDto.class);
var root = cq.from(Catalog.class);
CatalogDto.select(cq, root);
cq.where(form.where(cb, root));
cq.orderBy(cb.asc(root.get(Catalog_.name)));
return cq;
};
return catalogRepo.search(queryFunc, countFunc, page, size);
}
@Transactional(readOnly = true)
public CatalogDetailsDto findById(int id) {
return catalogRepo.findById(id).map(CatalogDetailsDto::from)
.orElseThrow(() -> new ApiBusinessException("Invalid catalog id."));
}
public DataModificationResult<Integer> create(CatalogForm form) {
var goldPrice = findGoldPrice();
var category = categoryRepo.findById(form.getCategoryId())
.orElseThrow(() -> new ApiBusinessException("Invalid category id."));
var entity = form.entity();
entity.setCategory(category);
entity = catalogRepo.saveAndFlush(entity);
priceChangeService.calculate(entity.getId(), goldPrice);
return new DataModificationResult<Integer>(entity.getId(), "Catalog has been created.");
}
public DataModificationResult<Integer> update(int id, CatalogForm form) {
var goldPrice = findGoldPrice();
var entity = catalogRepo.findById(id)
.orElseThrow(() -> new ApiBusinessException("Invalid catalog id."));
var category = categoryRepo.findById(form.getCategoryId())
.orElseThrow(() -> new ApiBusinessException("Invalid category id."));
entity.setCategory(category);
entity.setName(form.getName());
entity.setDescription(form.getDescription());
entity.setBasedPrice(form.getBasedPrice());
entity.setPurity(form.getPurity());
entity.setWeight(form.getWeight());
entity.setLostWeight(form.getLostWeight());
entity.setGoldSmithFees(form.getGoldSmithFees());
entity = catalogRepo.saveAndFlush(entity);
priceChangeService.calculate(entity.getId(), goldPrice);
return new DataModificationResult<Integer>(entity.getId(), "Catalog has been updated.");
}
public DataModificationResult<Integer> uploadPhoto(int id, List<MultipartFile> files) {
var entity = catalogRepo.findById(id)
.orElseThrow(() -> new ApiBusinessException("Invalid catalog id."));
var images = photoUploadService.saveCatalogImages(id, files);
entity.getImages().addAll(images);
if(!StringUtils.hasLength(entity.getCoverImage()) && !entity.getImages().isEmpty()) {
entity.setCoverImage(entity.getImages().get(0));
}
return new DataModificationResult<Integer>(entity.getId(), "Catalog has been updated.");
}
private GoldPriceDto findGoldPrice() {
| Function<CriteriaBuilder, CriteriaQuery<GoldPrice>> queryFunc = cb -> { | 6 | 2023-12-04 06:59:55+00:00 | 8k |
WiIIiam278/HuskClaims | common/src/main/java/net/william278/huskclaims/command/TrustableTabCompletable.java | [
{
"identifier": "Settings",
"path": "common/src/main/java/net/william278/huskclaims/config/Settings.java",
"snippet": "@SuppressWarnings(\"FieldMayBeFinal\")\n@Getter\n@Configuration\n@NoArgsConstructor(access = AccessLevel.PRIVATE)\npublic final class Settings {\n\n static final String CONFIG_HEADER = \"\"\"\n ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓\n ┃ HuskClaims - Config ┃\n ┃ Developed by William278 ┃\n ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛\n ┣╸ Information: https://william278.net/project/huskclaims/\n ┣╸ Config Help: https://william278.net/docs/huskclaims/config/\n ┗╸ Documentation: https://william278.net/docs/huskclaims/\"\"\";\n\n @Comment(\"Locale of the default language file to use. Docs: https://william278.net/docs/huskclaims/translations\")\n private String language = Locales.DEFAULT_LOCALE;\n\n @Comment(\"Whether to automatically check for plugin updates on startup\")\n private boolean checkForUpdates = true;\n\n @Comment(\"Database settings\")\n private DatabaseSettings database = new DatabaseSettings();\n\n @Getter\n @Configuration\n @NoArgsConstructor(access = AccessLevel.PRIVATE)\n public static class DatabaseSettings {\n\n @Comment(\"Type of database to use (SQLITE, MYSQL or MARIADB)\")\n private Database.Type type = Database.Type.SQLITE;\n\n @Comment(\"Specify credentials here if you are using MYSQL or MARIADB\")\n private DatabaseCredentials credentials = new DatabaseCredentials();\n\n @Comment({\"MYSQL / MARIADB database Hikari connection pool properties\",\n \"Don't modify this unless you know what you're doing!\"})\n private PoolOptions poolOptions = new PoolOptions();\n\n @Comment(\"Names of tables to use on your database. Don't modify this unless you know what you're doing!\")\n private Map<Database.Table, String> tableNames = new TreeMap<>(Map.of(\n Database.Table.META_DATA, Database.Table.META_DATA.getDefaultName(),\n Database.Table.USER_DATA, Database.Table.USER_DATA.getDefaultName(),\n Database.Table.USER_GROUP_DATA, Database.Table.USER_GROUP_DATA.getDefaultName(),\n Database.Table.CLAIM_DATA, Database.Table.CLAIM_DATA.getDefaultName()\n ));\n\n @Getter\n @Configuration\n @NoArgsConstructor(access = AccessLevel.PRIVATE)\n public static class DatabaseCredentials {\n private String host = \"localhost\";\n int port = 3306;\n String database = \"huskclaims\";\n String username = \"root\";\n String password = \"pa55w0rd\";\n String parameters = \"?autoReconnect=true&useSSL=false&useUnicode=true&characterEncoding=UTF-8&allowPublicKeyRetrieval=true\";\n }\n\n @Getter\n @Configuration\n @NoArgsConstructor(access = AccessLevel.PRIVATE)\n public static class PoolOptions {\n private int size = 12;\n private int idle = 12;\n private long lifetime = 1800000;\n private long keepAlive = 30000;\n private long timeout = 20000;\n }\n\n @NotNull\n public String getTableName(@NotNull Database.Table tableName) {\n return Optional.ofNullable(tableNames.get(tableName)).orElse(tableName.getDefaultName());\n }\n }\n\n @Comment(\"Cross-server settings\")\n private CrossServerSettings crossServer = new CrossServerSettings();\n\n @Getter\n @Configuration\n @NoArgsConstructor(access = AccessLevel.PRIVATE)\n public static class CrossServerSettings {\n @Comment(\"Whether to enable cross-server mode\")\n private boolean enabled = false;\n\n @Comment({\"The cluster ID, for if you're networking multiple separate groups of HuskClaims-enabled servers.\",\n \"Do not change unless you know what you're doing\"})\n private String clusterId = \"main\";\n\n @Comment(\"Type of network message broker to ues for data synchronization (PLUGIN_MESSAGE or REDIS)\")\n private Broker.Type brokerType = Broker.Type.PLUGIN_MESSAGE;\n\n @Comment(\"Settings for if you're using REDIS as your message broker\")\n private RedisSettings redis = new RedisSettings();\n\n @Getter\n @Configuration\n @NoArgsConstructor\n public static class RedisSettings {\n private String host = \"localhost\";\n private int port = 6379;\n @Comment(\"Password for your Redis server. Leave blank if you're not using a password.\")\n private String password = \"\";\n private boolean useSsl = false;\n\n @Comment({\"Settings for if you're using Redis Sentinels.\",\n \"If you're not sure what this is, please ignore this section.\"})\n private SentinelSettings sentinel = new SentinelSettings();\n\n @Getter\n @Configuration\n @NoArgsConstructor\n public static class SentinelSettings {\n private String masterName = \"\";\n @Comment(\"List of host:port pairs\")\n private List<String> nodes = Lists.newArrayList();\n private String password = \"\";\n }\n }\n }\n\n\n @Comment(\"Claim flags & world settings\")\n private ClaimSettings claims = new ClaimSettings();\n\n @Getter\n @Configuration\n @NoArgsConstructor(access = AccessLevel.PRIVATE)\n public static class ClaimSettings {\n @Comment(\"Default flags for regular claims\")\n private List<OperationType> defaultFlags = List.of(\n OperationType.PLAYER_DAMAGE_MONSTER,\n OperationType.EXPLOSION_DAMAGE_ENTITY,\n OperationType.PLAYER_DAMAGE_PLAYER,\n OperationType.MONSTER_SPAWN,\n OperationType.PASSIVE_MOB_SPAWN\n );\n\n @Comment(\"Default flags for admin claims\")\n private List<OperationType> adminFlags = List.of(\n OperationType.PLAYER_DAMAGE_MONSTER,\n OperationType.EXPLOSION_DAMAGE_ENTITY,\n OperationType.PLAYER_DAMAGE_PLAYER,\n OperationType.MONSTER_SPAWN,\n OperationType.PASSIVE_MOB_SPAWN\n );\n\n @Comment(\"List of enabled claim types. Must include at least the regular \\\"CLAIMS\\\" mode\")\n private List<ClaimingMode> enabledClaimingModes = List.of(\n ClaimingMode.values() // Allow all claiming modes\n );\n\n @Comment(\"Default flags for the wilderness (outside claims)\")\n private List<OperationType> wildernessRules = List.of(\n OperationType.values() // Allow all operation types\n );\n\n @Comment(\"List of worlds where users cannot claim\")\n private List<String> unclaimableWorlds = List.of();\n\n @Comment(\"The number of claim blocks a user gets when they first join the server\")\n private long startingClaimBlocks = 100;\n\n @Comment({\"The number of claim blocks a user gets hourly.\",\n \"Override with the \\\"huskclaims.hourly_blocks.(amount)\\\" permission\"})\n private long hourlyClaimBlocks = 100;\n\n @Comment(\"Claim inspection tool (right click with this to inspect claims)\")\n private String inspectionTool = \"minecraft:stick\";\n\n @Comment(\"Claim creation & resize tool (right click with this to create/resize claims)\")\n private String claimTool = \"minecraft:golden_shovel\";\n\n @Comment(\"Require players to hold the claim tool to use claim commands (e.g. /claim <radius>, /extendclaim)\")\n private boolean requireToolForCommands = true;\n\n @Comment(\"Minimum size of claims. This does not affect child or admin claims.\")\n private int minimumClaimSize = 5;\n\n @Comment(\"Max range of inspector tools\")\n private int inspectionDistance = 64;\n\n @Comment(\"Whether to allow inspecting nearby claims by sneaking when using the inspection tool\")\n private boolean allowNearbyClaimInspection = true;\n\n @Comment(\"Whether to require confirmation when deleting claims that have children\")\n private boolean confirmDeletingParentClaims = true;\n\n public boolean isWorldUnclaimable(@NotNull World world) {\n return unclaimableWorlds.stream().anyMatch(world.getName()::equalsIgnoreCase);\n }\n\n }\n\n @Comment(\"Groups of operations that can be toggled on/off in claims\")\n public List<OperationGroup> operationGroups = List.of(\n OperationGroup.builder()\n .name(\"Claim Explosions\")\n .description(\"Toggle whether explosions can damage terrain in claims\")\n .allowedOperations(List.of(\n OperationType.EXPLOSION_DAMAGE_TERRAIN,\n OperationType.MONSTER_DAMAGE_TERRAIN\n ))\n .toggleCommandAliases(List.of(\"claimexplosions\"))\n .build()\n );\n\n @Getter\n @Builder\n @Configuration\n @NoArgsConstructor(access = AccessLevel.PRIVATE)\n @AllArgsConstructor(access = AccessLevel.PRIVATE)\n public static class OperationGroup {\n private String name;\n private String description;\n private List<String> toggleCommandAliases;\n private List<OperationType> allowedOperations;\n }\n\n @Comment(\"Settings for user groups, letting users quickly manage trust for groups of multiple players at once\")\n private UserGroupSettings userGroups = new UserGroupSettings();\n\n @Getter\n @Configuration\n @NoArgsConstructor(access = AccessLevel.PRIVATE)\n public static class UserGroupSettings {\n @Comment(\"Whether to enable user groups\")\n private boolean enabled = true;\n\n @Comment(\"The prefix to use when specifying a group in a trust command (e.g. /trust @groupname)\")\n private String groupSpecifierPrefix = \"@\";\n\n @Comment(\"Whether to restrict group names with a regex filter\")\n private boolean restrictGroupNames = true;\n\n @Comment(\"Regex for group names\")\n private String groupNameRegex = \"[a-zA-Z0-9-_]*\";\n\n @Comment(\"Max members per group\")\n private int maxMembersPerGroup = 10;\n\n @Comment(\"Max groups per player\")\n private int maxGroupsPerPlayer = 3;\n }\n\n @Comment(\"Settings for trust tags, special representations of things you can trust in a claim\")\n private TrustTagSettings trustTags = new TrustTagSettings();\n\n @Getter\n @Configuration\n @NoArgsConstructor(access = AccessLevel.PRIVATE)\n public static class TrustTagSettings {\n @Comment(\"Whether to enable trust tags\")\n private boolean enabled = true;\n\n @Comment(\"The prefix to use when specifying a trust tag in a trust command (e.g. /trust #tagname)\")\n private String tagSpecifierPrefix = \"#\";\n\n @Comment(\"The name of the default public access tag (to let anyone access certain claim levels)\")\n private String publicAccessName = \"public\";\n\n }\n\n @Comment(\"Settings for the claim inspection/creation highlighter\")\n private HighlighterSettings highlighter = new HighlighterSettings();\n\n @Getter\n @Configuration\n @NoArgsConstructor(access = AccessLevel.PRIVATE)\n public static class HighlighterSettings {\n @Comment(\"Whether to use block display entities for glowing (requires Paper 1.19.4+)\")\n private boolean blockDisplays = true;\n\n @Comment(\"If using block displays, whether highlights should use a glow effect (requires Paper 1.19.4+)\")\n private boolean glowEffect = true;\n\n @Comment(\"The blocks to use when highlighting claims\")\n private Map<Highlightable.Type, String> blockTypes = new TreeMap<>(Map.of(\n Highlightable.Type.EDGE, \"minecraft:gold_block\",\n Highlightable.Type.CORNER, \"minecraft:glowstone\",\n Highlightable.Type.ADMIN_CORNER, \"minecraft:glowstone\",\n Highlightable.Type.ADMIN_EDGE, \"minecraft:pumpkin\",\n Highlightable.Type.CHILD_CORNER, \"minecraft:iron_block\",\n Highlightable.Type.CHILD_EDGE, \"minecraft:white_wool\",\n Highlightable.Type.OVERLAP_CORNER, \"minecraft:red_nether_bricks\",\n Highlightable.Type.OVERLAP_EDGE, \"minecraft:netherrack\",\n Highlightable.Type.SELECTION, \"minecraft:diamond_block\"\n ));\n\n @NotNull\n public BlockProvider.MaterialBlock getBlock(@NotNull Highlightable.Type type,\n @NotNull HuskClaims plugin) {\n return Optional.ofNullable(blockTypes.get(type))\n .map(plugin::getBlockFor)\n .orElse(plugin.getBlockFor(\"minecraft:yellow_concrete\"));\n }\n\n @Comment(\"The color of the glow effect used for blocks when highlighting claims\")\n private Map<Highlightable.Type, GlowColor> glowColors = new TreeMap<>(Map.of(\n Highlightable.Type.EDGE, GlowColor.YELLOW,\n Highlightable.Type.CORNER, GlowColor.YELLOW,\n Highlightable.Type.ADMIN_CORNER, GlowColor.ORANGE,\n Highlightable.Type.ADMIN_EDGE, GlowColor.ORANGE,\n Highlightable.Type.CHILD_CORNER, GlowColor.SILVER,\n Highlightable.Type.CHILD_EDGE, GlowColor.SILVER,\n Highlightable.Type.OVERLAP_CORNER, GlowColor.RED,\n Highlightable.Type.OVERLAP_EDGE, GlowColor.RED,\n Highlightable.Type.SELECTION, GlowColor.AQUA\n ));\n\n @NotNull\n public Settings.HighlighterSettings.GlowColor getGlowColor(@NotNull Highlightable.Type type) {\n return Optional.ofNullable(glowColors.get(type)).orElse(GlowColor.WHITE);\n }\n\n @Getter\n public enum GlowColor {\n\n WHITE(16777215),\n SILVER(12632256),\n GRAY(8421504),\n BLACK(0),\n RED(16711680),\n MAROON(8388608),\n YELLOW(16776960),\n OLIVE(8421376),\n LIME(65280),\n GREEN(32768),\n AQUA(65535),\n TEAL(32896),\n BLUE(255),\n NAVY(128),\n FUCHSIA(16711935),\n PURPLE(8388736),\n ORANGE(16753920);\n\n private final int rgb;\n\n GlowColor(int rgb) {\n this.rgb = rgb;\n }\n }\n }\n\n @Comment(\"Settings for integration hooks with other plugins\")\n private HookSettings hooks = new HookSettings();\n\n @Getter\n @Configuration\n @NoArgsConstructor(access = AccessLevel.PRIVATE)\n public static class HookSettings {\n\n private LuckPermsHookSettings luckPerms = new LuckPermsHookSettings();\n\n @Getter\n @Configuration\n @NoArgsConstructor(access = AccessLevel.PRIVATE)\n public static class LuckPermsHookSettings {\n @Comment(\"Whether to hook into LuckPerms for permission group trust tags\")\n private boolean enabled = true;\n\n @Comment(\"Require users to have the \\\"huskclaims.trust.luckperms\\\" permission to use LuckPerms trust tags\")\n private boolean trustTagUsePermission = true;\n\n @Comment(\"The prefix to use when specifying a LuckPerms group trust tag (e.g. /trust #role/groupname)\")\n private String trustTagPrefix = \"role/\";\n }\n\n private PlanHookSettings plan = new PlanHookSettings();\n\n @Getter\n @Configuration\n @NoArgsConstructor(access = AccessLevel.PRIVATE)\n public static class PlanHookSettings {\n @Comment(\"Whether to hook into Plan to display claim analytics\")\n private boolean enabled = true;\n }\n\n private HuskHomesHookSettings huskHomes = new HuskHomesHookSettings();\n\n @Getter\n @Configuration\n @NoArgsConstructor(access = AccessLevel.PRIVATE)\n public static class HuskHomesHookSettings {\n @Comment(\"Whether to hook into HuskHomes for claim teleportation and home restriction\")\n private boolean enabled = true;\n\n @Comment(\"Whether to restrict setting a home in claims to a trust level\")\n private boolean restrictSetHome = true;\n\n @Comment(\"The trust level required to set a home in a claim (the ID of a level in 'trust_levels.yml')\")\n private String setHomeTrustLevel = \"access\";\n }\n\n private EconomyHookSettings economy = new EconomyHookSettings();\n\n @Getter\n @Configuration\n @NoArgsConstructor(access = AccessLevel.PRIVATE)\n public static class EconomyHookSettings {\n @Comment(\"Whether to hook into an economy plugin to allow buying claim blocks\")\n private boolean enabled = true;\n\n @Comment(\"The cost of buying 1 claim block\")\n private double costPerBlock = 1.0;\n }\n\n private PlaceholderSettings placeholders = new PlaceholderSettings();\n\n @Getter\n @Configuration\n @NoArgsConstructor(access = AccessLevel.PRIVATE)\n public static class PlaceholderSettings {\n @Comment(\"Whether to hook into PlaceholderAPI to provide a HuskClaims placeholder expansion\")\n private boolean enabled = true;\n }\n\n private MapHookSettings map = new MapHookSettings();\n\n @Getter\n @Configuration\n @NoArgsConstructor(access = AccessLevel.PRIVATE)\n public static class MapHookSettings {\n @Comment(\"Whether to hook into Dynmap, BlueMap, or Pl3xMap to show claims on the map\")\n private boolean enabled = true;\n\n @Comment(\"What colors to use for types of claims on the map. Remove a pairing to hide claims of that type.\")\n private Map<ClaimingMode, String> colors = new TreeMap<>(Map.of(\n ClaimingMode.CLAIMS, NamedTextColor.YELLOW.asHexString(),\n ClaimingMode.ADMIN_CLAIMS, NamedTextColor.DARK_RED.asHexString(),\n ClaimingMode.CHILD_CLAIMS, NamedTextColor.WHITE.asHexString()\n ));\n\n @Comment(\"The name of the marker set key\")\n private String markerSetName = \"Claims\";\n\n @Comment(\"The label format for markers. '%s' will be replaced with the claim owner's name\")\n private String labelFormat = \"Claim by %s\";\n }\n\n }\n}"
},
{
"identifier": "CommandUser",
"path": "common/src/main/java/net/william278/huskclaims/user/CommandUser.java",
"snippet": "public interface CommandUser {\n\n @NotNull\n Audience getAudience();\n\n boolean hasPermission(@NotNull String permission, boolean isDefault);\n\n boolean hasPermission(@NotNull String permission);\n\n default void sendMessage(@NotNull Component component) {\n getAudience().sendMessage(component);\n }\n\n default void sendMessage(@NotNull MineDown mineDown) {\n this.sendMessage(mineDown.toComponent());\n }\n\n}"
},
{
"identifier": "OnlineUser",
"path": "common/src/main/java/net/william278/huskclaims/user/OnlineUser.java",
"snippet": "public abstract class OnlineUser extends User implements OperationUser, CommandUser {\n\n protected final HuskClaims plugin;\n\n protected OnlineUser(@NotNull String username, @NotNull UUID uuid, @NotNull HuskClaims plugin) {\n super(username, uuid);\n this.plugin = plugin;\n }\n\n @NotNull\n public abstract Position getPosition();\n\n @NotNull\n public final World getWorld() {\n return getPosition().getWorld();\n }\n\n @NotNull\n public Audience getAudience() {\n return plugin.getAudience(getUuid());\n }\n\n public void sendMessage(@NotNull Component message) {\n getAudience().sendMessage(message);\n }\n\n public void sendMessage(@NotNull MineDown mineDown) {\n sendMessage(mineDown.toComponent());\n }\n\n public abstract void sendPluginMessage(@NotNull String channel, byte[] message);\n\n public abstract boolean hasPermission(@NotNull String permission, boolean isDefault);\n\n public abstract boolean hasPermission(@NotNull String permission);\n\n public abstract boolean isHolding(@NotNull String material);\n\n public abstract Optional<Long> getNumericalPermission(@NotNull String prefix);\n\n public abstract boolean isSneaking();\n\n}"
}
] | import net.william278.huskclaims.config.Settings;
import net.william278.huskclaims.user.CommandUser;
import net.william278.huskclaims.user.OnlineUser;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.List;
import java.util.UUID; | 4,938 | /*
* This file is part of HuskClaims, licensed under the Apache License 2.0.
*
* Copyright (c) William278 <[email protected]>
* Copyright (c) contributors
*
* 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 net.william278.huskclaims.command;
public interface TrustableTabCompletable extends UserListTabCompletable {
@Nullable
@Override
default List<String> suggest(@NotNull CommandUser user, @NotNull String[] args) { | /*
* This file is part of HuskClaims, licensed under the Apache License 2.0.
*
* Copyright (c) William278 <[email protected]>
* Copyright (c) contributors
*
* 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 net.william278.huskclaims.command;
public interface TrustableTabCompletable extends UserListTabCompletable {
@Nullable
@Override
default List<String> suggest(@NotNull CommandUser user, @NotNull String[] args) { | final OnlineUser onlineUser = (OnlineUser) user; | 2 | 2023-11-28 01:09:43+00:00 | 8k |
realgpp/aem-cdn-cache-invalidator | core/src/main/java/com/baglio/autocdninvalidator/core/listeners/AbstractListener.java | [
{
"identifier": "LoggingHelper",
"path": "core/src/main/java/com/baglio/autocdninvalidator/core/helpers/LoggingHelper.java",
"snippet": "public class LoggingHelper {\n\n private final Logger logger;\n\n /**\n * Construct helper for the given class to log messages to. This will create a Logger named after the class.\n *\n * @param clazz the class to name the logger after\n */\n public LoggingHelper(final Class clazz) {\n this.logger = LoggerFactory.getLogger(clazz);\n }\n\n /**\n * Log a debug message if debug logging is enabled.\n *\n * @param message the log message possibly with {} placeholders\n * @param args arguments to fill placeholders\n */\n public void debug(final String message, final Object... args) {\n if (logger.isDebugEnabled()) {\n logger.debug(message, args);\n }\n }\n\n /**\n * Log an info message if info logging is enabled.\n *\n * @param message the log message possibly with {} placeholders\n * @param args arguments to fill placeholders\n */\n public void info(final String message, final Object... args) {\n if (logger.isInfoEnabled()) {\n logger.info(message, args);\n }\n }\n\n /**\n * Log a warn message if warn logging is enabled.\n *\n * @param message the log message possibly with {} placeholders\n * @param args arguments to fill placeholders\n */\n public void warn(final String message, final Object... args) {\n if (logger.isWarnEnabled()) {\n logger.warn(message, args);\n }\n }\n\n /**\n * Log a trace message if trace logging is enabled.\n *\n * @param message the log message possibly with {} placeholders\n * @param args arguments to fill placeholders\n */\n public void trace(final String message, final Object... args) {\n if (logger.isTraceEnabled()) {\n logger.trace(message, args);\n }\n }\n\n /**\n * Log an error message if error logging is enabled.\n *\n * @param message the log message possibly with {} placeholders\n * @param args arguments to fill placeholders\n */\n public void error(final String message, final Object... args) {\n if (logger.isErrorEnabled()) {\n logger.error(message, args);\n }\n }\n}"
},
{
"identifier": "EditorialAssetInvalidationJobConsumer",
"path": "core/src/main/java/com/baglio/autocdninvalidator/core/jobs/EditorialAssetInvalidationJobConsumer.java",
"snippet": "@Component(service = JobConsumer.class, immediate = true)\n@Designate(ocd = EditorialAssetInvalidationJobConsumer.Config.class)\npublic class EditorialAssetInvalidationJobConsumer extends AbstractInvalidationJob implements JobConsumer {\n private static final LoggingHelper LOGGER = new LoggingHelper(EditorialAssetInvalidationJobConsumer.class);\n /** Job property for paths to invalidate. */\n public static final String JOB_PROPERTY_PATHS = \"paths\";\n\n private static final String VALUE_SEPARATOR = \"=\";\n private static final int VALUE_LEFT_OPERAND_INDEX = 0;\n private static final int VALUE_RIGHT_OPERAND_INDEX = 1;\n\n private boolean isEnabled;\n private String cdnConfigurationID;\n private Map<String, String> invalidationRules;\n private String invalidationType;\n private String externalLinkScheme;\n private String externalLinkDomain;\n\n @Reference private Externalizer externalizer;\n @Reference private ReadService readService;\n @Reference private UtilityService utilityService;\n\n /**\n * Activate method to initialize configuration.\n *\n * @param config The OSGi configuration\n */\n @Activate\n protected void activate(final EditorialAssetInvalidationJobConsumer.Config config) {\n LOGGER.info(\"Configuration values={}\", config);\n this.isEnabled = config.isEnabled();\n this.cdnConfigurationID = config.cdnConfigurationID();\n this.invalidationType = config.invalidation_type();\n this.externalLinkDomain =\n StringUtils.defaultIfBlank(config.externalLinkDomain(), Config.DEFAULT_EXTERNAL_LINK_DOMAIN);\n this.externalLinkScheme =\n StringUtils.defaultIfBlank(config.externalLinkScheme(), Config.EXTERNAL_LINK_SCHEME_OPTION_HTTPS);\n\n if (null != config.tagCodeMappings()) {\n this.invalidationRules =\n Arrays.stream(config.tagCodeMappings())\n .filter(mapping -> mapping.contains(VALUE_SEPARATOR)) // Ignore values without comma\n .map(\n configValue -> {\n final String[] split = configValue.split(VALUE_SEPARATOR, 2);\n return new KeyValueOption(split[VALUE_LEFT_OPERAND_INDEX], split[VALUE_RIGHT_OPERAND_INDEX]);\n }) // Split each string by separator\n .filter(\n option ->\n !option.getKey().isEmpty() && !option.getValue().isEmpty()) // Remove from map if one is empty\n .collect(\n Collectors.toMap(\n KeyValueOption::getKey,\n KeyValueOption::getValue,\n (v1, v2) -> v1,\n TreeMap::new) // Collect the results into a TreeMap\n );\n }\n }\n\n /**\n * Execute the job. If the job has been processed successfully, JobResult.OK should be returned. If the job has not\n * been processed completely, but might be rescheduled JobResult.FAILED should be returned. If the job processing\n * failed and should not be rescheduled, JobResult.CANCEL should be returned.\n *\n * @param job The job\n * @return The job result\n */\n @Override\n public JobResult process(final Job job) {\n\n if (!isEnabled()) {\n LOGGER.debug(\"Job is disabled\");\n return JobResult.CANCEL;\n }\n\n try {\n final CdnInvalidationService cdnInvalidationService =\n getUtilityService().getService(CdnInvalidationService.class, cdnConfigurationID);\n if (cdnInvalidationService == null) {\n LOGGER.error(\"Impossible to call CDN Api because service retrieval failed\");\n return JobResult.FAILED;\n }\n\n LOGGER.debug(\"Consuming job - topic: {}, properties: {}\", job.getTopic(), job);\n\n Set<String> paths = (Set<String>) job.getProperty(JOB_PROPERTY_PATHS);\n if (paths.isEmpty()) {\n LOGGER.debug(\"No Paths have been provided: processing cancelled\");\n return JobResult.CANCEL;\n }\n LOGGER.info(\"Paths to process: {}\", paths);\n\n return handleInvalidate(invalidationType, cdnInvalidationService, paths, job);\n } catch (Exception e) {\n LOGGER.error(\"Unexpected error while invalidating in CDN\", e);\n return JobResult.FAILED;\n }\n }\n\n /**\n * Handles invalidating by code or tag based on configuration.\n *\n * @param jobInvalidationType type of invalidation\n * @param cdnInvalidationService the CDN invalidation service to use\n * @param paths the content paths that changed\n * @param job the current job being processed\n * @return the job result based on success or failure\n */\n private JobResult handleInvalidate(\n final String jobInvalidationType,\n final CdnInvalidationService cdnInvalidationService,\n final Set<String> paths,\n final Job job) {\n LOGGER.debug(\"About to get invalidation for items: {}\", paths);\n\n Set<String> items;\n switch (jobInvalidationType) {\n case Config.INVALIDATION_TYPE_OPTION_CODE:\n case Config.INVALIDATION_TYPE_OPTION_TAG:\n items = processValues(paths);\n break;\n case Config.INVALIDATION_TYPE_OPTION_URLS:\n items = processURLs(paths);\n break;\n default:\n LOGGER.error(\"Invalidation type is not allowed: {}\", jobInvalidationType);\n return JobResult.FAILED;\n }\n\n LOGGER.debug(\"Items to invalidate: {}\", items);\n\n items = beforeInvalidation(items);\n boolean result;\n switch (jobInvalidationType) {\n case Config.INVALIDATION_TYPE_OPTION_CODE:\n result = cdnInvalidationService.purgeByCode(items);\n break;\n case Config.INVALIDATION_TYPE_OPTION_TAG:\n result = cdnInvalidationService.purgeByTag(items);\n break;\n case Config.INVALIDATION_TYPE_OPTION_URLS:\n LOGGER.debug(\"Values after processing: {}\", items);\n result = cdnInvalidationService.purgeByURLs(items);\n break;\n default:\n LOGGER.error(\"Invalidation type is not allowed: {}\", jobInvalidationType);\n return JobResult.FAILED;\n }\n\n result = afterInvalidation(result, job);\n return getFinalResult(result, job);\n }\n\n /**\n * Processes the content paths to generate invalidation values.\n *\n * <p>Applies before, main, and after processing pipeline.\n *\n * @param paths the content paths that changed\n * @return the set of processed invalidation values\n */\n private Set<String> processValues(final Set<String> paths) {\n\n LOGGER.debug(\"About to process values: {}\", paths);\n\n Set<String> values = preprocessInvalidationValues(paths);\n LOGGER.trace(\"Invalidation values after initial processing: {}\", values);\n\n values = getInvalidationValues(values, invalidationRules);\n LOGGER.trace(\"Invalidation values after main processing: {}\", values);\n\n values = postprocessInvalidationValues(values);\n LOGGER.debug(\"Final invalidation values to send: {}\", values);\n\n return values;\n }\n\n /**\n * Processes the paths to get public URLs.\n *\n * <p>Applies before, main, and after processing pipeline.\n *\n * @param paths the content paths\n * @return the set of public URLs\n */\n private Set<String> processURLs(final Set<String> paths) {\n\n LOGGER.debug(\"About to process urls: {}\", paths);\n\n Set<String> urls = preprocessPublicUrls(paths);\n LOGGER.trace(\"Invalidation urls after initial processing: {}\", urls);\n\n urls = getPublicUrls(urls, externalLinkDomain, externalLinkScheme);\n LOGGER.trace(\"Invalidation urls after main processing: {}\", urls);\n\n urls = postprocessPublicUrls(urls);\n LOGGER.debug(\"Final invalidation urls to send: {}\", urls);\n\n return urls;\n }\n\n /** {@inheritDoc} */\n @Override\n public boolean isEnabled() {\n return this.isEnabled;\n }\n\n /** {@inheritDoc} */\n @Override\n public Set<String> preprocessInvalidationValues(final Set<String> paths) {\n return paths;\n }\n\n /** {@inheritDoc} */\n @Override\n public Set<String> postprocessInvalidationValues(final Set<String> values) {\n return values;\n }\n\n /**\n * Determines final job result based on processing result.\n *\n * @param result outcome of processing invalidation\n * @param job the job being processed\n * @return the final JobResult status\n */\n private JobResult getFinalResult(final boolean result, final Job job) {\n // check result and return OK or FAILED\n\n if (result) {\n LOGGER.info(\"Job processed successfully: {}\", job);\n return JobResult.OK;\n }\n\n LOGGER.error(\"Job did not finished as expected. See logs for further info: {}\", job);\n return JobResult.FAILED;\n }\n\n /** {@inheritDoc} */\n @Override\n public Set<String> preprocessPublicUrls(final Set<String> paths) {\n LOGGER.trace(\"preprocessPublicUrls - objects: {}\", paths);\n return paths;\n }\n\n /** {@inheritDoc} */\n @Override\n public Set<String> postprocessPublicUrls(final Set<String> paths) {\n LOGGER.trace(\"postprocessPublicUrls - objects: {}\", paths);\n return paths;\n }\n\n /** {@inheritDoc} */\n @Override\n public Set<String> beforeInvalidation(final Set<String> values) {\n LOGGER.trace(\"beforeInvalidation - objects: {}\", values);\n return values;\n }\n\n /** {@inheritDoc} */\n @Override\n public boolean afterInvalidation(final boolean result, final Job job) {\n LOGGER.trace(\"afterInvalidation - result: {}, job: {}\", result, job);\n return result;\n }\n\n /** {@inheritDoc} */\n @Override\n Externalizer getExternalizer() {\n return externalizer;\n }\n\n /** {@inheritDoc} */\n @Override\n ReadService getReadService() {\n return readService;\n }\n\n /** {@inheritDoc} */\n @Override\n UtilityService getUtilityService() {\n return utilityService;\n }\n\n /** OSGi configuration definition. */\n @ObjectClassDefinition(name = \"Auto CDN Invalidator - Job Consumer - Website Generic\")\n public @interface Config {\n\n String INVALIDATION_TYPE_OPTION_URLS = \"urls\";\n String INVALIDATION_TYPE_OPTION_TAG = \"tag\";\n String INVALIDATION_TYPE_OPTION_CODE = \"code\";\n String EXTERNAL_LINK_SCHEME_OPTION_HTTPS = \"https\";\n String DEFAULT_EXTERNAL_LINK_DOMAIN = \"publish\";\n\n @AttributeDefinition(name = \"Enable\", type = AttributeType.BOOLEAN, description = \"Tick to enable it\")\n boolean isEnabled() default false;\n\n @AttributeDefinition(\n name = \"Job Topic\",\n description = \"Defines which topic this consumer is able to process\",\n cardinality = 1)\n String[] job_topics();\n\n @AttributeDefinition(name = \"CDN Configuration ID\", description = \"Defines which CDN Configuration to leverage\")\n String cdnConfigurationID();\n\n @AttributeDefinition(\n name = \"Type of Invalidation\",\n description = \"Defines type of invalidate to be leveraged\",\n options = {\n @Option(label = \"URLs\", value = INVALIDATION_TYPE_OPTION_URLS),\n @Option(label = \"Tag\", value = INVALIDATION_TYPE_OPTION_TAG),\n @Option(label = \"Code\", value = INVALIDATION_TYPE_OPTION_CODE),\n })\n String invalidation_type() default INVALIDATION_TYPE_OPTION_TAG;\n\n @AttributeDefinition(\n name = \"Tag/Code Mappings\",\n description =\n \"Pattern to Tage/Code associations for invalidation rules. Format: \"\n + \"<pattern-of-trigger-content>=<pattern-of-tag-or-code>\")\n String[] tagCodeMappings();\n\n @AttributeDefinition(\n name = \"External Link Domain\",\n description =\n \"Used to create an absolute URL for a named domain. Value must be present in filed 'externalizer.domains' \"\n + \"of service 'Day CQ Link Externalizer'\")\n String externalLinkDomain() default DEFAULT_EXTERNAL_LINK_DOMAIN;\n\n @AttributeDefinition(\n name = \"External Link Protocol Scheme\",\n description = \"Protocol scheme that will be part of the URL\",\n options = {\n @Option(label = \"HTTPS\", value = EXTERNAL_LINK_SCHEME_OPTION_HTTPS),\n @Option(label = \"HTTP\", value = \"http\")\n })\n String externalLinkScheme() default EXTERNAL_LINK_SCHEME_OPTION_HTTPS;\n }\n\n static final class KeyValueOption {\n private final String key;\n private final String value;\n\n KeyValueOption(final String k, final String v) {\n this.key = k;\n this.value = v;\n }\n\n public String getKey() {\n return StringUtils.isBlank(key) ? key : key.trim();\n }\n\n public String getValue() {\n return StringUtils.isBlank(value) ? value : value.trim();\n }\n }\n}"
}
] | import com.baglio.autocdninvalidator.core.helpers.LoggingHelper;
import com.baglio.autocdninvalidator.core.jobs.EditorialAssetInvalidationJobConsumer;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import org.apache.commons.lang.StringUtils;
import org.apache.jackrabbit.vault.util.JcrConstants;
import org.apache.sling.event.jobs.Job;
import org.apache.sling.event.jobs.JobManager; | 4,035 | package com.baglio.autocdninvalidator.core.listeners;
/**
* Abstract base class for listeners that process repository change events. Provides common logic to filter paths,
* create jobs, and offload work.
*/
public abstract class AbstractListener {
/**
* Gives the Logger.
*
* @return the Logger
*/
abstract LoggingHelper getLogger();
/**
* Gets the OSGi JobManager service to create jobs.
*
* @return the JobManager
*/
abstract JobManager getJobManager();
/**
* Processes a set of resource paths when changed in the repository. Applies configured regex filter and offloads work
* via job.
*
* @param paths the resource paths changed
* @param filterRegex regex to filter relevant paths
* @param jobTopic job topic to use for offloading
* @return true if a job was scheduled, false otherwise
*/
public boolean processEvent(final Set<String> paths, final String filterRegex, final String jobTopic) {
Set<String> resourcePaths = filterPaths(paths, filterRegex);
if (resourcePaths.isEmpty()) {
getLogger().warn("No resources to process for paths={} with filter regex={}", paths, filterRegex);
return false;
}
Map<String, Object> jobprops = new HashMap<>(); | package com.baglio.autocdninvalidator.core.listeners;
/**
* Abstract base class for listeners that process repository change events. Provides common logic to filter paths,
* create jobs, and offload work.
*/
public abstract class AbstractListener {
/**
* Gives the Logger.
*
* @return the Logger
*/
abstract LoggingHelper getLogger();
/**
* Gets the OSGi JobManager service to create jobs.
*
* @return the JobManager
*/
abstract JobManager getJobManager();
/**
* Processes a set of resource paths when changed in the repository. Applies configured regex filter and offloads work
* via job.
*
* @param paths the resource paths changed
* @param filterRegex regex to filter relevant paths
* @param jobTopic job topic to use for offloading
* @return true if a job was scheduled, false otherwise
*/
public boolean processEvent(final Set<String> paths, final String filterRegex, final String jobTopic) {
Set<String> resourcePaths = filterPaths(paths, filterRegex);
if (resourcePaths.isEmpty()) {
getLogger().warn("No resources to process for paths={} with filter regex={}", paths, filterRegex);
return false;
}
Map<String, Object> jobprops = new HashMap<>(); | jobprops.put(EditorialAssetInvalidationJobConsumer.JOB_PROPERTY_PATHS, resourcePaths); | 1 | 2023-11-27 14:47:45+00:00 | 8k |
Manzzx/multi-channel-message-reach | metax-gateway/src/main/java/com/metax/gateway/filter/XssFilter.java | [
{
"identifier": "StringUtils",
"path": "metax-common/metax-common-core/src/main/java/com/metax/common/core/utils/StringUtils.java",
"snippet": "public class StringUtils extends org.apache.commons.lang3.StringUtils\n{\n /** 空字符串 */\n private static final String NULLSTR = \"\";\n\n /** 下划线 */\n private static final char SEPARATOR = '_';\n\n /**\n * 获取参数不为空值\n * \n * @param value defaultValue 要判断的value\n * @return value 返回值\n */\n public static <T> T nvl(T value, T defaultValue)\n {\n return value != null ? value : defaultValue;\n }\n\n /**\n * * 判断一个Collection是否为空, 包含List,Set,Queue\n * \n * @param coll 要判断的Collection\n * @return true:为空 false:非空\n */\n public static boolean isEmpty(Collection<?> coll)\n {\n return isNull(coll) || coll.isEmpty();\n }\n\n /**\n * * 判断一个Collection是否非空,包含List,Set,Queue\n * \n * @param coll 要判断的Collection\n * @return true:非空 false:空\n */\n public static boolean isNotEmpty(Collection<?> coll)\n {\n return !isEmpty(coll);\n }\n\n /**\n * * 判断一个对象数组是否为空\n * \n * @param objects 要判断的对象数组\n ** @return true:为空 false:非空\n */\n public static boolean isEmpty(Object[] objects)\n {\n return isNull(objects) || (objects.length == 0);\n }\n\n /**\n * * 判断一个对象数组是否非空\n * \n * @param objects 要判断的对象数组\n * @return true:非空 false:空\n */\n public static boolean isNotEmpty(Object[] objects)\n {\n return !isEmpty(objects);\n }\n\n /**\n * * 判断一个Map是否为空\n * \n * @param map 要判断的Map\n * @return true:为空 false:非空\n */\n public static boolean isEmpty(Map<?, ?> map)\n {\n return isNull(map) || map.isEmpty();\n }\n\n /**\n * * 判断一个Map是否为空\n * \n * @param map 要判断的Map\n * @return true:非空 false:空\n */\n public static boolean isNotEmpty(Map<?, ?> map)\n {\n return !isEmpty(map);\n }\n\n /**\n * * 判断一个字符串是否为空串\n * \n * @param str String\n * @return true:为空 false:非空\n */\n public static boolean isEmpty(String str)\n {\n return isNull(str) || NULLSTR.equals(str.trim());\n }\n\n /**\n * * 判断一个字符串是否为非空串\n * \n * @param str String\n * @return true:非空串 false:空串\n */\n public static boolean isNotEmpty(String str)\n {\n return !isEmpty(str);\n }\n\n /**\n * * 判断一个对象是否为空\n * \n * @param object Object\n * @return true:为空 false:非空\n */\n public static boolean isNull(Object object)\n {\n return object == null;\n }\n\n /**\n * * 判断一个对象是否非空\n * \n * @param object Object\n * @return true:非空 false:空\n */\n public static boolean isNotNull(Object object)\n {\n return !isNull(object);\n }\n\n /**\n * * 判断一个对象是否是数组类型(Java基本型别的数组)\n * \n * @param object 对象\n * @return true:是数组 false:不是数组\n */\n public static boolean isArray(Object object)\n {\n return isNotNull(object) && object.getClass().isArray();\n }\n\n /**\n * 去空格\n */\n public static String trim(String str)\n {\n return (str == null ? \"\" : str.trim());\n }\n\n /**\n * 截取字符串\n * \n * @param str 字符串\n * @param start 开始\n * @return 结果\n */\n public static String substring(final String str, int start)\n {\n if (str == null)\n {\n return NULLSTR;\n }\n\n if (start < 0)\n {\n start = str.length() + start;\n }\n\n if (start < 0)\n {\n start = 0;\n }\n if (start > str.length())\n {\n return NULLSTR;\n }\n\n return str.substring(start);\n }\n\n /**\n * 截取字符串\n * \n * @param str 字符串\n * @param start 开始\n * @param end 结束\n * @return 结果\n */\n public static String substring(final String str, int start, int end)\n {\n if (str == null)\n {\n return NULLSTR;\n }\n\n if (end < 0)\n {\n end = str.length() + end;\n }\n if (start < 0)\n {\n start = str.length() + start;\n }\n\n if (end > str.length())\n {\n end = str.length();\n }\n\n if (start > end)\n {\n return NULLSTR;\n }\n\n if (start < 0)\n {\n start = 0;\n }\n if (end < 0)\n {\n end = 0;\n }\n\n return str.substring(start, end);\n }\n\n /**\n * 判断是否为空,并且不是空白字符\n * \n * @param str 要判断的value\n * @return 结果\n */\n public static boolean hasText(String str)\n {\n return (str != null && !str.isEmpty() && containsText(str));\n }\n\n private static boolean containsText(CharSequence str)\n {\n int strLen = str.length();\n for (int i = 0; i < strLen; i++)\n {\n if (!Character.isWhitespace(str.charAt(i)))\n {\n return true;\n }\n }\n return false;\n }\n\n /**\n * 格式化文本, {} 表示占位符<br>\n * 此方法只是简单将占位符 {} 按照顺序替换为参数<br>\n * 如果想输出 {} 使用 \\\\转义 { 即可,如果想输出 {} 之前的 \\ 使用双转义符 \\\\\\\\ 即可<br>\n * 例:<br>\n * 通常使用:format(\"this is {} for {}\", \"a\", \"b\") -> this is a for b<br>\n * 转义{}: format(\"this is \\\\{} for {}\", \"a\", \"b\") -> this is \\{} for a<br>\n * 转义\\: format(\"this is \\\\\\\\{} for {}\", \"a\", \"b\") -> this is \\a for b<br>\n * \n * @param template 文本模板,被替换的部分用 {} 表示\n * @param params 参数值\n * @return 格式化后的文本\n */\n public static String format(String template, Object... params)\n {\n if (isEmpty(params) || isEmpty(template))\n {\n return template;\n }\n return StrFormatter.format(template, params);\n }\n\n /**\n * 是否为http(s)://开头\n * \n * @param link 链接\n * @return 结果\n */\n public static boolean ishttp(String link)\n {\n return StringUtils.startsWithAny(link, Constants.HTTP, Constants.HTTPS);\n }\n\n /**\n * 判断给定的collection列表中是否包含数组array 判断给定的数组array中是否包含给定的元素value\n *\n * @param collection 给定的集合\n * @param array 给定的数组\n * @return boolean 结果\n */\n public static boolean containsAny(Collection<String> collection, String... array)\n {\n if (isEmpty(collection) || isEmpty(array))\n {\n return false;\n }\n else\n {\n for (String str : array)\n {\n if (collection.contains(str))\n {\n return true;\n }\n }\n return false;\n }\n }\n\n /**\n * 驼峰转下划线命名\n */\n public static String toUnderScoreCase(String str)\n {\n if (str == null)\n {\n return null;\n }\n StringBuilder sb = new StringBuilder();\n // 前置字符是否大写\n boolean preCharIsUpperCase = true;\n // 当前字符是否大写\n boolean curreCharIsUpperCase = true;\n // 下一字符是否大写\n boolean nexteCharIsUpperCase = true;\n for (int i = 0; i < str.length(); i++)\n {\n char c = str.charAt(i);\n if (i > 0)\n {\n preCharIsUpperCase = Character.isUpperCase(str.charAt(i - 1));\n }\n else\n {\n preCharIsUpperCase = false;\n }\n\n curreCharIsUpperCase = Character.isUpperCase(c);\n\n if (i < (str.length() - 1))\n {\n nexteCharIsUpperCase = Character.isUpperCase(str.charAt(i + 1));\n }\n\n if (preCharIsUpperCase && curreCharIsUpperCase && !nexteCharIsUpperCase)\n {\n sb.append(SEPARATOR);\n }\n else if ((i != 0 && !preCharIsUpperCase) && curreCharIsUpperCase)\n {\n sb.append(SEPARATOR);\n }\n sb.append(Character.toLowerCase(c));\n }\n\n return sb.toString();\n }\n\n /**\n * 是否包含字符串\n * \n * @param str 验证字符串\n * @param strs 字符串组\n * @return 包含返回true\n */\n public static boolean inStringIgnoreCase(String str, String... strs)\n {\n if (str != null && strs != null)\n {\n for (String s : strs)\n {\n if (str.equalsIgnoreCase(trim(s)))\n {\n return true;\n }\n }\n }\n return false;\n }\n\n /**\n * 将下划线大写方式命名的字符串转换为驼峰式。如果转换前的下划线大写方式命名的字符串为空,则返回空字符串。 例如:HELLO_WORLD->HelloWorld\n * \n * @param name 转换前的下划线大写方式命名的字符串\n * @return 转换后的驼峰式命名的字符串\n */\n public static String convertToCamelCase(String name)\n {\n StringBuilder result = new StringBuilder();\n // 快速检查\n if (name == null || name.isEmpty())\n {\n // 没必要转换\n return \"\";\n }\n else if (!name.contains(\"_\"))\n {\n // 不含下划线,仅将首字母大写\n return name.substring(0, 1).toUpperCase() + name.substring(1);\n }\n // 用下划线将原始字符串分割\n String[] camels = name.split(\"_\");\n for (String camel : camels)\n {\n // 跳过原始字符串中开头、结尾的下换线或双重下划线\n if (camel.isEmpty())\n {\n continue;\n }\n // 首字母大写\n result.append(camel.substring(0, 1).toUpperCase());\n result.append(camel.substring(1).toLowerCase());\n }\n return result.toString();\n }\n\n /**\n * 驼峰式命名法\n * 例如:user_name->userName\n */\n public static String toCamelCase(String s)\n {\n if (s == null)\n {\n return null;\n }\n if (s.indexOf(SEPARATOR) == -1)\n {\n return s;\n }\n s = s.toLowerCase();\n StringBuilder sb = new StringBuilder(s.length());\n boolean upperCase = false;\n for (int i = 0; i < s.length(); i++)\n {\n char c = s.charAt(i);\n\n if (c == SEPARATOR)\n {\n upperCase = true;\n }\n else if (upperCase)\n {\n sb.append(Character.toUpperCase(c));\n upperCase = false;\n }\n else\n {\n sb.append(c);\n }\n }\n return sb.toString();\n }\n\n /**\n * 查找指定字符串是否匹配指定字符串列表中的任意一个字符串\n * \n * @param str 指定字符串\n * @param strs 需要检查的字符串数组\n * @return 是否匹配\n */\n public static boolean matches(String str, List<String> strs)\n {\n if (isEmpty(str) || isEmpty(strs))\n {\n return false;\n }\n for (String pattern : strs)\n {\n if (isMatch(pattern, str))\n {\n return true;\n }\n }\n return false;\n }\n\n /**\n * 判断url是否与规则配置: \n * ? 表示单个字符; \n * * 表示一层路径内的任意字符串,不可跨层级; \n * ** 表示任意层路径;\n * \n * @param pattern 匹配规则\n * @param url 需要匹配的url\n * @return\n */\n public static boolean isMatch(String pattern, String url)\n {\n AntPathMatcher matcher = new AntPathMatcher();\n return matcher.match(pattern, url);\n }\n\n @SuppressWarnings(\"unchecked\")\n public static <T> T cast(Object obj)\n {\n return (T) obj;\n }\n\n /**\n * 数字左边补齐0,使之达到指定长度。注意,如果数字转换为字符串后,长度大于size,则只保留 最后size个字符。\n * \n * @param num 数字对象\n * @param size 字符串指定长度\n * @return 返回数字的字符串格式,该字符串为指定长度。\n */\n public static final String padl(final Number num, final int size)\n {\n return padl(num.toString(), size, '0');\n }\n\n /**\n * 字符串左补齐。如果原始字符串s长度大于size,则只保留最后size个字符。\n * \n * @param s 原始字符串\n * @param size 字符串指定长度\n * @param c 用于补齐的字符\n * @return 返回指定长度的字符串,由原字符串左补齐或截取得到。\n */\n public static final String padl(final String s, final int size, final char c)\n {\n final StringBuilder sb = new StringBuilder(size);\n if (s != null)\n {\n final int len = s.length();\n if (s.length() <= size)\n {\n for (int i = size - len; i > 0; i--)\n {\n sb.append(c);\n }\n sb.append(s);\n }\n else\n {\n return s.substring(len - size, len);\n }\n }\n else\n {\n for (int i = size; i > 0; i--)\n {\n sb.append(c);\n }\n }\n return sb.toString();\n }\n}"
},
{
"identifier": "EscapeUtil",
"path": "metax-common/metax-common-core/src/main/java/com/metax/common/core/utils/html/EscapeUtil.java",
"snippet": "public class EscapeUtil\n{\n public static final String RE_HTML_MARK = \"(<[^<]*?>)|(<[\\\\s]*?/[^<]*?>)|(<[^<]*?/[\\\\s]*?>)\";\n\n private static final char[][] TEXT = new char[64][];\n\n static\n {\n for (int i = 0; i < 64; i++)\n {\n TEXT[i] = new char[] { (char) i };\n }\n\n // special HTML characters\n TEXT['\\''] = \"'\".toCharArray(); // 单引号\n TEXT['\"'] = \""\".toCharArray(); // 双引号\n TEXT['&'] = \"&\".toCharArray(); // &符\n TEXT['<'] = \"<\".toCharArray(); // 小于号\n TEXT['>'] = \">\".toCharArray(); // 大于号\n }\n\n /**\n * 转义文本中的HTML字符为安全的字符\n * \n * @param text 被转义的文本\n * @return 转义后的文本\n */\n public static String escape(String text)\n {\n return encode(text);\n }\n\n /**\n * 还原被转义的HTML特殊字符\n * \n * @param content 包含转义符的HTML内容\n * @return 转换后的字符串\n */\n public static String unescape(String content)\n {\n return decode(content);\n }\n\n /**\n * 清除所有HTML标签,但是不删除标签内的内容\n * \n * @param content 文本\n * @return 清除标签后的文本\n */\n public static String clean(String content)\n {\n return new HTMLFilter().filter(content);\n }\n\n /**\n * Escape编码\n * \n * @param text 被编码的文本\n * @return 编码后的字符\n */\n private static String encode(String text)\n {\n if (StringUtils.isEmpty(text))\n {\n return StringUtils.EMPTY;\n }\n\n final StringBuilder tmp = new StringBuilder(text.length() * 6);\n char c;\n for (int i = 0; i < text.length(); i++)\n {\n c = text.charAt(i);\n if (c < 256)\n {\n tmp.append(\"%\");\n if (c < 16)\n {\n tmp.append(\"0\");\n }\n tmp.append(Integer.toString(c, 16));\n }\n else\n {\n tmp.append(\"%u\");\n if (c <= 0xfff)\n {\n // issue#I49JU8@Gitee\n tmp.append(\"0\");\n }\n tmp.append(Integer.toString(c, 16));\n }\n }\n return tmp.toString();\n }\n\n /**\n * Escape解码\n * \n * @param content 被转义的内容\n * @return 解码后的字符串\n */\n public static String decode(String content)\n {\n if (StringUtils.isEmpty(content))\n {\n return content;\n }\n\n StringBuilder tmp = new StringBuilder(content.length());\n int lastPos = 0, pos = 0;\n char ch;\n while (lastPos < content.length())\n {\n pos = content.indexOf(\"%\", lastPos);\n if (pos == lastPos)\n {\n if (content.charAt(pos + 1) == 'u')\n {\n ch = (char) Integer.parseInt(content.substring(pos + 2, pos + 6), 16);\n tmp.append(ch);\n lastPos = pos + 6;\n }\n else\n {\n ch = (char) Integer.parseInt(content.substring(pos + 1, pos + 3), 16);\n tmp.append(ch);\n lastPos = pos + 3;\n }\n }\n else\n {\n if (pos == -1)\n {\n tmp.append(content.substring(lastPos));\n lastPos = content.length();\n }\n else\n {\n tmp.append(content.substring(lastPos, pos));\n lastPos = pos;\n }\n }\n }\n return tmp.toString();\n }\n\n public static void main(String[] args)\n {\n String html = \"<script>alert(1);</script>\";\n String escape = EscapeUtil.escape(html);\n // String html = \"<scr<script>ipt>alert(\\\"XSS\\\")</scr<script>ipt>\";\n // String html = \"<123\";\n // String html = \"123>\";\n System.out.println(\"clean: \" + EscapeUtil.clean(html));\n System.out.println(\"escape: \" + escape);\n System.out.println(\"unescape: \" + EscapeUtil.unescape(escape));\n }\n}"
},
{
"identifier": "XssProperties",
"path": "metax-gateway/src/main/java/com/metax/gateway/config/properties/XssProperties.java",
"snippet": "@Configuration\n@RefreshScope\n@ConfigurationProperties(prefix = \"security.xss\")\npublic class XssProperties\n{\n /**\n * Xss开关\n */\n private Boolean enabled;\n\n /**\n * 排除路径\n */\n private List<String> excludeUrls = new ArrayList<>();\n\n public Boolean getEnabled()\n {\n return enabled;\n }\n\n public void setEnabled(Boolean enabled)\n {\n this.enabled = enabled;\n }\n\n public List<String> getExcludeUrls()\n {\n return excludeUrls;\n }\n\n public void setExcludeUrls(List<String> excludeUrls)\n {\n this.excludeUrls = excludeUrls;\n }\n}"
}
] | import java.nio.charset.StandardCharsets;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.core.io.buffer.DefaultDataBufferFactory;
import org.springframework.core.io.buffer.NettyDataBufferFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpRequestDecorator;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import com.metax.common.core.utils.StringUtils;
import com.metax.common.core.utils.html.EscapeUtil;
import com.metax.gateway.config.properties.XssProperties;
import io.netty.buffer.ByteBufAllocator;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono; | 6,158 | package com.metax.gateway.filter;
/**
* 跨站脚本过滤器
*
* @author ruoyi
*/
@Component
@ConditionalOnProperty(value = "security.xss.enabled", havingValue = "true")
public class XssFilter implements GlobalFilter, Ordered
{
// 跨站脚本的 xss 配置,nacos自行添加
@Autowired
private XssProperties xss;
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain)
{
ServerHttpRequest request = exchange.getRequest();
// xss开关未开启 或 通过nacos关闭,不过滤
if (!xss.getEnabled())
{
return chain.filter(exchange);
}
// GET DELETE 不过滤
HttpMethod method = request.getMethod();
if (method == null || method == HttpMethod.GET || method == HttpMethod.DELETE)
{
return chain.filter(exchange);
}
// 非json类型,不过滤
if (!isJsonRequest(exchange))
{
return chain.filter(exchange);
}
// excludeUrls 不过滤
String url = request.getURI().getPath();
if (StringUtils.matches(url, xss.getExcludeUrls()))
{
return chain.filter(exchange);
}
ServerHttpRequestDecorator httpRequestDecorator = requestDecorator(exchange);
return chain.filter(exchange.mutate().request(httpRequestDecorator).build());
}
private ServerHttpRequestDecorator requestDecorator(ServerWebExchange exchange)
{
ServerHttpRequestDecorator serverHttpRequestDecorator = new ServerHttpRequestDecorator(exchange.getRequest())
{
@Override
public Flux<DataBuffer> getBody()
{
Flux<DataBuffer> body = super.getBody();
return body.buffer().map(dataBuffers -> {
DataBufferFactory dataBufferFactory = new DefaultDataBufferFactory();
DataBuffer join = dataBufferFactory.join(dataBuffers);
byte[] content = new byte[join.readableByteCount()];
join.read(content);
DataBufferUtils.release(join);
String bodyStr = new String(content, StandardCharsets.UTF_8);
// 防xss攻击过滤 | package com.metax.gateway.filter;
/**
* 跨站脚本过滤器
*
* @author ruoyi
*/
@Component
@ConditionalOnProperty(value = "security.xss.enabled", havingValue = "true")
public class XssFilter implements GlobalFilter, Ordered
{
// 跨站脚本的 xss 配置,nacos自行添加
@Autowired
private XssProperties xss;
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain)
{
ServerHttpRequest request = exchange.getRequest();
// xss开关未开启 或 通过nacos关闭,不过滤
if (!xss.getEnabled())
{
return chain.filter(exchange);
}
// GET DELETE 不过滤
HttpMethod method = request.getMethod();
if (method == null || method == HttpMethod.GET || method == HttpMethod.DELETE)
{
return chain.filter(exchange);
}
// 非json类型,不过滤
if (!isJsonRequest(exchange))
{
return chain.filter(exchange);
}
// excludeUrls 不过滤
String url = request.getURI().getPath();
if (StringUtils.matches(url, xss.getExcludeUrls()))
{
return chain.filter(exchange);
}
ServerHttpRequestDecorator httpRequestDecorator = requestDecorator(exchange);
return chain.filter(exchange.mutate().request(httpRequestDecorator).build());
}
private ServerHttpRequestDecorator requestDecorator(ServerWebExchange exchange)
{
ServerHttpRequestDecorator serverHttpRequestDecorator = new ServerHttpRequestDecorator(exchange.getRequest())
{
@Override
public Flux<DataBuffer> getBody()
{
Flux<DataBuffer> body = super.getBody();
return body.buffer().map(dataBuffers -> {
DataBufferFactory dataBufferFactory = new DefaultDataBufferFactory();
DataBuffer join = dataBufferFactory.join(dataBuffers);
byte[] content = new byte[join.readableByteCount()];
join.read(content);
DataBufferUtils.release(join);
String bodyStr = new String(content, StandardCharsets.UTF_8);
// 防xss攻击过滤 | bodyStr = EscapeUtil.clean(bodyStr); | 1 | 2023-12-04 05:10:13+00:00 | 8k |
ydb-platform/yoj-project | repository-ydb-v1/src/main/java/tech/ydb/yoj/repository/ydb/client/YdbSessionManager.java | [
{
"identifier": "QueryInterruptedException",
"path": "repository/src/main/java/tech/ydb/yoj/repository/db/exception/QueryInterruptedException.java",
"snippet": "public class QueryInterruptedException extends RepositoryException {\n public QueryInterruptedException(String message) {\n super(message);\n }\n\n public QueryInterruptedException(String message, Throwable cause) {\n super(message, cause);\n }\n}"
},
{
"identifier": "RetryableException",
"path": "repository/src/main/java/tech/ydb/yoj/repository/db/exception/RetryableException.java",
"snippet": "public abstract class RetryableException extends RepositoryException {\n private final RetryPolicy retryPolicy;\n\n protected RetryableException(String message, RetryPolicy retryPolicy, Throwable cause) {\n super(message, cause);\n this.retryPolicy = retryPolicy;\n }\n\n protected RetryableException(String message, RetryPolicy retryPolicy) {\n super(message);\n this.retryPolicy = retryPolicy;\n }\n\n protected RetryableException(String message, Throwable cause) {\n this(message, RetryPolicy.retryImmediately(), cause);\n }\n\n protected RetryableException(String message) {\n this(message, RetryPolicy.retryImmediately());\n }\n\n /**\n * Sleeps for the recommended amount of time before retrying.\n *\n * @param attempt request attempt count (starting from 1)\n */\n public void sleep(int attempt) {\n try {\n MILLISECONDS.sleep(retryPolicy.calcDuration(attempt).toMillis());\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n throw new QueryInterruptedException(\"DB query interrupted\", e);\n }\n }\n\n public RepositoryException rethrow() {\n return UnavailableException.afterRetries(\"Retries failed\", this);\n }\n}"
},
{
"identifier": "UnavailableException",
"path": "repository/src/main/java/tech/ydb/yoj/repository/db/exception/UnavailableException.java",
"snippet": "public class UnavailableException extends RepositoryException {\n @Getter\n public final boolean alreadyRetried;\n\n public UnavailableException(String message) {\n super(message);\n this.alreadyRetried = false;\n }\n\n public UnavailableException(String message, Throwable cause) {\n this(message, cause, false);\n }\n\n public UnavailableException(String message, Throwable cause, boolean alreadyRetried) {\n super(message, cause);\n this.alreadyRetried = alreadyRetried;\n }\n\n public static UnavailableException afterRetries(String message, Throwable cause) {\n return new UnavailableException(message, cause, true);\n }\n}"
},
{
"identifier": "YdbConfig",
"path": "repository-ydb-v1/src/main/java/tech/ydb/yoj/repository/ydb/YdbConfig.java",
"snippet": "@Value\n@Builder\npublic class YdbConfig {\n private static final Duration SESSION_KEEP_ALIVE_TIME_DEFAULT = Duration.ofMinutes(5);\n private static final Duration SESSION_MAX_IDLE_TIME_DEFAULT = Duration.ofMinutes(5);\n private static final Duration TCP_KEEP_ALIVE_TIME_DEFAULT = Duration.ofSeconds(5);\n private static final Duration TCP_KEEP_ALIVE_TIMEOUT_DEFAULT = Duration.ofSeconds(1);\n private static final Duration SESSION_CREATE_TIMEOUT_DEFAULT = Duration.ofSeconds(1);\n private static final int SESSION_POOL_SIZE_DEFAULT = 100;\n private static final int SESSION_CREATE_RETRY_COUNT_DEFAULT = 3;\n\n public static YdbConfig createForTesting(String host, int port, String tablespace, String database) {\n return new YdbConfig(\n tablespace,\n database,\n null,\n List.of(HostAndPort.fromParts(host, port)),\n SESSION_CREATE_TIMEOUT_DEFAULT,\n SESSION_CREATE_RETRY_COUNT_DEFAULT,\n SESSION_KEEP_ALIVE_TIME_DEFAULT,\n SESSION_MAX_IDLE_TIME_DEFAULT,\n SESSION_POOL_SIZE_DEFAULT,\n SESSION_POOL_SIZE_DEFAULT,\n TCP_KEEP_ALIVE_TIME_DEFAULT,\n TCP_KEEP_ALIVE_TIMEOUT_DEFAULT,\n false,\n false,\n null\n );\n }\n\n /**\n * Base path for all YDB tables.\n */\n @NonNull\n @With\n String tablespace;\n\n /**\n * Path to the YDB database.\n */\n @NonNull\n @With\n String database;\n\n // oneof {discoveryEndpoint, endpoints}\n @With\n String discoveryEndpoint;\n\n /**\n * In sdk-v2 only one endpoint is possible.\n * Please use only {@link YdbConfig#discoveryEndpoint} in config.\n */\n @Deprecated(forRemoval = true)\n List<HostAndPort> endpoints;\n\n @With\n Duration sessionCreationTimeout;\n @With\n Integer sessionCreationMaxRetries;\n @With\n Duration sessionKeepAliveTime;\n @With\n Duration sessionMaxIdleTime;\n @With\n Integer sessionPoolMin;\n @With\n Integer sessionPoolMax;\n\n @With\n Duration tcpKeepaliveTime;\n @With\n Duration tcpKeepaliveTimeout;\n\n @With\n boolean useTLS;\n\n // oneof {useTrustStore, rootCA}\n /**\n * Use RootCA certificates from JDK TrustStore.\n */\n @With\n boolean useTrustStore;\n /**\n * RootCA certificate content. (Will be ignored if {@link #useTrustStore} is {@code true})\n */\n @With\n byte[] rootCA;\n\n public Duration getSessionCreationTimeout() {\n return Optional.ofNullable(sessionCreationTimeout).orElse(SESSION_CREATE_TIMEOUT_DEFAULT);\n }\n\n public Integer getSessionCreationMaxRetries() {\n return Optional.ofNullable(sessionCreationMaxRetries).orElse(SESSION_CREATE_RETRY_COUNT_DEFAULT);\n }\n\n public Duration getSessionKeepAliveTime() {\n return Optional.ofNullable(sessionKeepAliveTime).orElse(SESSION_KEEP_ALIVE_TIME_DEFAULT);\n }\n\n public Duration getSessionMaxIdleTime() {\n return Optional.ofNullable(sessionMaxIdleTime).orElse(SESSION_MAX_IDLE_TIME_DEFAULT);\n }\n\n public Integer getSessionPoolMin() {\n return Optional.ofNullable(sessionPoolMin).orElse(SESSION_POOL_SIZE_DEFAULT);\n }\n\n public Integer getSessionPoolMax() {\n return Optional.ofNullable(sessionPoolMax).orElse(SESSION_POOL_SIZE_DEFAULT);\n }\n\n public Duration getTcpKeepaliveTime() {\n return Optional.ofNullable(tcpKeepaliveTime).orElse(TCP_KEEP_ALIVE_TIME_DEFAULT);\n }\n\n public Duration getTcpKeepaliveTimeout() {\n return Optional.ofNullable(tcpKeepaliveTimeout).orElse(TCP_KEEP_ALIVE_TIMEOUT_DEFAULT);\n }\n}"
},
{
"identifier": "GaugeSupplierCollector",
"path": "repository-ydb-common/src/main/java/tech/ydb/yoj/repository/ydb/metrics/GaugeSupplierCollector.java",
"snippet": "public class GaugeSupplierCollector extends SimpleCollector<GaugeSupplierCollector.Child> implements Collector.Describable {\n private static final Logger log = LoggerFactory.getLogger(GaugeSupplierCollector.class);\n\n private GaugeSupplierCollector(Builder builder) {\n super(builder);\n }\n\n public static Builder build() {\n return new Builder();\n }\n\n @Override\n public List<MetricFamilySamples> collect() {\n List<MetricFamilySamples.Sample> samples = new ArrayList<>();\n children.forEach((labelValues, child) -> {\n try {\n samples.add(new MetricFamilySamples.Sample(fullname, labelNames, labelValues, child.getValue()));\n } catch (Exception e) {\n log.error(\"Could not add child sample\", e);\n }\n });\n return familySamplesList(Type.GAUGE, samples);\n }\n\n @Override\n public List<MetricFamilySamples> describe() {\n return List.of(new GaugeMetricFamily(fullname, help, labelNames));\n }\n\n @Override\n protected Child newChild() {\n return new Child();\n }\n\n public void supplier(Supplier<Number> supplier) {\n this.noLabelsChild.supplier(supplier);\n }\n\n @Accessors(fluent = true)\n public static class Builder extends SimpleCollector.Builder<Builder, GaugeSupplierCollector> {\n @Override\n public GaugeSupplierCollector create() {\n return new GaugeSupplierCollector(this);\n }\n }\n\n public class Child {\n private Supplier<? extends Number> supplier = () -> 0.;\n\n public GaugeSupplierCollector supplier(Supplier<? extends Number> supplier) {\n this.supplier = supplier;\n return GaugeSupplierCollector.this;\n }\n\n public double getValue() {\n return supplier.get().doubleValue();\n }\n }\n}"
},
{
"identifier": "checkGrpcContextStatus",
"path": "repository-ydb-v1/src/main/java/tech/ydb/yoj/repository/ydb/client/YdbValidator.java",
"snippet": "public static void checkGrpcContextStatus(String errorMessage, @Nullable Throwable cause) {\n if (Context.current().getDeadline() != null && Context.current().getDeadline().isExpired()) {\n // время на обработку запроса закончилось, нужно выбросить отдельное исключение чтобы не было ретраев\n throw new DeadlineExceededException(\"DB query deadline exceeded. Response from DB: \" + errorMessage, cause);\n } else if (Context.current().isCancelled()) {\n // запрос отменил сам клиент, эту ошибку не нужно ретраить\n throw new QueryCancelledException(\"DB query cancelled. Response from DB: \" + errorMessage);\n }\n}"
},
{
"identifier": "validate",
"path": "repository-ydb-v1/src/main/java/tech/ydb/yoj/repository/ydb/client/YdbValidator.java",
"snippet": "public static void validate(String request, StatusCode statusCode, String response) {\n switch (statusCode) {\n case SUCCESS:\n return;\n\n case BAD_SESSION:\n case SESSION_EXPIRED:\n case NOT_FOUND: // вероятнее всего это проблемы с prepared запросом. Стоит поретраить с новой сессией. Еще может быть Transaction not found\n throw new BadSessionException(response);\n\n case ABORTED:\n throw new OptimisticLockException(response);\n\n case OVERLOADED: // БД перегружена - нужно ретраить с экспоненциальной задержкой\n case TIMEOUT: // БВ отовечечала слишком долго - нужно ретраить с экспоненциальной задержкой\n case CANCELLED: // запрос был отменен, тк закончился установленный в запросе таймаут (CancelAfter). Запрос на сервере гарантированно отменен.\n case CLIENT_RESOURCE_EXHAUSTED: // недостаточно свободных ресурсов для обслуживания запроса\n case CLIENT_DEADLINE_EXPIRED: // deadline expired before request was sent to server.\n case CLIENT_DEADLINE_EXCEEDED: // запрос был отменен на транспортном уровне, тк закончился установленный дедлайн.\n checkGrpcContextStatus(response, null);\n\n // Резльтат обработки запроса не известен - может быть отменен или выполнен.\n log.warn(\"Database is overloaded, but we still got a reply from the DB\\n\" +\n \"Request: {}\\nResponse: {}\", request, response);\n\n throw new YdbOverloadedException(request, response);\n\n case CLIENT_CANCELLED:\n case CLIENT_INTERNAL_ERROR: // неизвестная ошибка на клиентской стороне (чаще всего транспортного уровня)\n checkGrpcContextStatus(response, null);\n\n log.warn(\"Some database components are not available, but we still got a reply from the DB\\n\"\n + \"Request: {}\\nResponse: {}\", request, response);\n throw new YdbComponentUnavailableException(request, response);\n case UNAVAILABLE: // БД ответила, что она или часть ее подсистем не доступны\n case TRANSPORT_UNAVAILABLE: // проблемы с сетевой связностью\n case CLIENT_DISCOVERY_FAILED: // ошибка в ходе получения списка эндпоинтов\n case CLIENT_LIMITS_REACHED: // достигнут лимит на количество сессий на клиентской стороне\n case UNDETERMINED:\n case SESSION_BUSY: // в этот сессии скорей всего исполняется другой запрос, стоит поретраить с новой сессией\n case PRECONDITION_FAILED:\n log.warn(\"Some database components are not available, but we still got a reply from the DB\\n\" +\n \"Request: {}\\nResponse: {}\", request, response);\n throw new YdbComponentUnavailableException(request, response);\n\n case CLIENT_UNAUTHENTICATED: // grpc сообщил, что запрос не аутентифицирован. Это интернал ошибка, но возможно\n // была проблема с выпиской токена и можно попробовать поретраить - если не поможет, то отдать наружу\n log.warn(\"Database said we are not authenticated\\nRequest: {}\\nResponse: {}\", request, response);\n throw new YdbUnauthenticatedException(request, response);\n\n case UNAUTHORIZED: // БД сообщила, что запрос не авторизован. Ретраи могут помочь\n log.warn(\"Database said we are not authorized\\nRequest: {}\\nResponse: {}\", request, response);\n throw new YdbUnauthorizedException(request, response);\n\n case SCHEME_ERROR:\n throw new YdbSchemaException(\"schema error\", request, response);\n\n case CLIENT_CALL_UNIMPLEMENTED:\n case BAD_REQUEST:\n case UNSUPPORTED:\n case INTERNAL_ERROR:\n case GENERIC_ERROR:\n case UNUSED_STATUS:\n case ALREADY_EXISTS: // Этот статус используется другими ydb-сервисами. Это не вид precondition failed!\n default:\n log.error(\"Bad response status\\nRequest: {}\\nResponse: {}\", request, response);\n throw new YdbRepositoryException(request, response);\n }\n}"
},
{
"identifier": "isThreadInterrupted",
"path": "util/src/main/java/tech/ydb/yoj/util/lang/Interrupts.java",
"snippet": "public static boolean isThreadInterrupted(Throwable t) {\n return isThreadInterrupted() || isInterruptException(t);\n}"
}
] | import com.yandex.ydb.core.Result;
import com.yandex.ydb.core.grpc.GrpcTransport;
import com.yandex.ydb.table.Session;
import com.yandex.ydb.table.TableClient;
import com.yandex.ydb.table.rpc.grpc.GrpcTableRpc;
import com.yandex.ydb.table.stats.SessionPoolStats;
import lombok.Getter;
import lombok.NonNull;
import tech.ydb.yoj.repository.db.exception.QueryInterruptedException;
import tech.ydb.yoj.repository.db.exception.RetryableException;
import tech.ydb.yoj.repository.db.exception.UnavailableException;
import tech.ydb.yoj.repository.ydb.YdbConfig;
import tech.ydb.yoj.repository.ydb.metrics.GaugeSupplierCollector;
import java.time.Duration;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.ExecutionException;
import static tech.ydb.yoj.repository.ydb.client.YdbValidator.checkGrpcContextStatus;
import static tech.ydb.yoj.repository.ydb.client.YdbValidator.validate;
import static tech.ydb.yoj.util.lang.Interrupts.isThreadInterrupted; | 4,230 | package tech.ydb.yoj.repository.ydb.client;
public class YdbSessionManager implements SessionManager {
private static final GaugeSupplierCollector sessionStatCollector = GaugeSupplierCollector.build()
.namespace("ydb")
.subsystem("session_manager")
.name("pool_stats")
.help("Session pool statistics")
.labelNames("type")
.register();
private final YdbConfig config;
private final GrpcTableRpc tableRpc;
@Getter
private TableClient tableClient;
public YdbSessionManager(@NonNull YdbConfig config, GrpcTransport transport) {
this.config = config;
this.tableRpc = GrpcTableRpc.useTransport(transport);
this.tableClient = createClient();
sessionStatCollector
.labels("pending_acquire_count").supplier(() -> tableClient.getSessionPoolStats().getPendingAcquireCount())
.labels("acquired_count").supplier(() -> tableClient.getSessionPoolStats().getAcquiredCount())
.labels("idle_count").supplier(() -> tableClient.getSessionPoolStats().getIdleCount())
.labels("disconnected_count").supplier(() -> tableClient.getSessionPoolStats().getDisconnectedCount());
}
private TableClient createClient() {
return TableClient.newClient(tableRpc)
.keepQueryText(false)
.queryCacheSize(0)
.sessionCreationMaxRetries(config.getSessionCreationMaxRetries())
.sessionKeepAliveTime(config.getSessionKeepAliveTime())
.sessionMaxIdleTime(config.getSessionMaxIdleTime())
.sessionPoolSize(config.getSessionPoolMin(), config.getSessionPoolMax())
.build();
}
@Override
public Session getSession() {
CompletableFuture<Result<Session>> future = tableClient.getOrCreateSession(getSessionTimeout());
try {
Result<Session> result = future.get();
validate("session create", result.getCode(), result.toString());
return result.expect("Can't get session");
} catch (CancellationException | CompletionException | ExecutionException | InterruptedException e) {
// We need to cancel future bacause in other case we can get session leak
future.cancel(false);
if (isThreadInterrupted(e)) {
Thread.currentThread().interrupt();
throw new QueryInterruptedException("get session interrupted", e);
}
checkGrpcContextStatus(e.getMessage(), e);
throw new UnavailableException("DB is unavailable", e);
}
}
private Duration getSessionTimeout() {
Duration max = Duration.ofMinutes(5);
Duration configTimeout = config.getSessionCreationTimeout();
return Duration.ZERO.equals(configTimeout) || configTimeout.compareTo(max) > 0 ? max : configTimeout;
}
@Override
public void release(Session session) {
session.release();
}
@Override
//todo: client load balancing
public void warmup() {
Session session = null;
int maxRetrySessionCreateCount = 10;
for (int i = 0; i < maxRetrySessionCreateCount; i++) {
try {
session = getSession();
break; | package tech.ydb.yoj.repository.ydb.client;
public class YdbSessionManager implements SessionManager {
private static final GaugeSupplierCollector sessionStatCollector = GaugeSupplierCollector.build()
.namespace("ydb")
.subsystem("session_manager")
.name("pool_stats")
.help("Session pool statistics")
.labelNames("type")
.register();
private final YdbConfig config;
private final GrpcTableRpc tableRpc;
@Getter
private TableClient tableClient;
public YdbSessionManager(@NonNull YdbConfig config, GrpcTransport transport) {
this.config = config;
this.tableRpc = GrpcTableRpc.useTransport(transport);
this.tableClient = createClient();
sessionStatCollector
.labels("pending_acquire_count").supplier(() -> tableClient.getSessionPoolStats().getPendingAcquireCount())
.labels("acquired_count").supplier(() -> tableClient.getSessionPoolStats().getAcquiredCount())
.labels("idle_count").supplier(() -> tableClient.getSessionPoolStats().getIdleCount())
.labels("disconnected_count").supplier(() -> tableClient.getSessionPoolStats().getDisconnectedCount());
}
private TableClient createClient() {
return TableClient.newClient(tableRpc)
.keepQueryText(false)
.queryCacheSize(0)
.sessionCreationMaxRetries(config.getSessionCreationMaxRetries())
.sessionKeepAliveTime(config.getSessionKeepAliveTime())
.sessionMaxIdleTime(config.getSessionMaxIdleTime())
.sessionPoolSize(config.getSessionPoolMin(), config.getSessionPoolMax())
.build();
}
@Override
public Session getSession() {
CompletableFuture<Result<Session>> future = tableClient.getOrCreateSession(getSessionTimeout());
try {
Result<Session> result = future.get();
validate("session create", result.getCode(), result.toString());
return result.expect("Can't get session");
} catch (CancellationException | CompletionException | ExecutionException | InterruptedException e) {
// We need to cancel future bacause in other case we can get session leak
future.cancel(false);
if (isThreadInterrupted(e)) {
Thread.currentThread().interrupt();
throw new QueryInterruptedException("get session interrupted", e);
}
checkGrpcContextStatus(e.getMessage(), e);
throw new UnavailableException("DB is unavailable", e);
}
}
private Duration getSessionTimeout() {
Duration max = Duration.ofMinutes(5);
Duration configTimeout = config.getSessionCreationTimeout();
return Duration.ZERO.equals(configTimeout) || configTimeout.compareTo(max) > 0 ? max : configTimeout;
}
@Override
public void release(Session session) {
session.release();
}
@Override
//todo: client load balancing
public void warmup() {
Session session = null;
int maxRetrySessionCreateCount = 10;
for (int i = 0; i < maxRetrySessionCreateCount; i++) {
try {
session = getSession();
break; | } catch (RetryableException ex) { | 1 | 2023-12-05 15:57:58+00:00 | 8k |
Vera-Firefly/PojavLauncher-Experimental-Edition | app_pojavlauncher/src/main/java/com/kdt/mcgui/ProgressLayout.java | [
{
"identifier": "ExtraCore",
"path": "app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/extra/ExtraCore.java",
"snippet": "@SuppressWarnings({\"rawtypes\", \"unchecked\"})\npublic final class ExtraCore {\n // No unwanted instantiation\n private ExtraCore(){}\n\n // Singleton instance\n private static volatile ExtraCore sExtraCoreSingleton = null;\n\n // Store the key-value pair\n private final Map<String, Object> mValueMap = new ConcurrentHashMap<>();\n\n // Store what each ExtraListener listen to\n private final Map<String, ConcurrentLinkedQueue<WeakReference<ExtraListener>>> mListenerMap = new ConcurrentHashMap<>();\n\n // All public methods will pass through this one\n private static ExtraCore getInstance(){\n if(sExtraCoreSingleton == null){\n synchronized(ExtraCore.class){\n if(sExtraCoreSingleton == null){\n sExtraCoreSingleton = new ExtraCore();\n }\n }\n }\n return sExtraCoreSingleton;\n }\n\n /**\n * Set the value associated to a key and trigger all listeners\n * @param key The key\n * @param value The value\n */\n public static void setValue(String key, Object value){\n if(value == null || key == null) return; // null values create an NPE on insertion\n\n getInstance().mValueMap.put(key, value);\n ConcurrentLinkedQueue<WeakReference<ExtraListener>> extraListenerList = getInstance().mListenerMap.get(key);\n if(extraListenerList == null) return; //No listeners\n for(WeakReference<ExtraListener> listener : extraListenerList){\n if(listener.get() == null){\n extraListenerList.remove(listener);\n continue;\n }\n\n //Notify the listener about a state change and remove it if asked for\n if(listener.get().onValueSet(key, value)){\n ExtraCore.removeExtraListenerFromValue(key, listener.get());\n }\n }\n }\n\n /** @return The value behind the key */\n public static Object getValue(String key){\n return getInstance().mValueMap.get(key);\n }\n\n /** @return The value behind the key, or the default value */\n public static Object getValue(String key, Object defaultValue){\n Object value = getInstance().mValueMap.get(key);\n return value != null ? value : defaultValue;\n }\n\n /** Remove the key and its value from the valueMap */\n public static void removeValue(String key){\n getInstance().mValueMap.remove(key);\n }\n\n public static Object consumeValue(String key){\n Object value = getInstance().mValueMap.get(key);\n getInstance().mValueMap.remove(key);\n return value;\n }\n\n /** Remove all values */\n public static void removeAllValues(){\n getInstance().mValueMap.clear();\n }\n\n /**\n * Link an ExtraListener to a value\n * @param key The value key to look for\n * @param listener The ExtraListener to link\n */\n public static void addExtraListener(String key, ExtraListener listener){\n ConcurrentLinkedQueue<WeakReference<ExtraListener>> listenerList = getInstance().mListenerMap.get(key);\n // Look for new sets\n if(listenerList == null){\n listenerList = new ConcurrentLinkedQueue<>();\n getInstance().mListenerMap.put(key, listenerList);\n }\n\n // This is kinda naive, I should look for duplicates\n listenerList.add(new WeakReference<>(listener));\n }\n\n /**\n * Unlink an ExtraListener from a value.\n * Unlink null references found along the way\n * @param key The value key to ignore now\n * @param listener The ExtraListener to unlink\n */\n public static void removeExtraListenerFromValue(String key, ExtraListener listener){\n ConcurrentLinkedQueue<WeakReference<ExtraListener>> listenerList = getInstance().mListenerMap.get(key);\n // Look for new sets\n if(listenerList == null){\n listenerList = new ConcurrentLinkedQueue<>();\n getInstance().mListenerMap.put(key, listenerList);\n }\n\n // Removes all occurrences of ExtraListener and all null references\n for(WeakReference<ExtraListener> listenerWeakReference : listenerList){\n ExtraListener actualListener = listenerWeakReference.get();\n\n if(actualListener == null || actualListener == listener){\n listenerList.remove(listenerWeakReference);\n }\n }\n }\n\n /**\n * Unlink all ExtraListeners from a value\n * @param key The key to which ExtraListener are linked\n */\n public static void removeAllExtraListenersFromValue(String key){\n ConcurrentLinkedQueue<WeakReference<ExtraListener>> listenerList = getInstance().mListenerMap.get(key);\n // Look for new sets\n if(listenerList == null){\n listenerList = new ConcurrentLinkedQueue<>();\n getInstance().mListenerMap.put(key, listenerList);\n }\n\n listenerList.clear();\n }\n\n /**\n * Remove all ExtraListeners from listening to any value\n */\n public static void removeAllExtraListeners(){\n getInstance().mListenerMap.clear();\n }\n\n}"
},
{
"identifier": "ProgressKeeper",
"path": "app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/progresskeeper/ProgressKeeper.java",
"snippet": "public class ProgressKeeper {\n private static final HashMap<String, List<ProgressListener>> sProgressListeners = new HashMap<>();\n private static final HashMap<String, ProgressState> sProgressStates = new HashMap<>();\n private static final List<TaskCountListener> sTaskCountListeners = new ArrayList<>();\n\n public static synchronized void submitProgress(String progressRecord, int progress, int resid, Object... va) {\n ProgressState progressState = sProgressStates.get(progressRecord);\n boolean shouldCallStarted = progressState == null;\n boolean shouldCallEnded = resid == -1 && progress == -1;\n if(shouldCallEnded) {\n shouldCallStarted = false;\n sProgressStates.remove(progressRecord);\n updateTaskCount();\n }else if(shouldCallStarted){\n sProgressStates.put(progressRecord, (progressState = new ProgressState()));\n updateTaskCount();\n }\n if(progressState != null) {\n progressState.progress = progress;\n progressState.resid = resid;\n progressState.varArg = va;\n }\n\n List<ProgressListener> progressListeners = sProgressListeners.get(progressRecord);\n if(progressListeners != null)\n for(ProgressListener listener : progressListeners) {\n if(shouldCallStarted) listener.onProgressStarted();\n else if(shouldCallEnded) listener.onProgressEnded();\n else listener.onProgressUpdated(progress, resid, va);\n }\n }\n\n private static synchronized void updateTaskCount() {\n int count = sProgressStates.size();\n for(TaskCountListener listener : sTaskCountListeners) {\n listener.onUpdateTaskCount(count);\n }\n }\n\n public static synchronized void addListener(String progressRecord, ProgressListener listener) {\n ProgressState state = sProgressStates.get(progressRecord);\n if(state != null && (state.resid != -1 || state.progress != -1)) {\n listener.onProgressStarted();\n listener.onProgressUpdated(state.progress, state.resid, state.varArg);\n }else{\n listener.onProgressEnded();\n }\n List<ProgressListener> listenerWeakReferenceList = sProgressListeners.get(progressRecord);\n if(listenerWeakReferenceList == null) sProgressListeners.put(progressRecord, (listenerWeakReferenceList = new ArrayList<>()));\n listenerWeakReferenceList.add(listener);\n }\n\n public static synchronized void removeListener(String progressRecord, ProgressListener listener) {\n List<ProgressListener> listenerWeakReferenceList = sProgressListeners.get(progressRecord);\n if(listenerWeakReferenceList != null) listenerWeakReferenceList.remove(listener);\n }\n\n public static synchronized void addTaskCountListener(TaskCountListener listener) {\n listener.onUpdateTaskCount(sProgressStates.size());\n if(!sTaskCountListeners.contains(listener)) sTaskCountListeners.add(listener);\n }\n public static synchronized void addTaskCountListener(TaskCountListener listener, boolean runUpdate) {\n if(runUpdate) listener.onUpdateTaskCount(sProgressStates.size());\n if(!sTaskCountListeners.contains(listener)) sTaskCountListeners.add(listener);\n }\n public static synchronized void removeTaskCountListener(TaskCountListener listener) {\n sTaskCountListeners.remove(listener);\n }\n\n /**\n * Waits until all tasks are done and runs the runnable, or if there were no pending process remaining\n * The runnable runs from the thread that updated the task count last, and it might be the UI thread,\n * so don't put long running processes in it\n * @param runnable the runnable to run when no tasks are remaining\n */\n public static void waitUntilDone(final Runnable runnable) {\n // If we do it the other way the listener would be removed before it was added, which will cause a listener object leak\n if(getTaskCount() == 0) {\n runnable.run();\n return;\n }\n TaskCountListener listener = new TaskCountListener() {\n @Override\n public void onUpdateTaskCount(int taskCount) {\n if(taskCount == 0) {\n runnable.run();\n }\n removeTaskCountListener(this);\n }\n };\n addTaskCountListener(listener);\n }\n\n public static synchronized int getTaskCount() {\n return sProgressStates.size();\n }\n\n public static boolean hasOngoingTasks() {\n return getTaskCount() > 0;\n }\n}"
},
{
"identifier": "ProgressListener",
"path": "app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/progresskeeper/ProgressListener.java",
"snippet": "public interface ProgressListener {\n void onProgressStarted();\n void onProgressUpdated(int progress, int resid, Object... va);\n void onProgressEnded();\n}"
},
{
"identifier": "TaskCountListener",
"path": "app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/progresskeeper/TaskCountListener.java",
"snippet": "public interface TaskCountListener {\n void onUpdateTaskCount(int taskCount);\n}"
},
{
"identifier": "ProgressService",
"path": "app_pojavlauncher/src/main/java/net/kdt/pojavlaunch/services/ProgressService.java",
"snippet": "public class ProgressService extends Service implements TaskCountListener {\n\n private NotificationManagerCompat notificationManagerCompat;\n\n /** Simple wrapper to start the service */\n public static void startService(Context context){\n Intent intent = new Intent(context, ProgressService.class);\n ContextCompat.startForegroundService(context, intent);\n }\n\n private NotificationCompat.Builder mNotificationBuilder;\n\n @Override\n public void onCreate() {\n Tools.buildNotificationChannel(getApplicationContext());\n notificationManagerCompat = NotificationManagerCompat.from(getApplicationContext());\n Intent killIntent = new Intent(getApplicationContext(), ProgressService.class);\n killIntent.putExtra(\"kill\", true);\n PendingIntent pendingKillIntent = PendingIntent.getService(this, NotificationUtils.PENDINGINTENT_CODE_KILL_PROGRESS_SERVICE\n , killIntent, Build.VERSION.SDK_INT >=23 ? PendingIntent.FLAG_IMMUTABLE : 0);\n mNotificationBuilder = new NotificationCompat.Builder(this, \"channel_id\")\n .setContentTitle(getString(R.string.lazy_service_default_title))\n .addAction(android.R.drawable.ic_menu_close_clear_cancel, getString(R.string.notification_terminate), pendingKillIntent)\n .setSmallIcon(R.drawable.notif_icon)\n .setNotificationSilent();\n }\n\n @SuppressLint(\"StringFormatInvalid\")\n @Override\n public int onStartCommand(Intent intent, int flags, int startId) {\n if(intent != null) {\n if(intent.getBooleanExtra(\"kill\", false)) {\n stopSelf(); // otherwise Android tries to restart the service since it \"crashed\"\n Process.killProcess(Process.myPid());\n return START_NOT_STICKY;\n }\n }\n Log.d(\"ProgressService\", \"Started!\");\n mNotificationBuilder.setContentText(getString(R.string.progresslayout_tasks_in_progress, ProgressKeeper.getTaskCount()));\n startForeground(NotificationUtils.NOTIFICATION_ID_PROGRESS_SERVICE, mNotificationBuilder.build());\n if(ProgressKeeper.getTaskCount() < 1) stopSelf();\n else ProgressKeeper.addTaskCountListener(this, false);\n\n return START_NOT_STICKY;\n }\n\n @Nullable\n @Override\n public IBinder onBind(Intent intent) {\n return null;\n }\n\n @Override\n public void onDestroy() {\n ProgressKeeper.removeTaskCountListener(this);\n }\n\n @Override\n public void onUpdateTaskCount(int taskCount) {\n Tools.MAIN_HANDLER.post(()->{\n if(taskCount > 0) {\n mNotificationBuilder.setContentText(getString(R.string.progresslayout_tasks_in_progress, taskCount));\n notificationManagerCompat.notify(1, mNotificationBuilder.build());\n }else{\n stopSelf();\n }\n });\n }\n}"
}
] | import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.collection.ArrayMap;
import androidx.constraintlayout.widget.ConstraintLayout;
import net.kdt.pojavlaunch.R;
import net.kdt.pojavlaunch.extra.ExtraCore;
import net.kdt.pojavlaunch.progresskeeper.ProgressKeeper;
import net.kdt.pojavlaunch.progresskeeper.ProgressListener;
import net.kdt.pojavlaunch.progresskeeper.TaskCountListener;
import net.kdt.pojavlaunch.services.ProgressService;
import java.util.ArrayList; | 3,866 | package com.kdt.mcgui;
/** Class staring at specific values and automatically show something if the progress is present
* Since progress is posted in a specific way, The packing/unpacking is handheld by the class
*
* This class relies on ExtraCore for its behavior.
*/
public class ProgressLayout extends ConstraintLayout implements View.OnClickListener, TaskCountListener{
public static final String UNPACK_RUNTIME = "unpack_runtime";
public static final String DOWNLOAD_MINECRAFT = "download_minecraft";
public static final String DOWNLOAD_VERSION_LIST = "download_verlist";
public static final String AUTHENTICATE_MICROSOFT = "authenticate_microsoft";
public static final String INSTALL_MODPACK = "install_modpack";
public static final String EXTRACT_COMPONENTS = "extract_components";
public static final String EXTRACT_SINGLE_FILES = "extract_single_files";
public ProgressLayout(@NonNull Context context) {
super(context);
init();
}
public ProgressLayout(@NonNull Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init();
}
public ProgressLayout(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
public ProgressLayout(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init();
}
private final ArrayList<LayoutProgressListener> mMap = new ArrayList<>();
private LinearLayout mLinearLayout;
private TextView mTaskNumberDisplayer;
private ImageView mFlipArrow;
public void observe(String progressKey){
mMap.add(new LayoutProgressListener(progressKey));
}
public void cleanUpObservers() {
for(LayoutProgressListener progressListener : mMap) {
ProgressKeeper.removeListener(progressListener.progressKey, progressListener);
}
}
public boolean hasProcesses(){
return ProgressKeeper.getTaskCount() > 0;
}
private void init(){
inflate(getContext(), R.layout.view_progress, this);
mLinearLayout = findViewById(R.id.progress_linear_layout);
mTaskNumberDisplayer = findViewById(R.id.progress_textview);
mFlipArrow = findViewById(R.id.progress_flip_arrow);
setBackgroundColor(getResources().getColor(R.color.background_bottom_bar));
setOnClickListener(this);
}
/** Update the progress bar content */
public static void setProgress(String progressKey, int progress){
ProgressKeeper.submitProgress(progressKey, progress, -1, (Object)null);
}
/** Update the text and progress content */
public static void setProgress(String progressKey, int progress, @StringRes int resource, Object... message){
ProgressKeeper.submitProgress(progressKey, progress, resource, message);
}
/** Update the text and progress content */
public static void setProgress(String progressKey, int progress, String message){
setProgress(progressKey,progress, -1, message);
}
/** Update the text and progress content */
public static void clearProgress(String progressKey){
setProgress(progressKey, -1, -1);
}
@Override
public void onClick(View v) {
mLinearLayout.setVisibility(mLinearLayout.getVisibility() == GONE ? VISIBLE : GONE);
mFlipArrow.setRotation(mLinearLayout.getVisibility() == GONE? 0 : 180);
}
@Override
public void onUpdateTaskCount(int tc) {
post(()->{
if(tc > 0) {
mTaskNumberDisplayer.setText(getContext().getString(R.string.progresslayout_tasks_in_progress, tc));
setVisibility(VISIBLE);
}else
setVisibility(GONE);
});
}
| package com.kdt.mcgui;
/** Class staring at specific values and automatically show something if the progress is present
* Since progress is posted in a specific way, The packing/unpacking is handheld by the class
*
* This class relies on ExtraCore for its behavior.
*/
public class ProgressLayout extends ConstraintLayout implements View.OnClickListener, TaskCountListener{
public static final String UNPACK_RUNTIME = "unpack_runtime";
public static final String DOWNLOAD_MINECRAFT = "download_minecraft";
public static final String DOWNLOAD_VERSION_LIST = "download_verlist";
public static final String AUTHENTICATE_MICROSOFT = "authenticate_microsoft";
public static final String INSTALL_MODPACK = "install_modpack";
public static final String EXTRACT_COMPONENTS = "extract_components";
public static final String EXTRACT_SINGLE_FILES = "extract_single_files";
public ProgressLayout(@NonNull Context context) {
super(context);
init();
}
public ProgressLayout(@NonNull Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init();
}
public ProgressLayout(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
public ProgressLayout(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init();
}
private final ArrayList<LayoutProgressListener> mMap = new ArrayList<>();
private LinearLayout mLinearLayout;
private TextView mTaskNumberDisplayer;
private ImageView mFlipArrow;
public void observe(String progressKey){
mMap.add(new LayoutProgressListener(progressKey));
}
public void cleanUpObservers() {
for(LayoutProgressListener progressListener : mMap) {
ProgressKeeper.removeListener(progressListener.progressKey, progressListener);
}
}
public boolean hasProcesses(){
return ProgressKeeper.getTaskCount() > 0;
}
private void init(){
inflate(getContext(), R.layout.view_progress, this);
mLinearLayout = findViewById(R.id.progress_linear_layout);
mTaskNumberDisplayer = findViewById(R.id.progress_textview);
mFlipArrow = findViewById(R.id.progress_flip_arrow);
setBackgroundColor(getResources().getColor(R.color.background_bottom_bar));
setOnClickListener(this);
}
/** Update the progress bar content */
public static void setProgress(String progressKey, int progress){
ProgressKeeper.submitProgress(progressKey, progress, -1, (Object)null);
}
/** Update the text and progress content */
public static void setProgress(String progressKey, int progress, @StringRes int resource, Object... message){
ProgressKeeper.submitProgress(progressKey, progress, resource, message);
}
/** Update the text and progress content */
public static void setProgress(String progressKey, int progress, String message){
setProgress(progressKey,progress, -1, message);
}
/** Update the text and progress content */
public static void clearProgress(String progressKey){
setProgress(progressKey, -1, -1);
}
@Override
public void onClick(View v) {
mLinearLayout.setVisibility(mLinearLayout.getVisibility() == GONE ? VISIBLE : GONE);
mFlipArrow.setRotation(mLinearLayout.getVisibility() == GONE? 0 : 180);
}
@Override
public void onUpdateTaskCount(int tc) {
post(()->{
if(tc > 0) {
mTaskNumberDisplayer.setText(getContext().getString(R.string.progresslayout_tasks_in_progress, tc));
setVisibility(VISIBLE);
}else
setVisibility(GONE);
});
}
| class LayoutProgressListener implements ProgressListener { | 2 | 2023-12-01 16:16:12+00:00 | 8k |
kawashirov/distant-horizons | fabric/src/main/java/com/seibel/distanthorizons/fabric/mixins/client/MixinClientPacketListener.java | [
{
"identifier": "ClientLevelWrapper",
"path": "common/src/main/java/com/seibel/distanthorizons/common/wrappers/world/ClientLevelWrapper.java",
"snippet": "public class ClientLevelWrapper implements IClientLevelWrapper\n{\n\tprivate static final Logger LOGGER = DhLoggerBuilder.getLogger(ClientLevelWrapper.class.getSimpleName());\n\tprivate static final ConcurrentHashMap<ClientLevel, ClientLevelWrapper> LEVEL_WRAPPER_BY_CLIENT_LEVEL = new ConcurrentHashMap<>();\n\tprivate static final IKeyedClientLevelManager KEYED_CLIENT_LEVEL_MANAGER = SingletonInjector.INSTANCE.get(IKeyedClientLevelManager.class);\n\t\n\tprivate final ClientLevel level;\n\tprivate final ClientBlockDetailMap blockMap = new ClientBlockDetailMap(this);\n\t\n\t\n\t\n\t//=============//\n\t// constructor //\n\t//=============//\n\t\n\tprotected ClientLevelWrapper(ClientLevel level) { this.level = level; }\n\t\n\t\n\t\n\t//===============//\n\t// wrapper logic //\n\t//===============//\n\t\n\t@Nullable\n\tpublic static IClientLevelWrapper getWrapper(@Nullable ClientLevel level)\n\t{\n\t\tif (level == null)\n\t\t{\n\t\t\treturn null;\n\t\t}\n\t\t\n\t\t// used if the client is connected to a server that defines the currently loaded level\n\t\tif (KEYED_CLIENT_LEVEL_MANAGER.getUseOverrideWrapper())\n\t\t{\n\t\t\treturn KEYED_CLIENT_LEVEL_MANAGER.getOverrideWrapper();\n\t\t}\n\t\t\n\t\treturn getWrapperIgnoringOverride(level);\n\t}\n\tpublic static IClientLevelWrapper getWrapperIgnoringOverride(@NotNull ClientLevel level) { return LEVEL_WRAPPER_BY_CLIENT_LEVEL.computeIfAbsent(level, ClientLevelWrapper::new); }\n\t\n\t@Nullable\n\t@Override\n\tpublic IServerLevelWrapper tryGetServerSideWrapper()\n\t{\n\t\ttry\n\t\t{\n\t\t\tIterable<ServerLevel> serverLevels = MinecraftClientWrapper.INSTANCE.mc.getSingleplayerServer().getAllLevels();\n\t\t\t\n\t\t\t// attempt to find the server level with the same dimension type\n\t\t\t// TODO this assumes only one level per dimension type, the SubDimensionLevelMatcher will need to be added for supporting multiple levels per dimension\n\t\t\tServerLevelWrapper foundLevelWrapper = null;\n\t\t\t\n\t\t\t// TODO: Surely there is a more efficient way to write this code\n\t\t\tfor (ServerLevel serverLevel : serverLevels)\n\t\t\t{\n\t\t\t\tif (serverLevel.dimension() == this.level.dimension())\n\t\t\t\t{\n\t\t\t\t\tfoundLevelWrapper = ServerLevelWrapper.getWrapper(serverLevel);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\treturn foundLevelWrapper;\n\t\t}\n\t\tcatch (Exception e)\n\t\t{\n\t\t\tLOGGER.error(\"Failed to get server side wrapper for client level: \" + level);\n\t\t\treturn null;\n\t\t}\n\t}\n\t\n\t\n\t\n\t//====================//\n\t// base level methods //\n\t//====================//\n\t\n\t@Override\n\tpublic int computeBaseColor(DhBlockPos pos, IBiomeWrapper biome, IBlockStateWrapper blockState)\n\t{\n\t\treturn this.blockMap.getColor(((BlockStateWrapper) blockState).blockState, (BiomeWrapper) biome, pos);\n\t}\n\t\n\t@Override\n\tpublic IDimensionTypeWrapper getDimensionType() { return DimensionTypeWrapper.getDimensionTypeWrapper(this.level.dimensionType()); }\n\t\n\t@Override\n\tpublic EDhApiLevelType getLevelType() { return EDhApiLevelType.CLIENT_LEVEL; }\n\t\n\tpublic ClientLevel getLevel() { return this.level; }\n\t\n\t@Override\n\tpublic boolean hasCeiling() { return this.level.dimensionType().hasCeiling(); }\n\t\n\t@Override\n\tpublic boolean hasSkyLight() { return this.level.dimensionType().hasSkyLight(); }\n\t\n\t@Override\n\tpublic int getHeight() { return this.level.getHeight(); }\n\t\n\t@Override\n\tpublic int getMinHeight()\n\t{\n #if PRE_MC_1_17_1\n return 0;\n #else\n\t\treturn this.level.getMinBuildHeight();\n #endif\n\t}\n\t\n\t@Override\n\tpublic IChunkWrapper tryGetChunk(DhChunkPos pos)\n\t{\n\t\tif (!this.level.hasChunk(pos.x, pos.z))\n\t\t{\n\t\t\treturn null;\n\t\t}\n\t\t\n\t\tChunkAccess chunk = this.level.getChunk(pos.x, pos.z, ChunkStatus.EMPTY, false);\n\t\tif (chunk == null)\n\t\t{\n\t\t\treturn null;\n\t\t}\n\t\t\n\t\treturn new ChunkWrapper(chunk, this.level, this);\n\t}\n\t\n\t@Override\n\tpublic boolean hasChunkLoaded(int chunkX, int chunkZ)\n\t{\n\t\tChunkSource source = this.level.getChunkSource();\n\t\treturn source.hasChunk(chunkX, chunkZ);\n\t}\n\t\n\t@Override\n\tpublic IBlockStateWrapper getBlockState(DhBlockPos pos)\n\t{\n\t\treturn BlockStateWrapper.fromBlockState(this.level.getBlockState(McObjectConverter.Convert(pos)), this);\n\t}\n\t\n\t@Override\n\tpublic IBiomeWrapper getBiome(DhBlockPos pos) { return BiomeWrapper.getBiomeWrapper(this.level.getBiome(McObjectConverter.Convert(pos)), this); }\n\t\n\t@Override\n\tpublic ClientLevel getWrappedMcObject() { return this.level; }\n\t\n\t@Override\n\tpublic void onUnload() { LEVEL_WRAPPER_BY_CLIENT_LEVEL.remove(this.level); }\n\t\n\t@Override\n\tpublic String toString()\n\t{\n\t\tif (this.level == null)\n\t\t{\n\t\t\treturn \"Wrapped{null}\";\n\t\t}\n\t\t\n\t\treturn \"Wrapped{\" + this.level.toString() + \"@\" + this.getDimensionType().getDimensionName() + \"}\";\n\t}\n\t\n}"
},
{
"identifier": "ChunkWrapper",
"path": "common/src/main/java/com/seibel/distanthorizons/common/wrappers/chunk/ChunkWrapper.java",
"snippet": "public class ChunkWrapper implements IChunkWrapper\n{\n\tprivate static final Logger LOGGER = DhLoggerBuilder.getLogger();\n\t\n\t/** useful for debugging, but can slow down chunk operations quite a bit due to being called every time. */\n\tprivate static final boolean RUN_RELATIVE_POS_INDEX_VALIDATION = ModInfo.IS_DEV_BUILD;\n\t\n\t/** can be used for interactions with the underlying chunk where creating new BlockPos objects could cause issues for the garbage collector. */\n\tprivate static final ThreadLocal<BlockPos.MutableBlockPos> MUTABLE_BLOCK_POS_REF = ThreadLocal.withInitial(() -> new BlockPos.MutableBlockPos());\n\t\n\t\n\tprivate final ChunkAccess chunk;\n\tprivate final DhChunkPos chunkPos;\n\tprivate final LevelReader lightSource;\n\tprivate final ILevelWrapper wrappedLevel;\n\t\n\tprivate boolean isDhLightCorrect = false;\n\t/** only used when connected to a dedicated server */\n\tprivate boolean isMcClientLightingCorrect = false;\n\t\n\tprivate ChunkLightStorage blockLightStorage;\n\tprivate ChunkLightStorage skyLightStorage;\n\t\n\tprivate ArrayList<DhBlockPos> blockLightPosList = null;\n\t\n\tprivate boolean useDhLighting;\n\t\n\t/**\n\t * Due to vanilla `isClientLightReady()` not being designed for use by a non-render thread, it may return 'true'\n\t * before the light engine has ticked, (right after all light changes is marked by the engine to be processed).\n\t * To fix this, on client-only mode, we mixin-redirect the `isClientLightReady()` so that after the call, it will\n\t * trigger a synchronous update of this flag here on all chunks that are wrapped. <br><br>\n\t *\n\t * Note: Using a static weak hash map to store the chunks that need to be updated, as instance of chunk wrapper\n\t * can be duplicated, with same chunk instance. And the data stored here are all temporary, and thus will not be\n\t * visible when a chunk is re-wrapped later. <br>\n\t * (Also, thread safety done via a reader writer lock)\n\t */\n\tprivate static final ConcurrentLinkedQueue<ChunkWrapper> chunksNeedingClientLightUpdating = new ConcurrentLinkedQueue<>(); \n\t\n\t\n\t\n\t//=============//\n\t// constructor //\n\t//=============//\n\t\n\tpublic ChunkWrapper(ChunkAccess chunk, LevelReader lightSource, ILevelWrapper wrappedLevel)\n\t{\n\t\tthis.chunk = chunk;\n\t\tthis.lightSource = lightSource;\n\t\tthis.wrappedLevel = wrappedLevel;\n\t\tthis.chunkPos = new DhChunkPos(chunk.getPos().x, chunk.getPos().z);\n\t\t\n\t\t// TODO is this the best way to differentiate between when we are generating chunks and when MC gave us a chunk?\n\t\tboolean isDhGeneratedChunk = (this.lightSource.getClass() == DhLitWorldGenRegion.class);\n\t\t// MC loaded chunks should get their lighting from MC, DH generated chunks should get their lighting from DH\n\t\tthis.useDhLighting = isDhGeneratedChunk;\n\t\t\n\t\t// FIXME +1 is to handle the fact that LodDataBuilder adds +1 to all block lighting calculations, also done in the relative position validator\n\n\t\tchunksNeedingClientLightUpdating.add(this);\n\t}\n\t\n\t\n\t\n\t//=========//\n\t// methods //\n\t//=========//\n\t\n\t@Override\n\tpublic int getHeight()\n\t{\n\t\t#if PRE_MC_1_17_1\n\t\treturn 255;\n\t\t#else\n\t\treturn this.chunk.getHeight();\n\t\t#endif\n\t}\n\t\n\t@Override\n\tpublic int getMinBuildHeight()\n\t{\n\t\t#if PRE_MC_1_17_1\n\t\treturn 0;\n\t\t#else\n\t\treturn this.chunk.getMinBuildHeight();\n\t\t#endif\n\t}\n\t@Override\n\tpublic int getMaxBuildHeight() { return this.chunk.getMaxBuildHeight(); }\n\t\n\t@Override\n\tpublic int getMinFilledHeight()\n\t{\n\t\tLevelChunkSection[] sections = this.chunk.getSections();\n\t\tfor (int index = 0; index < sections.length; index++)\n\t\t{\n\t\t\tif (sections[index] == null)\n\t\t\t{\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t\n\t\t\t#if MC_1_16_5\n\t\t\tif (!sections[index].isEmpty())\n\t\t\t{\n\t\t\t\t// convert from an index to a block coordinate\n\t\t\t\treturn this.chunk.getSections()[index].bottomBlockY() * 16;\n\t\t\t}\n\t\t\t#elif MC_1_17_1\n\t\t\tif (!sections[index].isEmpty())\n\t\t\t{\n\t\t\t\t// convert from an index to a block coordinate\n\t\t\t\treturn this.chunk.getSections()[index].bottomBlockY() * 16;\n\t\t\t}\t\n\t\t\t#else\n\t\t\tif (!sections[index].hasOnlyAir())\n\t\t\t{\n\t\t\t\t// convert from an index to a block coordinate\n\t\t\t\treturn this.chunk.getSectionYFromSectionIndex(index) * 16;\n\t\t\t}\n\t\t\t#endif\n\t\t}\n\t\treturn Integer.MAX_VALUE;\n\t}\n\t\n\t\n\t@Override\n\tpublic int getSolidHeightMapValue(int xRel, int zRel) { return this.chunk.getOrCreateHeightmapUnprimed(Heightmap.Types.WORLD_SURFACE).getFirstAvailable(xRel, zRel); }\n\t\n\t@Override\n\tpublic int getLightBlockingHeightMapValue(int xRel, int zRel) { return this.chunk.getOrCreateHeightmapUnprimed(Heightmap.Types.MOTION_BLOCKING).getFirstAvailable(xRel, zRel); }\n\t\n\t\n\t\n\t@Override\n\tpublic IBiomeWrapper getBiome(int relX, int relY, int relZ)\n\t{\n\t\t#if PRE_MC_1_17_1\n\t\treturn BiomeWrapper.getBiomeWrapper(this.chunk.getBiomes().getNoiseBiome(\n\t\t\t\trelX >> 2, relY >> 2, relZ >> 2),\n\t\t\t\tthis.wrappedLevel);\n\t\t#elif PRE_MC_1_18_2\n\t\treturn BiomeWrapper.getBiomeWrapper(this.chunk.getBiomes().getNoiseBiome(\n\t\t\t\tQuartPos.fromBlock(relX), QuartPos.fromBlock(relY), QuartPos.fromBlock(relZ)),\n\t\t\t\tthis.wrappedLevel);\n\t\t#elif PRE_MC_1_18_2\n\t\treturn BiomeWrapper.getBiomeWrapper(this.chunk.getNoiseBiome(\n\t\t\t\tQuartPos.fromBlock(relX), QuartPos.fromBlock(relY), QuartPos.fromBlock(relZ)),\n\t\t\t\tthis.wrappedLevel);\n\t\t#else \n\t\t//Now returns a Holder<Biome> instead of Biome\n\t\treturn BiomeWrapper.getBiomeWrapper(this.chunk.getNoiseBiome(\n\t\t\t\tQuartPos.fromBlock(relX), QuartPos.fromBlock(relY), QuartPos.fromBlock(relZ)),\n\t\t\t\tthis.wrappedLevel);\n\t\t#endif\n\t}\n\t\n\t@Override\n\tpublic DhChunkPos getChunkPos() { return this.chunkPos; }\n\t\n\tpublic ChunkAccess getChunk() { return this.chunk; }\n\t\n\t@Override\n\tpublic int getMaxBlockX() { return this.chunk.getPos().getMaxBlockX(); }\n\t@Override\n\tpublic int getMaxBlockZ() { return this.chunk.getPos().getMaxBlockZ(); }\n\t@Override\n\tpublic int getMinBlockX() { return this.chunk.getPos().getMinBlockX(); }\n\t@Override\n\tpublic int getMinBlockZ() { return this.chunk.getPos().getMinBlockZ(); }\n\t\n\t@Override\n\tpublic long getLongChunkPos() { return this.chunk.getPos().toLong(); }\n\t\n\t@Override\n\tpublic void setIsDhLightCorrect(boolean isDhLightCorrect) { this.isDhLightCorrect = isDhLightCorrect; }\n\t\n\t@Override\n\tpublic void setUseDhLighting(boolean useDhLighting) { this.useDhLighting = useDhLighting; }\n\t\n\t\n\t\n\t@Override\n\tpublic boolean isLightCorrect()\n\t{\n\t\tif (this.useDhLighting)\n\t\t{\n\t\t\treturn this.isDhLightCorrect;\n\t\t}\n\t\t\n\t\t\n\t\t#if MC_1_16_5 || MC_1_17_1\n\t\treturn false; // MC's lighting engine doesn't work consistently enough to trust for 1.16 or 1.17\n\t\t#else\n\t\tif (this.chunk instanceof LevelChunk)\n\t\t{\n\t\t\tLevelChunk levelChunk = (LevelChunk) this.chunk;\n\t\t\tif (levelChunk.getLevel() instanceof ClientLevel)\n\t\t\t{\n\t\t\t\t// connected to a server\n\t\t\t\treturn this.isMcClientLightingCorrect;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t// in a single player world\n\t\t\t\treturn this.chunk.isLightCorrect() && levelChunk.loaded;\t\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// called when in a single player world and the chunk is a proto chunk (in world gen, and not active)\n\t\t\treturn this.chunk.isLightCorrect();\n\t\t}\n\t\t#endif\n\t}\n\t\n\t\n\t@Override\n\tpublic int getDhBlockLight(int relX, int y, int relZ)\n\t{\n\t\tthis.throwIndexOutOfBoundsIfRelativePosOutsideChunkBounds(relX, y, relZ);\n\t\treturn this.getBlockLightStorage().get(relX, y, relZ);\n\t}\n\t@Override\n\tpublic void setDhBlockLight(int relX, int y, int relZ, int lightValue)\n\t{\n\t\tthis.throwIndexOutOfBoundsIfRelativePosOutsideChunkBounds(relX, y, relZ);\n\t\tthis.getBlockLightStorage().set(relX, y, relZ, lightValue);\n\t}\n\t\n\tprivate ChunkLightStorage getBlockLightStorage()\n\t{\n\t\tif (this.blockLightStorage == null)\n\t\t{\n\t\t\tthis.blockLightStorage = new ChunkLightStorage(this.getMinBuildHeight(), this.getMaxBuildHeight());\n\t\t}\n\t\treturn this.blockLightStorage;\n\t}\n\t\n\t\n\t@Override\n\tpublic int getDhSkyLight(int relX, int y, int relZ)\n\t{\n\t\tthis.throwIndexOutOfBoundsIfRelativePosOutsideChunkBounds(relX, y, relZ);\n\t\treturn this.getSkyLightStorage().get(relX, y, relZ);\n\t}\n\t@Override\n\tpublic void setDhSkyLight(int relX, int y, int relZ, int lightValue)\n\t{\n\t\tthis.throwIndexOutOfBoundsIfRelativePosOutsideChunkBounds(relX, y, relZ);\n\t\tthis.getSkyLightStorage().set(relX, y, relZ, lightValue);\n\t}\n\t\n\tprivate ChunkLightStorage getSkyLightStorage()\n\t{\n\t\tif (this.skyLightStorage == null)\n\t\t{\n\t\t\tthis.skyLightStorage = new ChunkLightStorage(this.getMinBuildHeight(), this.getMaxBuildHeight());\n\t\t}\n\t\treturn this.skyLightStorage;\n\t}\n\t\n\t\n\t@Override\n\tpublic int getBlockLight(int relX, int y, int relZ)\n\t{\n\t\tthis.throwIndexOutOfBoundsIfRelativePosOutsideChunkBounds(relX, y, relZ);\n\t\t\n\t\t// use the full lighting engine when the chunks are within render distance or the config requests it\n\t\tif (this.useDhLighting)\n\t\t{\n\t\t\t// DH lighting method\n\t\t\treturn this.getBlockLightStorage().get(relX, y, relZ);\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// note: this returns 0 if the chunk is unload\n\t\t\t\n\t\t\t// MC lighting method\n\t\t\treturn this.lightSource.getBrightness(LightLayer.BLOCK, new BlockPos(relX + this.getMinBlockX(), y, relZ + this.getMinBlockZ()));\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic int getSkyLight(int relX, int y, int relZ)\n\t{\n\t\tthis.throwIndexOutOfBoundsIfRelativePosOutsideChunkBounds(relX, y, relZ);\n\t\t\n\t\t// use the full lighting engine when the chunks are within render distance or the config requests it\n\t\tif (this.useDhLighting)\n\t\t{\n\t\t\t// DH lighting method\n\t\t\treturn this.getSkyLightStorage().get(relX, y, relZ);\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// MC lighting method\n\t\t\treturn this.lightSource.getBrightness(LightLayer.SKY, new BlockPos(relX + this.getMinBlockX(), y, relZ + this.getMinBlockZ()));\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic ArrayList<DhBlockPos> getBlockLightPosList()\n\t{\n\t\t// only populate the list once\n\t\tif (this.blockLightPosList == null)\n\t\t{\n\t\t\tthis.blockLightPosList = new ArrayList<>();\n\t\t\t\n\t\t\t\n\t\t\t#if PRE_MC_1_20_1\n\t\t\tthis.chunk.getLights().forEach((blockPos) ->\n\t\t\t{\n\t\t\t\tthis.blockLightPosList.add(new DhBlockPos(blockPos.getX(), blockPos.getY(), blockPos.getZ()));\n\t\t\t});\n\t\t\t#else\n\t\t\tthis.chunk.findBlockLightSources((blockPos, blockState) ->\n\t\t\t{\n\t\t\t\tthis.blockLightPosList.add(new DhBlockPos(blockPos.getX(), blockPos.getY(), blockPos.getZ()));\n\t\t\t});\n\t\t\t#endif\n\t\t}\n\t\t\n\t\treturn this.blockLightPosList;\n\t}\n\t\n\t@Override\n\tpublic boolean doNearbyChunksExist()\n\t{\n\t\tif (this.lightSource instanceof DhLitWorldGenRegion)\n\t\t{\n\t\t\treturn true;\n\t\t}\n\t\t\n\t\tfor (int dx = -1; dx <= 1; dx++)\n\t\t{\n\t\t\tfor (int dz = -1; dz <= 1; dz++)\n\t\t\t{\n\t\t\t\tif (dx == 0 && dz == 0)\n\t\t\t\t{\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\telse if (this.lightSource.getChunk(dx + this.chunk.getPos().x, dz + this.chunk.getPos().z, ChunkStatus.BIOMES, false) == null)\n\t\t\t\t{\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn true;\n\t}\n\t\n\tpublic LevelReader getColorResolver() { return this.lightSource; }\n\t\n\t@Override\n\tpublic String toString() { return this.chunk.getClass().getSimpleName() + this.chunk.getPos(); }\n\t\n\t@Override\n\tpublic IBlockStateWrapper getBlockState(int relX, int relY, int relZ)\n\t{\n\t\tthis.throwIndexOutOfBoundsIfRelativePosOutsideChunkBounds(relX, relY, relZ);\n\t\t\n\t\tBlockPos.MutableBlockPos blockPos = MUTABLE_BLOCK_POS_REF.get();\n\t\t\n\t\tblockPos.setX(relX);\n\t\tblockPos.setY(relY);\n\t\tblockPos.setZ(relZ);\n\t\t\n\t\treturn BlockStateWrapper.fromBlockState(this.chunk.getBlockState(blockPos), this.wrappedLevel);\n\t}\n\t\n\t@Override\n\tpublic boolean isStillValid() { return this.wrappedLevel.tryGetChunk(this.chunkPos) == this; }\n\t\n\t\n\tpublic static void syncedUpdateClientLightStatus()\n\t{\n\t\t#if PRE_MC_1_18_2\n\t\t// TODO: Check what to do in 1.18.1 and older\n\t\t\n\t\t// since we don't currently handle this list,\n\t\t// clear it to prevent memory leaks\n\t\tchunksNeedingClientLightUpdating.clear();\n\t\t\n\t\t#else\n\t\t\n\t\t// update the chunks client lighting\n\t\tChunkWrapper chunkWrapper = chunksNeedingClientLightUpdating.poll();\n\t\twhile (chunkWrapper != null)\n\t\t{\n\t\t\tchunkWrapper.updateIsClientLightingCorrect();\n\t\t\tchunkWrapper = chunksNeedingClientLightUpdating.poll();\n\t\t}\n\t\t\n\t\t#endif\n\t}\n\t/** Should be called after client light updates are triggered. */\n\tprivate void updateIsClientLightingCorrect()\n\t{\n\t\tif (this.chunk instanceof LevelChunk && ((LevelChunk) this.chunk).getLevel() instanceof ClientLevel)\n\t\t{\n\t\t\tLevelChunk levelChunk = (LevelChunk) this.chunk;\n\t\t\tClientChunkCache clientChunkCache = ((ClientLevel) levelChunk.getLevel()).getChunkSource();\n\t\t\tthis.isMcClientLightingCorrect = clientChunkCache.getChunkForLighting(this.chunk.getPos().x, this.chunk.getPos().z) != null &&\n\t\t\t\t\t#if MC_1_16_5 || MC_1_17_1\n\t\t\t\t\tlevelChunk.isLightCorrect();\n\t\t\t\t\t#elif PRE_MC_1_20_1\n\t\t\t\t\tlevelChunk.isClientLightReady();\n\t\t\t\t\t#else\n\t\t\t\t\tcheckLightSectionsOnChunk(levelChunk, levelChunk.getLevel().getLightEngine());\n\t\t\t\t\t#endif\n\t\t}\n\t}\n\t#if POST_MC_1_20_1\n\tprivate static boolean checkLightSectionsOnChunk(LevelChunk chunk, LevelLightEngine engine)\n\t{\n\t\tLevelChunkSection[] sections = chunk.getSections();\n\t\tint minY = chunk.getMinSection();\n\t\tint maxY = chunk.getMaxSection();\n\t\tfor (int y = minY; y < maxY; ++y)\n\t\t{\n\t\t\tLevelChunkSection section = sections[chunk.getSectionIndexFromSectionY(y)];\n\t\t\tif (section.hasOnlyAir()) continue;\n\t\t\tif (!engine.lightOnInSection(SectionPos.of(chunk.getPos(), y)))\n\t\t\t{\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}\n\t#endif\n\t\n\t\n\t\n\t//================//\n\t// helper methods //\n\t//================//\n\t\n\t/** used to prevent accidentally attempting to get/set values outside this chunk's boundaries */\n\tprivate void throwIndexOutOfBoundsIfRelativePosOutsideChunkBounds(int x, int y, int z) throws IndexOutOfBoundsException\n\t{\n\t\tif (!RUN_RELATIVE_POS_INDEX_VALIDATION)\n\t\t{\n\t\t\treturn;\n\t\t}\n\t\t\n\t\t\n\t\t// FIXME +1 is to handle the fact that LodDataBuilder adds +1 to all block lighting calculations, also done in the constructor\n\t\tint minHeight = this.getMinBuildHeight();\n\t\tint maxHeight = this.getMaxBuildHeight() + 1;\n\t\t\n\t\tif (x < 0 || x >= LodUtil.CHUNK_WIDTH\n\t\t\t\t|| z < 0 || z >= LodUtil.CHUNK_WIDTH\n\t\t\t\t|| y < minHeight || y > maxHeight)\n\t\t{\n\t\t\tString errorMessage = \"Relative position [\" + x + \",\" + y + \",\" + z + \"] out of bounds. \\n\" +\n\t\t\t\t\t\"X/Z must be between 0 and 15 (inclusive) \\n\" +\n\t\t\t\t\t\"Y must be between [\" + minHeight + \"] and [\" + maxHeight + \"] (inclusive).\";\n\t\t\tthrow new IndexOutOfBoundsException(errorMessage);\n\t\t}\n\t}\n\t\n\t\n\t/**\n\t * Converts a 3D position into a 1D array index. <br><br>\n\t *\n\t * Source: <br>\n\t * <a href=\"https://stackoverflow.com/questions/7367770/how-to-flatten-or-index-3d-array-in-1d-array\">stackoverflow</a>\n\t */\n\tpublic int relativeBlockPosToIndex(int xRel, int y, int zRel)\n\t{\n\t\tint yRel = y - this.getMinBuildHeight();\n\t\treturn (zRel * LodUtil.CHUNK_WIDTH * this.getHeight()) + (yRel * LodUtil.CHUNK_WIDTH) + xRel;\n\t}\n\t\n\t/**\n\t * Converts a 3D position into a 1D array index. <br><br>\n\t *\n\t * Source: <br>\n\t * <a href=\"https://stackoverflow.com/questions/7367770/how-to-flatten-or-index-3d-array-in-1d-array\">stackoverflow</a>\n\t */\n\tpublic DhBlockPos indexToRelativeBlockPos(int index)\n\t{\n\t\tfinal int zRel = index / (LodUtil.CHUNK_WIDTH * this.getHeight());\n\t\tindex -= (zRel * LodUtil.CHUNK_WIDTH * this.getHeight());\n\t\t\n\t\tfinal int y = index / LodUtil.CHUNK_WIDTH;\n\t\tfinal int yRel = y + this.getMinBuildHeight();\n\t\t\n\t\tfinal int xRel = index % LodUtil.CHUNK_WIDTH;\n\t\treturn new DhBlockPos(xRel, yRel, zRel);\n\t}\n\t\n\t\n}"
}
] | import com.seibel.distanthorizons.common.wrappers.world.ClientLevelWrapper;
import com.seibel.distanthorizons.core.api.internal.ClientApi;
import com.seibel.distanthorizons.core.api.internal.SharedApi;
import net.minecraft.client.multiplayer.ClientLevel;
import net.minecraft.client.multiplayer.ClientPacketListener;
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 com.seibel.distanthorizons.core.wrapperInterfaces.world.IClientLevelWrapper;
import net.minecraft.world.level.chunk.LevelChunk;
import com.seibel.distanthorizons.common.wrappers.chunk.ChunkWrapper; | 6,404 | package com.seibel.distanthorizons.fabric.mixins.client;
#if POST_MC_1_20_1
#endif
@Mixin(ClientPacketListener.class)
public class MixinClientPacketListener
{
@Shadow
private ClientLevel level;
@Inject(method = "handleLogin", at = @At("RETURN"))
void onHandleLoginEnd(CallbackInfo ci) { ClientApi.INSTANCE.onClientOnlyConnected(); }
@Inject(method = "handleRespawn", at = @At("HEAD")) | package com.seibel.distanthorizons.fabric.mixins.client;
#if POST_MC_1_20_1
#endif
@Mixin(ClientPacketListener.class)
public class MixinClientPacketListener
{
@Shadow
private ClientLevel level;
@Inject(method = "handleLogin", at = @At("RETURN"))
void onHandleLoginEnd(CallbackInfo ci) { ClientApi.INSTANCE.onClientOnlyConnected(); }
@Inject(method = "handleRespawn", at = @At("HEAD")) | void onHandleRespawnStart(CallbackInfo ci) { ClientApi.INSTANCE.clientLevelUnloadEvent(ClientLevelWrapper.getWrapper(this.level)); } | 0 | 2023-12-04 11:41:46+00:00 | 8k |
gaojindeng/netty-spring-boot-starter | netty-spring-boot-starter/src/main/java/io/github/gaojindeng/netty/DefaultNettyContainer.java | [
{
"identifier": "BaseNettyClient",
"path": "netty-spring-boot-starter/src/main/java/io/github/gaojindeng/netty/client/BaseNettyClient.java",
"snippet": "public abstract class BaseNettyClient extends AbstractNetty implements NettyClient {\n private static final Logger log = LoggerFactory.getLogger(BaseNettyClient.class);\n protected final String host;\n protected final EventLoopGroup group;\n protected final Bootstrap bootstrap;\n protected final long timeout;\n\n\n public BaseNettyClient(NettyClientConfig nettyClientConfig) {\n super(nettyClientConfig);\n super.setConnectionManager(new ClientConnectionManger());\n super.setChannelInitializer(new ClientChannelHandlerManager(nettyClientConfig, getConnectionManager()));\n super.init();\n this.port = nettyClientConfig.getPort();\n this.host = nettyClientConfig.getHost();\n this.timeout = nettyClientConfig.getTimeout();\n group = new NioEventLoopGroup(nettyClientConfig.getIoThreads());\n bootstrap = new Bootstrap();\n bootstrap.group(group).channel(NioSocketChannel.class).handler(channelInitializer);\n }\n\n\n protected void execute(ClientChannel channel, Object message) {\n Object request = converterReq(message);\n channel.getChannel().writeAndFlush(request);\n }\n\n protected Object submit(ClientChannel channel, Object message, long timeout) {\n channel.cleanMessage();\n Object request = converterReq(message);\n channel.getChannel().writeAndFlush(request);\n Object result = channel.waitMessage(timeout < 1 ? this.timeout : timeout);\n return converterRes(result);\n }\n\n protected ClientChannel connect() {\n ChannelFuture future = null;\n try {\n future = bootstrap.connect(host, port).sync();\n } catch (InterruptedException e) {\n throw new IllegalStateException(e);\n }\n Channel channel = future.channel();\n getConnectionManager().addChannel(channel);\n return getConnectionManager().addWaitChannel(channel);\n }\n\n @Override\n public ClientConnectionManger getConnectionManager() {\n return ((ClientConnectionManger) super.getConnectionManager());\n }\n\n @Override\n public void close() {\n group.shutdownGracefully();\n }\n}"
},
{
"identifier": "LongNettyClient",
"path": "netty-spring-boot-starter/src/main/java/io/github/gaojindeng/netty/client/LongNettyClient.java",
"snippet": "public class LongNettyClient extends BaseNettyClient {\n\n private final int maxConn;\n\n public LongNettyClient(NettyClientConfig nettyClientConfig) {\n super(nettyClientConfig);\n this.maxConn = nettyClientConfig.getMaxConn();\n }\n\n public LongNettyClient(String name, NettyClientConfig nettyClientConfig) {\n this(nettyClientConfig);\n super.setName(name);\n }\n\n @Override\n public void execute(Object message) {\n ClientChannel channel = acquireChannel();\n try {\n execute(channel, message);\n } finally {\n releaseChannel(channel);\n }\n }\n\n @Override\n public Object submit(Object message, long timeout) {\n ClientChannel channel = acquireChannel();\n try {\n return submit(channel, message, timeout);\n } finally {\n releaseChannel(channel);\n }\n\n }\n\n /**\n * 获取连接\n *\n * @return\n */\n public ClientChannel acquireChannel() {\n ClientChannel channel = getConnectionManager().acquireChannel();\n\n if (channel == null) {\n channel = connect();\n } else if (!channel.getChannel().isActive()) {\n channel.close();\n channel = connect();\n }\n return channel;\n }\n\n /**\n * 释放连接\n *\n * @param channel\n */\n public void releaseChannel(ClientChannel channel) {\n if (getConnectionManager().getTotalConnection() < maxConn) {\n getConnectionManager().releaseChannel(channel);\n } else {\n channel.close();\n }\n }\n\n\n}"
},
{
"identifier": "NettyClient",
"path": "netty-spring-boot-starter/src/main/java/io/github/gaojindeng/netty/client/NettyClient.java",
"snippet": "public interface NettyClient {\n\n void execute(Object message);\n\n Object submit(Object message, long timeout);\n}"
},
{
"identifier": "ShortNettyClient",
"path": "netty-spring-boot-starter/src/main/java/io/github/gaojindeng/netty/client/ShortNettyClient.java",
"snippet": "public class ShortNettyClient extends BaseNettyClient {\n\n public ShortNettyClient(NettyClientConfig nettyClientConfig) {\n super(nettyClientConfig);\n }\n\n public ShortNettyClient(String name, NettyClientConfig nettyClientConfig) {\n this(nettyClientConfig);\n super.setName(name);\n }\n\n @Override\n public void execute(Object message) {\n ClientChannel channel = connect();\n try {\n execute(channel, message);\n } finally {\n channel.close();\n }\n }\n\n @Override\n public Object submit(Object message, long timeout) {\n ClientChannel channel = connect();\n try {\n return submit(channel, message, timeout);\n } finally {\n channel.close();\n }\n\n }\n}"
},
{
"identifier": "NettyClientConfig",
"path": "netty-spring-boot-starter/src/main/java/io/github/gaojindeng/netty/properties/NettyClientConfig.java",
"snippet": "public class NettyClientConfig extends AbstractProperties {\n private String host;\n /**\n * 是否保持连接\n */\n private boolean keepConn;\n private long timeout = 60000;\n\n public String getHost() {\n return host;\n }\n\n public void setHost(String host) {\n this.host = host;\n }\n\n public boolean isKeepConn() {\n return keepConn;\n }\n\n public void setKeepConn(boolean keepConn) {\n this.keepConn = keepConn;\n }\n\n public long getTimeout() {\n return timeout;\n }\n\n public void setTimeout(long timeout) {\n this.timeout = timeout;\n }\n}"
},
{
"identifier": "NettyConfigProperties",
"path": "netty-spring-boot-starter/src/main/java/io/github/gaojindeng/netty/properties/NettyConfigProperties.java",
"snippet": "@Configuration\n@ConfigurationProperties(prefix = \"netty\")\npublic class NettyConfigProperties {\n\n /**\n * 服务端配置\n */\n private NettyServerProperties server;\n\n /**\n * 客户端配置\n */\n private NettyClientProperties client;\n\n public static class NettyClientProperties extends NettyClientConfig {\n private Map<String, NettyClientConfig> configs;\n\n public Map<String, NettyClientConfig> getConfigs() {\n return configs;\n }\n\n public void setConfigs(Map<String, NettyClientConfig> configs) {\n this.configs = configs;\n }\n }\n\n public static class NettyServerProperties extends NettyServerConfig {\n private Map<String, NettyServerConfig> configs;\n\n public Map<String, NettyServerConfig> getConfigs() {\n return configs;\n }\n\n public void setConfigs(Map<String, NettyServerConfig> configs) {\n this.configs = configs;\n }\n }\n\n public NettyServerProperties getServer() {\n return server;\n }\n\n public void setServer(NettyServerProperties server) {\n this.server = server;\n }\n\n public NettyClientProperties getClient() {\n return client;\n }\n\n public void setClient(NettyClientProperties client) {\n this.client = client;\n }\n}"
},
{
"identifier": "NettyServerConfig",
"path": "netty-spring-boot-starter/src/main/java/io/github/gaojindeng/netty/properties/NettyServerConfig.java",
"snippet": "public class NettyServerConfig extends AbstractProperties {\n private int corePoolSize = 5;\n private int maxPoolSize = 100;\n\n public int getCorePoolSize() {\n return corePoolSize;\n }\n\n public void setCorePoolSize(int corePoolSize) {\n this.corePoolSize = corePoolSize;\n }\n\n public int getMaxPoolSize() {\n return maxPoolSize;\n }\n\n public void setMaxPoolSize(int maxPoolSize) {\n this.maxPoolSize = maxPoolSize;\n }\n}"
},
{
"identifier": "AbstractNettyServer",
"path": "netty-spring-boot-starter/src/main/java/io/github/gaojindeng/netty/server/AbstractNettyServer.java",
"snippet": "public abstract class AbstractNettyServer extends AbstractNetty {\n private static final Logger log = LoggerFactory.getLogger(AbstractNettyServer.class);\n\n protected EventLoopGroup bossGroup;\n protected EventLoopGroup workerGroup;\n\n\n public AbstractNettyServer(NettyServerConfig nettyServerConfig) {\n super(nettyServerConfig);\n super.setConnectionManager(new ServerConnectionManger());\n super.setChannelInitializer(new ServerChannelHandlerManager(nettyServerConfig, this, getConnectionManager()));\n super.init();\n this.port = nettyServerConfig.getPort();\n this.bossGroup = new NioEventLoopGroup(1);\n this.workerGroup = new NioEventLoopGroup(nettyServerConfig.getIoThreads());\n }\n\n public void start() {\n try {\n ServerBootstrap serverBootstrap = new ServerBootstrap();\n\n serverBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class);\n serverBootstrap.option(ChannelOption.SO_BACKLOG, 1024)\n .childOption(ChannelOption.SO_KEEPALIVE, true);\n\n ChannelFuture channelFuture = serverBootstrap.childHandler(channelInitializer).bind(port).addListener((ChannelFutureListener) future -> {\n if (future.isSuccess()) {\n log.info(\"Netty started successfully on port {}\", port);\n } else {\n log.error(\"Failed to start server on port {}\", port, future.cause());\n close();\n }\n });\n channelFuture.channel().closeFuture().sync();\n } catch (InterruptedException e) {\n log.error(\"InterruptedException to start server on port {}\", port, e);\n } finally {\n close();\n }\n }\n\n public abstract void handleMessage(Channel channel, Object object);\n\n\n @Override\n public void close() {\n bossGroup.shutdownGracefully();\n workerGroup.shutdownGracefully();\n }\n}"
},
{
"identifier": "NettyServer",
"path": "netty-spring-boot-starter/src/main/java/io/github/gaojindeng/netty/server/NettyServer.java",
"snippet": "public class NettyServer extends AbstractNettyServer {\n private static final Logger log = LoggerFactory.getLogger(NettyServer.class);\n\n private NettyServerListener nettyServerListener;\n\n private NettyServerReplyListener nettyServerReplyListener;\n\n private final NettyServerExecutor nettyServerExecutor;\n\n private boolean started;\n\n public NettyServer(NettyServerConfig nettyServerConfig) {\n super(nettyServerConfig);\n this.nettyServerExecutor = new NettyServerExecutor(getName(), nettyServerConfig.getCorePoolSize(), nettyServerConfig.getMaxPoolSize());\n }\n\n public NettyServer(String name, NettyServerConfig nettyServerConfig) {\n super(nettyServerConfig);\n super.setName(name);\n this.nettyServerExecutor = new NettyServerExecutor(name, nettyServerConfig.getCorePoolSize(), nettyServerConfig.getMaxPoolSize());\n }\n\n\n @Override\n public void start() {\n Thread thread = new Thread(super::start);\n thread.setName(\"NettyServerThread-\" + getName());\n nettyServerExecutor.getExecutor().execute(thread);\n started = true;\n }\n\n @Override\n public void handleMessage(Channel channel, Object object) {\n nettyServerExecutor.getExecutor().execute(() -> {\n Object req = converterReq(object);\n if (nettyServerListener != null) {\n nettyServerListener.onMessage(req);\n } else if (nettyServerReplyListener != null) {\n Object response = converterRes(nettyServerReplyListener.onMessage(req));\n channel.writeAndFlush(response);\n } else {\n\n }\n });\n }\n\n public boolean isStarted() {\n return started;\n }\n\n public void setNettyServerListener(NettyServerListener nettyServerListener) {\n this.nettyServerListener = nettyServerListener;\n }\n\n public void setNettyServerReplyListener(NettyServerReplyListener nettyServerReplyListener) {\n this.nettyServerReplyListener = nettyServerReplyListener;\n }\n}"
}
] | import io.github.gaojindeng.netty.client.BaseNettyClient;
import io.github.gaojindeng.netty.client.LongNettyClient;
import io.github.gaojindeng.netty.client.NettyClient;
import io.github.gaojindeng.netty.client.ShortNettyClient;
import io.github.gaojindeng.netty.properties.NettyClientConfig;
import io.github.gaojindeng.netty.properties.NettyConfigProperties;
import io.github.gaojindeng.netty.properties.NettyServerConfig;
import io.github.gaojindeng.netty.server.AbstractNettyServer;
import io.github.gaojindeng.netty.server.NettyServer;
import org.springframework.beans.factory.DisposableBean;
import java.util.HashMap;
import java.util.Map; | 3,861 | package io.github.gaojindeng.netty;
/**
* @author gjd
*/
public class DefaultNettyContainer implements DisposableBean {
private NettyConfigProperties nettyConfigProperties;
private NettyServer defaultNettyServer;
private NettyClient defaultNettyClient;
private final Map<String, NettyServer> nettyServerMap = new HashMap<>();
private final Map<String, NettyClient> nettyClientMap = new HashMap<>();
public DefaultNettyContainer(NettyConfigProperties nettyConfigProperties) {
this.nettyConfigProperties = nettyConfigProperties;
initNettyServer(nettyConfigProperties.getServer());
initNettyClient(nettyConfigProperties.getClient());
}
private void initNettyClient(NettyConfigProperties.NettyClientProperties client) {
if (client == null) {
return;
}
defaultNettyClient = getDefaultNettyClient(client);
if (defaultNettyClient != null) {
nettyClientMap.put(((AbstractNetty) defaultNettyClient).getName(), defaultNettyClient);
}
Map<String, NettyClientConfig> configs = client.getConfigs();
if (configs != null) {
configs.forEach((name, value) -> {
NettyClient nettyClient;
if (value.isKeepConn()) {
nettyClient = new LongNettyClient(name, value);
} else {
nettyClient = new ShortNettyClient(name, value);
}
nettyClientMap.put(((AbstractNetty) nettyClient).getName(), nettyClient);
});
}
}
private void initNettyServer(NettyConfigProperties.NettyServerProperties server) {
if (server == null) {
return;
}
defaultNettyServer = getDefaultNettyServer(server);
if (defaultNettyServer != null) {
nettyServerMap.put(defaultNettyServer.getName(), defaultNettyServer);
}
Map<String, NettyServerConfig> configs = server.getConfigs();
if (configs != null) {
configs.forEach((name, value) -> {
NettyServer nettyServer = new NettyServer(name, value);
nettyServerMap.put(nettyServer.getName(), nettyServer);
});
}
}
private NettyServer getDefaultNettyServer(NettyServerConfig nettyServerConfig) {
Integer port = nettyServerConfig.getPort();
if (port == null) {
return null;
}
return new NettyServer(nettyServerConfig);
}
private NettyClient getDefaultNettyClient(NettyClientConfig nettyClientConfig) {
String host = nettyClientConfig.getHost();
Integer port = nettyClientConfig.getPort();
if (host == null || port == null) {
return null;
}
if (nettyClientConfig.isKeepConn()) {
return new LongNettyClient(nettyClientConfig);
} else {
return new ShortNettyClient(nettyClientConfig);
}
}
public NettyServer getNettyServer(String name) {
return nettyServerMap.get(name);
}
public NettyClient getNettyClient(String name) {
return nettyClientMap.get(name);
}
public Map<String, NettyServer> getNettyServerMap() {
return nettyServerMap;
}
public Map<String, NettyClient> getNettyClientMap() {
return nettyClientMap;
}
@Override
public void destroy() { | package io.github.gaojindeng.netty;
/**
* @author gjd
*/
public class DefaultNettyContainer implements DisposableBean {
private NettyConfigProperties nettyConfigProperties;
private NettyServer defaultNettyServer;
private NettyClient defaultNettyClient;
private final Map<String, NettyServer> nettyServerMap = new HashMap<>();
private final Map<String, NettyClient> nettyClientMap = new HashMap<>();
public DefaultNettyContainer(NettyConfigProperties nettyConfigProperties) {
this.nettyConfigProperties = nettyConfigProperties;
initNettyServer(nettyConfigProperties.getServer());
initNettyClient(nettyConfigProperties.getClient());
}
private void initNettyClient(NettyConfigProperties.NettyClientProperties client) {
if (client == null) {
return;
}
defaultNettyClient = getDefaultNettyClient(client);
if (defaultNettyClient != null) {
nettyClientMap.put(((AbstractNetty) defaultNettyClient).getName(), defaultNettyClient);
}
Map<String, NettyClientConfig> configs = client.getConfigs();
if (configs != null) {
configs.forEach((name, value) -> {
NettyClient nettyClient;
if (value.isKeepConn()) {
nettyClient = new LongNettyClient(name, value);
} else {
nettyClient = new ShortNettyClient(name, value);
}
nettyClientMap.put(((AbstractNetty) nettyClient).getName(), nettyClient);
});
}
}
private void initNettyServer(NettyConfigProperties.NettyServerProperties server) {
if (server == null) {
return;
}
defaultNettyServer = getDefaultNettyServer(server);
if (defaultNettyServer != null) {
nettyServerMap.put(defaultNettyServer.getName(), defaultNettyServer);
}
Map<String, NettyServerConfig> configs = server.getConfigs();
if (configs != null) {
configs.forEach((name, value) -> {
NettyServer nettyServer = new NettyServer(name, value);
nettyServerMap.put(nettyServer.getName(), nettyServer);
});
}
}
private NettyServer getDefaultNettyServer(NettyServerConfig nettyServerConfig) {
Integer port = nettyServerConfig.getPort();
if (port == null) {
return null;
}
return new NettyServer(nettyServerConfig);
}
private NettyClient getDefaultNettyClient(NettyClientConfig nettyClientConfig) {
String host = nettyClientConfig.getHost();
Integer port = nettyClientConfig.getPort();
if (host == null || port == null) {
return null;
}
if (nettyClientConfig.isKeepConn()) {
return new LongNettyClient(nettyClientConfig);
} else {
return new ShortNettyClient(nettyClientConfig);
}
}
public NettyServer getNettyServer(String name) {
return nettyServerMap.get(name);
}
public NettyClient getNettyClient(String name) {
return nettyClientMap.get(name);
}
public Map<String, NettyServer> getNettyServerMap() {
return nettyServerMap;
}
public Map<String, NettyClient> getNettyClientMap() {
return nettyClientMap;
}
@Override
public void destroy() { | nettyServerMap.values().forEach(AbstractNettyServer::close); | 7 | 2023-12-03 13:11:09+00:00 | 8k |
binance/binance-sbe-java-sample-app | src/main/java/com/binance/sbe/sbesampleapp/SymbolFilters.java | [
{
"identifier": "asBool",
"path": "src/main/java/com/binance/sbe/sbesampleapp/Util.java",
"snippet": "public static boolean asBool(BoolEnum value) {\n switch (value) {\n case True:\n return true;\n case False:\n return false;\n case NULL_VAL: {\n System.err.println(\"Unexpectedly got `NULL_VAL` for BoolEnum\");\n System.exit(1);\n }\n }\n return false;\n}"
},
{
"identifier": "BoolEnum",
"path": "src/main/java/spot_sbe/BoolEnum.java",
"snippet": "@SuppressWarnings(\"all\")\npublic enum BoolEnum\n{\n False((short)0),\n\n True((short)1),\n\n /**\n * To be used to represent not present or null.\n */\n NULL_VAL((short)255);\n\n private final short value;\n\n BoolEnum(final short value)\n {\n this.value = value;\n }\n\n /**\n * The raw encoded value in the Java type representation.\n *\n * @return the raw value encoded.\n */\n public short value()\n {\n return value;\n }\n\n /**\n * Lookup the enum value representing the value.\n *\n * @param value encoded to be looked up.\n * @return the enum value representing the value.\n */\n public static BoolEnum get(final short value)\n {\n switch (value)\n {\n case 0: return False;\n case 1: return True;\n case 255: return NULL_VAL;\n }\n\n throw new IllegalArgumentException(\"Unknown value: \" + value);\n }\n}"
},
{
"identifier": "FilterType",
"path": "src/main/java/spot_sbe/FilterType.java",
"snippet": "@SuppressWarnings(\"all\")\npublic enum FilterType\n{\n MaxPosition((short)0),\n\n PriceFilter((short)1),\n\n TPlusSell((short)2),\n\n LotSize((short)3),\n\n MaxNumOrders((short)4),\n\n MinNotional((short)5),\n\n MaxNumAlgoOrders((short)6),\n\n ExchangeMaxNumOrders((short)7),\n\n ExchangeMaxNumAlgoOrders((short)8),\n\n IcebergParts((short)9),\n\n MarketLotSize((short)10),\n\n PercentPrice((short)11),\n\n MaxNumIcebergOrders((short)12),\n\n ExchangeMaxNumIcebergOrders((short)13),\n\n TrailingDelta((short)14),\n\n PercentPriceBySide((short)15),\n\n Notional((short)16),\n\n /**\n * To be used to represent not present or null.\n */\n NULL_VAL((short)255);\n\n private final short value;\n\n FilterType(final short value)\n {\n this.value = value;\n }\n\n /**\n * The raw encoded value in the Java type representation.\n *\n * @return the raw value encoded.\n */\n public short value()\n {\n return value;\n }\n\n /**\n * Lookup the enum value representing the value.\n *\n * @param value encoded to be looked up.\n * @return the enum value representing the value.\n */\n public static FilterType get(final short value)\n {\n switch (value)\n {\n case 0: return MaxPosition;\n case 1: return PriceFilter;\n case 2: return TPlusSell;\n case 3: return LotSize;\n case 4: return MaxNumOrders;\n case 5: return MinNotional;\n case 6: return MaxNumAlgoOrders;\n case 7: return ExchangeMaxNumOrders;\n case 8: return ExchangeMaxNumAlgoOrders;\n case 9: return IcebergParts;\n case 10: return MarketLotSize;\n case 11: return PercentPrice;\n case 12: return MaxNumIcebergOrders;\n case 13: return ExchangeMaxNumIcebergOrders;\n case 14: return TrailingDelta;\n case 15: return PercentPriceBySide;\n case 16: return Notional;\n case 255: return NULL_VAL;\n }\n\n throw new IllegalArgumentException(\"Unknown value: \" + value);\n }\n}"
},
{
"identifier": "TPlusSellFilterDecoder",
"path": "src/main/java/spot_sbe/TPlusSellFilterDecoder.java",
"snippet": "@SuppressWarnings(\"all\")\npublic final class TPlusSellFilterDecoder\n{\n public static final int BLOCK_LENGTH = 8;\n public static final int TEMPLATE_ID = 14;\n public static final int SCHEMA_ID = 1;\n public static final int SCHEMA_VERSION = 0;\n public static final String SEMANTIC_VERSION = \"5.2\";\n public static final java.nio.ByteOrder BYTE_ORDER = java.nio.ByteOrder.LITTLE_ENDIAN;\n\n private final TPlusSellFilterDecoder parentMessage = this;\n private DirectBuffer buffer;\n private int initialOffset;\n private int offset;\n private int limit;\n int actingBlockLength;\n int actingVersion;\n\n public int sbeBlockLength()\n {\n return BLOCK_LENGTH;\n }\n\n public int sbeTemplateId()\n {\n return TEMPLATE_ID;\n }\n\n public int sbeSchemaId()\n {\n return SCHEMA_ID;\n }\n\n public int sbeSchemaVersion()\n {\n return SCHEMA_VERSION;\n }\n\n public String sbeSemanticType()\n {\n return \"\";\n }\n\n public DirectBuffer buffer()\n {\n return buffer;\n }\n\n public int initialOffset()\n {\n return initialOffset;\n }\n\n public int offset()\n {\n return offset;\n }\n\n public TPlusSellFilterDecoder wrap(\n final DirectBuffer buffer,\n final int offset,\n final int actingBlockLength,\n final int actingVersion)\n {\n if (buffer != this.buffer)\n {\n this.buffer = buffer;\n }\n this.initialOffset = offset;\n this.offset = offset;\n this.actingBlockLength = actingBlockLength;\n this.actingVersion = actingVersion;\n limit(offset + actingBlockLength);\n\n return this;\n }\n\n public TPlusSellFilterDecoder wrapAndApplyHeader(\n final DirectBuffer buffer,\n final int offset,\n final MessageHeaderDecoder headerDecoder)\n {\n headerDecoder.wrap(buffer, offset);\n\n final int templateId = headerDecoder.templateId();\n if (TEMPLATE_ID != templateId)\n {\n throw new IllegalStateException(\"Invalid TEMPLATE_ID: \" + templateId);\n }\n\n return wrap(\n buffer,\n offset + MessageHeaderDecoder.ENCODED_LENGTH,\n headerDecoder.blockLength(),\n headerDecoder.version());\n }\n\n public TPlusSellFilterDecoder sbeRewind()\n {\n return wrap(buffer, initialOffset, actingBlockLength, actingVersion);\n }\n\n public int sbeDecodedLength()\n {\n final int currentLimit = limit();\n sbeSkip();\n final int decodedLength = encodedLength();\n limit(currentLimit);\n\n return decodedLength;\n }\n\n public int actingVersion()\n {\n return actingVersion;\n }\n\n public int encodedLength()\n {\n return limit - offset;\n }\n\n public int limit()\n {\n return limit;\n }\n\n public void limit(final int limit)\n {\n this.limit = limit;\n }\n\n public static int filterTypeId()\n {\n return 1;\n }\n\n public static int filterTypeSinceVersion()\n {\n return 0;\n }\n\n public static int filterTypeEncodingOffset()\n {\n return 0;\n }\n\n public static int filterTypeEncodingLength()\n {\n return 1;\n }\n\n public static String filterTypeMetaAttribute(final MetaAttribute metaAttribute)\n {\n if (MetaAttribute.PRESENCE == metaAttribute)\n {\n return \"constant\";\n }\n\n return \"\";\n }\n\n public short filterTypeRaw()\n {\n return FilterType.TPlusSell.value();\n }\n\n\n public FilterType filterType()\n {\n return FilterType.TPlusSell;\n }\n\n\n public static int endTimeId()\n {\n return 2;\n }\n\n public static int endTimeSinceVersion()\n {\n return 0;\n }\n\n public static int endTimeEncodingOffset()\n {\n return 0;\n }\n\n public static int endTimeEncodingLength()\n {\n return 8;\n }\n\n public static String endTimeMetaAttribute(final MetaAttribute metaAttribute)\n {\n if (MetaAttribute.PRESENCE == metaAttribute)\n {\n return \"optional\";\n }\n\n return \"\";\n }\n\n public static long endTimeNullValue()\n {\n return -9223372036854775808L;\n }\n\n public static long endTimeMinValue()\n {\n return -9223372036854775807L;\n }\n\n public static long endTimeMaxValue()\n {\n return 9223372036854775807L;\n }\n\n public long endTime()\n {\n return buffer.getLong(offset + 0, java.nio.ByteOrder.LITTLE_ENDIAN);\n }\n\n\n public String toString()\n {\n if (null == buffer)\n {\n return \"\";\n }\n\n final TPlusSellFilterDecoder decoder = new TPlusSellFilterDecoder();\n decoder.wrap(buffer, initialOffset, actingBlockLength, actingVersion);\n\n return decoder.appendTo(new StringBuilder()).toString();\n }\n\n public StringBuilder appendTo(final StringBuilder builder)\n {\n if (null == buffer)\n {\n return builder;\n }\n\n final int originalLimit = limit();\n limit(initialOffset + actingBlockLength);\n builder.append(\"[TPlusSellFilter](sbeTemplateId=\");\n builder.append(TEMPLATE_ID);\n builder.append(\"|sbeSchemaId=\");\n builder.append(SCHEMA_ID);\n builder.append(\"|sbeSchemaVersion=\");\n if (parentMessage.actingVersion != SCHEMA_VERSION)\n {\n builder.append(parentMessage.actingVersion);\n builder.append('/');\n }\n builder.append(SCHEMA_VERSION);\n builder.append(\"|sbeBlockLength=\");\n if (actingBlockLength != BLOCK_LENGTH)\n {\n builder.append(actingBlockLength);\n builder.append('/');\n }\n builder.append(BLOCK_LENGTH);\n builder.append(\"):\");\n builder.append(\"filterType=\");\n builder.append(this.filterType());\n builder.append('|');\n builder.append(\"endTime=\");\n builder.append(this.endTime());\n\n limit(originalLimit);\n\n return builder;\n }\n \n public TPlusSellFilterDecoder sbeSkip()\n {\n sbeRewind();\n\n return this;\n }\n}"
}
] | import java.util.Optional;
import static com.binance.sbe.sbesampleapp.Util.asBool;
import spot_sbe.BoolEnum;
import spot_sbe.FilterType;
import spot_sbe.TPlusSellFilterDecoder; | 4,270 | }
}
public static class NotionalFilter {
public final FilterType filterType;
public final Decimal minNotional;
public final boolean applyMinToMarket;
public final Decimal maxNotional;
public final boolean applyMaxToMarket;
public final int avgPriceMins;
NotionalFilter(
FilterType filterType,
byte exponent,
long minNotional,
BoolEnum applyMinToMarket,
long maxNotional,
BoolEnum applyMaxToMarket,
int avgPriceMins) {
this.filterType = filterType;
this.minNotional = new Decimal(minNotional, exponent);
this.applyMinToMarket = asBool(applyMinToMarket);
this.maxNotional = new Decimal(maxNotional, exponent);
this.applyMaxToMarket = asBool(applyMaxToMarket);
this.avgPriceMins = avgPriceMins;
}
}
public static class IcebergPartsFilter {
public final FilterType filterType;
public final long filterLimit;
IcebergPartsFilter(FilterType filterType, long filterLimit) {
this.filterType = filterType;
this.filterLimit = filterLimit;
}
}
public static class MarketLotSizeFilter {
public final FilterType filterType;
public final Decimal minQty;
public final Decimal maxQty;
public final Decimal stepSize;
MarketLotSizeFilter(
FilterType filterType, byte exponent, long minQty, long maxQty, long stepSize) {
this.filterType = filterType;
this.minQty = new Decimal(minQty, exponent);
this.maxQty = new Decimal(maxQty, exponent);
this.stepSize = new Decimal(stepSize, exponent);
}
}
public static class MaxNumOrdersFilter {
public final FilterType filterType;
public final long maxNumOrders;
MaxNumOrdersFilter(FilterType filterType, long maxNumOrders) {
this.filterType = filterType;
this.maxNumOrders = maxNumOrders;
}
}
public static class MaxNumAlgoOrdersFilter {
public final FilterType filterType;
public final long maxNumAlgoOrders;
MaxNumAlgoOrdersFilter(FilterType filterType, long maxNumAlgoOrders) {
this.filterType = filterType;
this.maxNumAlgoOrders = maxNumAlgoOrders;
}
}
public static class MaxNumIcebergOrdersFilter {
public final FilterType filterType;
public final long maxNumIcebergOrders;
MaxNumIcebergOrdersFilter(FilterType filterType, long maxNumIcebergOrders) {
this.filterType = filterType;
this.maxNumIcebergOrders = maxNumIcebergOrders;
}
}
public static class MaxPositionFilter {
public final FilterType filterType;
public final Decimal maxPosition;
MaxPositionFilter(FilterType filterType, byte exponent, long maxPosition) {
this.filterType = filterType;
this.maxPosition = new Decimal(maxPosition, exponent);
}
}
public static class TrailingDeltaFilter {
public final FilterType filterType;
public final long minTrailingAboveDelta;
public final long maxTrailingAboveDelta;
public final long minTrailingBelowDelta;
public final long maxTrailingBelowDelta;
TrailingDeltaFilter(
FilterType filterType,
long minTrailingAboveDelta,
long maxTrailingAboveDelta,
long minTrailingBelowDelta,
long maxTrailingBelowDelta) {
this.filterType = filterType;
this.minTrailingAboveDelta = minTrailingAboveDelta;
this.maxTrailingAboveDelta = maxTrailingAboveDelta;
this.minTrailingBelowDelta = minTrailingBelowDelta;
this.maxTrailingBelowDelta = maxTrailingBelowDelta;
}
}
public static class TPlusSellFilter {
public final FilterType filterType;
public final Optional<Long> endTime;
TPlusSellFilter(FilterType filterType, long endTime) {
this.filterType = filterType; | package com.binance.sbe.sbesampleapp;
public class SymbolFilters {
public static class PriceFilter {
public final FilterType filterType;
public final Decimal minPrice;
public final Decimal maxPrice;
public final Decimal tickSize;
public PriceFilter(
FilterType filterType, byte exponent, long minPrice, long maxPrice, long tickSize) {
this.filterType = filterType;
this.minPrice = new Decimal(minPrice, exponent);
this.maxPrice = new Decimal(maxPrice, exponent);
this.tickSize = new Decimal(tickSize, exponent);
}
}
public static class PercentPriceFilter {
public final FilterType filterType;
public final Decimal multiplierUp;
public final Decimal multiplierDown;
public final int avgPriceMins;
PercentPriceFilter(
FilterType filterType,
byte exponent,
long multiplierUp,
long multiplierDown,
int avgPriceMins) {
this.filterType = filterType;
this.multiplierUp = new Decimal(multiplierUp, exponent);
this.multiplierDown = new Decimal(multiplierDown, exponent);
this.avgPriceMins = avgPriceMins;
}
}
public static class PercentPriceBySideFilter {
public final FilterType filterType;
public final Decimal bidMultiplierUp;
public final Decimal bidMultiplierDown;
public final Decimal askMultiplierUp;
public final Decimal askMultiplierDown;
public final int avgPriceMins;
PercentPriceBySideFilter(
FilterType filterType,
byte exponent,
long bidMultiplierUp,
long bidMultiplierDown,
long askMultiplierUp,
long askMultiplierDown,
int avgPriceMins) {
this.filterType = filterType;
this.bidMultiplierUp = new Decimal(bidMultiplierUp, exponent);
this.bidMultiplierDown = new Decimal(bidMultiplierDown, exponent);
this.askMultiplierUp = new Decimal(askMultiplierUp, exponent);
this.askMultiplierDown = new Decimal(askMultiplierDown, exponent);
this.avgPriceMins = avgPriceMins;
}
}
public static class LotSizeFilter {
public final FilterType filterType;
public final Decimal minQty;
public final Decimal maxQty;
public final Decimal stepSize;
LotSizeFilter(FilterType filterType, byte exponent, long minQty, long maxQty, long stepSize) {
this.filterType = filterType;
this.minQty = new Decimal(minQty, exponent);
this.maxQty = new Decimal(maxQty, exponent);
this.stepSize = new Decimal(stepSize, exponent);
}
}
public static class MinNotionalFilter {
public final FilterType filterType;
public final Decimal minNotional;
public final boolean applyToMarket;
public final int avgPriceMins;
MinNotionalFilter(
FilterType filterType,
byte exponent,
long minNotional,
BoolEnum applyToMarket,
int avgPriceMins) {
this.filterType = filterType;
this.minNotional = new Decimal(minNotional, exponent);
this.applyToMarket = asBool(applyToMarket);
this.avgPriceMins = avgPriceMins;
}
}
public static class NotionalFilter {
public final FilterType filterType;
public final Decimal minNotional;
public final boolean applyMinToMarket;
public final Decimal maxNotional;
public final boolean applyMaxToMarket;
public final int avgPriceMins;
NotionalFilter(
FilterType filterType,
byte exponent,
long minNotional,
BoolEnum applyMinToMarket,
long maxNotional,
BoolEnum applyMaxToMarket,
int avgPriceMins) {
this.filterType = filterType;
this.minNotional = new Decimal(minNotional, exponent);
this.applyMinToMarket = asBool(applyMinToMarket);
this.maxNotional = new Decimal(maxNotional, exponent);
this.applyMaxToMarket = asBool(applyMaxToMarket);
this.avgPriceMins = avgPriceMins;
}
}
public static class IcebergPartsFilter {
public final FilterType filterType;
public final long filterLimit;
IcebergPartsFilter(FilterType filterType, long filterLimit) {
this.filterType = filterType;
this.filterLimit = filterLimit;
}
}
public static class MarketLotSizeFilter {
public final FilterType filterType;
public final Decimal minQty;
public final Decimal maxQty;
public final Decimal stepSize;
MarketLotSizeFilter(
FilterType filterType, byte exponent, long minQty, long maxQty, long stepSize) {
this.filterType = filterType;
this.minQty = new Decimal(minQty, exponent);
this.maxQty = new Decimal(maxQty, exponent);
this.stepSize = new Decimal(stepSize, exponent);
}
}
public static class MaxNumOrdersFilter {
public final FilterType filterType;
public final long maxNumOrders;
MaxNumOrdersFilter(FilterType filterType, long maxNumOrders) {
this.filterType = filterType;
this.maxNumOrders = maxNumOrders;
}
}
public static class MaxNumAlgoOrdersFilter {
public final FilterType filterType;
public final long maxNumAlgoOrders;
MaxNumAlgoOrdersFilter(FilterType filterType, long maxNumAlgoOrders) {
this.filterType = filterType;
this.maxNumAlgoOrders = maxNumAlgoOrders;
}
}
public static class MaxNumIcebergOrdersFilter {
public final FilterType filterType;
public final long maxNumIcebergOrders;
MaxNumIcebergOrdersFilter(FilterType filterType, long maxNumIcebergOrders) {
this.filterType = filterType;
this.maxNumIcebergOrders = maxNumIcebergOrders;
}
}
public static class MaxPositionFilter {
public final FilterType filterType;
public final Decimal maxPosition;
MaxPositionFilter(FilterType filterType, byte exponent, long maxPosition) {
this.filterType = filterType;
this.maxPosition = new Decimal(maxPosition, exponent);
}
}
public static class TrailingDeltaFilter {
public final FilterType filterType;
public final long minTrailingAboveDelta;
public final long maxTrailingAboveDelta;
public final long minTrailingBelowDelta;
public final long maxTrailingBelowDelta;
TrailingDeltaFilter(
FilterType filterType,
long minTrailingAboveDelta,
long maxTrailingAboveDelta,
long minTrailingBelowDelta,
long maxTrailingBelowDelta) {
this.filterType = filterType;
this.minTrailingAboveDelta = minTrailingAboveDelta;
this.maxTrailingAboveDelta = maxTrailingAboveDelta;
this.minTrailingBelowDelta = minTrailingBelowDelta;
this.maxTrailingBelowDelta = maxTrailingBelowDelta;
}
}
public static class TPlusSellFilter {
public final FilterType filterType;
public final Optional<Long> endTime;
TPlusSellFilter(FilterType filterType, long endTime) {
this.filterType = filterType; | if (endTime == TPlusSellFilterDecoder.endTimeNullValue()) { | 3 | 2023-11-27 09:46:42+00:00 | 8k |
hmcts/juror-sql-support-library | src/main/java/uk/gov/hmcts/juror/support/sql/generators/JurorPoolGeneratorUtil.java | [
{
"identifier": "ExcusableCode",
"path": "src/main/java/uk/gov/hmcts/juror/support/sql/entity/ExcusableCode.java",
"snippet": "@Getter\npublic enum ExcusableCode {\n\n CRIMINAL_RECORD(\"K\"),\n DECEASED(\"D\"),\n OVER_69(\"V\"),\n RECENTLY_SERVED(\"S\"),\n THE_FORCES(\"F\"),\n MEDICAL_PROFESSION(\"H\"),\n POSTPONEMENT_OF_SERVICE(\"P\"),\n RELIGIOUS_REASONS(\"R\"),\n CHILD_CARE(\"C\"),\n WORK_RELATED(\"W\"),\n MEDICAL(\"M\"),\n TRAVELLING_DIFFICULTIES(\"T\"),\n MOVED_FROM_AREA(\"A\"),\n OTHER(\"O\"),\n STUDENT(\"B\"),\n LANGUAGE_DIFFICULTIES(\"L\"),\n PARLIAMENT_EUROPEAN_ASSEMBLY(\"E\"),\n HOLIDAY(\"Y\"),\n CARER(\"X\"),\n FINANCIAL_HARDSHIP(\"G\"),\n BEREAVEMENT(\"Z\"),\n EXCUSE_BY_BUREAU_TOO_MANY_JURORS(\"J\"),\n ILL(\"I\"),\n MENTAL_HEALTH(\"N\");\n\n private final String code;\n\n ExcusableCode(String code) {\n this.code = code;\n }\n}"
},
{
"identifier": "Juror",
"path": "src/main/java/uk/gov/hmcts/juror/support/sql/entity/Juror.java",
"snippet": "@Entity\n@Table(name = \"juror\", schema = \"juror_mod\")\n@NoArgsConstructor\n@Getter\n@Setter\n@ToString\n@GenerateGenerationConfig\npublic class Juror implements Serializable {\n\n @Id\n ////@Audited\n ////@NotBlank\n @Column(name = \"juror_number\")\n ////@Pattern(regexp = JUROR_NUMBER)\n ////@Length(max = 9)\n @StringSequenceGenerator(format = \"%09d\",\n sequenceGenerator = @SequenceGenerator(id = \"juror_number\", start = 1)\n )\n private String jurorNumber;\n\n @Column(name = \"poll_number\")\n //@Length(max = 5)\n private String pollNumber;\n\n //@Audited\n @Column(name = \"title\")\n //@Length(max = 10)\n //@Pattern(regexp = NO_PIPES_REGEX)\n @RandomFromFileGenerator(file = \"data/titles.txt\")\n private String title;\n\n //@Audited\n @Column(name = \"first_name\")\n //@Length(max = 20)\n //@Pattern(regexp = NO_PIPES_REGEX)\n //@NotBlank\n @FirstNameGenerator\n private String firstName;\n\n //@Audited\n @Column(name = \"last_name\")\n //@Length(max = 20)\n //@Pattern(regexp = NO_PIPES_REGEX)\n //@NotBlank\n @LastNameGenerator\n private String lastName;\n\n //@Audited\n @Column(name = \"dob\")\n @LocalDateGenerator(\n minInclusive = @DateFilter(mode = DateFilter.Mode.MINUS, value = 75, unit = ChronoUnit.YEARS),\n maxExclusive = @DateFilter(mode = DateFilter.Mode.MINUS, value = 18, unit = ChronoUnit.YEARS)\n )\n private LocalDate dateOfBirth;\n\n //@Audited\n @Column(name = \"address_line_1\")\n @RegexGenerator(regex = Constants.ADDRESS_LINE_1_REGEX)\n private String addressLine1;\n\n //@Audited\n @Column(name = \"address_line_2\")\n @RegexGenerator(regex = Constants.ADDRESS_LINE_2_REGEX)\n private String addressLine2;\n\n //@Audited\n @Column(name = \"address_line_3\")\n //@Length(max = 35)\n //@Pattern(regexp = NO_PIPES_REGEX)\n @RandomFromFileGenerator(file = \"data/city.txt\")\n private String addressLine3;\n\n //@Audited\n @Column(name = \"address_line_4\")\n //@Length(max = 35)\n //@Pattern(regexp = NO_PIPES_REGEX)\n @RandomFromFileGenerator(file = \"data/county.txt\")\n private String addressLine4;\n\n //@Audited\n @Column(name = \"address_line_5\")\n //@Length(max = 35)\n //@Pattern(regexp = NO_PIPES_REGEX)\n @NullValueGenerator\n private String addressLine5;\n\n //@Audited\n @Column(name = \"postcode\")\n //@Length(max = 10)\n //@Pattern(regexp = POSTCODE_REGEX)\n @RandomFromFileGenerator(file = \"data/postcode.txt\")\n private String postcode;\n\n //@Audited\n @Column(name = \"h_phone\")\n //@Length(max = 15)\n @RegexGenerator(regex = Constants.PHONE_REGEX)\n private String phoneNumber;\n\n //@Audited\n @Column(name = \"w_phone\")\n //@Length(max = 15)\n @RegexGenerator(regex = Constants.PHONE_REGEX)\n private String workPhone;\n\n //@Audited\n @Column(name = \"w_ph_local\")\n //@Length(max = 4)\n private String workPhoneExtension;\n\n //@NotNull\n @Column(name = \"responded\")\n @FixedValueGenerator(value = \"true\")\n private boolean responded;\n\n @Column(name = \"date_excused\")\n private LocalDate excusalDate;\n\n //@Length(max = 1)\n @Column(name = \"excusal_code\")\n private String excusalCode;\n\n @Column(name = \"acc_exc\")\n private String excusalRejected;\n\n @Column(name = \"date_disq\")\n private LocalDate disqualifyDate;\n\n //@Length(max = 1)\n @Column(name = \"disq_code\")\n private String disqualifyCode;\n\n @Column(name = \"user_edtq\")\n //@Length(max = 20)\n private String userEdtq;\n\n //@Length(max = 2000)\n @Column(name = \"notes\")\n @RegexGenerator(regex = Constants.NOTES_REGEX)\n private String notes;\n\n @Column(name = \"no_def_pos\")\n private Integer noDefPos;\n\n @Column(name = \"perm_disqual\")\n private Boolean permanentlyDisqualify;\n\n //@Length(max = 1)\n @Column(name = \"reasonable_adj_code\")\n private String reasonableAdjustmentCode;\n\n //@Length(max = 60)\n @Column(name = \"reasonable_adj_msg\")\n private String reasonableAdjustmentMessage;\n\n //@Length(max = 20)\n @Column(name = \"smart_card\")\n private String smartCard;\n\n @Column(name = \"completion_date\")\n private LocalDate completionDate;\n\n //@Audited\n @Column(name = \"sort_code\")\n //@Length(max = 6)\n private String sortCode;\n\n //@Audited\n @Column(name = \"bank_acct_name\")\n //@Length(max = 18)\n private String bankAccountName;\n\n //@Audited\n @Column(name = \"bank_acct_no\")\n //@Length(max = 8)\n private String bankAccountNumber;\n\n //@Audited\n @Column(name = \"bldg_soc_roll_no\")\n //@Length(max = 18)\n private String buildingSocietyRollNumber;\n\n @Column(name = \"welsh\")\n private Boolean welsh;\n\n @Column(name = \"police_check\")\n @Enumerated(EnumType.STRING)\n private PoliceCheck policeCheck;\n\n //@Length(max = 20)\n @Column(name = \"summons_file\")\n private String summonsFile;\n\n //@Audited\n @Column(name = \"m_phone\")\n //@Length(max = 15)\n private String altPhoneNumber;\n\n //@Audited\n //@Length(max = 254)\n @Column(name = \"h_email\")\n @EmailGenerator\n private String email;\n\n @Column(name = \"contact_preference\")\n private Integer contactPreference;\n\n @Column(name = \"notifications\")\n private int notifications;\n\n //@LastModifiedDate\n @Column(name = \"last_update\")\n private LocalDateTime lastUpdate;\n\n //@CreatedDate\n @Column(name = \"date_created\", updatable = false)\n private LocalDateTime dateCreated;\n\n @Column(name = \"optic_reference\")\n //@Length(max = 8)\n private String opticRef;\n\n //@Audited\n @Column(name = \"pending_title\")\n //@Length(max = 10)\n //@Pattern(regexp = NO_PIPES_REGEX)\n private String pendingTitle;\n\n //@Audited\n @Column(name = \"pending_first_name\")\n //@Length(max = 20)\n //@Pattern(regexp = NO_PIPES_REGEX)\n private String pendingFirstName;\n\n //@Audited\n @Column(name = \"pending_last_name\")\n //@Length(max = 20)\n //@Pattern(regexp = NO_PIPES_REGEX)\n private String pendingLastName;\n}"
},
{
"identifier": "JurorStatus",
"path": "src/main/java/uk/gov/hmcts/juror/support/sql/entity/JurorStatus.java",
"snippet": "@Getter\npublic enum JurorStatus {\n SUMMONED(1),\n RESPONDED(2),\n PANEL(3),\n JUROR(4),\n EXCUSED(5),\n DISQUALIFIED(6),\n DEFERRED(7),\n REASSIGNED(8),\n TRANSFERRED(10),\n ADDITIONAL_INFO(11),\n FAILED_TO_ATTEND(12),\n COMPLETED(13);\n\n private final int id;\n\n JurorStatus(int id) {\n this.id = id;\n }\n}"
},
{
"identifier": "PoolRequest",
"path": "src/main/java/uk/gov/hmcts/juror/support/sql/entity/PoolRequest.java",
"snippet": "@Entity\n@Table(name = \"pool\", schema = \"juror_mod\")\n@NoArgsConstructor\n@Getter\n@Setter\n@ToString\n@GenerateGenerationConfig\npublic class PoolRequest implements Serializable {\n\n @Id\n// @NotNull\n @Column(name = \"pool_no\")\n// @Length(max = 9)\n @StringSequenceGenerator(format = \"%09d\",\n sequenceGenerator = @SequenceGenerator(id = \"pool_number\", start = 1)\n )\n private String poolNumber;\n\n\n // @NotNull\n @Column(name = \"owner\")\n// @Length(max = 3)\n private String owner;\n\n @ManyToOne\n @JoinColumn(name = \"loc_code\", nullable = false)\n private CourtLocation courtLocation;\n\n // @NotNull\n @Column(name = \"return_date\")\n @LocalDateGenerator(\n minInclusive = @DateFilter(mode = DateFilter.Mode.MINUS, value = 1, unit = ChronoUnit.DAYS),\n maxExclusive = @DateFilter(mode = DateFilter.Mode.PLUS, value = 14, unit = ChronoUnit.DAYS)\n )\n private LocalDate returnDate;\n\n @Column(name = \"no_requested\")\n private Integer numberRequested;\n\n private String poolType;\n\n @Column(name = \"attend_time\")\n private LocalDateTime attendTime;\n\n @Column(name = \"new_request\")\n private Character newRequest;\n\n @Column(name = \"last_update\")\n private LocalDateTime lastUpdate;\n\n @Column(name = \"additional_summons\")\n private Integer additionalSummons;\n\n @Column(name = \"total_no_required\")\n private int totalNoRequired;\n\n @Column(name = \"nil_pool\")\n private boolean nilPool;\n\n @Column(name = \"date_created\", updatable = false)\n private LocalDateTime dateCreated;\n}"
},
{
"identifier": "SqlSupportService",
"path": "src/main/java/uk/gov/hmcts/juror/support/sql/service/SqlSupportService.java",
"snippet": "@Component\n@RequiredArgsConstructor(onConstructor = @__(@Autowired))\n@Slf4j\npublic class SqlSupportService {\n private final JurorRepository jurorRepository;\n private final PoolRequestRepository poolRequestRepository;\n private final JurorPoolRepository jurorPoolRepository;\n private final DigitalResponseRepository digitalResponseRepository;\n private final PaperResponseRepository paperResponseRepository;\n private StopWatch stopWatch;\n\n private final CourtLocationRepository courtLocationRepository;\n\n\n private static final List<CourtLocation> courtLocations;\n private static final Set<String> courtOwners;\n private static final int BATCH_SIZE = 100;\n\n static {\n courtLocations = new ArrayList<>();\n courtOwners = new HashSet<>();\n }\n\n\n public static List<CourtLocation> getCourtLocations() {\n return Collections.unmodifiableList(courtLocations);\n }\n\n public static Set<String> getCourtOwners() {\n return Collections.unmodifiableSet(courtOwners);\n }\n\n\n @PostConstruct\n //Temporary for testing purposes\n public void postConstruct() {\n this.stopWatch = new StopWatch();\n courtLocationRepository.findAll().forEach(courtLocations::add);\n courtOwners.add(\"400\");\n courtOwners.add(\"415\");\n //TODO add back courtLocations.forEach(courtLocation -> courtOwners.add(courtLocation.getOwner()));\n clearDownDatabase();\n Map<JurorStatus, Integer> jurorStatusCountMapCourt = new EnumMap<>(JurorStatus.class);\n jurorStatusCountMapCourt.put(JurorStatus.DEFERRED, 12585);\n jurorStatusCountMapCourt.put(JurorStatus.DISQUALIFIED, 126);\n jurorStatusCountMapCourt.put(JurorStatus.EXCUSED, 15607);\n jurorStatusCountMapCourt.put(JurorStatus.FAILED_TO_ATTEND, 705);\n jurorStatusCountMapCourt.put(JurorStatus.JUROR, 3916);\n jurorStatusCountMapCourt.put(JurorStatus.PANEL, 472);\n jurorStatusCountMapCourt.put(JurorStatus.REASSIGNED, 41313);\n jurorStatusCountMapCourt.put(JurorStatus.RESPONDED, 208525);\n jurorStatusCountMapCourt.put(JurorStatus.SUMMONED, 56443);\n jurorStatusCountMapCourt.put(JurorStatus.TRANSFERRED, 1075);\n\n //TODO uncomment createJurorsAssociatedToPools(true, 12, 16, jurorStatusCountMapCourt);\n\n //TODO remove\n Map<JurorStatus, Integer> jurorStatusCountMapCourtTmp = new EnumMap<>(JurorStatus.class);\n jurorStatusCountMapCourtTmp.put(JurorStatus.SUMMONED, 100);\n jurorStatusCountMapCourtTmp.put(JurorStatus.RESPONDED, 100);\n jurorStatusCountMapCourtTmp.put(JurorStatus.DEFERRED, 100);\n jurorStatusCountMapCourtTmp.put(JurorStatus.EXCUSED, 100);\n //TODO remove end\n createJurorsAssociatedToPools(true, 12, 16, jurorStatusCountMapCourtTmp);\n\n log.info(\"DONE: \" + stopWatch.prettyPrint());\n }\n\n private void clearDownDatabase() {\n log.info(\"Clearing database\");\n stopWatch.start(\"Cleaning database\");\n jurorPoolRepository.deleteAll();\n poolRequestRepository.deleteAll();\n digitalResponseRepository.deleteAll();\n paperResponseRepository.deleteAll();\n jurorRepository.deleteAll();\n stopWatch.stop();\n log.info(\"Clearing database: DONE\");\n }\n\n\n public void createJurorsAssociatedToPools(boolean isCourtOwned, int jurorsInPoolMinimumInclusive,\n int jurorsInPoolMaximumExclusive,\n Map<JurorStatus, Integer> jurorStatusCountMap) {\n final int totalCount = jurorStatusCountMap.values().stream().reduce(0, Integer::sum);\n\n log.info(\"Creating Jurors save dtos\");\n List<JurorAccountDetailsDto> jurorAccountDetailsDtos =\n createJurorAccountDetailsDtos(isCourtOwned, jurorStatusCountMap);\n assert totalCount == jurorAccountDetailsDtos.size();\n\n log.info(\"Creating Pool Request's\");\n\n List<JurorPool> needRandomPool = new ArrayList<>();\n List<PoolRequest> pools = new ArrayList<>(totalCount / jurorsInPoolMinimumInclusive);\n PoolRequestGenerator poolRequestGenerator =\n PoolRequestGeneratorUtil.create(isCourtOwned, Constants.POOL_REQUEST_WEIGHT_MAP);\n\n int remainingJurors = totalCount;\n Collections.shuffle(jurorAccountDetailsDtos); //Ensures pools get a random distribution of juror types\n while (remainingJurors > 0) {\n final int totalJurorsInPool = RandomGenerator.nextInt(\n jurorsInPoolMinimumInclusive, jurorsInPoolMaximumExclusive);\n PoolRequest poolRequest = poolRequestGenerator.generate();\n poolRequest.setTotalNoRequired(RandomGenerator.nextInt(10, 16));\n pools.add(poolRequest);\n\n List<JurorAccountDetailsDto> selectedJurors = jurorAccountDetailsDtos.subList(\n Math.max(0, remainingJurors - totalJurorsInPool),\n remainingJurors);\n\n selectedJurors.parallelStream().forEach(juror -> {\n String firstJurorPoolOwner = null;\n List<JurorPool> jurorPools = juror.getJurorPools();\n\n for (JurorPool jurorPool : jurorPools) {\n if (firstJurorPoolOwner == null) {\n firstJurorPoolOwner = jurorPool.getOwner();\n }\n //Set owner so we know which pool this juror can not be in\n jurorPool.setOwner(jurorPool.getOwner());\n if (jurorPool.getOwner().equals(firstJurorPoolOwner)) {\n jurorPool.setPoolNumber(poolRequest.getPoolNumber());\n jurorPool.setStartDate(poolRequest.getReturnDate());\n } else {\n needRandomPool.add(jurorPool);\n }\n }\n }\n );\n remainingJurors -= totalJurorsInPool;\n }\n reassignJurorPoolsToRandomPoolWithNewOwner(needRandomPool, pools);\n\n stopWatch.start(\"Saving Pool Request's\");\n log.info(\"Saving Pool Request's to database\");\n Util.batchSave(poolRequestRepository, pools, BATCH_SIZE);\n stopWatch.stop();\n\n saveJurorAccountDetailsDtos(jurorAccountDetailsDtos);\n }\n\n private void saveJurorAccountDetailsDtos(List<JurorAccountDetailsDto> jurorAccountDetailsDtos) {\n stopWatch.start(\"Saving Juror's\");\n log.info(\"Saving Juror's to database\");\n Util.batchSave(jurorRepository,\n jurorAccountDetailsDtos.stream().map(JurorAccountDetailsDto::getJuror).toList(), BATCH_SIZE);\n stopWatch.stop();\n\n stopWatch.start(\"Saving Juror Paper Response's\");\n log.info(\"Saving Juror Paper Response's\");\n Util.batchSave(paperResponseRepository,\n jurorAccountDetailsDtos.stream().map(JurorAccountDetailsDto::getJurorResponse)\n .filter(PaperResponse.class::isInstance)\n .map(PaperResponse.class::cast)\n .toList(), BATCH_SIZE);\n stopWatch.stop();\n\n stopWatch.start(\"Saving Juror Digital Response's\");\n log.info(\"Saving Juror Digital Response's\");\n Util.batchSave(digitalResponseRepository,\n jurorAccountDetailsDtos.stream().map(JurorAccountDetailsDto::getJurorResponse)\n .filter(DigitalResponse.class::isInstance)\n .map(DigitalResponse.class::cast)\n .toList(), BATCH_SIZE);\n stopWatch.stop();\n\n stopWatch.start(\"Saving Juror Pool's\");\n log.info(\"Saving Juror Pool's to database\");\n Util.batchSave(jurorPoolRepository,\n jurorAccountDetailsDtos.stream().map(JurorAccountDetailsDto::getJurorPools).flatMap(List::stream).toList(),\n BATCH_SIZE);\n stopWatch.stop();\n }\n\n\n private void addSummonsReplyToJurorAccountDto(int digitalWeight, int paperWeight, JurorStatus jurorStatus,\n List<JurorAccountDetailsDto> jurors) {\n stopWatch.start(\"Creating Summons replies from jurors\");\n log.info(\"Creating {} juror responses from jurors\", jurors.size());\n DigitalResponseGenerator digitalResponseGenerator = DigitalResponseGeneratorUtil.create(jurorStatus);\n PaperResponseGenerator paperResponseGenerator = PaperResponseGeneratorUtil.create(jurorStatus);\n\n Map<AbstractJurorResponseGenerator<?>, Integer> weightMap = Map.of(\n digitalResponseGenerator, digitalWeight,\n paperResponseGenerator, paperWeight\n );\n jurors.forEach(jurorAccountDetailsDto -> {\n AbstractJurorResponseGenerator<?> generator = Util.getWeightedRandomItem(weightMap);\n AbstractJurorResponse jurorResponse = generator.generate();\n mapJurorToJurorResponse(jurorAccountDetailsDto.getJuror(), jurorResponse);\n jurorAccountDetailsDto.setJurorResponse(jurorResponse);\n });\n stopWatch.stop();\n }\n\n\n private void mapJurorToJurorResponse(final Juror juror, final AbstractJurorResponse jurorResponse) {\n jurorResponse.setJurorNumber(juror.getJurorNumber());\n jurorResponse.setTitle(juror.getTitle());\n jurorResponse.setFirstName(juror.getFirstName());\n jurorResponse.setLastName(juror.getLastName());\n jurorResponse.setDateOfBirth(juror.getDateOfBirth());\n jurorResponse.setPhoneNumber(juror.getPhoneNumber());\n jurorResponse.setAltPhoneNumber(juror.getAltPhoneNumber());\n jurorResponse.setEmail(juror.getEmail());\n\n jurorResponse.setAddressLine1(juror.getAddressLine1());\n jurorResponse.setAddressLine2(juror.getAddressLine2());\n jurorResponse.setAddressLine3(juror.getAddressLine3());\n jurorResponse.setAddressLine4(juror.getAddressLine4());\n jurorResponse.setAddressLine5(juror.getAddressLine5());\n jurorResponse.setPostcode(juror.getPostcode());\n }\n\n private List<JurorAccountDetailsDto> createJurorAccountDetailsDtos(boolean isCourtOwned,\n Map<JurorStatus, Integer> jurorStatusCountMap) {\n\n List<JurorAccountDetailsDto> jurorAccountDetailsDtos = jurorStatusCountMap.entrySet().stream()\n .map(entity -> {\n List<JurorAccountDetailsDto> jurors = createJurors(isCourtOwned, entity.getKey(),\n entity.getValue());\n addJurorPoolsToJurorAccountDto(isCourtOwned, entity.getKey(), jurors);\n addSummonsReplyToJurorAccountDto(66, 34,\n entity.getKey(), jurors);\n return jurors;\n }\n )\n .flatMap(List::stream)\n .collect(Collectors.toCollection(ArrayList::new));\n\n Collections.shuffle(jurorAccountDetailsDtos);\n return jurorAccountDetailsDtos;\n }\n\n\n private void reassignJurorPoolsToRandomPoolWithNewOwner(List<JurorPool> needRandomPool, List<PoolRequest> pools) {\n RandomFromCollectionGeneratorImpl<PoolRequest> randomPoolRequestGenerator =\n new RandomFromCollectionGeneratorImpl<>(pools);\n\n for (JurorPool jurorPool : needRandomPool) {\n PoolRequest poolRequest;\n //Get a pool request which is not the current owner (ensures a new pool is assigned)\n do {\n poolRequest = randomPoolRequestGenerator.generate();\n } while (poolRequest.getOwner().equals(jurorPool.getOwner()));\n jurorPool.setOwner(poolRequest.getOwner());\n jurorPool.setPoolNumber(poolRequest.getPoolNumber());\n jurorPool.setStartDate(poolRequest.getReturnDate());\n }\n }\n\n\n private void addJurorPoolsToJurorAccountDto(boolean isCourtOwned, JurorStatus jurorStatus,\n List<JurorAccountDetailsDto> jurors) {\n stopWatch.start(\"Creating Juror Pools for status: \" + jurorStatus);\n log.info(\"Creating juror pools with status {} for {} jurors\", jurorStatus, jurors.size());\n\n final JurorPoolGenerator jurorPoolGenerator = JurorPoolGeneratorUtil.create(isCourtOwned, jurorStatus);\n final JurorPoolGenerator respondeedJurorPoolGenerator = JurorPoolGeneratorUtil.create(isCourtOwned,\n JurorStatus.RESPONDED);\n\n\n BiFunction<Juror, JurorPool, List<JurorPool>> jurorPoolStatusConsumer = switch (jurorStatus) {\n case TRANSFERRED -> (juror, jurorPool) -> {\n JurorPool transferredToPool = respondeedJurorPoolGenerator.generate();\n transferredToPool.setJurorNumber(juror.getJurorNumber());\n transferredToPool.setOwner(Util.getRandomItem(getCourtOwners(), List.of(jurorPool.getOwner())));\n return List.of(transferredToPool);\n };\n case REASSIGNED -> (juror, jurorPool) -> {\n JurorPool reassignedToPool = respondeedJurorPoolGenerator.generate();\n reassignedToPool.setJurorNumber(juror.getJurorNumber());\n reassignedToPool.setOwner(jurorPool.getOwner());\n return List.of(reassignedToPool);\n };\n default -> (juror, jurorPool) -> List.of();\n };\n\n jurors.forEach(jurorAccountDetailsDto -> jurorAccountDetailsDto.setJurorPools(\n createJurorPoolsForJuror(\n jurorAccountDetailsDto.getJuror(),\n jurorPoolStatusConsumer,\n jurorPoolGenerator\n )\n ));\n stopWatch.stop();\n }\n\n private List<JurorPool> createJurorPoolsForJuror(Juror juror,\n BiFunction<Juror, JurorPool, List<JurorPool>> jurorPoolStatusConsumer,\n JurorPoolGenerator jurorPoolGenerator) {\n List<JurorPool> jurorPools = new ArrayList<>();\n JurorPool jurorPool = jurorPoolGenerator.generate();\n jurorPool.setJurorNumber(juror.getJurorNumber());\n\n jurorPools.add(jurorPool);\n jurorPools.addAll(jurorPoolStatusConsumer.apply(juror, jurorPool));\n return jurorPools;\n }\n\n\n private List<JurorAccountDetailsDto> createJurors(boolean isCourtOwned, JurorStatus jurorStatus, int count) {\n stopWatch.start(\"Creating Jurors\");\n log.info(\"Creating {} jurors with status {}\", count, jurorStatus);\n List<JurorAccountDetailsDto> jurors = new ArrayList<>(count);\n JurorGenerator jurorGenerator = JurorGeneratorUtil.create(isCourtOwned, jurorStatus);\n for (int i = 0; i < count; i++) {\n jurors.add(new JurorAccountDetailsDto(jurorGenerator.generate()));\n }\n stopWatch.stop();\n return jurors;\n }\n}"
}
] | import uk.gov.hmcts.juror.support.generation.generators.value.FixedValueGeneratorImpl;
import uk.gov.hmcts.juror.support.generation.generators.value.LocalDateGeneratorImpl;
import uk.gov.hmcts.juror.support.generation.generators.value.NullValueGeneratorImpl;
import uk.gov.hmcts.juror.support.generation.generators.value.RandomFromCollectionGeneratorImpl;
import uk.gov.hmcts.juror.support.sql.entity.ExcusableCode;
import uk.gov.hmcts.juror.support.sql.entity.Juror;
import uk.gov.hmcts.juror.support.sql.entity.JurorPoolGenerator;
import uk.gov.hmcts.juror.support.sql.entity.JurorStatus;
import uk.gov.hmcts.juror.support.sql.entity.PoolRequest;
import uk.gov.hmcts.juror.support.sql.service.SqlSupportService;
import java.time.LocalDate;
import java.util.Arrays; | 6,942 | package uk.gov.hmcts.juror.support.sql.generators;
public class JurorPoolGeneratorUtil {
public static JurorPoolGenerator summoned(boolean isCourtOwned) {
return createStandard(isCourtOwned, JurorStatus.SUMMONED);
}
public static JurorPoolGenerator responded(boolean isCourtOwned) {
return createStandard(isCourtOwned, JurorStatus.RESPONDED);
}
public static JurorPoolGenerator panel(boolean isCourtOwned) {
return createStandard(isCourtOwned, JurorStatus.PANEL);
}
public static JurorPoolGenerator juror(boolean isCourtOwned) {
return createStandard(isCourtOwned, JurorStatus.JUROR);
}
public static JurorPoolGenerator excused(boolean isCourtOwned) {
JurorPoolGenerator jurorPoolGenerator = createStandard(isCourtOwned, JurorStatus.EXCUSED);
jurorPoolGenerator.setNextDate(new NullValueGeneratorImpl<>());
return jurorPoolGenerator;
}
public static JurorPoolGenerator disqualified(boolean isCourtOwned) {
JurorPoolGenerator jurorPoolGenerator = createStandard(isCourtOwned, JurorStatus.DISQUALIFIED);
jurorPoolGenerator.setNextDate(new NullValueGeneratorImpl<>());
return jurorPoolGenerator;
}
public static JurorPoolGenerator deferred(boolean isCourtOwned) {
JurorPoolGenerator jurorPoolGenerator = createStandard(isCourtOwned, JurorStatus.DEFERRED);
//Next date set to date you are deferred too?? -- check
jurorPoolGenerator.setNextDate(new NullValueGeneratorImpl<>());
jurorPoolGenerator.setDeferralCode(new RandomFromCollectionGeneratorImpl<>( | package uk.gov.hmcts.juror.support.sql.generators;
public class JurorPoolGeneratorUtil {
public static JurorPoolGenerator summoned(boolean isCourtOwned) {
return createStandard(isCourtOwned, JurorStatus.SUMMONED);
}
public static JurorPoolGenerator responded(boolean isCourtOwned) {
return createStandard(isCourtOwned, JurorStatus.RESPONDED);
}
public static JurorPoolGenerator panel(boolean isCourtOwned) {
return createStandard(isCourtOwned, JurorStatus.PANEL);
}
public static JurorPoolGenerator juror(boolean isCourtOwned) {
return createStandard(isCourtOwned, JurorStatus.JUROR);
}
public static JurorPoolGenerator excused(boolean isCourtOwned) {
JurorPoolGenerator jurorPoolGenerator = createStandard(isCourtOwned, JurorStatus.EXCUSED);
jurorPoolGenerator.setNextDate(new NullValueGeneratorImpl<>());
return jurorPoolGenerator;
}
public static JurorPoolGenerator disqualified(boolean isCourtOwned) {
JurorPoolGenerator jurorPoolGenerator = createStandard(isCourtOwned, JurorStatus.DISQUALIFIED);
jurorPoolGenerator.setNextDate(new NullValueGeneratorImpl<>());
return jurorPoolGenerator;
}
public static JurorPoolGenerator deferred(boolean isCourtOwned) {
JurorPoolGenerator jurorPoolGenerator = createStandard(isCourtOwned, JurorStatus.DEFERRED);
//Next date set to date you are deferred too?? -- check
jurorPoolGenerator.setNextDate(new NullValueGeneratorImpl<>());
jurorPoolGenerator.setDeferralCode(new RandomFromCollectionGeneratorImpl<>( | Arrays.stream(ExcusableCode.values()).map(ExcusableCode::getCode).toList())); | 0 | 2023-12-01 11:38:42+00:00 | 8k |
vvbbnn00/JavaWeb-CanteenSystem | JavaBackend/src/main/java/cn/vvbbnn00/canteen/service/CanteenAdminService.java | [
{
"identifier": "CanteenAdminDao",
"path": "JavaBackend/src/main/java/cn/vvbbnn00/canteen/dao/CanteenAdminDao.java",
"snippet": "public interface CanteenAdminDao {\n /**\n * 插入一个餐厅管理员对象\n * @param canteenAdmin 餐厅管理员对象\n * @return 是否插入成功\n */\n boolean insert(CanteenAdmin canteenAdmin);\n\n /**\n * 移除一个餐厅管理员\n * @param canteenAdmin 餐厅管理员对象\n * @return 是否移除成功\n */\n boolean delete(CanteenAdmin canteenAdmin);\n\n /**\n * 查询餐厅管理员列表\n * @param canteenId 可选,餐厅ID\n * @param userId 可选,用户ID\n * @return 满足条件的列表\n */\n List<CanteenAdmin> query(Integer canteenId, Integer userId);\n\n /**\n * Queries the list of CanteenAdmin objects based on the given canteenId.\n *\n * @param canteenId the canteen ID to search for\n * @return a list of CanteenAdmin objects that match the given canteenId\n */\n List<CanteenAdmin> queryByCanteenId(Integer canteenId);\n\n /**\n * Queries the list of CanteenAdmin objects based on the given userId.\n *\n * @param userId the user ID to search for\n * @return a list of CanteenAdmin objects that match the given userId\n */\n List<CanteenAdmin> queryByUserId(Integer userId);\n\n}"
},
{
"identifier": "CanteenAdminDaoImpl",
"path": "JavaBackend/src/main/java/cn/vvbbnn00/canteen/dao/impl/CanteenAdminDaoImpl.java",
"snippet": "public class CanteenAdminDaoImpl implements CanteenAdminDao {\n @Override\n public boolean insert(CanteenAdmin canteenAdmin) {\n try (Connection connection = Hikari.getConnection()) {\n PreparedStatement ps = SqlStatementUtils.generateInsertStatement(connection, canteenAdmin, new String[]{\n \"canteenId\", \"userId\"\n });\n ps.executeUpdate();\n return true;\n } catch (Exception e) {\n LogUtils.error(e.getMessage(), e);\n return false;\n }\n }\n\n @Override\n public boolean delete(CanteenAdmin canteenAdmin) {\n try (Connection connection = Hikari.getConnection()) {\n String sql = \"DELETE FROM \" + Hikari.getDbName() + \".`canteen_admin`\" + \" WHERE canteen_id=? AND user_id=?;\";\n PreparedStatement ps = connection.prepareStatement(sql);\n ps.setInt(1, canteenAdmin.getCanteenId());\n ps.setInt(2, canteenAdmin.getUserId());\n ps.executeUpdate();\n return true;\n } catch (Exception e) {\n LogUtils.error(e.getMessage(), e);\n }\n return false;\n }\n\n @Override\n public List<CanteenAdmin> query(Integer canteenId, Integer userId) {\n String sql = SqlStatementUtils.generateBasicSelectSql(CanteenAdmin.class, new String[]{\n \"canteenId\", \"userId\"\n });\n ConditionAndParam conditionAndParam = new ConditionAndParam(canteenId, userId);\n List<String> conditions = conditionAndParam.conditions;\n List<Object> params = conditionAndParam.params;\n\n sql += SqlStatementUtils.generateWhereSql(conditions);\n\n try (Connection connection = Hikari.getConnection()) {\n PreparedStatement ps = connection.prepareStatement(sql);\n for (int i = 0; i < params.size(); i++) {\n ps.setObject(i + 1, params.get(i));\n }\n List<CanteenAdmin> canteenAdmins = new ArrayList<>();\n ResultSet rs = ps.executeQuery();\n while (rs.next()) {\n canteenAdmins.add((CanteenAdmin) SqlStatementUtils.makeEntityFromResult(rs, CanteenAdmin.class));\n }\n return canteenAdmins;\n } catch (Exception e) {\n LogUtils.error(e.getMessage(), e);\n }\n return null;\n }\n\n @Override\n public List<CanteenAdmin> queryByCanteenId(Integer canteenId) {\n return query(canteenId, null);\n }\n\n @Override\n public List<CanteenAdmin> queryByUserId(Integer userId) {\n return query(null, userId);\n }\n\n public static class ConditionAndParam {\n public List<String> conditions = new ArrayList<>();\n public List<Object> params = new ArrayList<>();\n\n public ConditionAndParam(Integer canteenId, Integer userId) {\n if (canteenId != null) {\n conditions.add(\"canteen_id = ?\");\n params.add(canteenId);\n }\n if (userId != null) {\n conditions.add(\"user_id = ?\");\n params.add(userId);\n }\n }\n }\n}"
},
{
"identifier": "CanteenDaoImpl",
"path": "JavaBackend/src/main/java/cn/vvbbnn00/canteen/dao/impl/CanteenDaoImpl.java",
"snippet": "public class CanteenDaoImpl implements CanteenDao {\n\n @Override\n public int insert(Canteen canteen) {\n try (Connection connection = Hikari.getConnection()) {\n PreparedStatement ps = SqlStatementUtils.generateInsertStatement(connection, canteen, new String[]{\n \"name\", \"location\", \"introduction\", \"compScore\",\n });\n\n ps.executeUpdate();\n\n ResultSet generatedKeys = ps.getGeneratedKeys();\n\n if (generatedKeys.next()) {\n return generatedKeys.getInt(1);\n } else {\n // Handle the case where no key was generated\n throw new SQLException(\"Insertion failed, no ID obtained.\");\n }\n } catch (Exception e) {\n LogUtils.severe(e.getMessage());\n return -1;\n }\n }\n\n @Override\n public Canteen queryCanteenById(Integer id) {\n try (Connection connection = Hikari.getConnection()) {\n String sql = SqlStatementUtils.generateBasicSelectSql(Canteen.class, new String[]{\n \"canteenId\", \"name\", \"location\", \"introduction\", \"compScore\", \"createdAt\", \"updatedAt\"\n }) + \" WHERE `canteen_id` = ?;\";\n PreparedStatement ps = connection.prepareStatement(sql);\n ps.setInt(1, id);\n ResultSet rs = ps.executeQuery();\n if (rs.next()) {\n return (Canteen) SqlStatementUtils.makeEntityFromResult(rs, Canteen.class);\n }\n } catch (Exception e) {\n LogUtils.severe(e.getMessage());\n }\n return null;\n }\n\n\n @Override\n public boolean update(Canteen canteen) {\n try (Connection connection = Hikari.getConnection()) {\n PreparedStatement ps = SqlStatementUtils.generateUpdateStatement(connection, canteen, new String[]{\n \"name\", \"location\", \"introduction\", \"compScore\"\n }, new String[]{\n \"canteenId\"\n });\n ps.executeUpdate();\n return true;\n } catch (Exception e) {\n LogUtils.severe(e.getMessage());\n }\n return false;\n }\n\n @Override\n public boolean delete(Integer id) {\n try (Connection connection = Hikari.getConnection()) {\n String sql = \"DELETE FROM \" + Hikari.getDbName() + \".`canteen` WHERE `canteen_id` = ?;\";\n PreparedStatement ps = connection.prepareStatement(sql);\n ps.setInt(1, id);\n ps.executeUpdate();\n return true;\n } catch (Exception e) {\n LogUtils.severe(e.getMessage());\n }\n return false;\n }\n\n @Override\n public List<Canteen> queryCanteens(Integer page, Integer pageSize, String kw, String orderBy, Boolean asc) {\n String sql = SqlStatementUtils.generateBasicSelectSql(Canteen.class, new String[]{\n \"canteenId\", \"name\", \"location\", \"introduction\", \"compScore\", \"createdAt\", \"updatedAt\"\n });\n\n ConditionAndParam condAndParam = new ConditionAndParam(kw);\n\n List<String> conditions = condAndParam.conditions;\n List<Object> params = condAndParam.params;\n\n sql += SqlStatementUtils.generateWhereSql(conditions);\n\n if (orderBy != null) {\n sql += \" ORDER BY \" + SqlStatementUtils.camelToSnakeQuote(orderBy);\n if (asc != null && !asc) {\n sql += \" DESC\";\n }\n }\n\n if (page != null && pageSize != null) {\n sql += \" LIMIT ?, ?\";\n params.add((page - 1) * pageSize);\n params.add(pageSize);\n }\n\n try (Connection connection = Hikari.getConnection()) {\n PreparedStatement ps = connection.prepareStatement(sql);\n for (int i = 0; i < params.size(); i++) {\n ps.setObject(i + 1, params.get(i));\n }\n\n ResultSet rs = ps.executeQuery();\n List<Canteen> canteens = new ArrayList<>();\n while (rs.next()) {\n canteens.add((Canteen) SqlStatementUtils.makeEntityFromResult(rs, Canteen.class));\n }\n return canteens;\n } catch (Exception e) {\n LogUtils.severe(e.getMessage());\n }\n return null;\n }\n\n public static class ConditionAndParam {\n public List<String> conditions = new ArrayList<>();\n public List<Object> params = new ArrayList<>();\n\n public ConditionAndParam(String kw) {\n if (kw != null) {\n conditions.add(\"(`name` LIKE ? OR `location` LIKE ? OR `introduction` LIKE ?)\");\n params.add(\"%\" + kw + \"%\");\n params.add(\"%\" + kw + \"%\");\n params.add(\"%\" + kw + \"%\");\n }\n }\n }\n\n @Override\n public Integer queryCanteensCount(String kw) {\n String sql = \"SELECT COUNT(*) FROM \" + Hikari.getDbName() + \".`canteen`\";\n ConditionAndParam condAndParam = new ConditionAndParam(kw);\n\n List<String> conditions = condAndParam.conditions;\n List<Object> params = condAndParam.params;\n\n sql += SqlStatementUtils.generateWhereSql(conditions);\n\n try (Connection connection = Hikari.getConnection()) {\n PreparedStatement ps = connection.prepareStatement(sql);\n for (int i = 0; i < params.size(); i++) {\n ps.setObject(i + 1, params.get(i));\n }\n\n ResultSet rs = ps.executeQuery();\n if (rs.next()) {\n return rs.getInt(1);\n }\n } catch (SQLException e) {\n throw new RuntimeException(e);\n }\n return null;\n }\n\n @Override\n public List<Canteen> batchQueryCanteens(List<Integer> canteenIds) {\n if (canteenIds.isEmpty()) {\n return new ArrayList<>();\n }\n String sql = SqlStatementUtils.generateBasicSelectSql(Canteen.class, new String[]{\n \"canteenId\", \"name\", \"location\", \"introduction\", \"compScore\", \"createdAt\", \"updatedAt\"\n });\n sql += \" WHERE `canteen_id` IN (\" + SqlStatementUtils.generateQuestionMarks(canteenIds.size()) + \");\";\n try (Connection connection = Hikari.getConnection()) {\n PreparedStatement ps = connection.prepareStatement(sql);\n for (int i = 0; i < canteenIds.size(); i++) {\n ps.setInt(i + 1, canteenIds.get(i));\n }\n ResultSet rs = ps.executeQuery();\n List<Canteen> canteens = new ArrayList<>();\n while (rs.next()) {\n canteens.add((Canteen) SqlStatementUtils.makeEntityFromResult(rs, Canteen.class));\n }\n return canteens;\n } catch (Exception e) {\n LogUtils.severe(e.getMessage());\n }\n return null;\n }\n}"
},
{
"identifier": "UserDaoImpl",
"path": "JavaBackend/src/main/java/cn/vvbbnn00/canteen/dao/impl/UserDaoImpl.java",
"snippet": "public class UserDaoImpl implements UserDao {\n\n @Override\n public boolean insert(User user) {\n try (Connection connection = Hikari.getConnection()) {\n PreparedStatement ps = SqlStatementUtils.generateInsertStatement(connection, user, new String[]{\n \"username\", \"password\", \"name\", \"employeeId\", \"level\", \"point\", \"available\", \"role\", \"isVerified\", \"email\"\n });\n ps.executeUpdate();\n return true;\n } catch (Exception e) {\n LogUtils.severe(e.getMessage());\n return false;\n }\n }\n\n @Override\n public User queryUserById(Integer id) {\n try (Connection connection = Hikari.getConnection()) {\n String sql = SqlStatementUtils.generateBasicSelectSql(User.class, new String[]{\n \"userId\", \"username\", \"password\", \"name\", \"employeeId\", \"level\", \"point\", \"available\", \"role\", \"isVerified\", \"createdAt\", \"updatedAt\", \"lastLoginAt\", \"email\"\n }) + \" WHERE `user_id` = ?;\";\n PreparedStatement ps = connection.prepareStatement(sql);\n ps.setInt(1, id);\n ResultSet rs = ps.executeQuery();\n if (rs.next()) {\n return (User) SqlStatementUtils.makeEntityFromResult(rs, User.class);\n }\n } catch (Exception e) {\n LogUtils.severe(e.getMessage());\n }\n return null;\n }\n\n\n @Override\n public boolean changeUserPoint(Integer id, Integer delta) {\n try (Connection connection = Hikari.getConnection()) {\n String sql = \"UPDATE \" + Hikari.getDbName() + \".`user` SET `point` = `point` + ? WHERE `user_id` = ?;\";\n PreparedStatement ps = connection.prepareStatement(sql);\n ps.setInt(1, delta);\n ps.setInt(2, id);\n ps.executeUpdate();\n return true;\n } catch (Exception e) {\n LogUtils.severe(e.getMessage());\n }\n return false;\n }\n\n @Override\n public User queryUserByUsername(String username) {\n try (Connection connection = Hikari.getConnection()) {\n String sql = SqlStatementUtils.generateBasicSelectSql(User.class, new String[]{\n \"userId\", \"username\", \"password\", \"name\", \"employeeId\", \"level\", \"point\", \"available\", \"role\", \"isVerified\", \"createdAt\", \"updatedAt\", \"lastLoginAt\", \"email\"\n }) + \" WHERE `username` = ?;\";\n PreparedStatement ps = connection.prepareStatement(sql);\n ps.setString(1, username);\n ResultSet rs = ps.executeQuery();\n if (rs.next()) {\n return (User) SqlStatementUtils.makeEntityFromResult(rs, User.class);\n }\n } catch (Exception e) {\n LogUtils.severe(e.getMessage());\n }\n return null;\n }\n\n @Override\n public boolean update(User user) {\n try (Connection connection = Hikari.getConnection()) {\n PreparedStatement ps = SqlStatementUtils.generateUpdateStatement(connection, user, new String[]{\n \"username\", \"password\", \"name\", \"employeeId\", \"level\", \"point\", \"available\", \"role\", \"isVerified\", \"email\"\n }, new String[]{\n \"userId\"\n });\n ps.executeUpdate();\n return true;\n } catch (Exception e) {\n LogUtils.severe(e.getMessage());\n }\n return false;\n }\n\n @Override\n public boolean delete(Integer id) {\n try (Connection connection = Hikari.getConnection()) {\n // 此处直接拼接字符串即可,无需调用复杂的方法\n String sql = \"DELETE FROM \" + Hikari.getDbName() + \".`user` WHERE `user_id` = ?;\";\n PreparedStatement ps = connection.prepareStatement(sql);\n ps.setInt(1, id);\n ps.executeUpdate();\n return true;\n } catch (Exception e) {\n LogUtils.severe(e.getMessage());\n }\n return false;\n }\n\n private static class ConditionAndParam {\n List<String> conditions;\n List<Object> params;\n\n ConditionAndParam(String kw, Boolean available, User.Role role, Boolean isVerified) {\n conditions = new ArrayList<>();\n params = new ArrayList<>();\n if (kw != null) {\n conditions.add(\"(`username` LIKE ? OR `name` LIKE ? OR `employee_id` LIKE ?)\");\n params.add(\"%\" + kw + \"%\");\n params.add(\"%\" + kw + \"%\");\n params.add(\"%\" + kw + \"%\");\n }\n\n if (available != null) {\n conditions.add(\"`available` = ?\");\n params.add(available ? 1 : 0);\n }\n\n if (role != null) {\n conditions.add(\"`role` = ?\");\n params.add(role.toString());\n }\n\n if (isVerified != null) {\n conditions.add(\"`is_verified` = ?\");\n params.add(isVerified ? 1 : 0);\n }\n }\n }\n\n @Override\n public List<User> queryUsers(Integer page, Integer pageSize, String kw, Boolean available, User.Role role, Boolean isVerified, String orderBy, Boolean asc) {\n // 密码不应该被查询出来\n String sql = SqlStatementUtils.generateBasicSelectSql(User.class, new String[]{\n \"userId\", \"username\", \"name\", \"employeeId\", \"level\", \"point\", \"available\", \"role\", \"isVerified\", \"createdAt\", \"updatedAt\", \"lastLoginAt\", \"email\"\n });\n\n ConditionAndParam condAndParam = new ConditionAndParam(kw, available, role, isVerified);\n\n List<String> conditions = condAndParam.conditions;\n List<Object> params = condAndParam.params;\n\n sql += SqlStatementUtils.generateWhereSql(conditions);\n\n if (orderBy != null) {\n sql += \" ORDER BY \" + SqlStatementUtils.camelToSnakeQuote(orderBy);\n if (asc != null && !asc) {\n sql += \" DESC\";\n }\n }\n\n if (page != null && pageSize != null) {\n sql += \" LIMIT ?, ?\";\n params.add((page - 1) * pageSize);\n params.add(pageSize);\n }\n\n try (Connection connection = Hikari.getConnection()) {\n PreparedStatement ps = connection.prepareStatement(sql);\n for (int i = 0; i < params.size(); i++) {\n ps.setObject(i + 1, params.get(i));\n }\n\n ResultSet rs = ps.executeQuery();\n List<User> users = new ArrayList<>();\n while (rs.next()) {\n users.add((User) SqlStatementUtils.makeEntityFromResult(rs, User.class));\n }\n return users;\n } catch (Exception e) {\n LogUtils.severe(e.getMessage());\n }\n return null;\n }\n\n @Override\n public Integer queryUsersCount(String kw, Boolean available, User.Role role, Boolean isVerified) {\n String sql = \"SELECT COUNT(*) FROM \" + Hikari.getDbName() + \".`user`\";\n ConditionAndParam condAndParam = new ConditionAndParam(kw, available, role, isVerified);\n\n List<String> conditions = condAndParam.conditions;\n List<Object> params = condAndParam.params;\n\n sql += SqlStatementUtils.generateWhereSql(conditions);\n\n try (Connection connection = Hikari.getConnection()) {\n PreparedStatement ps = connection.prepareStatement(sql);\n for (int i = 0; i < params.size(); i++) {\n ps.setObject(i + 1, params.get(i));\n }\n\n ResultSet rs = ps.executeQuery();\n if (rs.next()) {\n return rs.getInt(1);\n }\n } catch (Exception e) {\n LogUtils.severe(e.getMessage());\n }\n return null;\n }\n\n @Override\n public List<User> batchQueryUsers(List<Integer> userIds) {\n if (userIds.isEmpty()) {\n return new ArrayList<>();\n }\n try (Connection connection = Hikari.getConnection()) {\n String sql = SqlStatementUtils.generateBasicSelectSql(User.class, new String[]{\n \"userId\", \"username\", \"name\", \"employeeId\", \"level\", \"point\", \"available\", \"role\", \"isVerified\", \"createdAt\", \"updatedAt\", \"lastLoginAt\", \"email\"\n }) + \" WHERE `user_id` IN (\" + SqlStatementUtils.generateQuestionMarks(userIds.size()) + \");\";\n PreparedStatement ps = connection.prepareStatement(sql);\n for (int i = 0; i < userIds.size(); i++) {\n ps.setInt(i + 1, userIds.get(i));\n }\n // LogUtils.info(ps.toString());\n ResultSet rs = ps.executeQuery();\n List<User> users = new ArrayList<>();\n while (rs.next()) {\n users.add((User) SqlStatementUtils.makeEntityFromResult(rs, User.class));\n }\n return users;\n } catch (Exception e) {\n LogUtils.severe(e.getMessage(), e);\n }\n return null;\n }\n}"
},
{
"identifier": "Canteen",
"path": "JavaBackend/src/main/java/cn/vvbbnn00/canteen/model/Canteen.java",
"snippet": "@Data\n@JavaBean\npublic class Canteen implements Serializable {\n private Integer canteenId;\n\n @NotBlank(message = \"食堂名称不能为空\")\n @Size(max = 255, message = \"食堂名称长度不能超过255个字符\")\n private String name;\n\n @Size(max = 255, message = \"食堂位置长度不能超过255个字符\")\n private String location;\n\n @Size(max = 2000, message = \"食堂简介长度不能超过2000个字符\")\n private String introduction;\n\n @DecimalMin(value = \"0.00\", message = \"综合评分不能低于0.00\")\n @DecimalMax(value = \"5.00\", message = \"综合评分不能高于5.00\")\n private BigDecimal compScore;\n private LocalDateTime createdAt;\n private LocalDateTime updatedAt;\n}"
},
{
"identifier": "CanteenAdmin",
"path": "JavaBackend/src/main/java/cn/vvbbnn00/canteen/model/CanteenAdmin.java",
"snippet": "@Data\n@JavaBean\npublic class CanteenAdmin implements Serializable {\n private Integer canteenId;\n private Integer userId;\n}"
},
{
"identifier": "User",
"path": "JavaBackend/src/main/java/cn/vvbbnn00/canteen/model/User.java",
"snippet": "@Data\n@JavaBean\npublic class User implements Serializable {\n private Integer userId;\n\n @Pattern(regexp = \"^[a-zA-Z0-9_]{4,16}$\", message = \"用户名只能包含字母、数字和下划线,长度为4-16位\")\n private String username;\n\n // 此处的密码是加密后的密码\n @Pattern(regexp = \"^\\\\S{6,16}$\", message = \"密码不能包含空格,长度为6-16位\")\n private String password;\n private String name;\n private String employeeId;\n @Min(value = 0, message = \"level不能小于0\")\n @Max(value = 20, message = \"level不能大于20\")\n private Integer level;\n @Min(value = 0, message = \"point不能小于0\")\n private Long point;\n private Boolean available;\n\n @Enumerated(EnumType.STRING)\n private Role role;\n private Boolean isVerified;\n\n @Temporal(TemporalType.TIMESTAMP)\n private LocalDateTime createdAt;\n\n @Temporal(TemporalType.TIMESTAMP)\n private LocalDateTime updatedAt;\n\n @Temporal(TemporalType.TIMESTAMP)\n private LocalDateTime lastLoginAt;\n\n @Email(message = \"邮箱格式不正确\")\n private String email;\n\n public String getAvatar() {\n return StringUtils.getAvatarUrl(this.email);\n }\n\n public enum Role {\n user, canteen_admin, admin\n }\n}"
}
] | import cn.vvbbnn00.canteen.dao.CanteenAdminDao;
import cn.vvbbnn00.canteen.dao.impl.CanteenAdminDaoImpl;
import cn.vvbbnn00.canteen.dao.impl.CanteenDaoImpl;
import cn.vvbbnn00.canteen.dao.impl.UserDaoImpl;
import cn.vvbbnn00.canteen.model.Canteen;
import cn.vvbbnn00.canteen.model.CanteenAdmin;
import cn.vvbbnn00.canteen.model.User;
import java.util.List;
import java.util.stream.Collectors; | 6,816 | package cn.vvbbnn00.canteen.service;
public class CanteenAdminService {
private static final CanteenAdminDao canteenAdminDao = new CanteenAdminDaoImpl();
/**
* 检查是否可以添加或移除餐厅管理员
*
* @param canteenId 餐厅ID
* @param userId 用户ID
*/
private void checkUpdateAvailable(Integer canteenId, Integer userId) {
User user = new UserService().getUserById(userId);
if (user == null) {
throw new RuntimeException("用户不存在");
}
Canteen canteen = new CanteenService().getCanteenById(canteenId);
if (canteen == null) {
throw new RuntimeException("餐厅不存在");
}
}
/**
* 添加一个餐厅管理员
*
* @param canteenId 餐厅ID
* @param userId 用户ID
* @return 是否添加成功
*/
public boolean addCanteenAdmin(Integer canteenId, Integer userId) {
checkUpdateAvailable(canteenId, userId);
CanteenAdmin canteenAdmin = new CanteenAdmin();
canteenAdmin.setCanteenId(canteenId);
canteenAdmin.setUserId(userId);
List<CanteenAdmin> list = canteenAdminDao.query(canteenId, userId);
if (!list.isEmpty()) {
throw new RuntimeException("餐厅管理员已存在");
}
boolean result = canteenAdminDao.insert(canteenAdmin);
if (!result) {
throw new RuntimeException("添加失败");
}
return true;
}
/**
* 移除一个餐厅管理员
*
* @param canteenId 餐厅ID
* @param userId 用户ID
* @return 是否移除成功
*/
public boolean removeCanteenAdmin(Integer canteenId, Integer userId) {
checkUpdateAvailable(canteenId, userId);
CanteenAdmin canteenAdmin = new CanteenAdmin();
canteenAdmin.setCanteenId(canteenId);
canteenAdmin.setUserId(userId);
boolean result = canteenAdminDao.delete(canteenAdmin);
if (!result) {
throw new RuntimeException("移除失败");
}
return true;
}
/**
* 查询用户是否为餐厅管理员
*
* @param canteenId 餐厅ID
* @param userId 用户ID
* @return 是否为餐厅管理员
*/
public boolean checkHasCanteenAdmin(Integer canteenId, Integer userId) {
User user = new UserService().getUserById(userId);
if (user == null) {
return false;
}
Canteen canteen = new CanteenService().getCanteenById(canteenId);
if (canteen == null) {
return false;
}
if (user.getRole() == User.Role.admin) {
return true;
}
List<CanteenAdmin> list = canteenAdminDao.query(canteenId, userId);
if (list == null) {
throw new RuntimeException("查询失败");
}
return !list.isEmpty();
}
/**
* 查询餐厅管理员列表
*
* @param canteenId 餐厅ID
* @return 餐厅管理员列表
*/
public List<User> getCanteenAdminList(Integer canteenId) {
Canteen canteen = new CanteenService().getCanteenById(canteenId);
if (canteen == null) {
throw new RuntimeException("餐厅不存在");
}
List<CanteenAdmin> canteenAdminList = canteenAdminDao.queryByCanteenId(canteenId);
if (canteenAdminList == null) {
throw new RuntimeException("查询失败");
}
List<Integer> userIdList = canteenAdminList.stream().map(CanteenAdmin::getUserId).collect(Collectors.toList()); | package cn.vvbbnn00.canteen.service;
public class CanteenAdminService {
private static final CanteenAdminDao canteenAdminDao = new CanteenAdminDaoImpl();
/**
* 检查是否可以添加或移除餐厅管理员
*
* @param canteenId 餐厅ID
* @param userId 用户ID
*/
private void checkUpdateAvailable(Integer canteenId, Integer userId) {
User user = new UserService().getUserById(userId);
if (user == null) {
throw new RuntimeException("用户不存在");
}
Canteen canteen = new CanteenService().getCanteenById(canteenId);
if (canteen == null) {
throw new RuntimeException("餐厅不存在");
}
}
/**
* 添加一个餐厅管理员
*
* @param canteenId 餐厅ID
* @param userId 用户ID
* @return 是否添加成功
*/
public boolean addCanteenAdmin(Integer canteenId, Integer userId) {
checkUpdateAvailable(canteenId, userId);
CanteenAdmin canteenAdmin = new CanteenAdmin();
canteenAdmin.setCanteenId(canteenId);
canteenAdmin.setUserId(userId);
List<CanteenAdmin> list = canteenAdminDao.query(canteenId, userId);
if (!list.isEmpty()) {
throw new RuntimeException("餐厅管理员已存在");
}
boolean result = canteenAdminDao.insert(canteenAdmin);
if (!result) {
throw new RuntimeException("添加失败");
}
return true;
}
/**
* 移除一个餐厅管理员
*
* @param canteenId 餐厅ID
* @param userId 用户ID
* @return 是否移除成功
*/
public boolean removeCanteenAdmin(Integer canteenId, Integer userId) {
checkUpdateAvailable(canteenId, userId);
CanteenAdmin canteenAdmin = new CanteenAdmin();
canteenAdmin.setCanteenId(canteenId);
canteenAdmin.setUserId(userId);
boolean result = canteenAdminDao.delete(canteenAdmin);
if (!result) {
throw new RuntimeException("移除失败");
}
return true;
}
/**
* 查询用户是否为餐厅管理员
*
* @param canteenId 餐厅ID
* @param userId 用户ID
* @return 是否为餐厅管理员
*/
public boolean checkHasCanteenAdmin(Integer canteenId, Integer userId) {
User user = new UserService().getUserById(userId);
if (user == null) {
return false;
}
Canteen canteen = new CanteenService().getCanteenById(canteenId);
if (canteen == null) {
return false;
}
if (user.getRole() == User.Role.admin) {
return true;
}
List<CanteenAdmin> list = canteenAdminDao.query(canteenId, userId);
if (list == null) {
throw new RuntimeException("查询失败");
}
return !list.isEmpty();
}
/**
* 查询餐厅管理员列表
*
* @param canteenId 餐厅ID
* @return 餐厅管理员列表
*/
public List<User> getCanteenAdminList(Integer canteenId) {
Canteen canteen = new CanteenService().getCanteenById(canteenId);
if (canteen == null) {
throw new RuntimeException("餐厅不存在");
}
List<CanteenAdmin> canteenAdminList = canteenAdminDao.queryByCanteenId(canteenId);
if (canteenAdminList == null) {
throw new RuntimeException("查询失败");
}
List<Integer> userIdList = canteenAdminList.stream().map(CanteenAdmin::getUserId).collect(Collectors.toList()); | return new UserDaoImpl().batchQueryUsers(userIdList); | 3 | 2023-12-01 04:55:12+00:00 | 8k |
SuperRicky14/TpaPlusPlus | src/main/java/net/superricky/tpaplusplus/command/TPAAcceptCommand.java | [
{
"identifier": "Config",
"path": "src/main/java/net/superricky/tpaplusplus/util/configuration/Config.java",
"snippet": "public class Config {\n public static final ForgeConfigSpec.Builder BUILDER = new ForgeConfigSpec.Builder();\n public static final ForgeConfigSpec SPEC;\n\n public static final ForgeConfigSpec.ConfigValue<Boolean> BACK_COMMAND_ENABLED;\n public static final ForgeConfigSpec.ConfigValue<Integer> TPA_TIMEOUT_IN_SECONDS;\n public static final ForgeConfigSpec.ConfigValue<Integer> TPA_ACCEPT_TIME_IN_SECONDS;\n public static final ForgeConfigSpec.ConfigValue<Boolean> SEND_TELEPORT_REQUEST_COUNTDOWN_TO_BOTH_PLAYERS;\n public static final ForgeConfigSpec.ConfigValue<Double> ALLOWED_MOVEMENT_DURING_ACCEPT_COUNTDOWN;\n public static final ForgeConfigSpec.ConfigValue<Boolean> SEND_COUNTDOWN_MOVEMENT_CANCEL_TO_BOTH_PLAYERS;\n public static final ForgeConfigSpec.ConfigValue<Boolean> ALLOW_TPTOGGLED_PLAYERS_TO_SEND_REQUESTS;\n public static final ForgeConfigSpec.ConfigValue<Boolean> SEND_BLOCKED_MESSAGES_TO_BOTH_PLAYERS;\n\n // Commands\n public static final ForgeConfigSpec.ConfigValue<String> TPA_COMMAND_NAME;\n public static final ForgeConfigSpec.ConfigValue<String> TPAHERE_COMMAND_NAME;\n public static final ForgeConfigSpec.ConfigValue<String> TPAACCEPT_COMMAND_NAME;\n public static final ForgeConfigSpec.ConfigValue<String> TPADENY_COMMAND_NAME;\n public static final ForgeConfigSpec.ConfigValue<String> TPACANCEL_COMMAND_NAME;\n public static final ForgeConfigSpec.ConfigValue<String> TPTOGGLE_COMMAND_NAME;\n public static final ForgeConfigSpec.ConfigValue<String> TPBLOCK_COMMAND_NAME;\n public static final ForgeConfigSpec.ConfigValue<String> TPUNBLOCK_COMMAND_NAME;\n public static final ForgeConfigSpec.ConfigValue<String> BACK_COMMAND_NAME;\n\n // Limitations\n public static final ForgeConfigSpec.ConfigValue<Double> FURTHEST_ALLOWED_DISTANCE;\n public static final ForgeConfigSpec.ConfigValue<Double> CLOSEST_ALLOWED_DISTANCE;\n public static final ForgeConfigSpec.ConfigValue<Boolean> ALLOW_INTER_DIMENSIONAL_TELEPORT;\n public static final ForgeConfigSpec.ConfigValue<Boolean> DISABLE_RANGE_CHECKS_INTER_DIMENSIONAL;\n\n // Advanced Settings\n public static final ForgeConfigSpec.ConfigValue<Integer> ASYNC_GENERAL_TASKS_THREAD_POOL;\n public static final ForgeConfigSpec.ConfigValue<Integer> ASYNC_AUTOSAVE_THREAD_POOL;\n public static final ForgeConfigSpec.ConfigValue<Integer> AUTOSAVE_INTERVAL;\n\n static {\n BUILDER.push(\"TPA++ Configuration\");\n BUILDER.comment(\" Unlike the messages configuration, every value in this config can be changed and reloaded safely during runtime!\");\n\n // TPA TIMEOUT\n TPA_TIMEOUT_IN_SECONDS = BUILDER.comment(\"\\n How long until teleport requests expire (in seconds)\")\n .comment(\" The default is 60 seconds ( 1 minute ), if you wish to disable this set this to 0\")\n .defineInRange(\"TPA Timeout\", 60, 0, Integer.MAX_VALUE);\n\n // TPA ACCEPT TIME\n TPA_ACCEPT_TIME_IN_SECONDS = BUILDER.comment(\"\\n How long it takes until a player is teleported via /tpaaccept\")\n .comment(\" The default is 5 seconds, if you wish to disable this set this to 0\")\n .defineInRange(\"TPA Accept Time\", 5, 0, Integer.MAX_VALUE);\n\n // BACK COMMAND\n BACK_COMMAND_ENABLED = BUILDER.comment(\"\\n Whether or not the /back system is enabled.\")\n .comment(\" /back is the command that will teleport you to your latest death!\")\n .define(\"Use /back\", true);\n\n // TPA SEND ACCEPT TIME COUNTDOWN TO BOTH PLAYERS\n SEND_TELEPORT_REQUEST_COUNTDOWN_TO_BOTH_PLAYERS = BUILDER.comment(\"\\n Whether or not to send the TPAAccept Countdown to both players.\")\n .define(\"Send Countdown To Both Players\", true);\n\n // CANCEL TPA ACCEPT ON MOVE\n ALLOWED_MOVEMENT_DURING_ACCEPT_COUNTDOWN = BUILDER.comment(\"\\n How much the player has to move to trigger a cancellation of the TPA accept countdown, due to moving.\")\n .comment(\" I left this here as an option, since this can be useful if you want to stop players from moving from a general area\")\n .comment(\" This range supports decimal values (e.g. 1.5), and is measured in blocks.\")\n .comment(\" Set this to 0 to allow players to move during the Teleport Accept Countdown, or to a very low number that is NOT 0 to prevent players from moving AT ALL, during the accept countdown.\")\n .comment(\" This uses the euclidean distance formula.\")\n .comment(\" Equal to: sqrt((x2 - x1)^2 + (y2 - y1)^2 + (z2 - z1)^2) where x1, y1, and z1 are the coordinates of the player when they first accepted the request, and x2, y2, and z2 are the coordinates of the player every tick whilst the request is being accepted.\")\n .comment(\" This has NO EFFECT, if the TPA Accept Countdown is set to 0\")\n .defineInRange(\"Allowed Movement During Accept Countdown\", 1, 0, Double.MAX_VALUE);\n\n // SEND MESSAGE TO SENDER ON TPA ACCEPT\n SEND_COUNTDOWN_MOVEMENT_CANCEL_TO_BOTH_PLAYERS = BUILDER.comment(\"\\n Whether to send a message to the sender when the receiver moves during a TPA accept countdown.\")\n .define(\"Send Countdown Movement Cancel To Both Players\", true);\n\n // ALLOW SENDERS TO SEND REQUESTS EVEN IF THEY HAVE TPTOGGLE ENABLED\n ALLOW_TPTOGGLED_PLAYERS_TO_SEND_REQUESTS = BUILDER.comment(\"\\n Whether to allow players with /tptoggle enabled, to send a teleport request\")\n .define(\"Allow TPToggled Players To Send Requests\", false);\n\n // SEND MESSAGE TO THE PERSON BEING BLOCKED / UNBLOCKED\n SEND_BLOCKED_MESSAGES_TO_BOTH_PLAYERS = BUILDER.comment(\"\\n Whether to send a message to the person being blocked / unblocked, when the sender blocks them.\")\n .define(\"Send Blocked Messages To Both Players\", true);\n\n BUILDER.comment(\"\\n-------------------------Commands-------------------------\");\n BUILDER.comment(\" This section of the config allows you to change the commands to whatever you please!\");\n BUILDER.comment(\" For example, you can change the /tpa command to /teleport-request, which means instead of entering /tpa players will have to enter /teleport-request\");\n BUILDER.comment(\" Command aliases (running the same command with one or more commands, for example you can make /tpa, /teleport-request and /tpasend all run the same commant ( /tpa )\");\n BUILDER.comment(\" It is NOT recommended to use anything other than ASCII characters here!\");\n BUILDER.comment(\" Modifying any of these commands requires a restart to take effect.\");\n\n TPA_COMMAND_NAME = BUILDER.comment(\"\\n The name of the /tpa command (what players run in chat)\")\n .define(\"TPA_COMMAND_NAME\", \"tpa\");\n\n TPAHERE_COMMAND_NAME = BUILDER.comment(\"\\n The name of the /tpahere command (what players run in chat)\")\n .define(\"TPAHERE_COMMAND_NAME\", \"tpahere\");\n\n TPAACCEPT_COMMAND_NAME = BUILDER.comment(\"\\n The name of the /tpaaccept command (what players run in chat)\")\n .define(\"TPAACCEPT_COMMAND_NAME\", \"tpaaccept\");\n\n TPADENY_COMMAND_NAME = BUILDER.comment(\"\\n The name of the /tpadeny command (what players run in chat)\")\n .define(\"TPADENY_COMMAND_NAME\", \"tpadeny\");\n\n TPACANCEL_COMMAND_NAME = BUILDER.comment(\"\\n The name of the /tpacancel command (what players run in chat)\")\n .define(\"TPACANCEL_COMMAND_NAME\", \"tpacancel\");\n\n TPTOGGLE_COMMAND_NAME = BUILDER.comment(\"\\n The name of the /tptoggle command (what players run in chat)\")\n .define(\"TPTOGGLE_COMMAND_NAME\", \"tptoggle\");\n\n TPBLOCK_COMMAND_NAME = BUILDER.comment(\"\\n The name of the /tpblock command (what players run in chat)\")\n .define(\"TPBLOCK_COMMAND_NAME\", \"tpblock\");\n\n TPUNBLOCK_COMMAND_NAME = BUILDER.comment(\"\\n The name of the /tpunblock command (what players run in chat)\")\n .define(\"TPUNBLOCK_COMMAND_NAME\", \"tpunblock\");\n\n BACK_COMMAND_NAME = BUILDER.comment(\"\\n The name of the /back command\")\n .comment(\" This has no affect if /back is not enabled in the configuration file.\")\n .define(\"BACK_COMMAND_NAME\", \"back\");\n\n BUILDER.comment(\"\\n-------------------------Limitations-------------------------\");\n BUILDER.comment(\" All limitations are DISABLED by default.\");\n\n // FURTHEST ALLOWED DISTANCE\n FURTHEST_ALLOWED_DISTANCE = BUILDER.comment(\"\\n How far away a player can be from another player in order to teleport\")\n .comment(\" Set this to 0 if you wish to disable this limitation\")\n .defineInRange(\"Furthest Allowed Teleport Distance\", 0, 0, Double.MAX_VALUE);\n\n // CLOSEST ALLOWED DISTANCE\n CLOSEST_ALLOWED_DISTANCE = BUILDER.comment(\"\\n How close a player can be from another player in order to teleport\")\n .comment(\" Set this to 0 if you wish to disable this limitation\")\n .defineInRange(\"Closest Allowed Teleport Distance\", 0, 0, Double.MAX_VALUE);\n\n // CLOSEST ALLOWED DISTANCE\n ALLOW_INTER_DIMENSIONAL_TELEPORT = BUILDER.comment(\"\\n Whether or not to allow sending TPA requests if the player(s) are not in the same dimension\")\n .comment(\" Set this to false if you wish to disable this limitation\")\n .define(\"Allow Inter-Dimensional Teleport\", true);\n\n // FURTHEST ALLOWED DISTANCE\n DISABLE_RANGE_CHECKS_INTER_DIMENSIONAL = BUILDER.comment(\"\\n Whether or not to disable the range checks feature when teleporting inter-dimensionally\")\n .comment(\" This has no affect if \\\"Allow Inter-Dimensional Teleport\\\" is false, or if all range checks are disabled.\")\n .comment(\" TPAPlusPlus will automatically account for the nether's coordinate system ( 1 block in the nether is 8 blocks in the overworld! )\")\n .comment(\" Set this to false if you wish to disable this limitation\")\n .define(\"Disable Inter Dimensional Range Checks\", true);\n\n BUILDER.comment(\"\\n-------------------------Advanced Settings-------------------------\");\n BUILDER.comment(\" WARNING: CHANGING THESE SETTINGS COULD SEVERELY DAMAGE YOUR SERVER, COMPUTER, OR CAUSE CORRUPTION OF DATA.\");\n BUILDER.comment(\" IT IS NOT RECOMMENDED TO CHANGE THESE VALUES FROM THE DEFAULTS UNLESS YOU KNOW EXACTLY WHAT YOU ARE DOING\");\n BUILDER.comment(\" Most options here have already been optimized for most systems, I doubt you will experience significant performance gains by changing the options below.\");\n\n // THREAD POOL FOR GENERAL ASYNC TASKS\n ASYNC_GENERAL_TASKS_THREAD_POOL = BUILDER.comment(\"\\n How many threads to use for general async tasks in the mod, such as the TPA Accept Countdown, or the TPA Timeout Timer.\")\n .defineInRange(\"ASYNC_GENERAL_TASKS_THREAD_POOL\", 1, 0, Integer.MAX_VALUE);\n\n // THREAD POOL FOR AUTO-SAVING\n ASYNC_AUTOSAVE_THREAD_POOL = BUILDER.comment(\"\\n How many threads to use for asynchronous autosaving of data in the mod.\")\n .comment(\" Changing this setting will only provide negligible performance gains, even if you are using a very short autosave interval, this is because everything is synchronized between threads, preventing more than one thread from accessing it at a time.\")\n .defineInRange(\"ASYNC_AUTOSAVE_THREAD_POOL\", 1, 0, Integer.MAX_VALUE);\n\n // AUTO-SAVE INTERVAL\n AUTOSAVE_INTERVAL = BUILDER.comment(\"\\n How long (in seconds) between autosaves, if you experience data loss, set this number lower.\")\n .defineInRange(\"AUTOSAVE_INTERVAL\", 300, 0, Integer.MAX_VALUE);\n\n BUILDER.pop();\n SPEC = BUILDER.build();\n }\n\n private Config() {\n }\n}"
},
{
"identifier": "RequestManager",
"path": "src/main/java/net/superricky/tpaplusplus/util/manager/RequestManager.java",
"snippet": "public class RequestManager {\n static final Set<Request> requestSet = new HashSet<>();\n\n private RequestManager() {\n }\n\n public static boolean isPlayerIdentical(ServerPlayer player1, ServerPlayer player2) {\n return player1.getUUID().equals(player2.getUUID());\n }\n\n public static void clearRequestSet() {\n requestSet.clear();\n }\n\n public static boolean alreadySentTeleportRequest(Request request) {\n for (Request currentRequest : requestSet) {\n if (isPlayerIdentical(request.getSender(), currentRequest.getSender())\n && isPlayerIdentical(request.getReceiver(), currentRequest.getReceiver())) {\n return true;\n }\n }\n return false;\n }\n\n // Deny command is run by the receiver, hence why it's in the receiver's point of view.\n private static void denyFunctionality(Request request, ServerPlayer receiver) {\n if (Objects.isNull(request)) {\n receiver.sendSystemMessage(Component.literal(Messages.ERR_REQUEST_NOT_FOUND.get()));\n return;\n }\n\n request.getReceiver().sendSystemMessage(Component.literal(String.format(Messages.RECEIVER_DENIES_TPA.get(), request.getSender().getName().getString())));\n request.getSender().sendSystemMessage(Component.literal(String.format(Messages.SENDER_GOT_DENIED_TPA.get(), request.getReceiver().getName().getString())));\n\n requestSet.remove(request);\n }\n public static void denyTeleportRequest(ServerPlayer receiver) {\n Request request = RequestGrabUtil.getReceiverRequest(receiver);\n denyFunctionality(request, receiver);\n }\n\n // Deny command is run by the receiver, hence why it's in the receiver's point of view.\n public static void denyTeleportRequest(ServerPlayer receiver, ServerPlayer sender) {\n Request request = RequestGrabUtil.getReceiverRequest(receiver, sender);\n denyFunctionality(request, receiver);\n }\n\n // Cancel command is run by the sender, hence why it's in the sender's point of view.\n private static void cancelFunctionality(Request request, ServerPlayer sender) {\n if (Objects.isNull(request)) {\n sender.sendSystemMessage(Component.literal(Messages.ERR_REQUEST_NOT_FOUND.get()));\n return;\n }\n\n request.getSender().sendSystemMessage(Component.literal(String.format(Messages.SENDER_CANCELS_TPA.get(), request.getReceiver().getName().getString())));\n request.getReceiver().sendSystemMessage(Component.literal(String.format(Messages.RECEIVER_GOT_CANCELLED_TPA.get(), request.getSender().getName().getString())));\n\n requestSet.remove(request);\n }\n public static void cancelTeleportRequest(ServerPlayer sender) {\n Request request = RequestGrabUtil.getSenderRequest(sender);\n cancelFunctionality(request, sender);\n }\n\n public static void cancelTeleportRequest(ServerPlayer sender, ServerPlayer receiver) {\n Request request = RequestGrabUtil.getSenderRequest(sender, receiver);\n cancelFunctionality(request, sender);\n }\n\n // Send command is run by the sender, hence why its in the sender's point of view\n public static void sendTeleportRequest(ServerPlayer sender, ServerPlayer receiver, boolean isHereRequest) {\n if (isPlayerIdentical(sender, receiver)) {\n sender.sendSystemMessage(Component.literal(Messages.ERR_NO_SELF_TELEPORT.get()));\n return;\n }\n\n if (PlayerBlockingManager.isPlayerBlocked(sender, receiver)) return; // Return if one of the players has blocked the other player.\n\n PlayerData receiverData = SaveDataManager.getPlayerData(receiver);\n\n if (Boolean.FALSE.equals(Objects.isNull(receiverData)) && receiverData.getTPToggle()) { // receiverData is not null && receiver TP toggle is enabled.\n sender.sendSystemMessage(Component.literal(MessageParser.enhancedFormatter(Messages.ERR_RECEIVER_TP_DISABLED.get(),\n Map.of(\"receiverName\", receiver.getName().getString()))));\n return;\n }\n\n if (Boolean.FALSE.equals(Config.ALLOW_TPTOGGLED_PLAYERS_TO_SEND_REQUESTS.get())) { // Allow TPToggled players to send requests is disabled in the config\n PlayerData senderData = SaveDataManager.getPlayerData(sender);\n\n if (Boolean.FALSE.equals(Objects.isNull(senderData)) && senderData.getTPToggle()) { // senderData is not null && sender TP toggle is enabled.\n sender.sendSystemMessage(Component.literal(Messages.ERR_SENDER_TP_DISABLED.get()));\n return;\n }\n }\n\n // run the notify function and return if it false, to stop the player from sending the request.\n if (!LimitationManager.notifyAndCheckAllowedToTeleport(sender, receiver, false)) return;\n\n Request request = new Request(sender, receiver, isHereRequest);\n\n requestSet.add(request);\n\n AsyncTaskManager.scheduleTeleportTimeout(request);\n\n if (isHereRequest) {\n sender.sendSystemMessage(Component.literal(String.format(Messages.SENDER_SENT_TPAHERE.get(), receiver.getName().getString())));\n receiver.sendSystemMessage(Component.literal(String.format(Messages.RECEIVER_GOT_TPAHERE.get(), sender.getName().getString())));\n } else {\n sender.sendSystemMessage(Component.literal(String.format(Messages.SENDER_SENT_TPA.get(), receiver.getName().getString())));\n receiver.sendSystemMessage(Component.literal(String.format(Messages.RECEIVER_GOT_TPA.get(), sender.getName().getString())));\n }\n }\n\n // Accept command is run by the sender, hence why it's in the sender's point of view.\n static void acceptFunctionality(Request request, ServerPlayer receiver, boolean absolute) {\n if (Objects.isNull(request)) {\n receiver.sendSystemMessage(Component.literal(Messages.ERR_REQUEST_NOT_FOUND.get()));\n return;\n }\n\n if (absolute || Config.TPA_ACCEPT_TIME_IN_SECONDS.get() == 0) {\n absoluteAcceptFunctionality(request, receiver);\n } else {\n AsyncTaskManager.startTPAAcceptCountdown(request);\n }\n }\n\n private static void absoluteAcceptFunctionality(Request request, ServerPlayer receiver) {\n receiver.sendSystemMessage(Component.literal(String.format(Messages.RECEIVER_ACCEPTS_TPA.get(), request.getSender().getName().getString())));\n request.getSender().sendSystemMessage(Component.literal(String.format(Messages.SENDER_GOT_ACCEPTED_TPA.get(), request.getSender().getName().getString())));\n\n teleport(request);\n\n requestSet.remove(request);\n }\n\n public static void acceptTeleportRequest(ServerPlayer receiver) {\n Request request = RequestGrabUtil.getReceiverRequest(receiver);\n acceptFunctionality(request, receiver, false);\n }\n\n public static void acceptTeleportRequest(ServerPlayer receiver, ServerPlayer sender) {\n Request request = RequestGrabUtil.getReceiverRequest(receiver, sender);\n acceptFunctionality(request, receiver, false);\n }\n\n public static void teleport(Request request) {\n ServerPlayer sender = request.getSender();\n ServerPlayer receiver = request.getReceiver();\n\n // /tpahere\n if (request.isHereRequest()) {\n receiver.teleportTo(sender.serverLevel(), sender.getX(), sender.getY(), sender.getZ(), sender.getYRot(), sender.getXRot());\n }\n\n // /tpa\n sender.teleportTo(receiver.serverLevel(), receiver.getX(), receiver.getY(), receiver.getZ(), receiver.getYRot(), receiver.getXRot());\n }\n\n /**\n * A utility class used inside the request manager for grabbing teleport requests from the requestSet, based on the players point of view.\n * This is important as since we have commands that the receiver runs, that also have to grab the same teleport request that was sent by the sender,\n * and vice-versa, meaning that we have to use something like this since there is no one-size-fits-all solution here.\n */\n private static class RequestGrabUtil {\n @Nullable\n public static Request getSenderRequest(ServerPlayer sender) {\n for (Request request : RequestManager.requestSet) {\n if (isPlayerIdentical(request.getSender(), sender)) {\n return request;\n }\n }\n return null;\n }\n\n @Nullable\n public static Request getSenderRequest(ServerPlayer sender, ServerPlayer receiver) {\n for (Request request : RequestManager.requestSet) {\n if (isPlayerIdentical(request.getSender(), sender) &&\n isPlayerIdentical(request.getReceiver(), receiver)) {\n return request;\n }\n }\n return null;\n }\n\n @Nullable\n public static Request getReceiverRequest(ServerPlayer receiver) {\n for (Request request : RequestManager.requestSet) {\n if (isPlayerIdentical(request.getReceiver(), receiver)) {\n return request;\n }\n }\n return null;\n }\n\n @Nullable\n public static Request getReceiverRequest(ServerPlayer receiver, ServerPlayer sender) {\n for (Request request : RequestManager.requestSet) {\n if (isPlayerIdentical(request.getReceiver(), receiver) &&\n isPlayerIdentical(request.getSender(), sender)) {\n return request;\n }\n }\n return null;\n }\n }\n}"
}
] | import com.mojang.brigadier.exceptions.CommandSyntaxException;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.commands.arguments.EntityArgument;
import net.minecraft.server.level.ServerPlayer;
import net.minecraftforge.event.RegisterCommandsEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;
import net.superricky.tpaplusplus.util.configuration.Config;
import net.superricky.tpaplusplus.util.manager.RequestManager;
import org.apache.commons.lang3.NotImplementedException;
import static net.minecraft.commands.Commands.argument;
import static net.minecraft.commands.Commands.literal; | 5,053 | package net.superricky.tpaplusplus.command;
@Mod.EventBusSubscriber
public class TPAAcceptCommand {
@SubscribeEvent()
public static void onRegisterCommandEvent(RegisterCommandsEvent event) { | package net.superricky.tpaplusplus.command;
@Mod.EventBusSubscriber
public class TPAAcceptCommand {
@SubscribeEvent()
public static void onRegisterCommandEvent(RegisterCommandsEvent event) { | event.getDispatcher().register(literal(Config.TPAACCEPT_COMMAND_NAME.get()) | 0 | 2023-12-02 05:41:24+00:00 | 8k |
aosolorzano/city-tasks-aws-fullstack | apis/city-tasks-api/src/test/java/com/hiperium/city/tasks/api/controllers/TaskControllerValidationsTest.java | [
{
"identifier": "AbstractContainerBaseTest",
"path": "apis/city-tasks-api/src/test/java/com/hiperium/city/tasks/api/common/AbstractContainerBaseTest.java",
"snippet": "public abstract class AbstractContainerBaseTest {\n\n protected static final String AUTHORIZATION = \"Authorization\";\n\n private static final KeycloakContainer KEYCLOAK_CONTAINER;\n private static final PostgreSQLContainer POSTGRES_CONTAINER;\n private static final LocalStackContainer LOCALSTACK_CONTAINER;\n\n // Singleton containers.\n // See: https://www.testcontainers.org/test_framework_integration/manual_lifecycle_control/#singleton-containers\n static {\n KEYCLOAK_CONTAINER = new KeycloakContainer()\n .withRealmImportFile(\"keycloak-realm.json\");\n\n POSTGRES_CONTAINER = new PostgreSQLContainer<>(\"postgres:14.4\")\n .withUsername(\"postgres\")\n .withPassword(\"postgres123\")\n .withDatabaseName(\"CityTasksDB\");\n\n LOCALSTACK_CONTAINER = new LocalStackContainer(DockerImageName.parse(\"localstack/localstack:latest\"))\n .withServices(LocalStackContainer.Service.DYNAMODB)\n .withCopyToContainer(MountableFile.forClasspathResource(\"infra-setup.sh\"),\n \"/etc/localstack/init/ready.d/api-setup.sh\")\n .withCopyToContainer(MountableFile.forClasspathResource(\"data-setup.json\"),\n \"/var/lib/localstack/api-data.json\");\n\n KEYCLOAK_CONTAINER.start();\n POSTGRES_CONTAINER.start();\n LOCALSTACK_CONTAINER.start();\n }\n\n @DynamicPropertySource\n public static void dynamicPropertySource(DynamicPropertyRegistry registry) {\n // SPRING SECURITY OAUTH2 JWT\n registry.add(\"spring.security.oauth2.resourceserver.jwt.issuer-uri\",\n () -> KEYCLOAK_CONTAINER.getAuthServerUrl() + TestsUtil.KEYCLOAK_REALM);\n\n // SPRING DATA JDBC CONNECTION\n registry.add(\"spring.datasource.url\", POSTGRES_CONTAINER::getJdbcUrl);\n registry.add(\"spring.datasource.username\", POSTGRES_CONTAINER::getUsername);\n registry.add(\"spring.datasource.password\", POSTGRES_CONTAINER::getPassword);\n registry.add(\"spring.datasource.driver-class-name\", () -> TestsUtil.POSTGRESQL_DRIVER);\n\n // SPRING QUARTZ JDBC CONNECTION\n registry.add(\"spring.quartz.properties.org.quartz.dataSource.cityTasksQuartzDS.URL\",\n POSTGRES_CONTAINER::getJdbcUrl);\n registry.add(\"spring.quartz.properties.org.quartz.dataSource.cityTasksQuartzDS.user\",\n POSTGRES_CONTAINER::getUsername);\n registry.add(\"spring.quartz.properties.org.quartz.dataSource.cityTasksQuartzDS.password\",\n POSTGRES_CONTAINER::getPassword);\n registry.add(\"spring.quartz.properties.org.quartz.dataSource.cityTasksQuartzDS.driver\",\n () -> TestsUtil.POSTGRESQL_DRIVER);\n registry.add(\"spring.quartz.properties.org.quartz.dataSource.cityTasksQuartzDS.provider\",\n () -> TestsUtil.QUARTZ_DS_PROVIDER);\n\n // AWS REGION, CREDENTIALS, AND ENDPOINT-OVERRIDE\n registry.add(\"aws.region\", LOCALSTACK_CONTAINER::getRegion);\n registry.add(\"aws.accessKeyId\", LOCALSTACK_CONTAINER::getAccessKey);\n registry.add(\"aws.secretAccessKey\", LOCALSTACK_CONTAINER::getSecretKey);\n registry.add(PropertiesUtil.AWS_ENDPOINT_OVERRIDE_PROPERTY, () ->\n LOCALSTACK_CONTAINER.getEndpoint().toString());\n }\n\n protected String getBearerAccessToken() {\n Keycloak keycloakClient = KEYCLOAK_CONTAINER.getKeycloakAdminClient();\n AccessTokenResponse accessTokenResponse = keycloakClient.tokenManager().getAccessToken();\n return \"Bearer \" + Objects.requireNonNull(accessTokenResponse).getToken();\n }\n}"
},
{
"identifier": "ErrorDetailsDTO",
"path": "apis/city-tasks-api/src/main/java/com/hiperium/city/tasks/api/dto/ErrorDetailsDTO.java",
"snippet": "@Data\n@Builder\n@NoArgsConstructor\n@AllArgsConstructor\npublic class ErrorDetailsDTO {\n\n private ZonedDateTime errorDate;\n private String requestedPath;\n private String errorMessage;\n private String errorCode;\n}"
},
{
"identifier": "TaskDTO",
"path": "apis/city-tasks-api/src/main/java/com/hiperium/city/tasks/api/dto/TaskDTO.java",
"snippet": "@Data\n@Builder\n@NoArgsConstructor\n@AllArgsConstructor\npublic class TaskDTO {\n\n @Schema(description = \"Required for update and delete operations.\", example = \"8585\")\n private Long id;\n\n @NotEmpty(message = \"validation.task.name.NotEmpty.message\")\n private String name;\n\n private String description;\n\n @Schema(description = \"Active by default when creating the Task.\", example = \"ACT\")\n private EnumTaskStatus status;\n\n @Schema(example = \"123\")\n @NotEmpty(message = \"validation.device.id.NotEmpty.message\")\n private String deviceId;\n\n @Enumerated(EnumType.STRING)\n @NotNull(message = \"validation.device.action.NotEmpty.message\")\n @Schema(description = \"Operation performed against the Device when Task is triggered.\", example = \"ACTIVATE\")\n private EnumDeviceOperation deviceOperation;\n\n @Schema(description = \"Time of the day in 24/hours format when the Task will be triggered.\", example = \"20\")\n @Min(value = 0, message = \"validation.task.hour.Min.message\")\n @Max(value = 23, message = \"validation.task.hour.Max.message\")\n private int hour;\n\n @Schema(description = \"Minute of the day when the Task will be triggered.\", example = \"30\")\n @Min(value = 0, message = \"validation.task.minute.Min.message\")\n @Max(value = 59, message = \"validation.task.minute.Max.message\")\n private int minute;\n\n @Schema(description = \"Days of the week when the Task will be triggered.\", example = \"MON,TUE,SAT\")\n @NotEmpty(message = \"validation.task.execution.days.NotEmpty.message\")\n private String executionDays;\n\n @Schema(description = \"The last DateTime until which the Task will be triggered.\", example = \"2021-08-01T00:00:00.000Z\")\n @Future(message = \"validation.task.execute.until.Future.message\")\n private ZonedDateTime executeUntil;\n}"
},
{
"identifier": "TasksUtil",
"path": "apis/city-tasks-api/src/main/java/com/hiperium/city/tasks/api/utils/TasksUtil.java",
"snippet": "@NoArgsConstructor(access = AccessLevel.PRIVATE)\npublic final class TasksUtil {\n\n private static final List<String> DAYS_LIST = Arrays.asList(\"SUN\",\"MON\",\"TUE\",\"WED\",\"THU\",\"FRI\",\"SAT\");\n private static final char[] HEX_ARRAY = \"HiperiumTasksService\".toCharArray();\n private static final int JOB_ID_LENGTH = 20;\n\n public static String generateJobId() {\n MessageDigest salt;\n try {\n salt = MessageDigest.getInstance(\"SHA-256\");\n salt.update(UUID.randomUUID().toString().getBytes(StandardCharsets.UTF_8));\n } catch (NoSuchAlgorithmException e) {\n throw new UnsupportedOperationException(e.getMessage());\n }\n String uuid = bytesToHex(salt.digest());\n return uuid.substring(0, JOB_ID_LENGTH);\n }\n\n private static String bytesToHex(byte[] bytes) {\n char[] hexChars = new char[bytes.length * 2];\n for (int j = 0; j < bytes.length; j++) {\n int v = bytes[j] & 0xFF;\n hexChars[j * 2] = HEX_ARRAY[v >>> 4];\n hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F];\n }\n return new String(hexChars);\n }\n\n public static Task getTaskTemplate() {\n return Task.builder()\n .name(\"Test class\")\n .description(\"Task description.\")\n .status(EnumTaskStatus.ACT)\n .hour(12)\n .minute(0)\n .executionDays(\"MON,WED,SUN\")\n .executeUntil(ZonedDateTime.now().plusMonths(1))\n .deviceOperation(EnumDeviceOperation.ACTIVATE)\n .build();\n }\n\n public static TaskCriteriaDTO getTaskCriteriaTemplate() {\n return TaskCriteriaDTO.builder()\n .name(\"Task\")\n .status(EnumTaskStatus.ACT)\n .deviceId(\"1\")\n .deviceOperation(EnumDeviceOperation.ACTIVATE)\n .hour(Calendar.getInstance().get(Calendar.HOUR_OF_DAY))\n .minute(Calendar.getInstance().get(Calendar.MINUTE))\n .executionDay(DAYS_LIST.get(Calendar.getInstance().get(Calendar.DAY_OF_WEEK) - 1))\n .build();\n }\n\n public static TaskDTO getTaskDtoTemplate() {\n return TaskDTO.builder()\n .name(\"Task name\")\n .description(\"Task description\")\n .status(EnumTaskStatus.ACT)\n .deviceId(\"123\")\n .deviceOperation(EnumDeviceOperation.ACTIVATE)\n .hour(Calendar.getInstance().get(Calendar.HOUR_OF_DAY))\n .minute(Calendar.getInstance().get(Calendar.MINUTE))\n .executionDays(DAYS_LIST.get(Calendar.getInstance().get(Calendar.DAY_OF_WEEK) - 1))\n .executeUntil(ZonedDateTime.now().plusYears(1))\n .build();\n }\n}"
},
{
"identifier": "EnumLanguageCode",
"path": "apis/city-tasks-api/src/main/java/com/hiperium/city/tasks/api/utils/enums/EnumLanguageCode.java",
"snippet": "public enum EnumLanguageCode {\n\n EN(\"en\"),\n ES(\"es\");\n\n private final String code;\n\n EnumLanguageCode(String code) {\n this.code = code;\n }\n\n public String getCode() {\n return code;\n }\n}"
},
{
"identifier": "EnumValidationError",
"path": "apis/city-tasks-api/src/main/java/com/hiperium/city/tasks/api/utils/enums/EnumValidationError.java",
"snippet": "public enum EnumValidationError {\n\n FIELD_VALIDATION_ERROR(\"TSK-FLD-VAL\", null), // USED FOR BEAN VALIDATION EXCEPTIONS ONLY.\n NO_CRITERIA_FOUND(\"TSK-CRT-001\", \"validation.task.criteria.params.NotNull.message\");\n\n private final String code;\n private final String message;\n\n EnumValidationError(String code, String message) {\n this.code = code;\n this.message = message;\n }\n\n public String getCode() {\n return code;\n }\n\n public String getMessage() {\n return message;\n }\n}"
},
{
"identifier": "TASK_V1_PATH",
"path": "apis/city-tasks-api/src/main/java/com/hiperium/city/tasks/api/utils/PathsUtil.java",
"snippet": "public static final String TASK_V1_PATH = \"/api/v1/task\";"
}
] | import com.hiperium.city.tasks.api.common.AbstractContainerBaseTest;
import com.hiperium.city.tasks.api.dto.ErrorDetailsDTO;
import com.hiperium.city.tasks.api.dto.TaskDTO;
import com.hiperium.city.tasks.api.utils.TasksUtil;
import com.hiperium.city.tasks.api.utils.enums.EnumLanguageCode;
import com.hiperium.city.tasks.api.utils.enums.EnumValidationError;
import org.assertj.core.api.Assertions;
import org.jetbrains.annotations.NotNull;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.reactive.AutoConfigureWebTestClient;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.web.reactive.server.WebTestClient;
import java.time.ZonedDateTime;
import static com.hiperium.city.tasks.api.utils.PathsUtil.TASK_V1_PATH;
import static org.junit.jupiter.api.TestInstance.Lifecycle.PER_CLASS; | 4,385 | Assertions.assertThat(errorDetailsDTO.getErrorCode())
.isEqualTo(EnumValidationError.FIELD_VALIDATION_ERROR.getCode());
Assertions.assertThat(errorDetailsDTO.getErrorMessage())
.isEqualTo("El minuto de la tarea debe ser mayor o igual a 0.");
});
}
@Test
@DisplayName("Create Task without executions days")
void givenTaskWithoutExecutionDays_whenCreate_thenReturnError404() {
taskDTO = TasksUtil.getTaskDtoTemplate();
taskDTO.setExecutionDays(null);
this.getValidationErrorResponse(taskDTO, EnumLanguageCode.EN)
.value(errorDetailsDTO -> {
Assertions.assertThat(errorDetailsDTO.getErrorCode())
.isEqualTo(EnumValidationError.FIELD_VALIDATION_ERROR.getCode());
Assertions.assertThat(errorDetailsDTO.getErrorMessage())
.isEqualTo("Task execution days cannot be empty.");
});
}
@Test
@DisplayName("Create Task without executions days - Spanish")
void givenTaskWithoutExecutionDays_whenCreate_thenReturnError404InSpanish() {
taskDTO = TasksUtil.getTaskDtoTemplate();
taskDTO.setExecutionDays(null);
this.getValidationErrorResponse(taskDTO, EnumLanguageCode.ES)
.value(errorDetailsDTO -> {
Assertions.assertThat(errorDetailsDTO.getErrorCode())
.isEqualTo(EnumValidationError.FIELD_VALIDATION_ERROR.getCode());
Assertions.assertThat(errorDetailsDTO.getErrorMessage())
.isEqualTo("Los días de ejecución de la tarea no pueden estar vacíos.");
});
}
@Test
@DisplayName("Create Task with past execute until date")
void givenTaskWithPastExecuteUntil_whenCreate_thenReturnError404() {
taskDTO = TasksUtil.getTaskDtoTemplate();
taskDTO.setExecuteUntil(ZonedDateTime.now().minusDays(1));
this.getValidationErrorResponse(taskDTO, EnumLanguageCode.EN)
.value(errorDetailsDTO -> {
Assertions.assertThat(errorDetailsDTO.getErrorCode())
.isEqualTo(EnumValidationError.FIELD_VALIDATION_ERROR.getCode());
Assertions.assertThat(errorDetailsDTO.getErrorMessage())
.isEqualTo("Task execute until must be in the future.");
});
}
@Test
@DisplayName("Create Task with past execute until date - Spanish")
void givenTaskWithPastExecuteUntil_whenCreate_thenReturnError404InSpanish() {
taskDTO = TasksUtil.getTaskDtoTemplate();
taskDTO.setExecuteUntil(ZonedDateTime.now().minusDays(1));
this.getValidationErrorResponse(taskDTO, EnumLanguageCode.ES)
.value(errorDetailsDTO -> {
Assertions.assertThat(errorDetailsDTO.getErrorCode())
.isEqualTo(EnumValidationError.FIELD_VALIDATION_ERROR.getCode());
Assertions.assertThat(errorDetailsDTO.getErrorMessage())
.isEqualTo("La fecha final de ejecución de la tarea debe ser posterior a la fecha actual.");
});
}
@Test
@DisplayName("Create Task without Device ID")
void givenTaskWithoutDeviceId_whenCreate_thenReturnError404() {
taskDTO = TasksUtil.getTaskDtoTemplate();
taskDTO.setDeviceId(null);
this.getValidationErrorResponse(taskDTO, EnumLanguageCode.EN)
.value(errorDetailsDTO -> {
Assertions.assertThat(errorDetailsDTO.getErrorCode())
.isEqualTo(EnumValidationError.FIELD_VALIDATION_ERROR.getCode());
Assertions.assertThat(errorDetailsDTO.getErrorMessage())
.isEqualTo("Device ID cannot be empty.");
});
}
@Test
@DisplayName("Create Task without Device ID - Spanish")
void givenTaskWithoutDeviceId_whenCreate_thenReturnError404inSpanish() {
taskDTO = TasksUtil.getTaskDtoTemplate();
taskDTO.setDeviceId(null);
this.getValidationErrorResponse(taskDTO, EnumLanguageCode.ES)
.value(errorDetailsDTO -> {
Assertions.assertThat(errorDetailsDTO.getErrorCode())
.isEqualTo(EnumValidationError.FIELD_VALIDATION_ERROR.getCode());
Assertions.assertThat(errorDetailsDTO.getErrorMessage())
.isEqualTo("El ID del dispositivo no puede estar vacío.");
});
}
@Test
@DisplayName("Create Task without Device Action")
void givenTaskWithoutDeviceAction_whenCreate_thenReturnError404() {
taskDTO = TasksUtil.getTaskDtoTemplate();
taskDTO.setDeviceOperation(null);
this.getValidationErrorResponse(taskDTO, EnumLanguageCode.EN)
.value(errorDetailsDTO -> {
Assertions.assertThat(errorDetailsDTO.getErrorCode())
.isEqualTo(EnumValidationError.FIELD_VALIDATION_ERROR.getCode());
Assertions.assertThat(errorDetailsDTO.getErrorMessage())
.isEqualTo("Device action cannot be empty.");
});
}
@Test
@DisplayName("Create Task without Device Action - Spanish")
void givenTaskWithoutDeviceAction_whenCreate_thenReturnError404InSpanish() {
taskDTO = TasksUtil.getTaskDtoTemplate();
taskDTO.setDeviceOperation(null);
this.getValidationErrorResponse(taskDTO, EnumLanguageCode.ES)
.value(errorDetailsDTO -> {
Assertions.assertThat(errorDetailsDTO.getErrorCode())
.isEqualTo(EnumValidationError.FIELD_VALIDATION_ERROR.getCode());
Assertions.assertThat(errorDetailsDTO.getErrorMessage())
.isEqualTo("La acción del dispositivo no puede estar vacía.");
});
}
@NotNull | package com.hiperium.city.tasks.api.controllers;
@ActiveProfiles("test")
@TestInstance(PER_CLASS)
@AutoConfigureWebTestClient
@TestPropertySource(locations = "classpath:application-test.properties")
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class TaskControllerValidationsTest extends AbstractContainerBaseTest {
@Autowired
private WebTestClient webTestClient;
private static TaskDTO taskDTO;
@Test
@DisplayName("Create Task without name")
void givenTaskWithoutName_whenCreate_thenReturnError404() {
taskDTO = TasksUtil.getTaskDtoTemplate();
taskDTO.setName(null);
this.getValidationErrorResponse(taskDTO, EnumLanguageCode.EN)
.value(errorDetailsDTO -> {
Assertions.assertThat(errorDetailsDTO.getErrorCode())
.isEqualTo(EnumValidationError.FIELD_VALIDATION_ERROR.getCode());
Assertions.assertThat(errorDetailsDTO.getErrorMessage())
.isEqualTo("Task name cannot be empty.");
});
}
@Test
@DisplayName("Create Task without name - Spanish")
void givenTaskWithoutName_whenCreate_thenReturnError404InSpanish() {
taskDTO = TasksUtil.getTaskDtoTemplate();
taskDTO.setName(null);
this.getValidationErrorResponse(taskDTO, EnumLanguageCode.ES)
.value(errorDetailsDTO -> {
Assertions.assertThat(errorDetailsDTO.getErrorCode())
.isEqualTo(EnumValidationError.FIELD_VALIDATION_ERROR.getCode());
Assertions.assertThat(errorDetailsDTO.getErrorMessage())
.isEqualTo("El nombre de la tarea no puede estar vacío.");
});
}
@Test
@DisplayName("Create Task with wrong hour")
void givenTaskWithWrongHour_whenCreate_thenReturnError404() {
taskDTO = TasksUtil.getTaskDtoTemplate();
taskDTO.setHour(25);
this.getValidationErrorResponse(taskDTO, EnumLanguageCode.EN)
.value(errorDetailsDTO -> {
Assertions.assertThat(errorDetailsDTO.getErrorCode())
.isEqualTo(EnumValidationError.FIELD_VALIDATION_ERROR.getCode());
Assertions.assertThat(errorDetailsDTO.getErrorMessage())
.isEqualTo("Task hour must be less than or equal to 23.");
});
}
@Test
@DisplayName("Create Task with wrong hour - Spanish")
void givenTaskWithWrongHour_whenCreate_thenReturnError404InSpanish() {
taskDTO = TasksUtil.getTaskDtoTemplate();
taskDTO.setHour(25);
this.getValidationErrorResponse(taskDTO, EnumLanguageCode.ES)
.value(errorDetailsDTO -> {
Assertions.assertThat(errorDetailsDTO.getErrorCode())
.isEqualTo(EnumValidationError.FIELD_VALIDATION_ERROR.getCode());
Assertions.assertThat(errorDetailsDTO.getErrorMessage())
.isEqualTo("La hora de la tarea debe ser menor o igual a 23.");
});
}
@Test
@DisplayName("Create Task with wrong minute")
void givenTaskWithWrongMinute_whenCreate_thenReturnError404() {
taskDTO = TasksUtil.getTaskDtoTemplate();
taskDTO.setMinute(-20);
this.getValidationErrorResponse(taskDTO, EnumLanguageCode.EN)
.value(errorDetailsDTO -> {
Assertions.assertThat(errorDetailsDTO.getErrorCode())
.isEqualTo(EnumValidationError.FIELD_VALIDATION_ERROR.getCode());
Assertions.assertThat(errorDetailsDTO.getErrorMessage())
.isEqualTo("Task minute must be greater than or equal to 0.");
});
}
@Test
@DisplayName("Create Task with wrong minute - Spanish")
void givenTaskWithWrongMinute_whenCreate_thenReturnError404InSpanish() {
taskDTO = TasksUtil.getTaskDtoTemplate();
taskDTO.setMinute(-20);
this.getValidationErrorResponse(taskDTO, EnumLanguageCode.ES)
.value(errorDetailsDTO -> {
Assertions.assertThat(errorDetailsDTO.getErrorCode())
.isEqualTo(EnumValidationError.FIELD_VALIDATION_ERROR.getCode());
Assertions.assertThat(errorDetailsDTO.getErrorMessage())
.isEqualTo("El minuto de la tarea debe ser mayor o igual a 0.");
});
}
@Test
@DisplayName("Create Task without executions days")
void givenTaskWithoutExecutionDays_whenCreate_thenReturnError404() {
taskDTO = TasksUtil.getTaskDtoTemplate();
taskDTO.setExecutionDays(null);
this.getValidationErrorResponse(taskDTO, EnumLanguageCode.EN)
.value(errorDetailsDTO -> {
Assertions.assertThat(errorDetailsDTO.getErrorCode())
.isEqualTo(EnumValidationError.FIELD_VALIDATION_ERROR.getCode());
Assertions.assertThat(errorDetailsDTO.getErrorMessage())
.isEqualTo("Task execution days cannot be empty.");
});
}
@Test
@DisplayName("Create Task without executions days - Spanish")
void givenTaskWithoutExecutionDays_whenCreate_thenReturnError404InSpanish() {
taskDTO = TasksUtil.getTaskDtoTemplate();
taskDTO.setExecutionDays(null);
this.getValidationErrorResponse(taskDTO, EnumLanguageCode.ES)
.value(errorDetailsDTO -> {
Assertions.assertThat(errorDetailsDTO.getErrorCode())
.isEqualTo(EnumValidationError.FIELD_VALIDATION_ERROR.getCode());
Assertions.assertThat(errorDetailsDTO.getErrorMessage())
.isEqualTo("Los días de ejecución de la tarea no pueden estar vacíos.");
});
}
@Test
@DisplayName("Create Task with past execute until date")
void givenTaskWithPastExecuteUntil_whenCreate_thenReturnError404() {
taskDTO = TasksUtil.getTaskDtoTemplate();
taskDTO.setExecuteUntil(ZonedDateTime.now().minusDays(1));
this.getValidationErrorResponse(taskDTO, EnumLanguageCode.EN)
.value(errorDetailsDTO -> {
Assertions.assertThat(errorDetailsDTO.getErrorCode())
.isEqualTo(EnumValidationError.FIELD_VALIDATION_ERROR.getCode());
Assertions.assertThat(errorDetailsDTO.getErrorMessage())
.isEqualTo("Task execute until must be in the future.");
});
}
@Test
@DisplayName("Create Task with past execute until date - Spanish")
void givenTaskWithPastExecuteUntil_whenCreate_thenReturnError404InSpanish() {
taskDTO = TasksUtil.getTaskDtoTemplate();
taskDTO.setExecuteUntil(ZonedDateTime.now().minusDays(1));
this.getValidationErrorResponse(taskDTO, EnumLanguageCode.ES)
.value(errorDetailsDTO -> {
Assertions.assertThat(errorDetailsDTO.getErrorCode())
.isEqualTo(EnumValidationError.FIELD_VALIDATION_ERROR.getCode());
Assertions.assertThat(errorDetailsDTO.getErrorMessage())
.isEqualTo("La fecha final de ejecución de la tarea debe ser posterior a la fecha actual.");
});
}
@Test
@DisplayName("Create Task without Device ID")
void givenTaskWithoutDeviceId_whenCreate_thenReturnError404() {
taskDTO = TasksUtil.getTaskDtoTemplate();
taskDTO.setDeviceId(null);
this.getValidationErrorResponse(taskDTO, EnumLanguageCode.EN)
.value(errorDetailsDTO -> {
Assertions.assertThat(errorDetailsDTO.getErrorCode())
.isEqualTo(EnumValidationError.FIELD_VALIDATION_ERROR.getCode());
Assertions.assertThat(errorDetailsDTO.getErrorMessage())
.isEqualTo("Device ID cannot be empty.");
});
}
@Test
@DisplayName("Create Task without Device ID - Spanish")
void givenTaskWithoutDeviceId_whenCreate_thenReturnError404inSpanish() {
taskDTO = TasksUtil.getTaskDtoTemplate();
taskDTO.setDeviceId(null);
this.getValidationErrorResponse(taskDTO, EnumLanguageCode.ES)
.value(errorDetailsDTO -> {
Assertions.assertThat(errorDetailsDTO.getErrorCode())
.isEqualTo(EnumValidationError.FIELD_VALIDATION_ERROR.getCode());
Assertions.assertThat(errorDetailsDTO.getErrorMessage())
.isEqualTo("El ID del dispositivo no puede estar vacío.");
});
}
@Test
@DisplayName("Create Task without Device Action")
void givenTaskWithoutDeviceAction_whenCreate_thenReturnError404() {
taskDTO = TasksUtil.getTaskDtoTemplate();
taskDTO.setDeviceOperation(null);
this.getValidationErrorResponse(taskDTO, EnumLanguageCode.EN)
.value(errorDetailsDTO -> {
Assertions.assertThat(errorDetailsDTO.getErrorCode())
.isEqualTo(EnumValidationError.FIELD_VALIDATION_ERROR.getCode());
Assertions.assertThat(errorDetailsDTO.getErrorMessage())
.isEqualTo("Device action cannot be empty.");
});
}
@Test
@DisplayName("Create Task without Device Action - Spanish")
void givenTaskWithoutDeviceAction_whenCreate_thenReturnError404InSpanish() {
taskDTO = TasksUtil.getTaskDtoTemplate();
taskDTO.setDeviceOperation(null);
this.getValidationErrorResponse(taskDTO, EnumLanguageCode.ES)
.value(errorDetailsDTO -> {
Assertions.assertThat(errorDetailsDTO.getErrorCode())
.isEqualTo(EnumValidationError.FIELD_VALIDATION_ERROR.getCode());
Assertions.assertThat(errorDetailsDTO.getErrorMessage())
.isEqualTo("La acción del dispositivo no puede estar vacía.");
});
}
@NotNull | private WebTestClient.BodySpec<ErrorDetailsDTO, ?> getValidationErrorResponse(TaskDTO taskOperationDto, | 1 | 2023-11-28 16:35:22+00:00 | 8k |
shawn-sheep/Activity_Diary | app/src/main/java/de/rampro/activitydiary/helpers/TimeSpanFormatter.java | [
{
"identifier": "ActivityDiaryApplication",
"path": "app/src/main/java/de/rampro/activitydiary/ActivityDiaryApplication.java",
"snippet": "public class ActivityDiaryApplication extends Application {\n\n private static Context context;\n\n public void onCreate() {\n SpeechUtility.createUtility(ActivityDiaryApplication.this, SpeechConstant.APPID +\"=e3db48a0\");\n super.onCreate();\n ActivityDiaryApplication.context = getApplicationContext();\n\n /* now do some init stuff */\n String colors[] = context.getResources().getStringArray(R.array.activityColorPalette);\n\n for (int i = 0; i < colors.length; i++) {\n GraphicsHelper.activityColorPalette.add(Color.parseColor(colors[i]));\n }\n }\n\n @Override\n protected void attachBaseContext(Context base) {\n super.attachBaseContext(base);\n\n ACRA.init(this, new CoreConfigurationBuilder()\n .withBuildConfigClass(BuildConfig.class)\n .withReportFormat(StringFormat.JSON)\n .withReportContent(ReportField.APP_VERSION_CODE,\n ReportField.APP_VERSION_NAME,\n ReportField.USER_COMMENT,\n ReportField.SHARED_PREFERENCES,\n ReportField.ANDROID_VERSION,\n ReportField.BRAND,\n ReportField.PHONE_MODEL,\n ReportField.CUSTOM_DATA,\n ReportField.STACK_TRACE,\n ReportField.BUILD,\n ReportField.BUILD_CONFIG,\n ReportField.CRASH_CONFIGURATION,\n ReportField.DISPLAY)\n .withReportFormat(StringFormat.KEY_VALUE_LIST)\n .withAlsoReportToAndroidFramework(true)\n .withBuildConfigClass(de.rampro.activitydiary.BuildConfig.class)\n .withPluginConfigurations(\n new DialogConfigurationBuilder()\n .withCommentPrompt(getString(R.string.crash_dialog_comment_prompt))\n .withText(getString(R.string.crash_dialog_text))\n .build(),\n new MailSenderConfigurationBuilder()\n .withMailTo(\"[email protected]\")\n .withReportAsFile(true)\n .withReportFileName(\"Crash.txt\")\n .build()\n )\n );\n }\n\n public static Context getAppContext() {\n return ActivityDiaryApplication.context;\n }\n}"
},
{
"identifier": "SettingsActivity",
"path": "app/src/main/java/de/rampro/activitydiary/ui/settings/SettingsActivity.java",
"snippet": "public class SettingsActivity extends BaseActivity implements SharedPreferences.OnSharedPreferenceChangeListener {\n private static final String TAG = SettingsActivity.class.getName();\n\n public static final String KEY_PREF_DATETIME_FORMAT = \"pref_datetimeFormat\";\n public static final String KEY_PREF_AUTO_SELECT = \"pref_auto_select_new\";\n public static final String KEY_PREF_STORAGE_FOLDER = \"pref_storageFolder\";\n public static final String KEY_PREF_TAG_IMAGES = \"pref_tag_images\";\n public static final String KEY_PREF_DB_EXPORT = \"pref_db_export\";\n public static final String KEY_PREF_DB_IMPORT = \"pref_db_import\";\n public static final String KEY_PREF_COND_ALPHA = \"pref_cond_alpha\";\n public static final String KEY_PREF_COND_PREDECESSOR = \"pref_cond_predecessor\";\n public static final String KEY_PREF_COND_OCCURRENCE = \"pref_cond_occurrence\";\n public static final String KEY_PREF_NOTIF_SHOW_CUR_ACT = \"pref_show_cur_activity_notification\";\n public static final String KEY_PREF_SILENT_RENOTIFICATIONS = \"pref_silent_renotification\";\n public static final String KEY_PREF_DISABLE_CURRENT = \"pref_disable_current_on_click\";\n public static final String KEY_PREF_COND_DAYTIME = \"pref_cond_daytime\";\n public static final String KEY_PREF_USE_LOCATION = \"pref_use_location\";\n public static final String KEY_PREF_LOCATION_AGE = \"pref_location_age\";\n public static final String KEY_PREF_LOCATION_DIST = \"pref_location_dist\";\n public static final String KEY_PREF_PAUSED = \"pref_cond_paused\";\n public static final String KEY_PREF_DURATION_FORMAT = \"pref_duration_format\";\n\n public static final int ACTIVITIY_RESULT_EXPORT = 17;\n public static final int ACTIVITIY_RESULT_IMPORT = 18;\n\n private Preference dateformatPref;\n private ListPreference durationFormatPref;\n private Preference autoSelectPref;\n private Preference storageFolderPref;\n private Preference tagImagesPref;\n private Preference condAlphaPref;\n private Preference condPredecessorPref;\n private Preference condPausedPref;\n private Preference condOccurrencePref;\n private Preference condDayTimePref;\n private Preference nofifShowCurActPref;\n private Preference silentRenotifPref;\n private Preference exportPref;\n private Preference importPref;\n private Preference disableOnClickPref;\n private ListPreference useLocationPref;\n private EditTextPreference locationAgePref;\n private EditTextPreference locationDistPref;\n\n private PreferenceManager mPreferenceManager;\n\n public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,\n String key) {\n if (key.equals(KEY_PREF_DATETIME_FORMAT)) {\n String def = getResources().getString(R.string.default_datetime_format);\n // Set summary to be the user-description for the selected value\n dateformatPref.setSummary(DateFormat.format(sharedPreferences.getString(key, def), new Date()));\n }else if(key.equals(KEY_PREF_AUTO_SELECT)){\n updateAutoSelectSummary();\n }else if(key.equals(KEY_PREF_STORAGE_FOLDER)) {\n /* TODO: we could ask here whether we shall move the pictures... */\n updateStorageFolderSummary();\n }else if(key.equals(KEY_PREF_TAG_IMAGES)) {\n updateTagImageSummary();\n }else if(key.equals(KEY_PREF_COND_ALPHA)) {\n updateCondAlphaSummary();\n }else if(key.equals(KEY_PREF_COND_PREDECESSOR)) {\n updateCondPredecessorSummary();\n }else if(key.equals(KEY_PREF_COND_OCCURRENCE)) {\n updateCondOccurenceSummary();\n }else if(key.equals(KEY_PREF_NOTIF_SHOW_CUR_ACT)) {\n updateNotifShowCurActivity();\n }else if(key.equals(KEY_PREF_SILENT_RENOTIFICATIONS)){\n updateSilentNotifications();\n }else if(key.equals(KEY_PREF_COND_DAYTIME)){\n updateCondDayTimeSummary();\n }else if(key.equals(KEY_PREF_DISABLE_CURRENT)){\n updateDisableCurrent();\n }else if(key.equals(KEY_PREF_USE_LOCATION)){\n updateUseLocation();\n }else if(key.equals(KEY_PREF_LOCATION_AGE)){\n updateLocationAge();\n }else if(key.equals(KEY_PREF_LOCATION_DIST)){\n updateLocationDist();\n }else if(key.equals(KEY_PREF_PAUSED)){\n updateCondPaused();\n }else if(key.equals(KEY_PREF_DURATION_FORMAT)){\n updateDurationFormat();\n }\n }\n\n private void updateDurationFormat() {\n\n String value = PreferenceManager\n .getDefaultSharedPreferences(ActivityDiaryApplication.getAppContext())\n .getString(KEY_PREF_DURATION_FORMAT, \"dynamic\");\n\n if(value.equals(\"dynamic\")){\n durationFormatPref.setSummary(getResources().getString(R.string.setting_duration_format_summary_dynamic));\n }else if(value.equals(\"nodays\")){\n durationFormatPref.setSummary(getResources().getString(R.string.setting_duration_format_summary_nodays));\n }else if(value.equals(\"precise\")){\n durationFormatPref.setSummary(getResources().getString(R.string.setting_duration_format_summary_precise));\n }else if(value.equals(\"hour_min\")){\n durationFormatPref.setSummary(getResources().getString(R.string.setting_duration_format_summary_hour_min));\n }\n }\n\n private void updateUseLocation() {\n int permissionCheckFine = PackageManager.PERMISSION_DENIED;\n int permissionCheckCoarse = PackageManager.PERMISSION_DENIED;\n\n String value = PreferenceManager\n .getDefaultSharedPreferences(ActivityDiaryApplication.getAppContext())\n .getString(KEY_PREF_USE_LOCATION, \"off\");\n\n if(value.equals(\"off\")){\n locationAgePref.setEnabled(false);\n locationDistPref.setEnabled(false);\n useLocationPref.setSummary(getResources().getString(R.string.setting_use_location_off_summary));\n }else {\n locationAgePref.setEnabled(true);\n locationDistPref.setEnabled(true);\n useLocationPref.setSummary(getResources().getString(R.string.setting_use_location_summary, useLocationPref.getEntry()));\n }\n\n if(value.equals(\"gps\")) {\n permissionCheckFine = ContextCompat.checkSelfPermission(ActivityDiaryApplication.getAppContext(),\n Manifest.permission.ACCESS_FINE_LOCATION);\n if (permissionCheckFine != PackageManager.PERMISSION_GRANTED) {\n if (ActivityCompat.shouldShowRequestPermissionRationale(this,\n Manifest.permission.ACCESS_FINE_LOCATION)) {\n\n Toast.makeText(this, R.string.perm_location_xplain, Toast.LENGTH_LONG).show();\n }\n ActivityCompat.requestPermissions(this,\n new String[]{Manifest.permission.ACCESS_FINE_LOCATION},\n 4712);\n }\n }else{\n permissionCheckCoarse = ContextCompat.checkSelfPermission(ActivityDiaryApplication.getAppContext(),\n Manifest.permission.ACCESS_COARSE_LOCATION);\n if (permissionCheckCoarse != PackageManager.PERMISSION_GRANTED) {\n if (ActivityCompat.shouldShowRequestPermissionRationale(this,\n Manifest.permission.ACCESS_COARSE_LOCATION)) {\n\n Toast.makeText(this, R.string.perm_location_xplain, Toast.LENGTH_LONG).show();\n }\n ActivityCompat.requestPermissions(this,\n new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},\n 4713);\n }\n }\n }\n\n private void updateLocationDist() {\n String def = getResources().getString(R.string.pref_location_dist_default);\n String value = PreferenceManager\n .getDefaultSharedPreferences(ActivityDiaryApplication.getAppContext())\n .getString(KEY_PREF_LOCATION_DIST, def);\n if(value.length() == 0){\n value = \"0\";\n }\n\n int v = Integer.parseInt(value.replaceAll(\"\\\\D\",\"\"));\n\n String nvalue = Integer.toString(v);\n if(!value.equals(nvalue)){\n SharedPreferences.Editor editor = PreferenceManager\n .getDefaultSharedPreferences(ActivityDiaryApplication.getAppContext()).edit();\n editor.putString(KEY_PREF_LOCATION_DIST, nvalue);\n editor.apply();\n value = PreferenceManager\n .getDefaultSharedPreferences(ActivityDiaryApplication.getAppContext())\n .getString(KEY_PREF_LOCATION_DIST, def);\n }\n\n locationDistPref.setSummary(getResources().getString(R.string.pref_location_dist, value));\n }\n\n private void updateLocationAge() {\n String def = getResources().getString(R.string.pref_location_age_default);\n String value = PreferenceManager\n .getDefaultSharedPreferences(ActivityDiaryApplication.getAppContext())\n .getString(KEY_PREF_LOCATION_AGE, def);\n if(value.length() == 0){\n value = \"5\";\n }\n int v = Integer.parseInt(value.replaceAll(\"\\\\D\",\"\"));\n if(v < 2){\n v = 2;\n }else if(v > 60){\n v = 60;\n }\n String nvalue = Integer.toString(v);\n if(!value.equals(nvalue)){\n SharedPreferences.Editor editor = PreferenceManager\n .getDefaultSharedPreferences(ActivityDiaryApplication.getAppContext()).edit();\n editor.putString(KEY_PREF_LOCATION_AGE, nvalue);\n editor.apply();\n value = PreferenceManager\n .getDefaultSharedPreferences(ActivityDiaryApplication.getAppContext())\n .getString(KEY_PREF_LOCATION_AGE, def);\n }\n locationAgePref.setSummary(getResources().getString(R.string.pref_location_age, value));\n }\n\n private void updateDisableCurrent() {\n if(PreferenceManager\n .getDefaultSharedPreferences(ActivityDiaryApplication.getAppContext())\n .getBoolean(KEY_PREF_DISABLE_CURRENT, true)){\n disableOnClickPref.setSummary(getResources().getString(R.string.setting_disable_on_click_summary_active));\n }else{\n disableOnClickPref.setSummary(getResources().getString(R.string.setting_disable_on_click_summary_inactive));\n }\n }\n\n private void updateTagImageSummary() {\n if(PreferenceManager\n .getDefaultSharedPreferences(ActivityDiaryApplication.getAppContext())\n .getBoolean(KEY_PREF_TAG_IMAGES, true)){\n tagImagesPref.setSummary(getResources().getString(R.string.setting_tag_yes));\n }else{\n tagImagesPref.setSummary(getResources().getString(R.string.setting_tag_no));\n }\n }\n\n private void updateStorageFolderSummary() {\n String dir = PreferenceManager\n .getDefaultSharedPreferences(ActivityDiaryApplication.getAppContext())\n .getString(KEY_PREF_STORAGE_FOLDER, \"ActivityDiary\");\n\n storageFolderPref.setSummary(getResources().getString(R.string.setting_storage_folder_summary, dir));\n }\n\n private void updateCondAlphaSummary() {\n String def = getResources().getString(R.string.pref_cond_alpha_default);\n String value = PreferenceManager\n .getDefaultSharedPreferences(ActivityDiaryApplication.getAppContext())\n .getString(KEY_PREF_COND_ALPHA, def);\n\n if(Double.parseDouble(value) == 0.0){\n condAlphaPref.setSummary(getResources().getString(R.string.setting_cond_alpha_not_used_summary));\n }else {\n condAlphaPref.setSummary(getResources().getString(R.string.setting_cond_alpha_summary, value));\n }\n }\n\n private void updateCondPredecessorSummary() {\n String def = getResources().getString(R.string.pref_cond_predecessor_default);\n String value = PreferenceManager\n .getDefaultSharedPreferences(ActivityDiaryApplication.getAppContext())\n .getString(KEY_PREF_COND_PREDECESSOR, def);\n\n if(Double.parseDouble(value) == 0.0){\n condPredecessorPref.setSummary(getResources().getString(R.string.setting_cond_predecessor_not_used_summary));\n }else {\n condPredecessorPref.setSummary(getResources().getString(R.string.setting_cond_predecessor_summary, value));\n }\n }\n\n private void updateCondPaused() {\n String def = getResources().getString(R.string.pref_cond_paused_default);\n String value = PreferenceManager\n .getDefaultSharedPreferences(ActivityDiaryApplication.getAppContext())\n .getString(KEY_PREF_PAUSED, def);\n\n if(Double.parseDouble(value) == 0.0){\n condPausedPref.setSummary(getResources().getString(R.string.setting_cond_paused_not_used_summary));\n }else {\n condPausedPref.setSummary(getResources().getString(R.string.setting_cond_paused_summary, value));\n }\n }\n\n private void updateCondDayTimeSummary() {\n String def = getResources().getString(R.string.pref_cond_daytime_default);\n String value = PreferenceManager\n .getDefaultSharedPreferences(ActivityDiaryApplication.getAppContext())\n .getString(KEY_PREF_COND_DAYTIME, def);\n\n if(Double.parseDouble(value) == 0.0){\n condDayTimePref.setSummary(getResources().getString(R.string.setting_cond_daytime_not_used_summary));\n }else {\n condDayTimePref.setSummary(getResources().getString(R.string.setting_cond_daytime_summary, value));\n }\n }\n\n private void updateCondOccurenceSummary() {\n String def = getResources().getString(R.string.pref_cond_occurrence_default);\n String value = PreferenceManager\n .getDefaultSharedPreferences(ActivityDiaryApplication.getAppContext())\n .getString(KEY_PREF_COND_OCCURRENCE, def);\n\n if(Double.parseDouble(value) == 0.0){\n condOccurrencePref.setSummary(getResources().getString(R.string.setting_cond_occurrence_not_used_summary));\n }else {\n condOccurrencePref.setSummary(getResources().getString(R.string.setting_cond_occurrence_summary, value));\n }\n }\n\n\n private void updateAutoSelectSummary() {\n if(PreferenceManager\n .getDefaultSharedPreferences(ActivityDiaryApplication.getAppContext())\n .getBoolean(KEY_PREF_AUTO_SELECT, true)){\n autoSelectPref.setSummary(getResources().getString(R.string.setting_auto_select_new_summary_active));\n }else{\n autoSelectPref.setSummary(getResources().getString(R.string.setting_auto_select_new_summary_inactive));\n }\n }\n\n private void updateNotifShowCurActivity() {\n if(PreferenceManager\n .getDefaultSharedPreferences(ActivityDiaryApplication.getAppContext())\n .getBoolean(KEY_PREF_NOTIF_SHOW_CUR_ACT, true)){\n nofifShowCurActPref.setSummary(getResources().getString(R.string.setting_show_cur_activitiy_notification_summary_active));\n }else{\n nofifShowCurActPref.setSummary(getResources().getString(R.string.setting_show_cur_activitiy_notification_summary_inactive));\n }\n ActivityHelper.helper.showCurrentActivityNotification();\n }\n\n private void updateSilentNotifications() {\n if(PreferenceManager\n .getDefaultSharedPreferences(ActivityDiaryApplication.getAppContext())\n .getBoolean(KEY_PREF_SILENT_RENOTIFICATIONS, true)){\n silentRenotifPref.setSummary(getResources().getString(R.string.setting_silent_reconfication_summary_active));\n }else{\n silentRenotifPref.setSummary(getResources().getString(R.string.setting_silent_reconfication_summary_inactive));\n }\n ActivityHelper.helper.showCurrentActivityNotification();\n }\n\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n\n LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);\n\n View contentView = inflater.inflate(R.layout.activity_settings, null, false);\n\n setContent(contentView);\n SettingsFragment sf = (SettingsFragment)getSupportFragmentManager().findFragmentById(R.id.settings_fragment);\n\n mPreferenceManager = sf.getPreferenceManager();\n dateformatPref = mPreferenceManager.findPreference(KEY_PREF_DATETIME_FORMAT);\n\n String def = getResources().getString(R.string.default_datetime_format);\n\n dateformatPref.setSummary(DateFormat.format(\n PreferenceManager\n .getDefaultSharedPreferences(ActivityDiaryApplication.getAppContext())\n .getString(KEY_PREF_DATETIME_FORMAT, def)\n , new Date()));\n\n durationFormatPref = (ListPreference)mPreferenceManager.findPreference(KEY_PREF_DURATION_FORMAT);\n autoSelectPref = mPreferenceManager.findPreference(KEY_PREF_AUTO_SELECT);\n disableOnClickPref = mPreferenceManager.findPreference(KEY_PREF_DISABLE_CURRENT);\n storageFolderPref = mPreferenceManager.findPreference(KEY_PREF_STORAGE_FOLDER);\n useLocationPref = (ListPreference) mPreferenceManager.findPreference(KEY_PREF_USE_LOCATION);\n locationAgePref = (EditTextPreference)mPreferenceManager.findPreference(KEY_PREF_LOCATION_AGE);\n locationDistPref = (EditTextPreference)mPreferenceManager.findPreference(KEY_PREF_LOCATION_DIST);\n\n tagImagesPref = mPreferenceManager.findPreference(KEY_PREF_TAG_IMAGES);\n nofifShowCurActPref = mPreferenceManager.findPreference(KEY_PREF_NOTIF_SHOW_CUR_ACT);\n silentRenotifPref = mPreferenceManager.findPreference(KEY_PREF_SILENT_RENOTIFICATIONS);\n\n exportPref = mPreferenceManager.findPreference(KEY_PREF_DB_EXPORT);\n exportPref.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {\n public boolean onPreferenceClick(Preference preference) {\n /* export database */\n if (Build.VERSION.SDK_INT >= 19) {\n Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);\n intent.setType(\"application/x-sqlite3\");\n intent.putExtra(Intent.EXTRA_TITLE, getResources().getString(R.string.db_export_name_suggestion) + \".sqlite3\");\n intent.addCategory(Intent.CATEGORY_OPENABLE);\n\n startActivityForResult(Intent.createChooser(intent, getResources().getString(R.string.db_export_selection)), ACTIVITIY_RESULT_EXPORT);\n }else{\n Toast.makeText(SettingsActivity.this, getResources().getString(R.string.unsupported_on_api_level, 19), Toast.LENGTH_SHORT).show();\n }\n\n return true;\n }\n });\n importPref = mPreferenceManager.findPreference(KEY_PREF_DB_IMPORT);\n importPref.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {\n public boolean onPreferenceClick(Preference preference) {\n /* import database */\n if (Build.VERSION.SDK_INT >= 19) {\n Intent intent = new Intent(Intent.ACTION_GET_CONTENT);\n intent.setType(\"application/*\");\n intent.addCategory(Intent.CATEGORY_OPENABLE);\n startActivityForResult(Intent.createChooser(intent, getResources().getString(R.string.db_import_selection)), ACTIVITIY_RESULT_IMPORT);\n }else{\n Toast.makeText(SettingsActivity.this, getResources().getString(R.string.unsupported_on_api_level, 19), Toast.LENGTH_SHORT).show();\n }\n\n return true;\n }\n });\n\n condAlphaPref = mPreferenceManager.findPreference(KEY_PREF_COND_ALPHA);\n condPredecessorPref = mPreferenceManager.findPreference(KEY_PREF_COND_PREDECESSOR);\n condPausedPref = mPreferenceManager.findPreference(KEY_PREF_PAUSED);\n condOccurrencePref = mPreferenceManager.findPreference(KEY_PREF_COND_OCCURRENCE);\n condDayTimePref = mPreferenceManager.findPreference(KEY_PREF_COND_DAYTIME);\n\n updateAutoSelectSummary();\n updateStorageFolderSummary();\n updateTagImageSummary();\n updateCondAlphaSummary();\n updateCondPredecessorSummary();\n updateCondPaused();\n updateCondOccurenceSummary();\n updateCondDayTimeSummary();\n updateNotifShowCurActivity();\n updateSilentNotifications();\n updateDisableCurrent();\n updateUseLocation();\n updateLocationAge();\n updateLocationDist();\n updateDurationFormat();\n\n mDrawerToggle.setDrawerIndicatorEnabled(false);\n }\n\n @Override\n public void onResume(){\n mNavigationView.getMenu().findItem(R.id.nav_settings).setChecked(true);\n super.onResume();\n mPreferenceManager.getPreferenceScreen().getSharedPreferences()\n .registerOnSharedPreferenceChangeListener(this);\n\n }\n\n @Override\n protected void onPause() {\n super.onPause();\n mPreferenceManager.getPreferenceScreen().getSharedPreferences()\n .unregisterOnSharedPreferenceChangeListener(this);\n }\n\n @Override\n protected void onActivityResult(int requestCode, int resultCode, Intent data) {\n super.onActivityResult(requestCode, resultCode, data);\n if(requestCode == ACTIVITIY_RESULT_IMPORT && resultCode == RESULT_OK) {\n Uri selectedfile = data.getData(); //The uri with the location of the file\n // import\n // TODO: replace /data by Context.getFilesDir().getPath() -> see lint\n File db = new File(\"/data/data/\" + getPackageName() + \"/databases/\" + ActivityDiaryContract.AUTHORITY);\n File bak = new File(\"/data/data/\" + getPackageName() + \"/databases/\" + ActivityDiaryContract.AUTHORITY + \".bak\");\n InputStream inputStream = null;\n OutputStream outputStream = null;\n try {\n db.renameTo(bak);\n\n String s = getResources().getString(R.string.db_import_success, data.getData().toString());\n inputStream = getContentResolver().openInputStream(data.getData());\n outputStream = new FileOutputStream(db);\n byte[] buff = new byte[4048];\n int len;\n while ((len = inputStream.read(buff)) > 0 ){\n outputStream.write(buff,0,len);\n outputStream.flush();\n }\n outputStream.close();\n outputStream = null;\n inputStream.close();\n inputStream = null;\n\n SQLiteDatabase sdb = SQLiteDatabase.openDatabase(db.getPath(), null, SQLiteDatabase.OPEN_READONLY);\n int v = sdb.getVersion();\n sdb.close();\n if(v > LocalDBHelper.CURRENT_VERSION){\n throw new Exception(\"selected file has version \" + v + \" which is too high...\");\n }\n\n ActivityHelper.helper.reloadAll();\n Toast.makeText(SettingsActivity.this, s, Toast.LENGTH_LONG).show();\n }catch (Exception e) {\n if(inputStream != null){\n try {\n inputStream.close();\n } catch (IOException e1) {\n /* ignore */\n }\n }\n if(outputStream != null){\n try {\n outputStream.close();\n } catch (IOException e1) {\n /* ignore */\n }\n }\n bak.renameTo(db);\n Log.e(TAG, \"error on database import: \" + e.getMessage());\n String s = getResources().getString(R.string.db_import_error, data.getData().toString());\n Toast.makeText(SettingsActivity.this, s, Toast.LENGTH_LONG).show();\n bak.renameTo(db);\n\n }\n }\n if(requestCode == ACTIVITIY_RESULT_EXPORT && resultCode == RESULT_OK) {\n\n // export\n // TODO: replace /data by Context.getFilesDir().getPath() -> see lint\n File db = new File(\"/data/data/\" + getPackageName() + \"/databases/\" + ActivityDiaryContract.AUTHORITY);\n try {\n String s = getResources().getString(R.string.db_export_success, data.getData().toString());\n InputStream inputStream = new FileInputStream(db);\n OutputStream outputStream = getContentResolver().openOutputStream(data.getData());\n byte[] buff = new byte[4048];\n int len;\n while ((len = inputStream.read(buff)) > 0 ){\n outputStream.write(buff,0,len);\n outputStream.flush();\n }\n outputStream.close();\n inputStream.close();\n Toast.makeText(SettingsActivity.this, s, Toast.LENGTH_LONG).show();\n }catch (Exception e){\n Log.e(TAG,\"error on database export: \"+e.getMessage());\n String s = getResources().getString(R.string.db_export_error, data.getData().toString());\n Toast.makeText(SettingsActivity.this, s, Toast.LENGTH_LONG).show();\n }\n }\n }\n}"
}
] | import android.content.res.Resources;
import androidx.preference.PreferenceManager;
import java.text.DecimalFormat;
import java.util.Date;
import de.rampro.activitydiary.ActivityDiaryApplication;
import de.rampro.activitydiary.R;
import de.rampro.activitydiary.ui.settings.SettingsActivity; | 5,870 | /*
* ActivityDiary
*
* Copyright (C) 2017-2018 Raphael Mack http://www.raphael-mack.de
*
* 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 de.rampro.activitydiary.helpers;
public class TimeSpanFormatter {
public static String fuzzyFormat(Date start, Date end) { | /*
* ActivityDiary
*
* Copyright (C) 2017-2018 Raphael Mack http://www.raphael-mack.de
*
* 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 de.rampro.activitydiary.helpers;
public class TimeSpanFormatter {
public static String fuzzyFormat(Date start, Date end) { | Resources res = ActivityDiaryApplication.getAppContext().getResources(); | 0 | 2023-12-02 12:36:40+00:00 | 8k |
RabbitHareLu/K-Tools | frontend/src/main/java/com/ktools/frontend/action/NewFolderAction.java | [
{
"identifier": "KToolsContext",
"path": "warehouse/src/main/java/com/ktools/warehouse/KToolsContext.java",
"snippet": "@Getter\npublic class KToolsContext {\n\n private static volatile KToolsContext INSTANCE;\n\n private final MybatisContext mybatisContext;\n\n private final Properties properties;\n\n private final TaskManager taskManager;\n\n private final IdGenerator idGenerator;\n\n private final KDataSourceManager dataSourceManager;\n\n private KToolsContext() {\n // 初始化系统数据源\n DataSource dataSource = SysDataSource.init();\n // 初始化mybatis\n this.mybatisContext = new MybatisContext(dataSource);\n // 像mybatis注册系统数据源\n mybatisContext.addDataSource(SysDataSource.DATASOURCE_NAME, dataSource);\n // 初始化配置信息\n this.properties = this.mybatisContext.loadAllProperties();\n // 初始化任务管理器\n this.taskManager = new TaskManager();\n // 初始化id生成器\n this.idGenerator = new IdGenerator(mybatisContext);\n // 初始化数据源管理器\n this.dataSourceManager = new KDataSourceManager();\n }\n\n public static KToolsContext getInstance() {\n if (INSTANCE == null) {\n synchronized (KToolsContext.class) {\n if (INSTANCE == null) {\n INSTANCE = new KToolsContext();\n }\n }\n }\n return INSTANCE;\n }\n\n public void showdown() {\n this.mybatisContext.showdown();\n this.taskManager.shutdown();\n }\n\n public <T> T getApi(Class<T> tClass) {\n if (tClass == SystemApi.class) {\n return tClass.cast(new SystemService());\n } else if (tClass == DataSourceApi.class){\n return tClass.cast(new DataSourceService());\n }\n return null;\n }\n}"
},
{
"identifier": "Main",
"path": "frontend/src/main/java/com/ktools/frontend/Main.java",
"snippet": "@Data\npublic class Main {\n\n public static KToolsRootJFrame kToolsRootJFrame = null;\n\n public static void main(String[] args) {\n FlatIntelliJLaf.setup();\n // 使用 FlatLaf 提供的组件样式\n UIManager.put(\"Button.arc\", 50); // 设置按钮的弧度\n UIManager.put(\"Component.focusWidth\", 1); // 设置组件的焦点边框宽度\n UIManager.put(\"TextComponent.arc\", 10);\n FontUtil.putUIFont();\n\n SwingUtilities.invokeLater(() -> kToolsRootJFrame = new KToolsRootJFrame());\n }\n}"
},
{
"identifier": "SystemApi",
"path": "warehouse/src/main/java/com/ktools/warehouse/api/SystemApi.java",
"snippet": "public interface SystemApi {\n\n List<TreeEntity> getTree(int nodeId);\n\n void addNode(TreeEntity treeEntity) throws KToolException;\n\n void updateNode(TreeEntity treeEntity) throws KToolException;\n\n void deleteNode(TreeEntity treeEntity);\n\n void deleteChildNode(TreeEntity treeEntity);\n\n void saveOrUpdateProp(String key, String value);\n\n}"
},
{
"identifier": "TreeNodeType",
"path": "frontend/src/main/java/com/ktools/frontend/common/model/TreeNodeType.java",
"snippet": "public class TreeNodeType {\n public static final String ROOT = \"ROOT\";\n public static final String FOLDER = \"FOLDER\";\n public static final String CONNECTION = \"CONNECTION\";\n public static final String SQL_CONSOLE = \"SQL_CONSOLE\";\n public static final String TABLE = \"TABLE\";\n public static final String COLUMN = \"COLUMN\";\n public static final String SCHEMA = \"SCHEMA\";\n}"
},
{
"identifier": "DialogUtil",
"path": "frontend/src/main/java/com/ktools/frontend/common/utils/DialogUtil.java",
"snippet": "public class DialogUtil {\n\n public static void showErrorDialog(Component parentComponent, Object message) {\n JOptionPane.showMessageDialog(\n parentComponent,\n message,\n \"Error\",\n JOptionPane.ERROR_MESSAGE\n );\n }\n\n\n}"
},
{
"identifier": "StringUtil",
"path": "warehouse/src/main/java/com/ktools/warehouse/common/utils/StringUtil.java",
"snippet": "public class StringUtil {\n\n /**\n * 字符串驼峰转下划线\n *\n * @param str 驼峰字符串\n * @return {@link String} 下划线字符串\n * @author lsl\n * @date 2023/11/22 16:58\n */\n public static String toUnderlineCase(CharSequence str) {\n char symbol = '_';\n if (str == null) {\n return null;\n }\n\n final int length = str.length();\n final StringBuilder sb = new StringBuilder();\n char c;\n for (int i = 0; i < length; i++) {\n c = str.charAt(i);\n if (Character.isUpperCase(c)) {\n final Character preChar = (i > 0) ? str.charAt(i - 1) : null;\n final Character nextChar = (i < str.length() - 1) ? str.charAt(i + 1) : null;\n\n if (null != preChar) {\n if (symbol == preChar) {\n // 前一个为分隔符\n if (null == nextChar || Character.isLowerCase(nextChar)) {\n //普通首字母大写,如_Abb -> _abb\n c = Character.toLowerCase(c);\n }\n //后一个为大写,按照专有名词对待,如_AB -> _AB\n } else if (Character.isLowerCase(preChar)) {\n // 前一个为小写\n sb.append(symbol);\n if (null == nextChar || Character.isLowerCase(nextChar) || isNumber(nextChar)) {\n //普通首字母大写,如aBcc -> a_bcc\n c = Character.toLowerCase(c);\n }\n // 后一个为大写,按照专有名词对待,如aBC -> a_BC\n } else {\n //前一个为大写\n if (null != nextChar && Character.isLowerCase(nextChar)) {\n // 普通首字母大写,如ABcc -> A_bcc\n sb.append(symbol);\n c = Character.toLowerCase(c);\n }\n // 后一个为大写,按照专有名词对待,如ABC -> ABC\n }\n } else {\n // 首字母,需要根据后一个判断是否转为小写\n if (null == nextChar || Character.isLowerCase(nextChar)) {\n // 普通首字母大写,如Abc -> abc\n c = Character.toLowerCase(c);\n }\n // 后一个为大写,按照专有名词对待,如ABC -> ABC\n }\n }\n sb.append(c);\n }\n return sb.toString();\n }\n\n public static boolean isNumber(char ch) {\n return ch >= '0' && ch <= '9';\n }\n\n public static boolean isNotEmpty(final CharSequence cs) {\n return !isEmpty(cs);\n }\n\n public static boolean isEmpty(final CharSequence cs) {\n return cs == null || cs.length() == 0;\n }\n\n public static boolean isNotBlank(final CharSequence cs) {\n return !isBlank(cs);\n }\n\n public static boolean isBlank(final CharSequence cs) {\n int strLen;\n if (cs == null || (strLen = cs.length()) == 0) {\n return true;\n }\n for (int i = 0; i < strLen; i++) {\n if (!Character.isWhitespace(cs.charAt(i))) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * 自定义分割函数,返回全部\n *\n * @param str 待分割的字符串\n * @param delim 分隔符\n * @return 分割后的返回结果\n */\n public static List<String> split(String str, final String delim) {\n if (null == str) {\n// return new ArrayList<>(0);\n return Collections.emptyList();\n }\n\n if (isEmpty(delim)) {\n List<String> result = new ArrayList<>(1);\n result.add(str);\n\n return result;\n }\n\n final List<String> stringList = new ArrayList<>();\n while (true) {\n int index = str.indexOf(delim);\n if (index < 0) {\n stringList.add(str);\n break;\n }\n stringList.add(str.substring(0, index));\n str = str.substring(index + delim.length());\n }\n return stringList;\n }\n\n public static void main(String[] args) {\n String str = \"aa\";\n List<String> split = split(str, \",\");\n System.out.println(split);\n }\n}"
},
{
"identifier": "Tree",
"path": "frontend/src/main/java/com/ktools/frontend/component/Tree.java",
"snippet": "@Data\n@Slf4j\npublic class Tree {\n private static final Tree INSTANCE = new Tree();\n\n private JTree jTree;\n\n private DefaultTreeModel defaultTreeModel;\n\n private Tree() {\n TreeNode root = initTree();\n\n defaultTreeModel = new DefaultTreeModel(root);\n jTree = new JTree(defaultTreeModel);\n jTree.setShowsRootHandles(true);\n jTree.setCellRenderer(new TreeNodeRenderer());\n jTree.setRootVisible(false);\n jTree.addMouseListener(new TreeMouseAdapter());\n jTree.setToggleClickCount(0); // 0 表示禁用双击展开\n }\n\n public static Tree getInstance() {\n return INSTANCE;\n }\n\n private TreeNode initTree() {\n SystemApi api = KToolsContext.getInstance().getApi(SystemApi.class);\n List<TreeEntity> tree = api.getTree(0);\n\n TreeNode rootNode = new TreeNode(0, null, \"ROOT\", TreeNodeType.ROOT, \"ROOT\");\n buildTree(rootNode, tree.getFirst().getChild());\n return rootNode;\n }\n\n private void buildTree(TreeNode parentNode, List<TreeEntity> children) {\n if (CollectionUtil.isNotEmpty(children)) {\n for (TreeEntity child : children) {\n TreeNode treeNode = new TreeNode(child);\n parentNode.add(treeNode);\n buildTree(treeNode, child.getChild());\n }\n }\n }\n\n\n public void expandTreeNode(TreePath selectionPath) {\n if (Objects.nonNull(selectionPath)) {\n if (!jTree.isExpanded(selectionPath)) {\n jTree.expandPath(selectionPath);\n }\n }\n }\n\n public TreeModel getTreeModel() {\n return jTree.getModel();\n }\n\n public DefaultTreeModel getDefaultTreeModel() {\n return (DefaultTreeModel) jTree.getModel();\n }\n\n public TreePath getCurrentTreePath() {\n TreePath selectionPath = jTree.getSelectionPath();\n\n // 如果selectionPath为null, 说明未选择任何节点, 因此直接默认在根节点的目录下创建\n if (Objects.isNull(selectionPath)) {\n selectionPath = new TreePath(jTree.getModel().getRoot());\n }\n return selectionPath;\n }\n\n public TreeNode getCurrentTreeNode() {\n JTree jTree = Tree.getInstance().getJTree();\n TreePath selectionPath = jTree.getSelectionPath();\n\n // 如果selectionPath为null, 说明未选择任何节点, 因此直接默认在根节点的目录下创建\n if (Objects.isNull(selectionPath)) {\n selectionPath = new TreePath(jTree.getModel().getRoot());\n }\n return (TreeNode) selectionPath.getLastPathComponent();\n }\n\n public TreeNode getCurrentTreeNode(TreePath treePath) {\n return (TreeNode) treePath.getLastPathComponent();\n }\n\n\n public TreeEntity getCurrentTreeEntity() {\n JTree jTree = Tree.getInstance().getJTree();\n TreePath selectionPath = jTree.getSelectionPath();\n\n // 如果selectionPath为null, 说明未选择任何节点, 因此直接默认在根节点的目录下创建\n if (Objects.isNull(selectionPath)) {\n selectionPath = new TreePath(jTree.getModel().getRoot());\n }\n return ((TreeNode) selectionPath.getLastPathComponent()).getTreeEntity();\n }\n\n public TreeEntity getCurrentTreeEntity(TreePath treePath) {\n return ((TreeNode) treePath.getLastPathComponent()).getTreeEntity();\n }\n\n public TreeEntity getCurrentTreeEntity(TreeNode treeNode) {\n return treeNode.getTreeEntity();\n }\n\n public String getNodePathString(List<String> nodePathList) {\n StringBuilder nodePathString = new StringBuilder();\n for (int i = nodePathList.size() - 1; i >= 0; i--) {\n nodePathString.append(nodePathList.get(i)).append(\"/\");\n }\n return nodePathString.delete(nodePathString.length() - 1, nodePathString.length()).toString();\n }\n\n public void buildTreeNodePath(List<String> list, TreePath selectionPath) {\n TreeNode currentTreeNode = (TreeNode) selectionPath.getLastPathComponent();\n Integer id = currentTreeNode.getTreeEntity().getId();\n list.add(String.valueOf(id));\n\n TreePath parentPath = selectionPath.getParentPath();\n if (Objects.nonNull(parentPath)) {\n buildTreeNodePath(list, parentPath);\n }\n }\n\n public void deleteTreeChildNode(TreeNode currentTreeNode) {\n currentTreeNode.removeAllChildren();\n getDefaultTreeModel().nodeStructureChanged(currentTreeNode);\n }\n}"
},
{
"identifier": "TreeNode",
"path": "frontend/src/main/java/com/ktools/frontend/component/TreeNode.java",
"snippet": "@Getter\n@Setter\n@NoArgsConstructor\npublic class TreeNode extends DefaultMutableTreeNode {\n\n private TreeEntity treeEntity;\n\n public TreeNode(TreeEntity treeEntity) {\n super(treeEntity.getNodeName());\n this.treeEntity = treeEntity;\n }\n\n public TreeNode(Integer id, Integer parentNodeId, String nodeName, String nodeType, String nodeComment) {\n super(nodeName);\n this.treeEntity = new TreeEntity(id, parentNodeId, nodeName, nodeType, nodeComment, \"0\", null, null);\n }\n\n public TreeEntity getTreeEntity() {\n return treeEntity;\n }\n\n public void setTreeEntity(TreeEntity treeEntity) {\n setUserObject(treeEntity.getNodeName());\n this.treeEntity = treeEntity;\n }\n}"
},
{
"identifier": "KToolException",
"path": "warehouse/src/main/java/com/ktools/warehouse/exception/KToolException.java",
"snippet": "public class KToolException extends Exception {\n\n public KToolException(String msg) {\n super(msg);\n }\n\n public KToolException(String msg, Exception e) {\n super(msg, e);\n }\n\n}"
},
{
"identifier": "UidKey",
"path": "warehouse/src/main/java/com/ktools/warehouse/manager/uid/UidKey.java",
"snippet": "@Getter\npublic enum UidKey {\n\n PROP(PropMapper.class),\n\n TREE(TreeMapper.class);\n\n private final Class<? extends BaseMapper<?>> mapper;\n\n UidKey(Class<? extends BaseMapper<?>> mapper) {\n this.mapper = mapper;\n }\n\n}"
},
{
"identifier": "TreeEntity",
"path": "warehouse/src/main/java/com/ktools/warehouse/mybatis/entity/TreeEntity.java",
"snippet": "@Data\n@Table(value = \"tree\", dataSource = SysDataSource.DATASOURCE_NAME)\n@NoArgsConstructor\n@AllArgsConstructor\npublic class TreeEntity {\n\n @Id(\"id\")\n private Integer id;\n\n @Column(\"parent_node_id\")\n private Integer parentNodeId;\n\n @Column(\"node_name\")\n private String nodeName;\n\n @Column(\"node_type\")\n private String nodeType;\n\n @Column(\"node_comment\")\n private String nodeComment;\n\n @Column(\"node_path\")\n private String nodePath;\n\n @Column(value = \"node_info\", typeHandler = NodeInfoHandler.class)\n private Map<String, String> nodeInfo;\n\n @Column(ignore = true)\n private List<TreeEntity> child;\n\n}"
}
] | import com.ktools.warehouse.KToolsContext;
import com.ktools.frontend.Main;
import com.ktools.warehouse.api.SystemApi;
import com.ktools.frontend.common.model.TreeNodeType;
import com.ktools.frontend.common.utils.DialogUtil;
import com.ktools.warehouse.common.utils.StringUtil;
import com.ktools.frontend.component.Tree;
import com.ktools.frontend.component.TreeNode;
import com.ktools.warehouse.exception.KToolException;
import com.ktools.warehouse.manager.uid.UidKey;
import com.ktools.warehouse.mybatis.entity.TreeEntity;
import lombok.extern.slf4j.Slf4j;
import javax.swing.*;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List; | 4,118 | package com.ktools.frontend.action;
/**
* @author lsl
* @version 1.0
* @date 2023年12月01日 10:50
*/
@Slf4j
public class NewFolderAction implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
Tree instance = Tree.getInstance();
TreePath selectionPath = instance.getCurrentTreePath();
TreeNode currentTreeNode = instance.getCurrentTreeNode(selectionPath);
String result = JOptionPane.showInputDialog(
Main.kToolsRootJFrame,
"目录名称",
"新建文件夹",
JOptionPane.INFORMATION_MESSAGE
);
if (StringUtil.isNotBlank(result)) {
log.info("新建文件夹: {}", result);
TreeEntity treeEntity = new TreeEntity(); | package com.ktools.frontend.action;
/**
* @author lsl
* @version 1.0
* @date 2023年12月01日 10:50
*/
@Slf4j
public class NewFolderAction implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
Tree instance = Tree.getInstance();
TreePath selectionPath = instance.getCurrentTreePath();
TreeNode currentTreeNode = instance.getCurrentTreeNode(selectionPath);
String result = JOptionPane.showInputDialog(
Main.kToolsRootJFrame,
"目录名称",
"新建文件夹",
JOptionPane.INFORMATION_MESSAGE
);
if (StringUtil.isNotBlank(result)) {
log.info("新建文件夹: {}", result);
TreeEntity treeEntity = new TreeEntity(); | treeEntity.setId(KToolsContext.getInstance().getIdGenerator().getId(UidKey.TREE)); | 0 | 2023-11-30 03:26:25+00:00 | 8k |
ChrisGenti/VPL | velocity/src/main/java/com/github/chrisgenti/vpl/velocity/commands/admin/VPLCommand.java | [
{
"identifier": "VPLPlugin",
"path": "velocity/src/main/java/com/github/chrisgenti/vpl/velocity/VPLPlugin.java",
"snippet": "@Plugin(\n id = \"vpl\",\n name = \"VPL\",\n version = \"1.0.0\",\n description = \"\",\n authors = {\"ChrisGenti\"}\n) @Getter\npublic class VPLPlugin {\n public static final ChannelIdentifier MODERN_CHANNEL = MinecraftChannelIdentifier.create(\"vpl\", \"main\");\n public static final ChannelIdentifier LEGACY_CHANNEL = new LegacyChannelIdentifier(\"vpl:main\");\n\n @Inject private ProxyServer proxy;\n @Inject private Logger logger;\n @Inject private EventManager eventManager;\n @Inject @DataDirectory Path directory;\n\n private ConfigFile configFile;\n private LanguageFile languageFile;\n\n private PlayerManager playerManager;\n private ServerManager serverManager;\n private DataProvider provider;\n\n private PluginTask registerTask;\n\n @Subscribe\n public void onInitialization(ProxyInitializeEvent event) {\n /*\n * FILES\n */\n this.configFile = new ConfigFile(directory.toFile(), \"config.toml\");\n this.languageFile = new LanguageFile(new File(directory.toFile(), \"lang\"), configFile.LANGUAGE);\n\n /*\n * SETUP MESSAGE\n */\n this.sendMessage(\n \"<reset>\", \"<bold><aqua>VPL | VELOCITY PREMIUM LOGIN</bold>\"\n );\n\n /*\n * MANAGERS\n */\n this.playerManager = new PlayerManager();\n this.serverManager = new ServerManager(this);\n\n /*\n * PROVIDERS\n */\n this.provider = new MySQLProvider(this, configFile.CREDENTIALS);\n this.provider.init();\n\n /*\n * COMMANDS\n */\n this.registerCommands(\n new VPLCommand(this), new PremiumCommand(this)\n );\n\n /*\n * LISTENERS\n */\n this.registerListeners(\n new PluginMessageListener(this),\n new ChatListener(this), new CommandListener(this), new TabCompleteListener(this),\n new PreLoginListener(this), new ProfileRequestListener(this), new InitialServerListener(this), new PostLoginListener(this), new DisconnectListener(this)\n );\n\n /*\n * TASKS\n */\n this.registerTask = new RegisterTask(this);\n this.registerTask.run();\n\n /*\n * CHANNELS\n */\n this.registerPluginChannels();\n }\n\n @Subscribe\n public void onShutdown(ProxyShutdownEvent event) {\n /*\n * TASKS\n */\n this.registerTask.stop();\n\n /*\n * CHANNELS\n */\n this.unregisterPluginChannels();\n }\n\n public void debug(String message) {\n if (configFile.DEBUG)\n logger.info(\"[DEBUG] {}\", message);\n }\n\n public void sendMessage(CommandSource source, String message) {\n if (!message.isEmpty())\n source.sendMessage(MiniMessage.miniMessage().deserialize(message));\n }\n\n public void sendMessage(String... messages) {\n CommandSource source = proxy.getConsoleCommandSource();\n Arrays.stream(messages).forEach(message -> this.sendMessage(source, message));\n }\n\n private void registerCommands(PluginCommand... commands) {\n CommandManager manager = proxy.getCommandManager();\n\n Arrays.stream(commands).forEach(command -> {\n CommandMeta commandMeta = manager.metaBuilder(command.name())\n .plugin(this)\n .build();\n manager.register(commandMeta, command);\n });\n }\n\n private void registerListeners(Listener<?>... listeners) {\n Arrays.stream(listeners).forEach(Listener::register);\n }\n\n private void registerPluginChannels() {\n this.proxy.getChannelRegistrar().register(MODERN_CHANNEL, LEGACY_CHANNEL);\n }\n\n private void unregisterPluginChannels() {\n this.proxy.getChannelRegistrar().unregister(MODERN_CHANNEL, LEGACY_CHANNEL);\n }\n}"
},
{
"identifier": "PluginCommand",
"path": "velocity/src/main/java/com/github/chrisgenti/vpl/velocity/commands/PluginCommand.java",
"snippet": "public interface PluginCommand extends SimpleCommand {\n String name();\n\n default String usage() { return \"/\" + this.name(); };\n}"
},
{
"identifier": "PluginSubCommand",
"path": "velocity/src/main/java/com/github/chrisgenti/vpl/velocity/commands/admin/subs/PluginSubCommand.java",
"snippet": "public interface PluginSubCommand {\n String name();\n\n String usage();\n\n void execute(CommandSource source, String[] arguments);\n\n default boolean hasPermission(SimpleCommand.Invocation invocation) {\n return true;\n }\n}"
},
{
"identifier": "AccountsSubCommand",
"path": "velocity/src/main/java/com/github/chrisgenti/vpl/velocity/commands/admin/subs/accounts/AccountsSubCommand.java",
"snippet": "public class AccountsSubCommand implements PluginSubCommand {\n private final VPLPlugin plugin;\n private final ProxyServer proxy;\n private final LanguageFile languageFile;\n private final DataProvider provider;\n\n public AccountsSubCommand(VPLPlugin plugin) {\n this.plugin = plugin; this.proxy = plugin.getProxy();\n this.languageFile = plugin.getLanguageFile(); this.provider = plugin.getProvider();\n }\n\n @Override\n public String name() {\n return \"accounts\";\n }\n\n @Override\n public String usage() {\n return \"/vpl accounts <username/address>\";\n }\n\n @Override @SuppressWarnings(\"UnstableApiUsage\")\n public void execute(CommandSource source, String[] arguments) {\n if (arguments.length != 1) {\n plugin.sendMessage(source, languageFile.NO_CORRECT_USAGE.replace(\"%command%\", this.usage()));\n return;\n }\n String value = arguments[0];\n\n if (InetAddresses.isInetAddress(value)) {\n this.continuation(source, null, value); return;\n }\n\n UUID uniqueID = UUIDAdapter.generateOfflineId(value);\n provider.presentInIP(uniqueID).thenAccept(checkPresent -> {\n if (checkPresent) {\n provider.getUserIP(uniqueID).thenAccept(address -> this.continuation(source, value, address));\n } else {\n plugin.sendMessage(source, languageFile.PLAYER_NOT_IN_DATABASE.replace(\"%player%\", value));\n }\n });\n }\n\n @Override\n public boolean hasPermission(SimpleCommand.Invocation invocation) {\n return invocation.source().hasPermission(\"vpl.accounts\");\n }\n\n private void continuation(CommandSource source, @Nullable String username, String address) {\n provider.getUsersByIP(address).thenAccept(users -> {\n if (users.isEmpty()) {\n plugin.sendMessage(source, languageFile.ADDRESS_NOT_IN_DATABASE.replace(\"%address%\", address));\n } else {\n StringBuilder builder = new StringBuilder();\n for (int i = 0; i < users.size(); i++) {\n String value = users.get(i);\n builder.append(proxy.getPlayer(value).isPresent() ? languageFile.ONLINE : languageFile.OFFLINE).append(value);\n\n if (i < users.size() - 1)\n builder.append(\", \");\n }\n plugin.sendMessage(source, languageFile.PLAYER_ACCOUNTS.replace(\"%value%\", username != null ? username : address).replace(\"%users%\", builder.toString()));\n }\n });\n }\n}"
},
{
"identifier": "CheckSubCommand",
"path": "velocity/src/main/java/com/github/chrisgenti/vpl/velocity/commands/admin/subs/check/CheckSubCommand.java",
"snippet": "public class CheckSubCommand implements PluginSubCommand {\n private final VPLPlugin plugin;\n private final LanguageFile languageFile;\n private final DataProvider provider;\n private final PlayerManager playerManager;\n\n public CheckSubCommand(VPLPlugin plugin) {\n this.plugin = plugin;\n this.languageFile = plugin.getLanguageFile(); this.provider = plugin.getProvider(); this.playerManager = plugin.getPlayerManager();\n }\n\n @Override\n public String name() {\n return \"check\";\n }\n\n @Override\n public String usage() {\n return \"/vpl check <player>\";\n }\n\n @Override\n public void execute(CommandSource source, String[] arguments) {\n if (arguments.length != 1) {\n plugin.sendMessage(source, languageFile.NO_CORRECT_USAGE.replace(\"%command%\", this.usage()));\n return;\n }\n String username = arguments[0]; UUID uniqueID = UUIDAdapter.generateOfflineId(username);\n\n if (playerManager.presentInPremium(uniqueID)) {\n this.continuation(source, username, true);\n } else {\n provider.presentInUsers(uniqueID).thenAccept(checkPresent -> {\n if (checkPresent) {\n provider.getUserPremium(uniqueID).thenAccept(premium -> this.continuation(source, username, premium));\n } else {\n plugin.sendMessage(source, languageFile.PLAYER_NOT_IN_DATABASE.replace(\"%player%\", username));\n }\n });\n }\n }\n\n @Override\n public boolean hasPermission(SimpleCommand.Invocation invocation) {\n return invocation.source().hasPermission(\"vpl.check\");\n }\n\n private void continuation(CommandSource source, String username, boolean premium) {\n plugin.sendMessage(source, languageFile.PREMIUM_CHECK.replace(\"%player%\", username).replace(\"%premium%\", premium ? languageFile.ENABLED : languageFile.DISABLED));\n }\n}"
},
{
"identifier": "DisableSubCommand",
"path": "velocity/src/main/java/com/github/chrisgenti/vpl/velocity/commands/admin/subs/disable/DisableSubCommand.java",
"snippet": "public class DisableSubCommand implements PluginSubCommand {\n private final VPLPlugin plugin;\n private final LanguageFile languageFile;\n private final DataProvider provider;\n private final PlayerManager playerManager;\n\n public DisableSubCommand(VPLPlugin plugin) {\n this.plugin = plugin;\n this.languageFile = plugin.getLanguageFile(); this.provider = plugin.getProvider(); this.playerManager = plugin.getPlayerManager();\n }\n\n @Override\n public String name() {\n return \"disable\";\n }\n\n @Override\n public String usage() {\n return \"/vpl disable <player>\";\n }\n\n @Override\n public void execute(CommandSource source, String[] arguments) {\n if (arguments.length != 1) {\n plugin.sendMessage(source, languageFile.NO_CORRECT_USAGE.replace(\"%command%\", this.usage()));\n return;\n }\n String username = arguments[0]; UUID uniqueID = UUIDAdapter.generateOfflineId(username);\n\n if (playerManager.presentInPremium(uniqueID)) {\n playerManager.removePremium(uniqueID); this.continuation(source, username, uniqueID);\n } else {\n provider.presentInUsers(uniqueID).thenAccept(checkPresent -> {\n if (checkPresent) {\n provider.getUserPremium(uniqueID).thenAccept(premium -> {\n if (premium) {\n this.continuation(source, username, uniqueID);\n } else {\n plugin.sendMessage(source, languageFile.PLAYER_NOT_PREMIUM.replace(\"%player%\", username));\n }\n });\n } else {\n plugin.sendMessage(source, languageFile.PLAYER_NOT_IN_DATABASE.replace(\"%player%\", username));\n }\n });\n }\n }\n\n @Override\n public boolean hasPermission(SimpleCommand.Invocation invocation) {\n return invocation.source().hasPermission(\"vpl.disable\");\n }\n\n private void continuation(CommandSource source, String username, UUID uniqueID) {\n provider.editUser(uniqueID, false).thenAccept(success -> {\n if (success) {\n plugin.sendMessage(source, languageFile.PREMIUM_DISABLED.replace(\"%player%\", username));\n } else {\n plugin.sendMessage(source, languageFile.FIND_ERROR);\n }\n });\n }\n}"
},
{
"identifier": "StatsSubCommand",
"path": "velocity/src/main/java/com/github/chrisgenti/vpl/velocity/commands/admin/subs/stats/StatsSubCommand.java",
"snippet": "public class StatsSubCommand implements PluginSubCommand {\n private final VPLPlugin plugin;\n private final LanguageFile languageFile;\n private final DataProvider provider;\n\n public StatsSubCommand(VPLPlugin plugin) {\n this.plugin = plugin;\n this.languageFile = plugin.getLanguageFile(); this.provider = plugin.getProvider();\n }\n\n @Override\n public String name() {\n return \"stats\";\n }\n\n @Override\n public String usage() {\n return \"/vpl stats\";\n }\n\n @Override\n public void execute(CommandSource source, String[] arguments) {\n if (arguments.length != 0) {\n plugin.sendMessage(source, languageFile.NO_CORRECT_USAGE.replace(\"%command%\", this.usage()));\n return;\n }\n\n provider.getUsers().thenAccept(users -> {\n plugin.sendMessage(languageFile.PREMIUM_STATS.replace(\"%count%\", String.valueOf(users.size())));\n });\n }\n\n @Override\n public boolean hasPermission(SimpleCommand.Invocation invocation) {\n return invocation.source().hasPermission(\"vpl.stats\");\n }\n}"
},
{
"identifier": "LanguageFile",
"path": "velocity/src/main/java/com/github/chrisgenti/vpl/velocity/configurations/language/LanguageFile.java",
"snippet": "public class LanguageFile extends TomlFile {\n public final String NO_CORRECT_USAGE, BLOCKED_COMMAND, NO_SUB_COMMAND, NO_PERMISSION, NO_CONSOLE, FIND_ERROR;\n\n public final String PREMIUM_NOTIFICATION, NO_PREMIUM_USERNAME, FORCE_UNREGISTERED, PREMIUM_RECONNECT, ALREADY_PREMIUM, PREMIUM_CONFIRM, PREMIUM_LOGIN;\n\n public final String ADDRESS_NOT_IN_DATABASE, PLAYER_NOT_IN_DATABASE, PLAYER_NOT_PREMIUM, PREMIUM_DISABLED, PLAYER_ACCOUNTS, PREMIUM_CHECK, PREMIUM_STATS, MAIN_INFO;\n\n public final String DISABLED, ENABLED, OFFLINE, ONLINE;\n\n public LanguageFile(File directory, LanguageType languageType) {\n super(directory, languageType.getValue());\n\n this.NO_CORRECT_USAGE = tomlRoot.getString(\"no_correct_usage\");\n this.BLOCKED_COMMAND = tomlRoot.getString(\"blocked_command\");\n this.NO_SUB_COMMAND = tomlRoot.getString(\"no_sub_command\");\n this.NO_PERMISSION = tomlRoot.getString(\"no_permission\");\n this.NO_CONSOLE = tomlRoot.getString(\"no_console\");\n this.FIND_ERROR = tomlRoot.getString(\"find_error\");\n\n this.PREMIUM_NOTIFICATION = tomlRoot.getString(\"premium_notification\");\n this.NO_PREMIUM_USERNAME = tomlRoot.getString(\"no_premium_username\");\n this.FORCE_UNREGISTERED = tomlRoot.getString(\"force_unregistered\");\n this.PREMIUM_RECONNECT = tomlRoot.getString(\"premium_reconnect\");\n this.ALREADY_PREMIUM = tomlRoot.getString(\"already_premium\");\n this.PREMIUM_CONFIRM = tomlRoot.getString(\"premium_confirm\");\n this.PREMIUM_LOGIN = tomlRoot.getString(\"premium_login\");\n\n this.ADDRESS_NOT_IN_DATABASE = tomlRoot.getString(\"address_not_in_database\");\n this.PLAYER_NOT_IN_DATABASE = tomlRoot.getString(\"player_not_in_database\");\n this.PLAYER_NOT_PREMIUM = tomlRoot.getString(\"player_not_premium\");\n this.PREMIUM_DISABLED = tomlRoot.getString(\"premium_disabled\");\n this.PLAYER_ACCOUNTS = tomlRoot.getString(\"player_accounts\");\n this.PREMIUM_CHECK = tomlRoot.getString(\"premium_check\");\n this.PREMIUM_STATS = tomlRoot.getString(\"premium_stats\");\n this.MAIN_INFO = tomlRoot.getString(\"main_info\");\n\n this.DISABLED = tomlRoot.getString(\"premium.disabled\");\n this.ENABLED = tomlRoot.getString(\"premium.enabled\");\n this.OFFLINE = tomlRoot.getString(\"account.offline\");\n this.ONLINE = tomlRoot.getString(\"account.online\");\n }\n}"
}
] | import com.github.chrisgenti.vpl.velocity.VPLPlugin;
import com.github.chrisgenti.vpl.velocity.commands.PluginCommand;
import com.github.chrisgenti.vpl.velocity.commands.admin.subs.PluginSubCommand;
import com.github.chrisgenti.vpl.velocity.commands.admin.subs.accounts.AccountsSubCommand;
import com.github.chrisgenti.vpl.velocity.commands.admin.subs.check.CheckSubCommand;
import com.github.chrisgenti.vpl.velocity.commands.admin.subs.disable.DisableSubCommand;
import com.github.chrisgenti.vpl.velocity.commands.admin.subs.stats.StatsSubCommand;
import com.github.chrisgenti.vpl.velocity.configurations.language.LanguageFile;
import com.velocitypowered.api.command.CommandSource;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap; | 3,870 | package com.github.chrisgenti.vpl.velocity.commands.admin;
public class VPLCommand implements PluginCommand {
private final Set<PluginSubCommand> subCommands = ConcurrentHashMap.newKeySet();
private final VPLPlugin plugin;
private final LanguageFile languageFile;
public VPLCommand(VPLPlugin plugin) {
this.plugin = plugin; this.languageFile = plugin.getLanguageFile();
this.subCommands.add(new StatsSubCommand(plugin)); | package com.github.chrisgenti.vpl.velocity.commands.admin;
public class VPLCommand implements PluginCommand {
private final Set<PluginSubCommand> subCommands = ConcurrentHashMap.newKeySet();
private final VPLPlugin plugin;
private final LanguageFile languageFile;
public VPLCommand(VPLPlugin plugin) {
this.plugin = plugin; this.languageFile = plugin.getLanguageFile();
this.subCommands.add(new StatsSubCommand(plugin)); | this.subCommands.add(new CheckSubCommand(plugin)); | 4 | 2023-11-28 10:12:04+00:00 | 8k |
Ethylene9160/Chess | src/chess/recorder/Saver.java | [
{
"identifier": "Chess",
"path": "src/chess/pieces/Chess.java",
"snippet": "public abstract class Chess {\n public final static String KING = \"king\", ROOK = \"rook\", QUEEN = \"queen\",\n KNIGHT = \"knight\", BISHOP = \"bishop\", PAWN = \"pawn\";\n public static Style style = Style.DEFAULT;\n public final static String[] PIECES = { KING, ROOK, QUEEN, KNIGHT, BISHOP, PAWN};\n\n public static final int FIRST_COLOR = 1, LATER_COLOR = -1;\n //棋子大小\n public static final int SIZE = 60;\n //棋子距边缘距离\n public static final int MARGIN = 20;\n //棋子间距\n public static final int SPACE = 60;\n //棋子名称\n protected String name;\n public String path;\n //棋子颜色、实际坐标、下标\n private static int IDBase = 0;\n public static void setIDBase(int var){\n IDBase = var;\n }\n protected int color, x, y, ID;\n public boolean moved, changed;\n\n\n //棋子的网格坐标\n protected Point point, initPoint;\n\n public String getName() {\n return this.name;\n }\n\n public int getID() {\n return this.ID;\n }\n\n public int getColor() {\n return color;\n }\n\n public void setColor(int color) {\n this.color = color;\n }\n\n public void setName(String name) {\n this.name = name;\n this.path = Constants.STYLE_PATH + File.separator + Style.getStyle(style) + File.separator + name + color+\".png\";\n }\n\n public void setID(int ID){\n this.ID = ID;\n }\n\n public void setPoint(Point point) {\n this.point = (Point) point.clone();\n if (initPoint == null) {\n initPoint = this.point;\n }\n calculatePosition();\n }\n\n public Chess(String name, Point point, int player) {\n this.name = name;\n this.color = player;\n\n this.path = Constants.STYLE_PATH + File.separator +Style.getStyle(style) + File.separator + name + color + \".png\";\n System.out.println(path);\n this.point = new Point(point);\n this.initPoint = new Point(point);\n this.calculatePosition();\n this.ID = ++IDBase;\n }\n\n public void setPoint(int x, int y) {\n if (x >= 0 && x < 8 && y > -1 && y < 8) {\n this.point.x = x;\n this.point.y = y;\n calculatePosition();\n }\n }\n\n\n public Point getPoint() {\n return this.point;\n }\n\n /**\n * 绘制棋子的方法\n *\n * @param g 棋子画笔\n * @param panel 棋盘所在的panel\n */\n public void draw(Graphics g, PanelBase panel) {\n g.drawImage(Toolkit.getDefaultToolkit().getImage(path),\n MARGIN+SPACE * point.x, MARGIN+SPACE * point.y, SIZE, SIZE, panel);\n }\n\n public void drawSelectedChess(Graphics g) {\n g.drawRect(this.x, this.y, SIZE, SIZE);\n }\n\n public void calculatePosition() {\n// this.x = MARGIN - SIZE / 2 + SPACE * (point.x);\n// this.y = MARGIN - SIZE / 2 + SPACE * (point.y);\n this.x=MARGIN+SPACE * point.x;\n this.y=MARGIN+SPACE * point.y;\n }\n\n /**\n * 根据x,y坐标计算网格坐标\n *\n * @param x\n * @param y\n */\n public static Point getNewPoint(int x, int y) {\n //todo: 添加判定方法!判断x,y是否合法。\n// x = (x - MARGIN + SIZE / 2) / SPACE;\n// y = (y - MARGIN + SIZE / 2) / SPACE;\n x = (x-MARGIN)/SPACE;\n y = (y-MARGIN)/SPACE;\n return new Point(x, y);\n }\n\n public void reverse() {\n point.y = 7 - point.y;\n initPoint = point;\n calculatePosition();\n }\n\n /*\n 下棋逻辑判断部分。\n */\n\n\n /**\n * 是否蹩脚。国际象棋里没有用。\n *\n * @param point\n * @param gamePanel\n * @return boolean\n */\n @Deprecated\n public boolean isPrevented(Point point, PanelBase gamePanel) {\n Point center = new Point();\n if (Chess.BISHOP.equals(name)) {\n center.x = (point.x + this.point.x) / 2;\n center.y = (point.y + this.point.y) / 2;\n return gamePanel.getChessFromPoint(center) != null;\n } else if (Chess.KNIGHT.equals(name)) {\n int line = whichLine(point);\n if (line == -2) {\n //x轴日字蹩脚:\n center.x = (point.x + this.point.x) / 2;\n center.y = this.point.y;\n } else if (line == -3) {\n //y轴日字蹩脚\n center.x = this.point.x;\n center.y = (point.y + this.point.y)/2;\n }\n return gamePanel.getChessFromPoint(center) != null;\n }\n return false;\n }\n\n /**\n * 判断棋子最初在河对岸还是我方。例如,y < 5, 在棋盘上方。\n *\n * @return\n */\n public boolean isUp() {\n return initPoint.y < 5;\n }\n\n /**\n * @param point 坐标\n * @return 3:沿x方向直线<p>\n * 2:沿着y方向直线<p>\n * 1:45°斜线<p>\n * -1:都不是<p>\n * -2: x轴日<p>\n * -3:y轴日\n */\n public int whichLine(Point point) {\n if (point.y == this.point.y) return 3;\n else if (point.x == this.point.x) return 2;\n else if (Math.abs(point.x - this.point.x) == Math.abs(point.y - this.point.y)) return 1;\n else if (Math.abs(this.point.x - point.x) == 2 && Math.abs(this.point.y - point.y) == 1) return -2;\n else if (Math.abs(this.point.y - point.y) == 2 && Math.abs(this.point.x - point.x) == 1) return -3;\n else return -1;\n }\n\n /**\n * 走的直角边数, 例如,马任走一次会走3个直角边,车从(2,1)走到(4,1)会走过2个直角边。\n *\n * @param point 目标点位置\n * @return 经过的小方格边数。\n * */\n public int getStep(Point point) {\n// int line = whichLine(point);\n// if (line == 3) return Math.abs(point.x - this.point.x);\n// else if (line == 2 || line == 1) return Math.abs(point.y - this.point.y);\n// else return line;\n return getStep(point, whichLine(point));\n }\n\n public int getStep(Point point, int line) {\n if (line == 3) return Math.abs(point.x - this.point.x);\n else if (line == 2 || line == 1) return Math.abs(point.y - this.point.y);\n else return line;\n }\n\n /**\n * 计算起点到终点之间的直线上有多少棋子。<b>不包括起点、终点</b>。\n * @param point 目标坐标\n * @return 棋子数量\n */\n @SuppressWarnings(\"can be update\")\n public int pieceCount(Point point, PanelBase gamePanel){\n return pieceCount(whichLine(point), point, gamePanel);\n }\n\n /**\n * 计算起点到终点之间的直线上有多少棋子。<b>不包括起点、终点</b>。这个方法可以被精简。\n * @param line 走棋方向,如果不是直线或者对角线,会直接返回line值。\n * @param point 目标坐标\n * @param gamePanel 游戏面板\n * @return int\n */\n @SuppressWarnings(\"can be update\")\n public int pieceCount(int line, Point point, PanelBase gamePanel){\n int start, end, cou = 0;\n Point tempP = new Point();\n if(line == 2){//沿y\n tempP.x = this.point.x;\n start = Math.min(point.y, this.point.y)+1;\n end = Math.max(point.y, this.point.y);\n\n for(int i = start ; i < end; i++){\n tempP.y = i;\n if(gamePanel.getChessFromPoint(tempP) != null) cou++;\n }\n }else if(line == 3){//沿x\n tempP.y = this.point.y;\n start = Math.min(point.x, this.point.x)+1;\n end = Math.max(point.x, this.point.x);\n for(int i = start ; i < end; i++){\n tempP.x = i;\n if(gamePanel.getChessFromPoint(tempP) != null) cou++;\n }\n }else if(line == 1){\n //todo: 完成象中途不能被挡住\n int startX = point.x, startY = point.y, endX = this.point.x;\n int deltaX = startX < endX? 1:-1, deltaY = startY < this.point.y? 1:-1;\n for(startX += deltaX, startY+=deltaY; startX != endX; startX+=deltaX, startY+=deltaY){\n tempP.x = startX; tempP.y = startY;\n if(gamePanel.getChessFromPoint(tempP) != null) {\n cou++;\n }\n }\n }\n return cou;\n }\n\n /**\n * 判断是否前进\n * @param point 目标坐标\n * @return 是否前进\n */\n public boolean isForward(Point point){\n if(isUp()){//如果本身在上面,那么只能往下走\n return point.y > this.point.y;\n }else{\n return point.y < this.point.y;\n }\n }\n\n /**\n * 判断王车换位能否成立。\n * @return 能为真,不能为假\n */\n @Deprecated\n public boolean canWangCheYiWei(){\n //todo: 判断王车易位能否成立\n return false;\n }\n\n /**\n * 兵的特殊走法:能否换成新的棋子。例如走到对方的皇位置,变成皇后。\n * @return\n */\n @Deprecated\n public boolean canUpdatePawn(){\n return false;\n }\n\n @Override\n public String toString() {\n return String.format(\"棋子名称:%s, ID:%d, 横坐标:%d, 纵坐标:%d, \\n属于【%d】阵营。\", name, this.ID, point.x, point.y, color);\n }\n\n public boolean equals(Chess chess){\n return chess.getID() == this.ID;\n }//这不是equal方法。\n\n public void moveProcess(PanelBase panel){\n Point tp = new Point(0,0);\n for (int i = 0; i < 8; i++) {\n for (int j = 0; j < 8; j++) {//遍历棋盘每一个点\n tp.x = i; tp.y = j;\n if(canMove(tp, panel) ) {//如果可以走,就绘制提示。\n if(panel.getChessFromPoint(tp) != null && panel.getChessFromPoint(tp).getColor() == color) continue;\n panel.drawHint(tp);\n System.out.println(i + \" \" + j + \"可以走\");\n }\n }\n }\n }\n\n @Deprecated\n public void shengWei(Point point){}\n\n public void shengWei(String name){}\n\n public boolean isAttacked(PanelBase panel){\n return false;\n }\n\n public void refactor(String s){}\n\n\n /**\n * 判断能否移动到Point处\n *\n * @param point 想要移动到的点位\n * @return 能否移动\n */\n public abstract boolean canMove(Point point, PanelBase panel);\n\n public void resetPath(){\n this.path = Constants.STYLE_PATH + File.separator + Style.getStyle(style) + File.separator + name + color + \".png\";\n }\n\n @Deprecated\n public static boolean canMove(Point oldPoint, Point targetPoint, PanelBase panel){\n return false;\n };\n\n public boolean isDoubleMove(){\n return false;\n }\n\n public void setDoubleMove(boolean flag){\n\n }\n}"
},
{
"identifier": "Constants",
"path": "src/chess/util/Constants.java",
"snippet": "public class Constants {\n public static final int FRAME_LENGTH = 1080,\n FRAME_HEIGHT = 720;\n public static final String SAVE_BUTTON = \"SAVE\", LOAD_BUTTON = \"LOAD\", REGRET_BUTTON = \"REGRET\", RESTART_BUTTON = \"RESTART\",\n APPLY_BUTTON = \"APPLY\", PREPARE_BUTTON = \"PREP\", CONFIRM_BUTTON = \"CFR\", FORGET_BUTTON = \"FGB\", SIGN_BUTTON = \"SetS\",\n YOUR_EMO = \"Yem\";\n\n public final static String BASE_PATH = \"D:\\\\resource\\\\WChess\\\\statics\", //这里设置资源文件根目录\n LIBRARY_PATH = BASE_PATH + \"\\\\Library\",\n IMAGE_PATH = BASE_PATH + File.separator + \"image\",\n EMO_PATH = IMAGE_PATH + File.separator +\"emo\",\n HEAD_PATH = IMAGE_PATH + File.separator + \"head\",\n STYLE_PATH = IMAGE_PATH + File.separator + \"style\";\n\n public final static String REGISTER_PATH = BASE_PATH + File.separator + \"register\\\\reg.ethy\";\n public final static String CHESS_REGIST = BASE_PATH + File.separator + \"register\\\\chessReg.ethy\";\n public final static int PANEL_WEIGHT = PanelBase.BOARD_WEIGHT + 200;\n public final static String[] HEADERS = new File(HEAD_PATH).list(),\n EMOS = new File(EMO_PATH).list();\n public static final Font LITTLE_BLACK = new Font(\"微软雅黑\", Font.BOLD, 16),\n LARGE_BLACK = new Font(\"微软雅黑\", Font.BOLD, 50);\n\n //在这里修改网络\n public static final int PORT = 8888;//port\n public static final String HOST = \"127.0.0.1\";//IP\n\n\n private static String[] getHead(){\n return new File(HEAD_PATH).list();\n }\n}"
},
{
"identifier": "Locker",
"path": "src/chess/util/Locker.java",
"snippet": "public class Locker {\n public static final String setLocker(String str){\n char[] ches = str.toCharArray();\n int len = ches.length;\n for (int i = 0; i < len; i++) {\n ches[i] += i%14;\n }\n String s = new String(ches);\n return s;\n }\n\n public static String getLocker(String str){\n char[] ches = str.toCharArray();\n int len = ches.length;\n// StringBuilder b = new StringBuilder();\n for (int i = 0; i < len; i++) {\n ches[i] -= i%14;\n// if(ches[i] != '\\n') b.append(ches[i]);\n\n }\n// return b.toString();\n return new String(ches);\n }\n\n\n public static void main(String[] args) {\n String str = \"你好呀!\";\n System.out.println(setLocker(str));\n System.out.println(getLocker(setLocker(str)));\n }\n\n}"
}
] | import chess.pieces.Chess;
import chess.util.Constants;
import chess.util.Locker;
import javax.swing.*;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.List; | 4,218 | package chess.recorder;
public class Saver {
private static String getListInfo(List<Record> recordList) {
StringBuilder sb = new StringBuilder();
for (Record r : recordList) sb.append(r);
// for (Record r : recordList) sb.append(r).append("\n");
return sb.toString();
}
| package chess.recorder;
public class Saver {
private static String getListInfo(List<Record> recordList) {
StringBuilder sb = new StringBuilder();
for (Record r : recordList) sb.append(r);
// for (Record r : recordList) sb.append(r).append("\n");
return sb.toString();
}
| public static void saveC(int currentMax, List<Record> recordList, ArrayList<Chess> chessList) { | 0 | 2023-12-01 02:33:32+00:00 | 8k |
dnslin/cloud189 | src/main/java/in/dnsl/logic/FileDirectory.java | [
{
"identifier": "AppFileListParam",
"path": "src/main/java/in/dnsl/domain/req/AppFileListParam.java",
"snippet": "@Data\n@Builder\npublic class AppFileListParam {\n\n @Builder.Default\n private int familyId = 0;\n\n private String fileId;\n\n private int orderBy;\n\n @Builder.Default\n private String orderSort = \"false\";\n\n @Builder.Default\n private int pageNum = 1;\n\n @Builder.Default\n private int pageSize = 60;\n\n @Builder.Default\n private boolean constructPath = false;\n\n}"
},
{
"identifier": "AppGetFileInfoParam",
"path": "src/main/java/in/dnsl/domain/req/AppGetFileInfoParam.java",
"snippet": "@Data\n@Builder\npublic class AppGetFileInfoParam {\n\n // 家庭云ID\n @Builder.Default\n private int familyId = 0;\n\n // FileId 文件ID,支持文件和文件夹\n @Builder.Default\n private String fileId = \"\";\n\n // FilePath 文件绝对路径,支持文件和文件夹\n @Builder.Default\n private String filePath = \"\";\n}"
},
{
"identifier": "AppFileEntity",
"path": "src/main/java/in/dnsl/domain/result/AppFileEntity.java",
"snippet": "@Data\n@Builder\npublic class AppFileEntity {\n\n private String fileId;\n\n private String parentId;\n\n private String fileMd5;\n\n private String fileName;\n\n private long fileSize;\n\n private String lastOpTime;\n\n private String createTime;\n\n private String path;\n\n private int mediaType;\n\n private boolean isFolder;\n\n private int subFileCount;\n\n private int startLabel;\n\n private int favoriteLabel;\n\n private int orientation;\n\n private String rev;\n\n private int fileCata;\n}"
},
{
"identifier": "AppErrorXmlResp",
"path": "src/main/java/in/dnsl/domain/xml/AppErrorXmlResp.java",
"snippet": "@Data\n@XStreamAlias(\"error\")\npublic class AppErrorXmlResp {\n\n private String code;\n\n private String message;\n\n}"
},
{
"identifier": "AppGetFileInfoResult",
"path": "src/main/java/in/dnsl/domain/xml/AppGetFileInfoResult.java",
"snippet": "@Data\n@XStreamAlias(\"folderInfo\")\npublic class AppGetFileInfoResult {\n\n // 文件ID\n private String id;\n\n // 父文件ID\n private String parentFolderId;\n\n // 文件名 or 文件夹名称\n private String name;\n\n private String createDate;\n\n private String lastOpTime;\n\n private String path;\n\n private String rev;\n\n private ParentFolderListNode parentFolderList;\n\n private String groupSpaceId;\n\n}"
},
{
"identifier": "FileSystemEntity",
"path": "src/main/java/in/dnsl/domain/xml/FileSystemEntity.java",
"snippet": "@Data\n@NoArgsConstructor\n@AllArgsConstructor\n@Builder\npublic class FileSystemEntity {\n private String id;\n private String parentId;\n private String name;\n private long size;\n private String md5;\n private int starLabel;\n private int fileCata;\n private String lastOpTime;\n private String createDate;\n private int mediaType;\n private String rev;\n private boolean isFolder;\n private int subFileCount; // 仅对文件夹有效\n @Builder.Default\n private List<FileSystemEntity> children = new ArrayList<>();\n\n\n // 添加子实体(文件或文件夹)\n public void addChild(FileSystemEntity entity) {\n if (this.children == null) {\n this.children = new ArrayList<>();\n }\n this.children.add(entity);\n }\n\n}"
},
{
"identifier": "ListFiles",
"path": "src/main/java/in/dnsl/domain/xml/ListFiles.java",
"snippet": "@XStreamAlias(\"listFiles\")\n@Getter\n@Setter\npublic class ListFiles {\n private String lastRev;\n private FileList fileList;\n\n @Getter\n @Setter\n public static class FileList {\n private int count;\n\n @XStreamImplicit(itemFieldName = \"folder\")\n private List<Folder> folder;\n\n @XStreamImplicit(itemFieldName = \"file\")\n private List<File> file;\n }\n\n @XStreamAlias(\"folder\")\n @Getter\n @Setter\n public static class Folder {\n private String id;\n private String parentId;\n private String name;\n private String createDate;\n private int starLabel;\n private String lastOpTime;\n private String rev;\n private int fileCount;\n private int fileCata;\n }\n\n @XStreamAlias(\"file\")\n @Getter\n @Setter\n public static class File {\n private String id;\n private String name;\n private long size;\n private String md5;\n private int starLabel;\n private int fileCata;\n private String lastOpTime;\n private String createDate;\n private int mediaType;\n private String rev;\n }\n}"
},
{
"identifier": "OrderEnums",
"path": "src/main/java/in/dnsl/enums/OrderEnums.java",
"snippet": "public enum OrderEnums {\n\n OrderByName(1, \"filename\"),\n\n OrderBySize(2, \"filesize\"),\n\n OrderByTime(3, \"lastOpTime\");\n\n\n private final int code;\n\n private final String name;\n\n OrderEnums(int i, String n) {\n this.code = i;\n this.name = n;\n }\n\n\n\n\n // 根据code获取枚举\n public static String getByCode(int code) {\n // 根据code获取枚举\n for (OrderEnums e : OrderEnums.values()) {\n if (e.getCode() == code) {\n return e.getName();\n }\n }\n return null;\n }\n\n private int getCode() {\n return code;\n }\n\n private String getName() {\n return name;\n }\n\n}"
},
{
"identifier": "XmlUtils",
"path": "src/main/java/in/dnsl/utils/XmlUtils.java",
"snippet": "@Slf4j\npublic class XmlUtils {\n private static final XStream xstream = new XStream();\n\n static {\n // 设置 XStream 安全性,允许任何类被序列化或反序列化\n xstream.addPermission(AnyTypePermission.ANY);\n }\n\n // 将XML转换为Java对象\n public static <T> T xmlToObject(String xml, Class<T> clazz) {\n xstream.processAnnotations(clazz);\n return clazz.cast(xstream.fromXML(xml));\n }\n\n // 将Java对象转换为XML字符串\n public static String objectToXml(Object obj) {\n xstream.processAnnotations(obj.getClass());\n return xstream.toXML(obj);\n }\n\n}"
},
{
"identifier": "API_URL",
"path": "src/main/java/in/dnsl/constant/ApiConstant.java",
"snippet": "public static final String API_URL = \"https://api.cloud.189.cn\";"
},
{
"identifier": "rootNode",
"path": "src/main/java/in/dnsl/constant/ApiConstant.java",
"snippet": "public static final String rootNode = \"-11\";"
},
{
"identifier": "getSession",
"path": "src/main/java/in/dnsl/logic/CloudLogin.java",
"snippet": "public static synchronized SessionDTO getSession() {\n if (sessionDTO == null) throw new RuntimeException(\"sessionDTO is null 用户未登录\");\n return sessionDTO;\n}"
},
{
"identifier": "ApiUtils",
"path": "src/main/java/in/dnsl/utils/ApiUtils.java",
"snippet": "public class ApiUtils {\n\n public static String PcClientInfoSuffixParam(){\n return \"clientType=TELEPC&version=6.2&channelId=web_cloud.189.cn&rand=\" + rand();\n }\n\n // 获取大写的UUID\n public static String uuidUpper() {\n return uuidDash().toUpperCase();\n }\n\n public static String dateOfGmtStr() {\n SimpleDateFormat dateFormat = new SimpleDateFormat(\"EEE, dd MMM yyyy HH:mm:ss 'GMT'\", Locale.US);\n dateFormat.setTimeZone(TimeZone.getTimeZone(\"GMT\"));\n Date currentDate = new Date();\n return dateFormat.format(currentDate);\n }\n\n // URL编码\n @SneakyThrows\n public static String urlEncode(String original) {\n return URLEncoder.encode(original, StandardCharsets.UTF_8);\n }\n\n}"
},
{
"identifier": "signatureOfHmac",
"path": "src/main/java/in/dnsl/utils/SignatureUtils.java",
"snippet": "@SneakyThrows\npublic static String signatureOfHmac(String secretKey, String sessionKey, String operate, String urlString, String dateOfGmt) {\n try {\n URI url = new URI(urlString);\n String requestUri = url.getPath();\n\n String plainStr = String.format(\"SessionKey=%s&Operate=%s&RequestURI=%s&Date=%s\",\n sessionKey, operate, requestUri, dateOfGmt);\n\n SecretKeySpec keySpec = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), \"HmacSHA1\");\n Mac mac = Mac.getInstance(\"HmacSHA1\");\n mac.init(keySpec);\n byte[] result = mac.doFinal(plainStr.getBytes(StandardCharsets.UTF_8));\n return bytesToHex(result).toUpperCase();\n } catch (NoSuchAlgorithmException | InvalidKeyException e) {\n throw new RuntimeException(\"Error while calculating HMAC\", e);\n }\n}"
}
] | import in.dnsl.domain.req.AppFileListParam;
import in.dnsl.domain.req.AppGetFileInfoParam;
import in.dnsl.domain.result.AppFileEntity;
import in.dnsl.domain.xml.AppErrorXmlResp;
import in.dnsl.domain.xml.AppGetFileInfoResult;
import in.dnsl.domain.xml.FileSystemEntity;
import in.dnsl.domain.xml.ListFiles;
import in.dnsl.enums.OrderEnums;
import in.dnsl.utils.XmlUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import me.kuku.utils.OkHttpUtils;
import okhttp3.Headers;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import static in.dnsl.constant.ApiConstant.API_URL;
import static in.dnsl.constant.ApiConstant.rootNode;
import static in.dnsl.logic.CloudLogin.getSession;
import static in.dnsl.utils.ApiUtils.*;
import static in.dnsl.utils.SignatureUtils.signatureOfHmac; | 3,907 | package in.dnsl.logic;
@Slf4j
public class FileDirectory {
//根据文件ID或者文件绝对路径获取文件信息,支持文件和文件夹
public static AppGetFileInfoResult appGetBasicFileInfo(AppGetFileInfoParam build) {
if (build.getFamilyId() > 0 && "-11".equals(build.getFileId())) build.setFileId("");
if (build.getFilePath().isBlank() && build.getFileId().isBlank()) build.setFilePath("/");
var session = getSession();
String sessionKey, sessionSecret, fullUrlPattern;
Object[] formatArgs;
if (build.getFamilyId() >= 0) {
// 个人云逻辑
sessionKey = session.getSessionKey();
sessionSecret = session.getSessionSecret();
fullUrlPattern = "%s/getFolderInfo.action?folderId=%s&folderPath=%s&pathList=0&dt=3&%s";
formatArgs = new Object[]{API_URL, build.getFileId(), urlEncode(build.getFilePath()), PcClientInfoSuffixParam()};
} else {
// 家庭云逻辑
sessionKey = session.getFamilySessionKey();
sessionSecret = session.getFamilySessionSecret();
if (build.getFileId().isEmpty()) throw new RuntimeException("FileId为空");
fullUrlPattern = "%s/family/file/getFolderInfo.action?familyId=%d&folderId=%s&folderPath=%s&pathList=0&%s";
formatArgs = new Object[]{API_URL, build.getFamilyId(), build.getFileId(), urlEncode(build.getFilePath()), PcClientInfoSuffixParam()};
}
var xmlData = send(fullUrlPattern, formatArgs, sessionKey, sessionSecret);
if (xmlData.contains("error")) {
var appErrorXmlResp = XmlUtils.xmlToObject(xmlData, AppErrorXmlResp.class);
throw new RuntimeException("请求失败:" + appErrorXmlResp.getCode());
}
return XmlUtils.xmlToObject(xmlData, AppGetFileInfoResult.class);
}
// 获取指定目录下的所有文件列表
@SneakyThrows
public static ListFiles appGetAllFileList(AppFileListParam param) {
// 参数校验
if (param.getPageSize() <= 0) param.setPageSize(200);
if (param.getFamilyId() > 0 && "-11".equals(param.getFileId())) param.setFileId("");
// 获取初始文件列表
var files = appFileList(param);
if (files == null) throw new RuntimeException("文件列表为空");
var fileList = files.getFileList();
int totalFilesCount = fileList.getCount();
// 检查是否需要分页
if (totalFilesCount > param.getPageSize()) {
int pageNum = (int) Math.ceil((double) totalFilesCount / param.getPageSize());
for (int i = 2; i <= pageNum; i++) {
param.setPageNum(i);
var additionalFiles = appFileList(param).getFileList();
if (additionalFiles != null) {
if (additionalFiles.getFile() != null) fileList.getFile().addAll(additionalFiles.getFile());
if (additionalFiles.getFolder() != null) fileList.getFolder().addAll(additionalFiles.getFolder());
}
TimeUnit.MILLISECONDS.sleep(100);
}
}
return files;
}
//获取文件列表
public static ListFiles appFileList(AppFileListParam param) {
Object[] formatArgs;
var session = getSession();
String sessionKey, sessionSecret, fullUrlPattern;
if (param.getFamilyId() <= 0) {
sessionKey = session.getSessionKey();
sessionSecret = session.getSessionSecret();
fullUrlPattern = "%s/listFiles.action?folderId=%s&recursive=0&fileType=0&iconOption=10&mediaAttr=0&orderBy=%s&descending=%s&pageNum=%s&pageSize=%s&%s";
formatArgs = new Object[]{API_URL, param.getFileId(), OrderEnums.getByCode(param.getOrderBy()), false, param.getPageNum(), param.getPageSize(), PcClientInfoSuffixParam()};
} else {
// 家庭云
if (rootNode.equals(param.getFileId())) param.setFileId("");
sessionKey = session.getFamilySessionKey();
sessionSecret = session.getFamilySessionSecret();
fullUrlPattern = "%s/family/file/listFiles.action?folderId=%s&familyId=%s&fileType=0&iconOption=0&mediaAttr=0&orderBy=%s&descending=%s&pageNum=%d&pageSize=%d&%s";
formatArgs = new Object[]{API_URL, param.getFileId(), param.getFamilyId(), OrderEnums.getByCode(param.getOrderBy()), false, param.getPageNum(), param.getPageSize(), PcClientInfoSuffixParam()};
}
var send = send(fullUrlPattern, formatArgs, sessionKey, sessionSecret);
return XmlUtils.xmlToObject(send, ListFiles.class);
}
// 通过FileId获取文件的绝对路径
@SneakyThrows
public static String appFilePathById(Integer familyId, String fileId) {
var fullPath = "";
var param = AppGetFileInfoParam.builder()
.familyId(familyId)
.fileId(fileId).build();
while (true) {
var fi = appGetBasicFileInfo(param);
if (fi == null) throw new RuntimeException("FileInfo is null");
if (!fi.getPath().isEmpty()) return fi.getPath();
if (fi.getId().startsWith("-") || fi.getParentFolderId().startsWith("-")) {
fullPath = "/" + fullPath;
break;
}
fullPath = fullPath.isEmpty() ? fi.getName() : fi.getName() + "/" + fullPath;
param = AppGetFileInfoParam.builder()
.fileId(fi.getParentFolderId()).build();
TimeUnit.MILLISECONDS.sleep(100);
}
return fullPath;
}
// 通过FileId获取文件详情
public static AppFileEntity appFileInfoById(Integer familyId, String fileId) {
var param = AppGetFileInfoParam.builder()
.familyId(familyId)
.fileId(fileId).build();
var result = appGetBasicFileInfo(param);
var build = AppFileListParam.builder()
.fileId(result.getParentFolderId())
.familyId(familyId).build();
var files = appGetAllFileList(build);
var file = files.getFileList().getFile();
if (file == null) throw new RuntimeException("文件列表为空");
var collect = convert(file, result.getPath(), result.getParentFolderId()).stream().filter(e -> e.getFileId().equals(fileId)).toList();
if (collect.isEmpty()) throw new RuntimeException("文件不存在");
return collect.getFirst();
}
// 递归获取文件夹下的所有文件 包括子文件夹 | package in.dnsl.logic;
@Slf4j
public class FileDirectory {
//根据文件ID或者文件绝对路径获取文件信息,支持文件和文件夹
public static AppGetFileInfoResult appGetBasicFileInfo(AppGetFileInfoParam build) {
if (build.getFamilyId() > 0 && "-11".equals(build.getFileId())) build.setFileId("");
if (build.getFilePath().isBlank() && build.getFileId().isBlank()) build.setFilePath("/");
var session = getSession();
String sessionKey, sessionSecret, fullUrlPattern;
Object[] formatArgs;
if (build.getFamilyId() >= 0) {
// 个人云逻辑
sessionKey = session.getSessionKey();
sessionSecret = session.getSessionSecret();
fullUrlPattern = "%s/getFolderInfo.action?folderId=%s&folderPath=%s&pathList=0&dt=3&%s";
formatArgs = new Object[]{API_URL, build.getFileId(), urlEncode(build.getFilePath()), PcClientInfoSuffixParam()};
} else {
// 家庭云逻辑
sessionKey = session.getFamilySessionKey();
sessionSecret = session.getFamilySessionSecret();
if (build.getFileId().isEmpty()) throw new RuntimeException("FileId为空");
fullUrlPattern = "%s/family/file/getFolderInfo.action?familyId=%d&folderId=%s&folderPath=%s&pathList=0&%s";
formatArgs = new Object[]{API_URL, build.getFamilyId(), build.getFileId(), urlEncode(build.getFilePath()), PcClientInfoSuffixParam()};
}
var xmlData = send(fullUrlPattern, formatArgs, sessionKey, sessionSecret);
if (xmlData.contains("error")) {
var appErrorXmlResp = XmlUtils.xmlToObject(xmlData, AppErrorXmlResp.class);
throw new RuntimeException("请求失败:" + appErrorXmlResp.getCode());
}
return XmlUtils.xmlToObject(xmlData, AppGetFileInfoResult.class);
}
// 获取指定目录下的所有文件列表
@SneakyThrows
public static ListFiles appGetAllFileList(AppFileListParam param) {
// 参数校验
if (param.getPageSize() <= 0) param.setPageSize(200);
if (param.getFamilyId() > 0 && "-11".equals(param.getFileId())) param.setFileId("");
// 获取初始文件列表
var files = appFileList(param);
if (files == null) throw new RuntimeException("文件列表为空");
var fileList = files.getFileList();
int totalFilesCount = fileList.getCount();
// 检查是否需要分页
if (totalFilesCount > param.getPageSize()) {
int pageNum = (int) Math.ceil((double) totalFilesCount / param.getPageSize());
for (int i = 2; i <= pageNum; i++) {
param.setPageNum(i);
var additionalFiles = appFileList(param).getFileList();
if (additionalFiles != null) {
if (additionalFiles.getFile() != null) fileList.getFile().addAll(additionalFiles.getFile());
if (additionalFiles.getFolder() != null) fileList.getFolder().addAll(additionalFiles.getFolder());
}
TimeUnit.MILLISECONDS.sleep(100);
}
}
return files;
}
//获取文件列表
public static ListFiles appFileList(AppFileListParam param) {
Object[] formatArgs;
var session = getSession();
String sessionKey, sessionSecret, fullUrlPattern;
if (param.getFamilyId() <= 0) {
sessionKey = session.getSessionKey();
sessionSecret = session.getSessionSecret();
fullUrlPattern = "%s/listFiles.action?folderId=%s&recursive=0&fileType=0&iconOption=10&mediaAttr=0&orderBy=%s&descending=%s&pageNum=%s&pageSize=%s&%s";
formatArgs = new Object[]{API_URL, param.getFileId(), OrderEnums.getByCode(param.getOrderBy()), false, param.getPageNum(), param.getPageSize(), PcClientInfoSuffixParam()};
} else {
// 家庭云
if (rootNode.equals(param.getFileId())) param.setFileId("");
sessionKey = session.getFamilySessionKey();
sessionSecret = session.getFamilySessionSecret();
fullUrlPattern = "%s/family/file/listFiles.action?folderId=%s&familyId=%s&fileType=0&iconOption=0&mediaAttr=0&orderBy=%s&descending=%s&pageNum=%d&pageSize=%d&%s";
formatArgs = new Object[]{API_URL, param.getFileId(), param.getFamilyId(), OrderEnums.getByCode(param.getOrderBy()), false, param.getPageNum(), param.getPageSize(), PcClientInfoSuffixParam()};
}
var send = send(fullUrlPattern, formatArgs, sessionKey, sessionSecret);
return XmlUtils.xmlToObject(send, ListFiles.class);
}
// 通过FileId获取文件的绝对路径
@SneakyThrows
public static String appFilePathById(Integer familyId, String fileId) {
var fullPath = "";
var param = AppGetFileInfoParam.builder()
.familyId(familyId)
.fileId(fileId).build();
while (true) {
var fi = appGetBasicFileInfo(param);
if (fi == null) throw new RuntimeException("FileInfo is null");
if (!fi.getPath().isEmpty()) return fi.getPath();
if (fi.getId().startsWith("-") || fi.getParentFolderId().startsWith("-")) {
fullPath = "/" + fullPath;
break;
}
fullPath = fullPath.isEmpty() ? fi.getName() : fi.getName() + "/" + fullPath;
param = AppGetFileInfoParam.builder()
.fileId(fi.getParentFolderId()).build();
TimeUnit.MILLISECONDS.sleep(100);
}
return fullPath;
}
// 通过FileId获取文件详情
public static AppFileEntity appFileInfoById(Integer familyId, String fileId) {
var param = AppGetFileInfoParam.builder()
.familyId(familyId)
.fileId(fileId).build();
var result = appGetBasicFileInfo(param);
var build = AppFileListParam.builder()
.fileId(result.getParentFolderId())
.familyId(familyId).build();
var files = appGetAllFileList(build);
var file = files.getFileList().getFile();
if (file == null) throw new RuntimeException("文件列表为空");
var collect = convert(file, result.getPath(), result.getParentFolderId()).stream().filter(e -> e.getFileId().equals(fileId)).toList();
if (collect.isEmpty()) throw new RuntimeException("文件不存在");
return collect.getFirst();
}
// 递归获取文件夹下的所有文件 包括子文件夹 | public static FileSystemEntity appFileListByPath(Integer familyId, String path) { | 5 | 2023-12-02 17:02:16+00:00 | 8k |
ynewmark/vector-lang | compiler/src/main/java/org/vectorlang/compiler/compiler/Typer.java | [
{
"identifier": "AssignStatement",
"path": "compiler/src/main/java/org/vectorlang/compiler/ast/AssignStatement.java",
"snippet": "public class AssignStatement extends Statement {\n\n private final String leftHand;\n private final Expression rightHand;\n\n public AssignStatement(String leftHand, Expression rightHand) {\n super();\n this.rightHand = rightHand;\n this.leftHand = leftHand;\n }\n\n public String getLeftHand() {\n return this.leftHand;\n }\n\n public Expression getRightHand() {\n return this.rightHand;\n }\n\n @Override\n public <T, R> R visitStatement(StatementVisitor<T, R> visitor, T arg) {\n return visitor.visitAssignStmt(this, arg);\n }\n}"
},
{
"identifier": "BinaryExpression",
"path": "compiler/src/main/java/org/vectorlang/compiler/ast/BinaryExpression.java",
"snippet": "public class BinaryExpression extends Expression {\n\n private final Expression left, right;\n private final BinaryOperator operator;\n\n public BinaryExpression(Expression left, Expression right, BinaryOperator operator, Type type) {\n super(type);\n this.left = left;\n this.right = right;\n this.operator = operator;\n }\n\n public BinaryExpression(Expression left, Expression right, BinaryOperator operator) {\n this(left, right, operator, null);\n }\n\n public Expression getLeft() {\n return this.left;\n }\n\n public Expression getRight() {\n return this.right;\n }\n\n public BinaryOperator getOperator() {\n return this.operator;\n }\n\n @Override\n public <T, R> R visitExpression(ExpressionVisitor<T, R> visitor, T arg) {\n return visitor.visitBinaryExpr(this, arg);\n }\n}"
},
{
"identifier": "BinaryOperator",
"path": "compiler/src/main/java/org/vectorlang/compiler/ast/BinaryOperator.java",
"snippet": "public enum BinaryOperator {\n ADD, SUBTRACT, MULTIPLY, DIVIDE, AND, OR, EQUAL, NOT_EQUAL, LESS_THAN, GREATER_THAN,\n EQUAL_LESS_THAN, EQUAL_GREATER_THAN, DOT_ADD, DOT_SUBTRACT, DOT_MULTIPLY, DOT_DIVIDE, CONCAT\n}"
},
{
"identifier": "BlockStatement",
"path": "compiler/src/main/java/org/vectorlang/compiler/ast/BlockStatement.java",
"snippet": "public class BlockStatement extends Statement {\n\n private final Statement[] statements;\n\n public BlockStatement(Statement[] statements) {\n super();\n this.statements = statements;\n }\n\n public Statement[] getStatements() {\n return this.statements;\n }\n\n @Override\n public <T, R> R visitStatement(StatementVisitor<T, R> visitor, T arg) {\n return visitor.visitBlockStmt(this, arg);\n }\n}"
},
{
"identifier": "CallExpression",
"path": "compiler/src/main/java/org/vectorlang/compiler/ast/CallExpression.java",
"snippet": "public class CallExpression extends Expression {\n \n private final String name;\n private final Expression[] args;\n\n public CallExpression(String name, Expression[] args, Type type) {\n super(type);\n this.name = name;\n this.args = args;\n }\n\n public String getName() {\n return name;\n }\n\n public Expression[] getArgs() {\n return args;\n }\n \n @Override\n public <T, R> R visitExpression(ExpressionVisitor<T, R> visitor, T arg) {\n return visitor.visitCallExpression(this, arg);\n }\n \n}"
},
{
"identifier": "CodeBase",
"path": "compiler/src/main/java/org/vectorlang/compiler/ast/CodeBase.java",
"snippet": "public class CodeBase {\n \n private final FunctionStatement[] functions;\n\n public CodeBase(FunctionStatement[] functions) {\n this.functions = functions;\n }\n\n public FunctionStatement[] getFunctions() {\n return functions;\n }\n}"
},
{
"identifier": "DeclareStatement",
"path": "compiler/src/main/java/org/vectorlang/compiler/ast/DeclareStatement.java",
"snippet": "public class DeclareStatement extends Statement {\n\n private final boolean constant;\n private final String name;\n private final Expression initial;\n private final Type type;\n\n public DeclareStatement(boolean constant, String name, Expression initial, Type type) {\n super();\n this.constant = constant;\n this.name = name;\n this.initial = initial;\n this.type = type;\n }\n\n public DeclareStatement(boolean constant, String name, Expression initial) {\n this(constant, name, initial, null);\n }\n\n public boolean isConst() {\n return this.constant;\n }\n\n public String getName() {\n return this.name;\n }\n\n public Expression getInitial() {\n return this.initial;\n }\n\n public Type getType() {\n return this.type;\n }\n\n @Override\n public <T, R> R visitStatement(StatementVisitor<T, R> visitor, T arg) {\n return visitor.visitDeclareStmt(this, arg);\n }\n}"
},
{
"identifier": "Expression",
"path": "compiler/src/main/java/org/vectorlang/compiler/ast/Expression.java",
"snippet": "public abstract class Expression extends Node {\n\n private final Type type;\n\n protected Expression(Type type) {\n super();\n this.type = type;\n }\n\n public Type getType() {\n return this.type;\n }\n\n @Override\n public <T, R> R accept(Visitor<T, R> visitor, T arg) {\n return visitExpression(visitor, arg);\n }\n\n public abstract <T, R> R visitExpression(ExpressionVisitor<T, R> visitor, T arg);\n}"
},
{
"identifier": "ForStatement",
"path": "compiler/src/main/java/org/vectorlang/compiler/ast/ForStatement.java",
"snippet": "public class ForStatement extends Statement {\n\n private final Statement initial, body, each;\n private final Expression condition;\n\n public ForStatement(Expression condition, Statement initial, Statement each, Statement body) {\n super();\n this.initial = initial;\n this.each = each;\n this.body = body;\n this.condition = condition;\n }\n\n public Statement getInitial() {\n return initial;\n }\n\n public Statement getEach() {\n return each;\n }\n\n public Statement getBody() {\n return body;\n }\n\n public Expression getCondition() {\n return condition;\n }\n\n @Override\n public <T, R> R visitStatement(StatementVisitor<T, R> visitor, T arg) {\n return visitor.visitForStmt(this, arg);\n }\n \n}"
},
{
"identifier": "FunctionStatement",
"path": "compiler/src/main/java/org/vectorlang/compiler/ast/FunctionStatement.java",
"snippet": "public class FunctionStatement extends Statement {\n \n private final String name;\n private final String[] parameterNames;\n private final Type[] parameterTypes;\n private final Statement[] body;\n private final Type returnType;\n\n public FunctionStatement(String name, String[] names, Type[] types, Statement[] body, Type type) {\n super();\n this.name = name;\n this.parameterNames = names;\n this.parameterTypes = types;\n this.body = body;\n this.returnType = type;\n }\n\n public String getName() {\n return name;\n }\n\n public String[] getParameterNames() {\n return parameterNames;\n }\n\n public Type[] getParameterTypes() {\n return parameterTypes;\n }\n\n public Statement[] getBody() {\n return body;\n }\n\n public Type getReturnType() {\n return returnType;\n }\n \n @Override\n public <T, R> R visitStatement(StatementVisitor<T, R> visitor, T arg) {\n return visitor.visitFunctionStmt(this, arg);\n }\n}"
},
{
"identifier": "GroupingExpression",
"path": "compiler/src/main/java/org/vectorlang/compiler/ast/GroupingExpression.java",
"snippet": "public class GroupingExpression extends Expression {\n\n private final Expression expression;\n\n public GroupingExpression(Expression expression, Type type) {\n super(type);\n this.expression = expression;\n }\n\n public GroupingExpression(Expression expression) {\n this(expression, null);\n }\n\n public Expression getExpression() {\n return this.expression;\n }\n\n @Override\n public <T, R> R visitExpression(ExpressionVisitor<T, R> visitor, T arg) {\n return visitor.visitGroupingExpr(this, arg);\n }\n \n}"
},
{
"identifier": "IdentifierExpression",
"path": "compiler/src/main/java/org/vectorlang/compiler/ast/IdentifierExpression.java",
"snippet": "public class IdentifierExpression extends Expression {\n\n private final String name;\n\n public IdentifierExpression(String name, Type type) {\n super(type);\n this.name = name;\n }\n\n public IdentifierExpression(String name) {\n this(name, null);\n }\n\n public String getName() {\n return this.name;\n }\n\n @Override\n public <T, R> R visitExpression(ExpressionVisitor<T, R> visitor, T arg) {\n return visitor.visitIdentifierExpr(this, arg);\n }\n}"
},
{
"identifier": "IfStatement",
"path": "compiler/src/main/java/org/vectorlang/compiler/ast/IfStatement.java",
"snippet": "public class IfStatement extends Statement {\n \n private final Statement ifStatment, elseStatement;\n private final Expression condition;\n\n public IfStatement(Statement ifStatement, Statement elseStatement, Expression condition) {\n super();\n this.ifStatment = ifStatement;\n this.elseStatement = elseStatement;\n this.condition = condition;\n }\n\n public Statement getIfStatement() {\n return this.ifStatment;\n }\n\n public Statement getElseStatement() {\n return this.elseStatement;\n }\n\n public Expression getCondition() {\n return this.condition;\n }\n\n @Override\n public <T, R> R visitStatement(StatementVisitor<T, R> visitor, T arg) {\n return visitor.visitIfStmt(this, arg);\n }\n}"
},
{
"identifier": "IndexExpression",
"path": "compiler/src/main/java/org/vectorlang/compiler/ast/IndexExpression.java",
"snippet": "public class IndexExpression extends Expression {\n\n private final Expression base, index;\n\n public IndexExpression(Expression base, Expression index, Type type) {\n super(type);\n this.base = base;\n this.index = index;\n }\n\n public IndexExpression(Expression base, Expression index) {\n this(base, index, null);\n }\n\n public Expression getBase() {\n return this.base;\n }\n\n public Expression getIndex() {\n return this.index;\n }\n\n @Override\n public <T, R> R visitExpression(ExpressionVisitor<T, R> visitor, T arg) {\n return visitor.visitIndexExpr(this, arg);\n }\n}"
},
{
"identifier": "LiteralExpression",
"path": "compiler/src/main/java/org/vectorlang/compiler/ast/LiteralExpression.java",
"snippet": "public class LiteralExpression extends Expression {\n\n private final int intValue;\n private final boolean boolValue;\n private final double floatValue;\n private final int type;\n\n public LiteralExpression(int value) {\n super(new Type(BaseType.INT, new int[0], true));\n this.intValue = value;\n this.boolValue = false;\n this.floatValue = 0;\n type = 0;\n }\n\n public LiteralExpression(boolean value) {\n super(new Type(BaseType.BOOL, new int[0], true));\n this.intValue = 0;\n this.boolValue = value;\n this.floatValue = 0;\n type = 1;\n }\n\n public LiteralExpression(double value) {\n super(new Type(BaseType.FLOAT, new int[0], true));\n this.intValue = 0;\n this.boolValue = false;\n this.floatValue = value;\n type = 2;\n }\n\n public int getInt() {\n return this.intValue;\n }\n\n public boolean getBool() {\n return this.boolValue;\n }\n\n public double getFloat() {\n return this.floatValue;\n }\n\n public long getRaw() {\n if (type == 0) {\n return this.intValue;\n } else if (type == 1) {\n return this.boolValue ? 1 : 0;\n } else if (type == 2) {\n return Double.doubleToLongBits(this.floatValue);\n } else {\n return 0;\n }\n }\n\n @Override\n public String toString() {\n if (type == 0) {\n return Integer.toString(intValue);\n } else if (type == 1) {\n return Boolean.toString(boolValue);\n } else if (type == 2) {\n return Double.toString(floatValue);\n } else {\n return \"?\";\n }\n }\n\n @Override\n public <T, R> R visitExpression(ExpressionVisitor<T, R> visitor, T arg) {\n return visitor.visitLiteralExpr(this, arg);\n }\n}"
},
{
"identifier": "Node",
"path": "compiler/src/main/java/org/vectorlang/compiler/ast/Node.java",
"snippet": "public abstract class Node {\n private int start;\n private int end;\n\n protected Node() {\n }\n\n public int getStart() {\n return start;\n }\n\n public int getEnd() {\n return end;\n }\n\n public void setPosition(int start, int end) {\n this.start = start;\n this.end = end;\n }\n\n public abstract <T, R> R accept(Visitor<T, R> visitor, T arg);\n}"
},
{
"identifier": "PrintStatement",
"path": "compiler/src/main/java/org/vectorlang/compiler/ast/PrintStatement.java",
"snippet": "public class PrintStatement extends Statement {\n\n private final Expression expression;\n\n public PrintStatement(Expression expression) {\n super();\n this.expression = expression;\n }\n\n public Expression getExpression() {\n return expression;\n }\n\n @Override\n public <T, R> R visitStatement(StatementVisitor<T, R> visitor, T arg) {\n return visitor.visitPrintStmt(this, arg);\n }\n \n}"
},
{
"identifier": "ReturnStatement",
"path": "compiler/src/main/java/org/vectorlang/compiler/ast/ReturnStatement.java",
"snippet": "public class ReturnStatement extends Statement {\n \n private final Expression expression;\n\n public ReturnStatement(Expression expression) {\n super();\n this.expression = expression;\n }\n\n public Expression getExpression() {\n return expression;\n }\n\n @Override\n public <T, R> R visitStatement(StatementVisitor<T, R> visitor, T arg) {\n return visitor.visitReturnStmt(this, arg);\n }\n}"
},
{
"identifier": "Statement",
"path": "compiler/src/main/java/org/vectorlang/compiler/ast/Statement.java",
"snippet": "public abstract class Statement extends Node {\n \n protected Statement() {\n super();\n }\n\n @Override\n public <T, R> R accept(Visitor<T, R> visitor, T arg) {\n return visitStatement(visitor, arg);\n }\n\n public abstract <T, R> R visitStatement(StatementVisitor<T, R> visitor, T arg);\n}"
},
{
"identifier": "StaticExpression",
"path": "compiler/src/main/java/org/vectorlang/compiler/ast/StaticExpression.java",
"snippet": "public class StaticExpression extends Expression {\n \n private final LiteralExpression[] data;\n\n public StaticExpression(LiteralExpression[] data, Type type) {\n super(type);\n this.data = data;\n }\n\n public LiteralExpression[] getData() {\n return data;\n }\n\n public long[] getRaw() {\n long[] raw = new long[data.length + 1];\n for (int i = 0; i < raw.length; i++) {\n raw[i] = data[i].getRaw();\n }\n raw[raw.length - 1] = data.length;\n return raw;\n }\n\n @Override\n public <T, R> R visitExpression(ExpressionVisitor<T, R> visitor, T arg) {\n return visitor.visitStaticExpr(this, arg);\n }\n}"
},
{
"identifier": "UnaryExpression",
"path": "compiler/src/main/java/org/vectorlang/compiler/ast/UnaryExpression.java",
"snippet": "public class UnaryExpression extends Expression {\n\n private final Expression expression;\n private final UnaryOperator operator;\n\n public UnaryExpression(Expression expression, UnaryOperator operator, Type type) {\n super(type);\n this.expression = expression;\n this.operator = operator;\n }\n\n public UnaryExpression(Expression expression, UnaryOperator operator) {\n this(expression, operator, null);\n }\n\n public Expression getExpression() {\n return this.expression;\n }\n\n public UnaryOperator getOperator() {\n return this.operator;\n }\n\n @Override\n public <T, R> R visitExpression(ExpressionVisitor<T, R> visitor, T arg) {\n return visitor.visitUnaryExpr(this, arg);\n }\n}"
},
{
"identifier": "UnaryOperator",
"path": "compiler/src/main/java/org/vectorlang/compiler/ast/UnaryOperator.java",
"snippet": "public enum UnaryOperator {\n NEGATE, INVERSE\n}"
},
{
"identifier": "VectorExpression",
"path": "compiler/src/main/java/org/vectorlang/compiler/ast/VectorExpression.java",
"snippet": "public class VectorExpression extends Expression {\n\n private final Expression[] expressions;\n\n public VectorExpression(Expression[] expressions, Type type) {\n super(type);\n this.expressions = expressions;\n }\n\n public VectorExpression(Expression[] expressions) {\n this(expressions, null);\n }\n\n public Expression[] getExpressions() {\n return this.expressions;\n }\n\n @Override\n public <T, R> R visitExpression(ExpressionVisitor<T, R> visitor, T arg) {\n return visitor.visitVectorExpr(this, arg);\n }\n}"
},
{
"identifier": "Visitor",
"path": "compiler/src/main/java/org/vectorlang/compiler/ast/Visitor.java",
"snippet": "public interface Visitor<T, R> extends ExpressionVisitor<T, R>, StatementVisitor<T, R> {\n}"
},
{
"identifier": "WhileStatement",
"path": "compiler/src/main/java/org/vectorlang/compiler/ast/WhileStatement.java",
"snippet": "public class WhileStatement extends Statement {\n\n private final Expression condition;\n private final Statement body;\n\n public WhileStatement(Expression condition, Statement body) {\n super();\n this.condition = condition;\n this.body = body;\n }\n\n public Expression getCondition() {\n return condition;\n }\n\n public Statement getBody() {\n return body;\n }\n\n @Override\n public <T, R> R visitStatement(StatementVisitor<T, R> visitor, T arg) {\n return visitor.visitWhileStmt(this, arg);\n }\n \n}"
}
] | import java.util.ArrayList;
import java.util.List;
import org.vectorlang.compiler.ast.AssignStatement;
import org.vectorlang.compiler.ast.BinaryExpression;
import org.vectorlang.compiler.ast.BinaryOperator;
import org.vectorlang.compiler.ast.BlockStatement;
import org.vectorlang.compiler.ast.CallExpression;
import org.vectorlang.compiler.ast.CodeBase;
import org.vectorlang.compiler.ast.DeclareStatement;
import org.vectorlang.compiler.ast.Expression;
import org.vectorlang.compiler.ast.ForStatement;
import org.vectorlang.compiler.ast.FunctionStatement;
import org.vectorlang.compiler.ast.GroupingExpression;
import org.vectorlang.compiler.ast.IdentifierExpression;
import org.vectorlang.compiler.ast.IfStatement;
import org.vectorlang.compiler.ast.IndexExpression;
import org.vectorlang.compiler.ast.LiteralExpression;
import org.vectorlang.compiler.ast.Node;
import org.vectorlang.compiler.ast.PrintStatement;
import org.vectorlang.compiler.ast.ReturnStatement;
import org.vectorlang.compiler.ast.Statement;
import org.vectorlang.compiler.ast.StaticExpression;
import org.vectorlang.compiler.ast.UnaryExpression;
import org.vectorlang.compiler.ast.UnaryOperator;
import org.vectorlang.compiler.ast.VectorExpression;
import org.vectorlang.compiler.ast.Visitor;
import org.vectorlang.compiler.ast.WhileStatement; | 6,059 | unaryTable.put(BaseType.BOOL, UnaryOperator.NEGATE, BaseType.BOOL);
unaryTable.put(BaseType.INT, UnaryOperator.INVERSE, BaseType.INT);
unaryTable.put(BaseType.FLOAT, UnaryOperator.INVERSE, BaseType.FLOAT);
binaryTable.put(BaseType.BOOL, BaseType.BOOL, BinaryOperator.AND, BaseType.BOOL);
binaryTable.put(BaseType.BOOL, BaseType.BOOL, BinaryOperator.OR, BaseType.BOOL);
binaryTable.put(BaseType.INT, BaseType.INT, BinaryOperator.ADD, BaseType.INT);
binaryTable.put(BaseType.INT, BaseType.INT, BinaryOperator.SUBTRACT, BaseType.INT);
binaryTable.put(BaseType.INT, BaseType.INT, BinaryOperator.MULTIPLY, BaseType.INT);
binaryTable.put(BaseType.INT, BaseType.INT, BinaryOperator.DIVIDE, BaseType.INT);
binaryTable.put(BaseType.FLOAT, BaseType.FLOAT, BinaryOperator.ADD, BaseType.FLOAT);
binaryTable.put(BaseType.FLOAT, BaseType.FLOAT, BinaryOperator.SUBTRACT, BaseType.FLOAT);
binaryTable.put(BaseType.FLOAT, BaseType.FLOAT, BinaryOperator.MULTIPLY, BaseType.FLOAT);
binaryTable.put(BaseType.FLOAT, BaseType.FLOAT, BinaryOperator.DIVIDE, BaseType.FLOAT);
binaryTable.put(BaseType.BOOL, BaseType.BOOL, BinaryOperator.EQUAL, BaseType.BOOL);
binaryTable.put(BaseType.BOOL, BaseType.BOOL, BinaryOperator.NOT_EQUAL, BaseType.BOOL);
binaryTable.put(BaseType.INT, BaseType.INT, BinaryOperator.EQUAL, BaseType.BOOL);
binaryTable.put(BaseType.INT, BaseType.INT, BinaryOperator.NOT_EQUAL, BaseType.BOOL);
binaryTable.put(BaseType.FLOAT, BaseType.FLOAT, BinaryOperator.EQUAL, BaseType.BOOL);
binaryTable.put(BaseType.FLOAT, BaseType.FLOAT, BinaryOperator.NOT_EQUAL, BaseType.BOOL);
binaryTable.put(BaseType.INT, BaseType.INT, BinaryOperator.LESS_THAN, BaseType.BOOL);
binaryTable.put(BaseType.INT, BaseType.INT, BinaryOperator.EQUAL_LESS_THAN, BaseType.BOOL);
binaryTable.put(BaseType.INT, BaseType.INT, BinaryOperator.GREATER_THAN, BaseType.BOOL);
binaryTable.put(BaseType.INT, BaseType.INT, BinaryOperator.EQUAL_GREATER_THAN, BaseType.BOOL);
binaryTable.put(BaseType.FLOAT, BaseType.FLOAT, BinaryOperator.LESS_THAN, BaseType.BOOL);
binaryTable.put(BaseType.FLOAT, BaseType.FLOAT, BinaryOperator.EQUAL_LESS_THAN, BaseType.BOOL);
binaryTable.put(BaseType.FLOAT, BaseType.FLOAT, BinaryOperator.GREATER_THAN, BaseType.BOOL);
binaryTable.put(BaseType.FLOAT, BaseType.FLOAT, BinaryOperator.EQUAL_GREATER_THAN, BaseType.BOOL);
}
public List<TypeFailure> getFailures() {
return failures;
}
public CodeBase type(CodeBase codeBase) {
TyperState state = new TyperState();
for (FunctionStatement statement : codeBase.getFunctions()) {
state.putFunc(statement.getName(), statement.getParameterTypes(), statement.getReturnType());
}
FunctionStatement[] functions = new FunctionStatement[codeBase.getFunctions().length];
for (int i = 0; i < functions.length; i++) {
functions[i] = (FunctionStatement) codeBase.getFunctions()[i].accept(this, state);
}
return new CodeBase(functions);
}
@Override
public Node visitBinaryExpr(BinaryExpression expression, TyperState arg) {
Expression left = (Expression) expression.getLeft().visitExpression(this, arg);
Expression right = (Expression) expression.getRight().visitExpression(this, arg);
if (expression.getOperator() == BinaryOperator.CONCAT) {
if (left.getType().indexed().equals(right.getType().indexed())) {
return new BinaryExpression(left, right, expression.getOperator(),
left.getType().concat(right.getType()));
} else {
failures.add(new TypeFailure(left.getType(), right.getType(), "cannot concat"));
return new BinaryExpression(left, right, expression.getOperator());
}
}
BaseType result = binaryTable.get(
left.getType().getBaseType(), right.getType().getBaseType(), expression.getOperator()
);
if (result == null) {
failures.add(new TypeFailure(left.getType(), right.getType(), "operator " + expression.getOperator()));
return new BinaryExpression(left, right, expression.getOperator());
}
Type type = new Type(result, left.getType().getShape(), true);
return new BinaryExpression(left, right, expression.getOperator(), type);
}
@Override
public Node visitGroupingExpr(GroupingExpression expression, TyperState arg) {
Expression newExpression = (Expression) expression.getExpression().visitExpression(this, arg);
return new GroupingExpression(newExpression, newExpression.getType());
}
@Override
public Node visitIdentifierExpr(IdentifierExpression expression, TyperState arg) {
Type type = arg.get(expression.getName());
if (type == null) {
failures.add(new TypeFailure(null, null, expression.getName() + " not found"));
return expression;
}
return new IdentifierExpression(expression.getName(), type);
}
@Override
public Node visitLiteralExpr(LiteralExpression expression, TyperState arg) {
return expression;
}
@Override
public Node visitUnaryExpr(UnaryExpression expression, TyperState arg) {
Expression expr = (Expression) expression.getExpression().visitExpression(this, arg);
BaseType result = unaryTable.get(expr.getType().getBaseType(), expression.getOperator());
if (result == null) {
failures.add(new TypeFailure(expr.getType(), null, "operator " + expression.getOperator()));
return new UnaryExpression(expr, expression.getOperator());
}
Type type = new Type(result, expr.getType().getShape(), true);
return new UnaryExpression(expr, expression.getOperator(), type);
}
@Override
public Node visitVectorExpr(VectorExpression expression, TyperState arg) {
if (expression.getExpressions().length == 0) {
failures.add(new TypeFailure(null, null, "length of 0"));
return expression;
}
Expression[] expressions = new Expression[expression.getExpressions().length];
expressions[0] = (Expression) expression.getExpressions()[0].visitExpression(this, arg);
for (int i = 1; i < expressions.length; i++) {
expressions[i] = (Expression) expression.getExpressions()[i].visitExpression(this, arg);
if (!expressions[i].getType().equals(expressions[0].getType())) {
failures.add(new TypeFailure(expressions[0].getType(), expressions[i].getType(), "mismatched vector"));
}
}
return new VectorExpression(expressions, expressions[0].getType().vectorize(expressions.length).constant());
}
@Override | package org.vectorlang.compiler.compiler;
public class Typer implements Visitor<TyperState, Node> {
private static UnaryTable<BaseType> unaryTable;
private static BinaryTable<BaseType> binaryTable;
private List<TypeFailure> failures;
public Typer() {
this.failures = new ArrayList<>();
}
static {
unaryTable = new UnaryTable<>();
binaryTable = new BinaryTable<>();
unaryTable.put(BaseType.BOOL, UnaryOperator.NEGATE, BaseType.BOOL);
unaryTable.put(BaseType.INT, UnaryOperator.INVERSE, BaseType.INT);
unaryTable.put(BaseType.FLOAT, UnaryOperator.INVERSE, BaseType.FLOAT);
binaryTable.put(BaseType.BOOL, BaseType.BOOL, BinaryOperator.AND, BaseType.BOOL);
binaryTable.put(BaseType.BOOL, BaseType.BOOL, BinaryOperator.OR, BaseType.BOOL);
binaryTable.put(BaseType.INT, BaseType.INT, BinaryOperator.ADD, BaseType.INT);
binaryTable.put(BaseType.INT, BaseType.INT, BinaryOperator.SUBTRACT, BaseType.INT);
binaryTable.put(BaseType.INT, BaseType.INT, BinaryOperator.MULTIPLY, BaseType.INT);
binaryTable.put(BaseType.INT, BaseType.INT, BinaryOperator.DIVIDE, BaseType.INT);
binaryTable.put(BaseType.FLOAT, BaseType.FLOAT, BinaryOperator.ADD, BaseType.FLOAT);
binaryTable.put(BaseType.FLOAT, BaseType.FLOAT, BinaryOperator.SUBTRACT, BaseType.FLOAT);
binaryTable.put(BaseType.FLOAT, BaseType.FLOAT, BinaryOperator.MULTIPLY, BaseType.FLOAT);
binaryTable.put(BaseType.FLOAT, BaseType.FLOAT, BinaryOperator.DIVIDE, BaseType.FLOAT);
binaryTable.put(BaseType.BOOL, BaseType.BOOL, BinaryOperator.EQUAL, BaseType.BOOL);
binaryTable.put(BaseType.BOOL, BaseType.BOOL, BinaryOperator.NOT_EQUAL, BaseType.BOOL);
binaryTable.put(BaseType.INT, BaseType.INT, BinaryOperator.EQUAL, BaseType.BOOL);
binaryTable.put(BaseType.INT, BaseType.INT, BinaryOperator.NOT_EQUAL, BaseType.BOOL);
binaryTable.put(BaseType.FLOAT, BaseType.FLOAT, BinaryOperator.EQUAL, BaseType.BOOL);
binaryTable.put(BaseType.FLOAT, BaseType.FLOAT, BinaryOperator.NOT_EQUAL, BaseType.BOOL);
binaryTable.put(BaseType.INT, BaseType.INT, BinaryOperator.LESS_THAN, BaseType.BOOL);
binaryTable.put(BaseType.INT, BaseType.INT, BinaryOperator.EQUAL_LESS_THAN, BaseType.BOOL);
binaryTable.put(BaseType.INT, BaseType.INT, BinaryOperator.GREATER_THAN, BaseType.BOOL);
binaryTable.put(BaseType.INT, BaseType.INT, BinaryOperator.EQUAL_GREATER_THAN, BaseType.BOOL);
binaryTable.put(BaseType.FLOAT, BaseType.FLOAT, BinaryOperator.LESS_THAN, BaseType.BOOL);
binaryTable.put(BaseType.FLOAT, BaseType.FLOAT, BinaryOperator.EQUAL_LESS_THAN, BaseType.BOOL);
binaryTable.put(BaseType.FLOAT, BaseType.FLOAT, BinaryOperator.GREATER_THAN, BaseType.BOOL);
binaryTable.put(BaseType.FLOAT, BaseType.FLOAT, BinaryOperator.EQUAL_GREATER_THAN, BaseType.BOOL);
}
public List<TypeFailure> getFailures() {
return failures;
}
public CodeBase type(CodeBase codeBase) {
TyperState state = new TyperState();
for (FunctionStatement statement : codeBase.getFunctions()) {
state.putFunc(statement.getName(), statement.getParameterTypes(), statement.getReturnType());
}
FunctionStatement[] functions = new FunctionStatement[codeBase.getFunctions().length];
for (int i = 0; i < functions.length; i++) {
functions[i] = (FunctionStatement) codeBase.getFunctions()[i].accept(this, state);
}
return new CodeBase(functions);
}
@Override
public Node visitBinaryExpr(BinaryExpression expression, TyperState arg) {
Expression left = (Expression) expression.getLeft().visitExpression(this, arg);
Expression right = (Expression) expression.getRight().visitExpression(this, arg);
if (expression.getOperator() == BinaryOperator.CONCAT) {
if (left.getType().indexed().equals(right.getType().indexed())) {
return new BinaryExpression(left, right, expression.getOperator(),
left.getType().concat(right.getType()));
} else {
failures.add(new TypeFailure(left.getType(), right.getType(), "cannot concat"));
return new BinaryExpression(left, right, expression.getOperator());
}
}
BaseType result = binaryTable.get(
left.getType().getBaseType(), right.getType().getBaseType(), expression.getOperator()
);
if (result == null) {
failures.add(new TypeFailure(left.getType(), right.getType(), "operator " + expression.getOperator()));
return new BinaryExpression(left, right, expression.getOperator());
}
Type type = new Type(result, left.getType().getShape(), true);
return new BinaryExpression(left, right, expression.getOperator(), type);
}
@Override
public Node visitGroupingExpr(GroupingExpression expression, TyperState arg) {
Expression newExpression = (Expression) expression.getExpression().visitExpression(this, arg);
return new GroupingExpression(newExpression, newExpression.getType());
}
@Override
public Node visitIdentifierExpr(IdentifierExpression expression, TyperState arg) {
Type type = arg.get(expression.getName());
if (type == null) {
failures.add(new TypeFailure(null, null, expression.getName() + " not found"));
return expression;
}
return new IdentifierExpression(expression.getName(), type);
}
@Override
public Node visitLiteralExpr(LiteralExpression expression, TyperState arg) {
return expression;
}
@Override
public Node visitUnaryExpr(UnaryExpression expression, TyperState arg) {
Expression expr = (Expression) expression.getExpression().visitExpression(this, arg);
BaseType result = unaryTable.get(expr.getType().getBaseType(), expression.getOperator());
if (result == null) {
failures.add(new TypeFailure(expr.getType(), null, "operator " + expression.getOperator()));
return new UnaryExpression(expr, expression.getOperator());
}
Type type = new Type(result, expr.getType().getShape(), true);
return new UnaryExpression(expr, expression.getOperator(), type);
}
@Override
public Node visitVectorExpr(VectorExpression expression, TyperState arg) {
if (expression.getExpressions().length == 0) {
failures.add(new TypeFailure(null, null, "length of 0"));
return expression;
}
Expression[] expressions = new Expression[expression.getExpressions().length];
expressions[0] = (Expression) expression.getExpressions()[0].visitExpression(this, arg);
for (int i = 1; i < expressions.length; i++) {
expressions[i] = (Expression) expression.getExpressions()[i].visitExpression(this, arg);
if (!expressions[i].getType().equals(expressions[0].getType())) {
failures.add(new TypeFailure(expressions[0].getType(), expressions[i].getType(), "mismatched vector"));
}
}
return new VectorExpression(expressions, expressions[0].getType().vectorize(expressions.length).constant());
}
@Override | public Node visitIndexExpr(IndexExpression expression, TyperState arg) { | 13 | 2023-11-30 04:22:36+00:00 | 8k |
ExternalService/sft | src/main/java/com/nbnw/sft/network/client/SleepFeatureToggleHandler.java | [
{
"identifier": "LangManager",
"path": "src/main/java/com/nbnw/sft/common/LangManager.java",
"snippet": "public class LangManager {\n public static final String keyCategories = \"sft.key.categories\";\n public static final String sleepToggle = \"sft.key.toggleSleepKey\";\n // 功能开启、关闭时的公共前缀信息\n public static final String toggleCommonMessage = \"sft.toggle.common.message\";\n // 功能开启时的后续信息\n public static final String toggleEnabledMessage = \"sft.toggle.enabled.message\";\n // 功能关闭时的后续信息\n public static final String toggleDisabledMessage = \"sft.toggle.disabled.message\";\n // 玩家睡觉时屏幕显示的公共信息\n public static final String sleepCountMessage = \"sft.sleep.count.message\";\n // 玩家睡觉时屏幕显示的正在睡觉的玩家的百分比提示前缀\n public static final String currentSleepPercentage = \"sft.current.sleep.percentage\";\n // 玩家睡觉时屏幕显示的服务器配置中要求的百分比提示前缀\n public static final String serverThresholdPercentage = \"sft.server.threshold.percentage\";\n\n public static String getFinalMessage(boolean newSetting) {\n //I18n.format方法将根据玩家客户端的当前语言设置自动选择正确的本地化字符串\n return I18n.format(LangManager.toggleCommonMessage) + (newSetting ? I18n.format(LangManager.toggleEnabledMessage) : I18n.format(LangManager.toggleDisabledMessage));\n }\n\n}"
},
{
"identifier": "ModConfig",
"path": "src/main/java/com/nbnw/sft/config/ModConfig.java",
"snippet": "public class ModConfig {\n private static final String LANGUAGE = \"language\";\n private static final String SEVERAL_PLAYER_SLEEP = \"several_player_sleep\";\n private static final String CONFIG_VERSION = \"config_version\";\n\n private static final String SPS_THRESHOLD = \"sps_threshold\";\n private static final String LOGIN_MESSAGE = \"login_message\";\n\n private static final int MESSAGE_COLOR = 0xE367E9;\n\n private Configuration config;\n // 保存单例实例\n private static ModConfig instance;\n // 私有构造器\n private ModConfig() {\n }\n public static ModConfig getInstance() {\n if (instance == null) {\n instance = new ModConfig();\n }\n return instance;\n }\n public Configuration getConfig() {\n return this.config;\n }\n public void init(FMLPreInitializationEvent event) {\n File modConfigDir = new File(event.getModConfigurationDirectory(), ModEntry.metadata.modId);\n modConfigDir.mkdirs();\n File configFile = new File(modConfigDir, \"sft_config.cfg\");\n // create mod config file\n this.config = new Configuration(configFile);\n loadAndSyncConfig();\n }\n\n // 加载和同步配置\n public void loadAndSyncConfig() {\n // 加载配置\n loadConfiguration();\n\n // 同步到所有客户端\n syncConfigToClients();\n }\n\n // TODO 将配置数据同步到所有客户端\n private void syncConfigToClients() {\n // 封装配置数据并发送到所有客户端\n // 使用Forge网络包系统进行通信\n }\n\n // TODO 客户端接收配置数据后,调用此方法同步配置\n public void onConfigSyncPacketReceived(ConfigSyncPacket packet) {\n // 更新客户端的配置实例\n }\n\n private void loadConfiguration() {\n // read config file.if not exist,then create it with the default settings\n String language = this.config.get(Configuration.CATEGORY_GENERAL,\n LANGUAGE, \"english\", \"Language setting\").getString();\n // 用于配置文件版本控制\n String configVersion = this.config.get(Configuration.CATEGORY_GENERAL,\n CONFIG_VERSION, ModEntry.metadata.version, \"Mod config file version\").getString();\n boolean enableSeveralPlayerSleep = this.config.get(Configuration.CATEGORY_GENERAL,\n SEVERAL_PLAYER_SLEEP, true, \"Enable whether several players sleep warp night or not\").getBoolean(true);\n // several player sleep feature threshold. default 0.5\n double spsThreshold = (long) this.config.get(Configuration.CATEGORY_GENERAL,\n SPS_THRESHOLD, 0.5, \"Several players sleep warp night sleeping player percentage(0.0-1.0), default 0.5\").getDouble(0.5);\n boolean enablePlayerLoginMessage = this.config.get(Configuration.CATEGORY_GENERAL,\n LOGIN_MESSAGE, true, \"Enable whether show mod message to players when they login or not(Use server side config)\").getBoolean(true);\n // if the configs has changed by players, save the changes\n if (this.config.hasChanged()) {\n this.config.save();\n }\n }\n /**\n * After player change configs, call this function to reload them.\n */\n public void reloadConfig() {\n if (this.config.hasChanged()) {\n this.config.save();\n }\n this.config.load(); // reload the config file\n }\n public String getLanguage() {\n return this.config.get(Configuration.CATEGORY_GENERAL, LANGUAGE, \"english\").getString();\n }\n public String getConfigVersion(){\n return this.config.get(Configuration.CATEGORY_GENERAL, CONFIG_VERSION, \"\").getString();\n }\n public boolean isSinglePlayerSleepEnabled() {\n return this.config.get(Configuration.CATEGORY_GENERAL, SEVERAL_PLAYER_SLEEP, true).getBoolean();\n }\n public double getSpsThreshold() {\n return this.config.get(Configuration.CATEGORY_GENERAL, SPS_THRESHOLD, 0.5).getDouble(0.5);\n }\n public boolean isPlayerLoginMessageEnabled() {\n return this.config.get(Configuration.CATEGORY_GENERAL, LOGIN_MESSAGE, true).getBoolean();\n }\n\n public int getMessageColor(){\n return MESSAGE_COLOR;\n }\n\n /**\n * 检查配置文件存储的版本号信息是否和模组一致\n * @return true: 一致, false: 不一致\n */\n public boolean versionCheck() {\n if(getConfigVersion().equals(ModEntry.VERSION)){ // 版本号一致\n return true;\n }\n return false; // 不一致\n }\n /**\n * 如果不一致则重置配置文件\n */\n public void checkAndResetConfigIfNeeded() {\n this.config.load(); // 首先加载配置文件\n // 检查配置文件的版本\n String configVersion = this.config.get(Configuration.CATEGORY_GENERAL, CONFIG_VERSION, ModEntry.VERSION).getString();\n // 如果配置文件的版本与模组版本不一致,则重置配置\n if (!versionCheck()) {\n resetConfiguration();\n // TODO:目前检测到版本号不一致会直接重新生成配置文件 但是对玩家不友好,玩家需要重新改配置,可以考虑删除以前的配置文件中无效的项并新增以前的配置文件没有的项.为了实现这个功能,需要一个类来记录当前版本的配置项列表\n } else {\n // 如果版本匹配,则正常加载配置\n loadConfiguration();\n }\n }\n\n /**\n * 重置配置文件\n */\n private void resetConfiguration() {\n // Reset all the configuration values to their defaults\n this.config.get(Configuration.CATEGORY_GENERAL, SEVERAL_PLAYER_SLEEP, true).set(true);\n this.config.get(Configuration.CATEGORY_GENERAL, SPS_THRESHOLD, 0.5).set(0.5);\n this.config.get(Configuration.CATEGORY_GENERAL, LOGIN_MESSAGE, true).set(true);\n this.config.get(Configuration.CATEGORY_GENERAL, LANGUAGE, \"english\").set(\"english\");\n this.config.get(Configuration.CATEGORY_GENERAL, CONFIG_VERSION, ModEntry.VERSION).set(ModEntry.VERSION);\n\n // Save the reset configuration\n if (this.config.hasChanged()) {\n this.config.save();\n }\n }\n\n @SubscribeEvent\n public void onConfigChanged(ConfigChangedEvent.OnConfigChangedEvent event) {\n if (event.modID.equals(ModEntry.MODID)) {\n reloadConfig();\n }\n }\n}"
},
{
"identifier": "ScreenMessageHandler",
"path": "src/main/java/com/nbnw/sft/handler/ScreenMessageHandler.java",
"snippet": "public class ScreenMessageHandler {\n private static ScreenMessageHandler instance = null;\n private String serverMessage = \"\";\n\n private String thresholdMessage = \"\";\n private long displayTime = 0;\n private long startTime = 0;\n private int rgbColor = 0xFFFFFF;\n private ScreenMessageHandler() {\n // TODO 临时解决不切换功能开启和关闭就不会在玩家睡觉时显示功能是否开启的bug 这种方式不能保证客户端和服务端真实的信息一致\n // this.serverMessage = LangManager.getFinalMessage(ModConfig.getInstance().isPlayerLoginMessageEnabled()); // 不能使用这个方法,因为I18n类是客户端独有的\n }\n public static ScreenMessageHandler getInstance() {\n if (instance == null) {\n instance = new ScreenMessageHandler();\n }\n return instance;\n }\n public void showMessage(String serverMessage, String thresholdMessage,int displaySeconds) {\n if(!serverMessage.equals(\"\")){\n this.serverMessage = serverMessage;\n }\n if(!thresholdMessage.equals(\"\")){\n this.thresholdMessage = thresholdMessage;\n }\n this.displayTime = (long) displaySeconds * 1000; // 转换为毫秒时间\n this.startTime = System.currentTimeMillis();\n }\n public void showMessage(String serverMessage, String thresholdMessage, int displaySeconds, int color) {\n showMessage(serverMessage, thresholdMessage, displaySeconds);\n this.rgbColor = color;\n }\n\n @SubscribeEvent\n public void onRenderGameTipsOverlay(RenderGameOverlayEvent.Post event) {\n if (event.type != RenderGameOverlayEvent.ElementType.HOTBAR) {\n return;\n }\n if (System.currentTimeMillis() - startTime < displayTime && (!serverMessage.isEmpty() || !thresholdMessage.isEmpty())) {\n ScaledResolution scaledResolution = new ScaledResolution(Minecraft.getMinecraft(), Minecraft.getMinecraft().displayWidth, Minecraft.getMinecraft().displayHeight);\n FontRenderer fontRenderer = Minecraft.getMinecraft().fontRenderer;\n int screenWidth = scaledResolution.getScaledWidth();\n int screenHeight = scaledResolution.getScaledHeight();\n int serverMessageWidth = fontRenderer.getStringWidth(serverMessage);\n int sleepMessageWidth = fontRenderer.getStringWidth(thresholdMessage);\n\n int x = (screenWidth - serverMessageWidth) / 2;\n int y = screenHeight / 2;\n // 字体背景框 第五个参数是颜色(ARGB类型)\n // Gui.drawRect(x - 2, y - 2, x + serverMessageWidth + 2, y + fontRenderer.FONT_HEIGHT + 2, 0xAA000000); // Optional: draw a background rectangle\n fontRenderer.drawString(serverMessage, x, y, this.rgbColor);\n y = y / 7;\n fontRenderer.drawString(thresholdMessage, x, y, this.rgbColor);\n }\n }\n}"
},
{
"identifier": "CommonMessagePacket",
"path": "src/main/java/com/nbnw/sft/network/CommonMessagePacket.java",
"snippet": "public class CommonMessagePacket implements IMessage {\n private MessageType type; // 消息类型\n\n private String clientLanguageCode; // 客户端向服务端发送语言代码 用于服务端向客户端发送要求返回客户端语言代码时\n\n private int serverLangRequestCode; // 服务端向客户端请求本地化语言信息代码\n\n private int clientKeyPressedKeyCode; // 客户端向服务端发送按键代码\n\n // 下面三个属性用于服务端想客户端发送要显示的消息\n private String screenMessage; // 消息内容\n private int duration; // 消息时长\n private boolean sleepToggle; // 睡眠特性是否开启\n\n private int clientThresholdRequestCode; // 客户端请求返回睡眠百分比代码\n\n private String serverThresholdPercentageValue; // 服务端返回的睡眠百分比数据\n\n public CommonMessagePacket() {\n this.screenMessage = \"default message\";\n this.serverLangRequestCode = 1;\n this.duration = 5;\n }\n\n\n public CommonMessagePacket(MessageType type, String message) {\n this(); // 调用无参构造\n this.type = type;\n switch (type){\n case CLIENT_LANGUAGE_CODE:\n this.clientLanguageCode = message;\n break;\n case SERVER_THRESHOLD_PERCENTAGE_VALUE:\n this.serverThresholdPercentageValue = message;\n break;\n }\n }\n public CommonMessagePacket(MessageType type, int code) {\n this();\n this.type = type;\n switch (type){\n case SERVER_LANG_REQUEST_CODE:\n this.serverLangRequestCode = code;\n break;\n case CLIENT_KEY_PRESSED_CODE:\n this.clientKeyPressedKeyCode = code;\n break;\n case CLIENT_THRESHOLD_REQUEST_CODE:\n this.clientThresholdRequestCode = code;\n break;\n }\n }\n public CommonMessagePacket(MessageType type, String message, int numCode, boolean flag) {\n this();\n this.type = type;\n switch (type){\n case SERVER_SCREEN_MESSAGE:\n this.screenMessage = message;\n this.duration = numCode;\n this.sleepToggle = flag;\n }\n }\n\n @Override\n public void fromBytes(ByteBuf buf) {\n // 确保ByteBuf中有足够的字节可供读取\n if (buf.readableBytes() < 4) {\n throw new RuntimeException(\"ByteBuf does not contain enough data\");\n }\n this.type = MessageType.values()[buf.readInt()]; // 读取类型\n switch (type) {\n // 字符串类型\n case CLIENT_LANGUAGE_CODE:\n int length = buf.readInt();\n byte[] bytes = new byte[length];\n buf.readBytes(bytes);\n this.clientLanguageCode = new String(bytes, StandardCharsets.UTF_8);// 从数据包中读取语言代码\n break;\n case SERVER_THRESHOLD_PERCENTAGE_VALUE:\n int valueLength = buf.readInt();\n byte[] valueBytes = new byte[valueLength];\n buf.readBytes(valueBytes);\n this.serverThresholdPercentageValue = new String(valueBytes, StandardCharsets.UTF_8);// 从数据包中读取百分比\n break;\n // 整数类型\n case SERVER_LANG_REQUEST_CODE:\n this.serverLangRequestCode = buf.readInt();\n break;\n case CLIENT_KEY_PRESSED_CODE:\n this.clientKeyPressedKeyCode = buf.readInt();\n break;\n case CLIENT_THRESHOLD_REQUEST_CODE:\n this.clientThresholdRequestCode = buf.readInt();\n break;\n // 组合类型\n case SERVER_SCREEN_MESSAGE:\n int msgLength = buf.readInt();\n byte[] msgBytes = new byte[msgLength];\n buf.readBytes(msgBytes);\n this.screenMessage = new String(msgBytes, StandardCharsets.UTF_8);\n this.duration = buf.readInt();\n this.sleepToggle = buf.readBoolean();\n break;\n }\n }\n\n @Override\n public void toBytes(ByteBuf buf) {\n buf.writeInt(type.ordinal()); // 写入类型\n switch (type) {\n // 字符串类型\n case CLIENT_LANGUAGE_CODE:\n byte[] bytes = clientLanguageCode.getBytes(StandardCharsets.UTF_8); // 将语言代码写入数据包\n buf.writeInt(bytes.length);\n buf.writeBytes(bytes);\n break;\n case SERVER_THRESHOLD_PERCENTAGE_VALUE:\n byte[] valueBytes = serverThresholdPercentageValue.getBytes(StandardCharsets.UTF_8); // 将语言代码写入数据包\n buf.writeInt(valueBytes.length);\n buf.writeBytes(valueBytes);\n break;\n // 整数类型\n case SERVER_LANG_REQUEST_CODE:\n buf.writeInt(serverLangRequestCode);\n break;\n case CLIENT_KEY_PRESSED_CODE:\n buf.writeInt(clientKeyPressedKeyCode);\n break;\n case CLIENT_THRESHOLD_REQUEST_CODE:\n buf.writeInt(clientThresholdRequestCode);\n break;\n // 组合类型\n case SERVER_SCREEN_MESSAGE:\n byte[] messageBytes = screenMessage.getBytes(StandardCharsets.UTF_8);\n buf.writeInt(messageBytes.length);\n buf.writeBytes(messageBytes);\n buf.writeInt(duration);\n buf.writeBoolean(sleepToggle);\n break;\n }\n }\n\n public MessageType getType(){\n return type;\n }\n\n public String getClientLanguageCode(){\n return clientLanguageCode;\n }\n public int getServerLangRequestCode() {\n return serverLangRequestCode;\n }\n\n public int getClientKeyPressedCode() {\n return clientKeyPressedKeyCode;\n }\n public String getScreenMessage() {\n return screenMessage;\n }\n\n public int getDuration() {\n return duration;\n }\n\n public boolean getSleepToggle(){\n return sleepToggle;\n }\n\n public int getClientThresholdRequestCode(){\n return clientThresholdRequestCode;\n }\n\n public String getServerThresholdPercentageValue() {\n return serverThresholdPercentageValue;\n }\n\n public enum MessageType {\n CLIENT_LANGUAGE_CODE, // 客户端发送自身本地化语言代码信息\n SERVER_LANG_REQUEST_CODE, // 服务端发送请求语言信息\n CLIENT_KEY_PRESSED_CODE, // 客户端发送按键被按下信息\n SERVER_SCREEN_MESSAGE, // 服务端发送客户端需要显示的信息\n\n CLIENT_THRESHOLD_REQUEST_CODE, // 客户端请求返回百分比阈值信息\n SERVER_THRESHOLD_PERCENTAGE_VALUE // 服务端配置文件睡眠百分比\n }\n\n}"
},
{
"identifier": "MessageType",
"path": "src/main/java/com/nbnw/sft/network/CommonMessagePacket.java",
"snippet": "public enum MessageType {\n CLIENT_LANGUAGE_CODE, // 客户端发送自身本地化语言代码信息\n SERVER_LANG_REQUEST_CODE, // 服务端发送请求语言信息\n CLIENT_KEY_PRESSED_CODE, // 客户端发送按键被按下信息\n SERVER_SCREEN_MESSAGE, // 服务端发送客户端需要显示的信息\n\n CLIENT_THRESHOLD_REQUEST_CODE, // 客户端请求返回百分比阈值信息\n SERVER_THRESHOLD_PERCENTAGE_VALUE // 服务端配置文件睡眠百分比\n}"
}
] | import com.nbnw.sft.common.LangManager;
import cpw.mods.fml.common.network.simpleimpl.MessageContext;
import net.minecraftforge.common.config.Configuration;
import com.nbnw.sft.config.ModConfig;
import com.nbnw.sft.handler.ScreenMessageHandler;
import com.nbnw.sft.network.CommonMessagePacket;
import com.nbnw.sft.network.CommonMessagePacket.MessageType; | 4,627 | package com.nbnw.sft.network.client;
public class SleepFeatureToggleHandler {
private static final int rgbColor = 0xE367E9;
public void showServerResultMessage(CommonMessagePacket message, MessageContext ctx) {
if (ctx.side.isClient()) {
if (!message.getType().equals(MessageType.SERVER_SCREEN_MESSAGE)) {
return;
}
// 同步服务端信息
boolean newSetting = message.getSleepToggle(); | package com.nbnw.sft.network.client;
public class SleepFeatureToggleHandler {
private static final int rgbColor = 0xE367E9;
public void showServerResultMessage(CommonMessagePacket message, MessageContext ctx) {
if (ctx.side.isClient()) {
if (!message.getType().equals(MessageType.SERVER_SCREEN_MESSAGE)) {
return;
}
// 同步服务端信息
boolean newSetting = message.getSleepToggle(); | ModConfig.getInstance().getConfig().get(Configuration.CATEGORY_GENERAL, "several_player_sleep", true).set(newSetting); | 1 | 2023-11-29 15:20:07+00:00 | 8k |
id681ilyg316/jsp_medicine_jxc | 源码/jsp_medicine_jxc/src/com/medicine/action/StaffAction.java | [
{
"identifier": "StaffDao",
"path": "源码/jsp_medicine_jxc/src/com/medicine/dao/StaffDao.java",
"snippet": "public class StaffDao {\r\n\r\n\tpublic List<Staff> getStaffList(Connection con,Staff s_staff,PageBean pageBean) throws Exception{\r\n\t\tList<Staff> staffList=new ArrayList<Staff>();\r\n\t\tStringBuffer sb=new StringBuffer(\"select * from t_staff\");\t\r\n\t\tif(StringUtil.isNotEmpty(s_staff.getStaffName())){\r\n\t\t\tsb.append(\" and staffName like '%\"+s_staff.getStaffName()+\"%'\");\r\n\t\t}\r\n\t\tif(StringUtil.isNotEmpty(s_staff.getStaffAddress())){\r\n\t\t\tsb.append(\" and staffAddress like '%\"+s_staff.getStaffAddress()+\"%'\");\r\n\t\t}\r\n\t\tif(StringUtil.isNotEmpty(s_staff.getStaffPhone())){\r\n\t\t\tsb.append(\" and staffPhone like '%\"+s_staff.getStaffPhone()+\"%'\");\r\n\t\t}\r\n\t\tif(pageBean!=null){\r\n\t\t\tsb.append(\" limit \"+pageBean.getStart()+\",\"+pageBean.getPageSize());\r\n\t\t}\r\n\t\tPreparedStatement pstmt=con.prepareStatement(sb.toString());\r\n\t\tResultSet rs=pstmt.executeQuery();\r\n\t\twhile(rs.next()){\r\n\t\t\tStaff staff = new Staff();\r\n\t\t\tstaff.setStaffId(rs.getString(\"staffId\"));\r\n\t\t\tstaff.setStaffName(rs.getString(\"staffName\"));\r\n\t\t\tstaff.setStaffPhone(rs.getString(\"staffPhone\"));\r\n\t\t\tstaff.setStaffAddress(rs.getString(\"staffAddress\"));\r\n\t\t\tstaffList.add(staff);\r\n\t\t}\r\n\t\treturn staffList;\t\r\n\t}\r\n\t\r\n\t\r\n\t/**\r\n\t * 获取记录总数\r\n\t * */\r\n\tpublic int staffCount(Connection con,Staff s_staff)throws Exception{\r\n\t\tStringBuffer sb=new StringBuffer(\"select count(*) as total from t_staff\");\r\n\t\tif(StringUtil.isNotEmpty(s_staff.getStaffName())){\r\n\t\t\tsb.append(\" and staffName like '%\"+s_staff.getStaffName()+\"%'\");\r\n\t\t}\r\n\t\tif(StringUtil.isNotEmpty(s_staff.getStaffAddress())){\r\n\t\t\tsb.append(\" and staffAddress like '%\"+s_staff.getStaffAddress()+\"%'\");\r\n\t\t}\r\n\t\tif(StringUtil.isNotEmpty(s_staff.getStaffPhone())){\r\n\t\t\tsb.append(\" and staffPhone like '%\"+s_staff.getStaffPhone()+\"%'\");\r\n\t\t}\r\n\t\t\r\n\t\tPreparedStatement pstmt=con.prepareStatement(sb.toString());\r\n\t\tResultSet rs=pstmt.executeQuery();\r\n\t\tif(rs.next()){\r\n\t\t\treturn rs.getInt(\"total\");\r\n\t\t}else{\r\n\t\t\treturn 0;\r\n\t\t}\r\n\t}\r\n\t\r\n\t/**\r\n\t * 删除员工\r\n\t * */\r\n\t\r\n\tpublic int staffDelete(Connection con,String staffId)throws Exception{\r\n\t\tString sql=\"delete from t_staff where staffId=?\";\r\n\t\tPreparedStatement pstmt=con.prepareStatement(sql);\r\n\t\tpstmt.setString(1, staffId);\r\n\t\treturn pstmt.executeUpdate();\r\n\t}\r\n\t\r\n\t\r\n\t/**\r\n\t * 添加员工\r\n\t * */\r\n\tpublic int Addstaff(Connection con,Staff staff)throws Exception{\r\n\t\tString sql=\"insert into t_staff(staffName,staffAddress,staffPhone) values(?,?,?)\";\r\n\t\tPreparedStatement pstmt=con.prepareStatement(sql);\r\n\t\tpstmt.setString(1, staff.getStaffName());\r\n\t\tpstmt.setString(2, staff.getStaffAddress());\r\n\t\tpstmt.setString(3, staff.getStaffPhone());\r\n\t\treturn pstmt.executeUpdate();\r\n\t}\r\n\t\r\n\t\r\n\tpublic static void main(String[] args) throws Exception {\r\n\t\tConnection con = new DbUtil().getCon();\r\n\t\tStaff staff = new Staff();\r\n\t\tstaff.setStaffName(\"1\");\r\n\t\tstaff.setStaffAddress(\"1\");\r\n\t\tstaff.setStaffPhone(\"1\");\r\n\t\tnew StaffDao().Addstaff(con, staff);\r\n\t}\r\n\t\r\n\tpublic Staff getStaffById(Connection con,String staffId)throws Exception{\r\n\t\tString sql=\"select * from t_staff where staffId=?\";\r\n\t\tPreparedStatement pstmt=con.prepareStatement(sql);\r\n\t\tpstmt.setString(1, staffId);\r\n\t\tResultSet rs=pstmt.executeQuery();\r\n\t\tStaff staff=null;\r\n\t\tif(rs.next()){\r\n\t\t\tstaff=new Staff();\r\n\t\t\tstaff.setStaffId(rs.getString(\"staffId\"));\r\n\t\t\tstaff.setStaffName(rs.getString(\"staffName\"));\r\n\t\t\tstaff.setStaffPhone(rs.getString(\"staffPhone\"));\r\n\t\t\tstaff.setStaffAddress(rs.getString(\"staffAddress\"));\r\n\t\t}\r\n\t\treturn staff;\r\n\t}\r\n\t\r\n\t\r\n\tpublic int staffUpdate(Connection con,Staff staff)throws Exception{\r\n\t\tString sql=\"update t_staff set staffName=?,staffPhone=?,staffAddress=? where staffId=?\";\r\n\t\tPreparedStatement pstmt=con.prepareStatement(sql);\r\n\t\tpstmt.setString(1, staff.getStaffName());\r\n\t\tpstmt.setString(2, staff.getStaffPhone());\r\n\t\tpstmt.setString(3, staff.getStaffAddress());\r\n\t\tpstmt.setString(4,staff.getStaffId());\r\n\t\treturn pstmt.executeUpdate();\r\n\t}\r\n\r\n\r\n\tpublic Staff getStaffByName(Connection con, String staffName) throws Exception {\r\n\t\t\tString sql=\"select * from t_staff where staffName=?\";\r\n\t\t\tPreparedStatement pstmt=con.prepareStatement(sql);\r\n\t\t\tpstmt.setString(1, staffName);\r\n\t\t\tResultSet rs=pstmt.executeQuery();\r\n\t\t\tStaff staff=null;\r\n\t\t\tif(rs.next()){\r\n\t\t\t\tstaff=new Staff();\r\n\t\t\t\tstaff.setStaffName(rs.getString(\"staffName\"));\r\n\t\t\t\tstaff.setStaffAddress(rs.getString(\"staffAddress\"));\r\n\t\t\t\tstaff.setStaffPhone(rs.getString(\"staffPhone\"));\r\n\t\t\t\t\r\n\t\t\t}\r\n\t\t\treturn staff;\r\n\t\t\r\n\t}\r\n}\r"
},
{
"identifier": "PageBean",
"path": "源码/jsp_medicine_jxc/src/com/medicine/model/PageBean.java",
"snippet": "public class PageBean {\r\n\r\n\tprivate int page; // 第几页\r\n\tprivate int pageSize; // 每页记录数\r\n\tprivate int start; // 起始页\r\n\t\r\n\t\r\n\tpublic PageBean(int page, int pageSize) {\r\n\t\tsuper();\r\n\t\tthis.page = page;\r\n\t\tthis.pageSize = pageSize;\r\n\t}\r\n\t\r\n\tpublic int getPage() {\r\n\t\treturn page;\r\n\t}\r\n\tpublic void setPage(int page) {\r\n\t\tthis.page = page;\r\n\t}\r\n\t\r\n\tpublic int getPageSize() {\r\n\t\treturn pageSize;\r\n\t}\r\n\r\n\tpublic void setPageSize(int pageSize) {\r\n\t\tthis.pageSize = pageSize;\r\n\t}\r\n\r\n\tpublic int getStart() {\r\n\t\treturn (page-1)*pageSize;\r\n\t}\r\n\t\r\n\t\r\n}\r"
},
{
"identifier": "Staff",
"path": "源码/jsp_medicine_jxc/src/com/medicine/model/Staff.java",
"snippet": "public class Staff {\r\n\r\n\tprivate String staffId;\r\n\tprivate String staffName;\r\n\tprivate String staffPhone;\r\n\tprivate String staffAddress;\r\n\tpublic String getStaffId() {\r\n\t\treturn staffId;\r\n\t}\r\n\tpublic void setStaffId(String staffId) {\r\n\t\tthis.staffId = staffId;\r\n\t}\r\n\tpublic String getStaffName() {\r\n\t\treturn staffName;\r\n\t}\r\n\tpublic void setStaffName(String staffName) {\r\n\t\tthis.staffName = staffName;\r\n\t}\r\n\tpublic String getStaffPhone() {\r\n\t\treturn staffPhone;\r\n\t}\r\n\tpublic void setStaffPhone(String staffPhone) {\r\n\t\tthis.staffPhone = staffPhone;\r\n\t}\r\n\tpublic String getStaffAddress() {\r\n\t\treturn staffAddress;\r\n\t}\r\n\tpublic void setStaffAddress(String staffAddress) {\r\n\t\tthis.staffAddress = staffAddress;\r\n\t}\r\n\t\r\n\t\r\n}\r"
},
{
"identifier": "DbUtil",
"path": "源码/jsp_medicine_jxc/src/com/medicine/util/DbUtil.java",
"snippet": "public class DbUtil {\r\n\r\n\tpublic Connection getCon()throws Exception{\r\n\t\tClass.forName(PropertiesUtil.getValue(\"jdbcName\"));\r\n\t\tConnection con=DriverManager.getConnection(PropertiesUtil.getValue(\"dbUrl\"), PropertiesUtil.getValue(\"dbUserName\"), PropertiesUtil.getValue(\"dbPassword\"));\r\n\t\treturn con;\r\n\t}\r\n\t\r\n\tpublic void closeCon(Connection con)throws Exception{\r\n\t\tif(con!=null){\r\n\t\t\tcon.close();\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic static void main(String[] args) {\r\n\t\tDbUtil dbUtil=new DbUtil();\r\n\t\ttry {\r\n\t\t\tdbUtil.getCon();\r\n\t\t\tSystem.out.println(\"数据库连接成功\");\r\n\t\t} catch (Exception e) {\r\n\t\t\t// TODO Auto-generated catch block\r\n\t\t\te.printStackTrace();\r\n\t\t\tSystem.out.println(\"数据库连接失败\");\r\n\t\t}\r\n\t}\r\n}\r"
},
{
"identifier": "NavUtil",
"path": "源码/jsp_medicine_jxc/src/com/medicine/util/NavUtil.java",
"snippet": "public class NavUtil {\r\n\r\n\tpublic static String getNavgation(String mainMenu,String subMenu){\r\n\t\tStringBuffer navCode=new StringBuffer();\r\n\t\tnavCode.append(\"µ±Ç°Î»Ö㺠\");\r\n\t\tnavCode.append(\"<a href='\"+PropertiesUtil.getValue(\"projectName\")+\"/main.jsp'>Ö÷Ò³</a> > \");\r\n\t\tnavCode.append(\"<a href='#'>\"+mainMenu+\"</a> > \");\r\n\t\tnavCode.append(\"<a href='#'>\"+subMenu+\"</a>\");\r\n\t\treturn navCode.toString();\r\n\t}\r\n}\r"
},
{
"identifier": "PageUtil",
"path": "源码/jsp_medicine_jxc/src/com/medicine/util/PageUtil.java",
"snippet": "public class PageUtil {\r\n\r\n\r\n\t\r\n\tpublic static String genPagation(String targetUrl,int totalNum,int currentPage,int pageSize){\r\n\t\tint totalPage=totalNum%pageSize==0?totalNum/pageSize:totalNum/pageSize+1;\r\n\t\tStringBuffer pageCode=new StringBuffer();\r\n\t\tpageCode.append(\"<li><a href='\"+targetUrl+\"?page=1'>首页</a></li>\");\r\n\t\tif(currentPage==1){\r\n\t\t\tpageCode.append(\"<li class='disabled'><a href='#'>上一页</a></li>\");\t\t\t\r\n\t\t}else{\r\n\t\t\tpageCode.append(\"<li><a href='\"+targetUrl+\"?page=\"+(currentPage-1)+\"'>上一页</a></li>\");\t\t\t\r\n\t\t}\r\n\t\tfor(int i=currentPage-2;i<=currentPage+2;i++){\r\n\t\t\tif(i<1||i>totalPage){\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\t\t\tif(i==currentPage){\r\n\t\t\t\tpageCode.append(\"<li class='active'><a href='#'>\"+i+\"</a></li>\");\t\t\r\n\t\t\t}else{\r\n\t\t\t\tpageCode.append(\"<li><a href='\"+targetUrl+\"?page=\"+i+\"'>\"+i+\"</a></li>\");\t\r\n\t\t\t}\r\n\t\t}\r\n\t\tif(currentPage==totalPage){\r\n\t\t\tpageCode.append(\"<li class='disabled'><a href='#'>下一页</a></li>\");\t\t\t\r\n\t\t}else{\r\n\t\t\tpageCode.append(\"<li><a href='\"+targetUrl+\"?page=\"+(currentPage+1)+\"'>下一页</a></li>\");\t\t\r\n\t\t}\r\n\t\tpageCode.append(\"<li><a href='\"+targetUrl+\"?page=\"+totalPage+\"'>尾页</a></li>\");\r\n\t\treturn pageCode.toString();\r\n\t}\r\n}\r"
},
{
"identifier": "PropertiesUtil",
"path": "源码/jsp_medicine_jxc/src/com/medicine/util/PropertiesUtil.java",
"snippet": "public class PropertiesUtil {\r\n\r\n\tpublic static String getValue(String key){\r\n\t\tProperties prop=new Properties();\r\n\t\tInputStream in=new PropertiesUtil().getClass().getResourceAsStream(\"/medicine.properties\");\r\n\t\ttry {\r\n\t\t\tprop.load(in);\r\n\t\t} catch (IOException e) {\r\n\t\t\t// TODO Auto-generated catch block\r\n\t\t\te.printStackTrace();\r\n\t\t}\r\n\t\treturn prop.getProperty(key);\r\n\t}\r\n}\r"
},
{
"identifier": "ResponseUtil",
"path": "源码/jsp_medicine_jxc/src/com/medicine/util/ResponseUtil.java",
"snippet": "public class ResponseUtil {\r\n\r\n\tpublic static void write(Object o,HttpServletResponse response)throws Exception{\r\n\t\tresponse.setContentType(\"text/html;charset=utf-8\");\r\n\t\tPrintWriter out=response.getWriter();\r\n\t\tout.println(o.toString());\r\n\t\tout.flush();\r\n\t\tout.close();\r\n\t}\r\n}\r"
},
{
"identifier": "StringUtil",
"path": "源码/jsp_medicine_jxc/src/com/medicine/util/StringUtil.java",
"snippet": "public class StringUtil {\r\n\r\n\t/**\r\n\t * 判断是否是空\r\n\t * @param str\r\n\t * @return\r\n\t */\r\n\tpublic static boolean isEmpty(String str){\r\n\t\tif(\"\".equals(str)|| str==null){\r\n\t\t\treturn true;\r\n\t\t}else{\r\n\t\t\treturn false;\r\n\t\t}\r\n\t}\r\n\t\r\n\t/**\r\n\t * 判断是否不是空\r\n\t * @param str\r\n\t * @return\r\n\t */\r\n\tpublic static boolean isNotEmpty(String str){\r\n\t\tif(!\"\".equals(str)&&str!=null){\r\n\t\t\treturn true;\r\n\t\t}else{\r\n\t\t\treturn false;\r\n\t\t}\r\n\t}\r\n}\r"
}
] | import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.ServletRequestAware;
import com.medicine.dao.StaffDao;
import com.medicine.model.PageBean;
import com.medicine.model.Staff;
import com.medicine.util.DbUtil;
import com.medicine.util.NavUtil;
import com.medicine.util.PageUtil;
import com.medicine.util.PropertiesUtil;
import com.medicine.util.ResponseUtil;
import com.medicine.util.StringUtil;
import com.opensymphony.xwork2.ActionSupport;
import net.sf.json.JSONObject;
| 3,834 | package com.medicine.action;
public class StaffAction extends ActionSupport implements ServletRequestAware{
/**
*
*/
private static final long serialVersionUID = 1L;
private HttpServletRequest request;
private DbUtil dbUtil=new DbUtil();
private StaffDao staffDao = new StaffDao();
private String page;
private int total;
private String staffName;
public String getStaffName() {
return staffName;
}
public void setStaffName(String staffName) {
this.staffName = staffName;
}
public Staff getS_staff() {
return s_staff;
}
public void setS_staff(Staff s_staff) {
this.s_staff = s_staff;
}
public void setStaffId(String staffId) {
this.staffId = staffId;
}
private String pageCode;
private Staff s_staff;
private Staff staff;
private String staffId;
public String getStaffId() {
return staffId;
}
public Staff getStaff() {
return staff;
}
public void setStaff(Staff staff) {
this.staff = staff;
}
public String getPage() {
return page;
}
public void setPage(String page) {
this.page = page;
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public String getPageCode() {
return pageCode;
}
public void setPageCode(String pageCode) {
this.pageCode = pageCode;
}
private String mainPage;
private String navCode;
private List<Staff> staffList=new ArrayList<Staff>();
private List<Staff> s_staffList_n;
private List<Staff> s_staffList_a;
private List<Staff> s_staffList_p;
public List<Staff> getS_staffList_n() {
return s_staffList_n;
}
public void setS_staffList_n(List<Staff> s_staffList_n) {
this.s_staffList_n = s_staffList_n;
}
public List<Staff> getS_staffList_a() {
return s_staffList_a;
}
public void setS_staffList_a(List<Staff> s_staffList_a) {
this.s_staffList_a = s_staffList_a;
}
public List<Staff> getS_staffList_p() {
return s_staffList_p;
}
public void setS_staffList_p(List<Staff> s_staffList_p) {
this.s_staffList_p = s_staffList_p;
}
public String getMainPage() {
return mainPage;
}
public void setMainPage(String mainPage) {
this.mainPage = mainPage;
}
public String getNavCode() {
return navCode;
}
public void setNavCode(String navCode) {
this.navCode = navCode;
}
public List<Staff> getStaffList() {
return staffList;
}
public void setStaffList(List<Staff> staffList) {
this.staffList = staffList;
}
public String list(){
HttpSession session=request.getSession();
if(StringUtil.isEmpty(page)){
page="1";
}
if(s_staff!=null){
session.setAttribute("s_staff", s_staff);
}else{
Object o=session.getAttribute("s_staff");
if(o!=null){
s_staff=(Staff)o;
}else{
s_staff=new Staff();
}
}
Connection con=null;
try{
con=dbUtil.getCon();
PageBean pageBean=new PageBean(Integer.parseInt(page),Integer.parseInt(PropertiesUtil.getValue("pageSize")));
staffList=staffDao.getStaffList(con,s_staff,pageBean);
navCode=NavUtil.getNavgation("员工信息管理", "员工修改");
total=staffDao.staffCount(con, s_staff);
| package com.medicine.action;
public class StaffAction extends ActionSupport implements ServletRequestAware{
/**
*
*/
private static final long serialVersionUID = 1L;
private HttpServletRequest request;
private DbUtil dbUtil=new DbUtil();
private StaffDao staffDao = new StaffDao();
private String page;
private int total;
private String staffName;
public String getStaffName() {
return staffName;
}
public void setStaffName(String staffName) {
this.staffName = staffName;
}
public Staff getS_staff() {
return s_staff;
}
public void setS_staff(Staff s_staff) {
this.s_staff = s_staff;
}
public void setStaffId(String staffId) {
this.staffId = staffId;
}
private String pageCode;
private Staff s_staff;
private Staff staff;
private String staffId;
public String getStaffId() {
return staffId;
}
public Staff getStaff() {
return staff;
}
public void setStaff(Staff staff) {
this.staff = staff;
}
public String getPage() {
return page;
}
public void setPage(String page) {
this.page = page;
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public String getPageCode() {
return pageCode;
}
public void setPageCode(String pageCode) {
this.pageCode = pageCode;
}
private String mainPage;
private String navCode;
private List<Staff> staffList=new ArrayList<Staff>();
private List<Staff> s_staffList_n;
private List<Staff> s_staffList_a;
private List<Staff> s_staffList_p;
public List<Staff> getS_staffList_n() {
return s_staffList_n;
}
public void setS_staffList_n(List<Staff> s_staffList_n) {
this.s_staffList_n = s_staffList_n;
}
public List<Staff> getS_staffList_a() {
return s_staffList_a;
}
public void setS_staffList_a(List<Staff> s_staffList_a) {
this.s_staffList_a = s_staffList_a;
}
public List<Staff> getS_staffList_p() {
return s_staffList_p;
}
public void setS_staffList_p(List<Staff> s_staffList_p) {
this.s_staffList_p = s_staffList_p;
}
public String getMainPage() {
return mainPage;
}
public void setMainPage(String mainPage) {
this.mainPage = mainPage;
}
public String getNavCode() {
return navCode;
}
public void setNavCode(String navCode) {
this.navCode = navCode;
}
public List<Staff> getStaffList() {
return staffList;
}
public void setStaffList(List<Staff> staffList) {
this.staffList = staffList;
}
public String list(){
HttpSession session=request.getSession();
if(StringUtil.isEmpty(page)){
page="1";
}
if(s_staff!=null){
session.setAttribute("s_staff", s_staff);
}else{
Object o=session.getAttribute("s_staff");
if(o!=null){
s_staff=(Staff)o;
}else{
s_staff=new Staff();
}
}
Connection con=null;
try{
con=dbUtil.getCon();
PageBean pageBean=new PageBean(Integer.parseInt(page),Integer.parseInt(PropertiesUtil.getValue("pageSize")));
staffList=staffDao.getStaffList(con,s_staff,pageBean);
navCode=NavUtil.getNavgation("员工信息管理", "员工修改");
total=staffDao.staffCount(con, s_staff);
| pageCode=PageUtil.genPagation(request.getContextPath()+"/staff!list", total, Integer.parseInt(page), Integer.parseInt(PropertiesUtil.getValue("pageSize")));
| 5 | 2023-11-29 14:18:23+00:00 | 8k |
tuxiaobei-scu/Draw-and-guess | entry/src/main/java/com/tuxiaobei/drawandguess/provider/AnswerItemProvider.java | [
{
"identifier": "ResourceTable",
"path": "entry/build/generated/source/r/debug/com/tuxiaobei/drawandguess/ResourceTable.java",
"snippet": "public final class ResourceTable {\n public static final int Graphic_background_ability_main = 0x1000017;\n public static final int Graphic_background_answer = 0x1000018;\n public static final int Graphic_background_answer_ok = 0x1000019;\n public static final int Graphic_background_answer_sim = 0x100001a;\n public static final int Graphic_background_answer_wa = 0x100001b;\n public static final int Graphic_background_card = 0x100001c;\n public static final int Graphic_background_name_text_field = 0x100001d;\n public static final int Graphic_background_text_field = 0x100001e;\n public static final int Graphic_background_white_radius_10 = 0x100001f;\n public static final int Graphic_button_normal = 0x1000020;\n public static final int Graphic_button_pressed = 0x1000021;\n public static final int Graphic_button_selector = 0x1000022;\n public static final int Graphic_capsule_button_element = 0x1000023;\n public static final int Graphic_circle_button_element = 0x1000024;\n public static final int Graphic_ele_cursor_bubble = 0x1000025;\n\n public static final int Id_all = 0x100002d;\n public static final int Id_ans = 0x100002e;\n public static final int Id_anslist = 0x100002f;\n public static final int Id_back = 0x1000030;\n public static final int Id_black = 0x1000031;\n public static final int Id_blue = 0x1000032;\n public static final int Id_canvas = 0x1000033;\n public static final int Id_change_name = 0x1000034;\n public static final int Id_cyan = 0x1000035;\n public static final int Id_green = 0x1000036;\n public static final int Id_header = 0x1000037;\n public static final int Id_item_check = 0x1000038;\n public static final int Id_item_desc = 0x1000039;\n public static final int Id_item_info = 0x100003a;\n public static final int Id_item_ok = 0x100003b;\n public static final int Id_item_sim = 0x100003c;\n public static final int Id_item_type = 0x100003d;\n public static final int Id_item_wa = 0x100003e;\n public static final int Id_list_answers = 0x100003f;\n public static final int Id_list_container_device = 0x1000040;\n public static final int Id_list_container_words = 0x1000041;\n public static final int Id_name = 0x1000042;\n public static final int Id_operate_no = 0x1000043;\n public static final int Id_operate_yes = 0x1000044;\n public static final int Id_pink = 0x1000045;\n public static final int Id_play = 0x1000046;\n public static final int Id_red = 0x1000047;\n public static final int Id_show_score = 0x1000048;\n public static final int Id_submit = 0x1000049;\n public static final int Id_switchcolor = 0x100004a;\n public static final int Id_tip = 0x100004b;\n public static final int Id_title = 0x100004c;\n public static final int Id_transform = 0x100004d;\n public static final int Id_yellow = 0x100004e;\n\n public static final int Layout_ability_main = 0x1000026;\n public static final int Layout_dialog_device_item = 0x1000027;\n public static final int Layout_dialog_layout_device = 0x1000028;\n public static final int Layout_dialog_layout_name = 0x1000029;\n public static final int Layout_dialog_layout_words = 0x100002a;\n public static final int Layout_dialog_word_item = 0x100002b;\n public static final int Layout_item_answer = 0x100002c;\n\n public static final int Media_checked_point = 0x100000b;\n public static final int Media_dv_pad = 0x100000c;\n public static final int Media_dv_phone = 0x100000d;\n public static final int Media_dv_watch = 0x100000e;\n public static final int Media_ic_contacts_delete = 0x100000f;\n public static final int Media_ic_public_delete = 0x1000010;\n public static final int Media_ic_public_edit = 0x1000011;\n public static final int Media_ic_public_play = 0x1000012;\n public static final int Media_icon = 0x1000013;\n public static final int Media_icon_off = 0x1000014;\n public static final int Media_icon_transform = 0x1000015;\n public static final int Media_uncheck_point = 0x1000016;\n\n public static final int Strarray_words = 0x100000a;\n\n public static final int String_HelloWorld = 0x1000000;\n public static final int String_app_name = 0x1000001;\n public static final int String_back = 0x1000002;\n public static final int String_cancels = 0x1000003;\n public static final int String_mainability_description = 0x1000004;\n public static final int String_readwords_description = 0x1000005;\n public static final int String_select_the_word = 0x1000006;\n public static final int String_shareDevice = 0x1000007;\n public static final int String_title = 0x1000008;\n public static final int String_yes = 0x1000009;\n}"
},
{
"identifier": "MainAbilitySlice",
"path": "entry/src/main/java/com/tuxiaobei/drawandguess/slice/MainAbilitySlice.java",
"snippet": "public class MainAbilitySlice extends AbilitySlice {\n private static final String TAG = MainAbilitySlice.class.getName();\n private static final int PERMISSION_CODE = 20201203;\n private static final int DELAY_TIME = 10;\n private static final String STORE_ID_KEY = \"storeId\";\n private static final String POINTS_KEY = \"points\";\n private static final String ANS_KEY = \"ans\";\n private static final String COLOR_INDEX_KEY = \"colorIndex\";\n private static final String IS_FORM_LOCAL_KEY = \"isFormLocal\";\n private static String storeId;\n private DependentLayout canvas;\n private Image transform;\n private Image change_name;\n private KvManager kvManager;\n private SingleKvStore pointsSingleKvStore;\n private SingleKvStore ansSingleKvStore;\n private SingleKvStore nameSingleKvStore;\n private Text title;\n private DrawPoint drawl;\n private Image play;\n private Button back;\n private Text show_score;\n private Guesser guesser;\n private Text tip;\n private Button submit;\n private TextField ans;\n private MainGame main_game;\n private ListContainer ans_list;\n private final List<AnswerItem> ansData = new ArrayList<>();\n private AnswerItemProvider answerItemProvider;\n private String deviceId;\n private String local_name;\n private boolean isLocal;\n\n @Override\n public void onStart(Intent intent) {\n super.onStart(intent);\n\n super.setUIContent(ResourceTable.Layout_ability_main);\n storeId = STORE_ID_KEY + Tools.getRandom();\n isLocal = !intent.getBooleanParam(IS_FORM_LOCAL_KEY, false);\n drawl = new DrawPoint(this, isLocal);\n findComponentById(isLocal);\n requestPermission();\n initView(intent);\n initDatabase();\n if (isLocal) {\n nameSingleKvStore.putString(Tools.getDeviceId(this), \"系统\");\n }\n initDraw(intent);\n ohos.global.resource.ResourceManager resManager = getResourceManager();\n String[] words = null;\n try {\n words = resManager.getElement(ResourceTable.Strarray_words).getStringArray();\n } catch (IOException e) {\n e.printStackTrace();\n } catch (NotExistException e) {\n e.printStackTrace();\n } catch (WrongTypeException e) {\n e.printStackTrace();\n }\n main_game = new MainGame(this, words);\n initListContainer();\n }\n\n\n private void initListContainer() {\n answerItemProvider = new AnswerItemProvider(ansData, this, isLocal);\n ans_list.setItemProvider(answerItemProvider);\n }\n\n\n private void initView(Intent intent) {\n\n if (!isLocal) {\n local_name = Tools.getDeviceId(this).substring(0, 6);\n storeId = intent.getStringParam(STORE_ID_KEY);\n }\n title.setText(isLocal ? \"本地端\" : local_name);\n transform.setVisibility(isLocal ? Component.VISIBLE : Component.INVISIBLE);\n }\n\n private void requestPermission() {\n if (verifySelfPermission(DISTRIBUTED_DATASYNC) != IBundleManager.PERMISSION_GRANTED) {\n if (canRequestPermission(DISTRIBUTED_DATASYNC)) {\n requestPermissionsFromUser(new String[]{DISTRIBUTED_DATASYNC}, PERMISSION_CODE);\n }\n }\n }\n\n private void findComponentById(Boolean isLocal) {\n if (findComponentById(ResourceTable.Id_canvas) instanceof DependentLayout) {\n canvas = (DependentLayout) findComponentById(ResourceTable.Id_canvas);\n }\n if (findComponentById(ResourceTable.Id_transform) instanceof Image) {\n transform = (Image) findComponentById(ResourceTable.Id_transform);\n }\n if (findComponentById(ResourceTable.Id_change_name) instanceof Image) {\n change_name = (Image) findComponentById(ResourceTable.Id_change_name);\n }\n if (findComponentById(ResourceTable.Id_play) instanceof Image) {\n play = (Image) findComponentById(ResourceTable.Id_play);\n }\n if (findComponentById(ResourceTable.Id_title) instanceof Text) {\n title = (Text) findComponentById(ResourceTable.Id_title);\n }\n if (findComponentById(ResourceTable.Id_back) instanceof Button) {\n back = (Button) findComponentById(ResourceTable.Id_back);\n }\n if (findComponentById(ResourceTable.Id_ans) instanceof TextField) {\n ans = (TextField) findComponentById(ResourceTable.Id_ans);\n }\n if (findComponentById(ResourceTable.Id_submit) instanceof Button) {\n submit = (Button) findComponentById(ResourceTable.Id_submit);\n }\n if (findComponentById(ResourceTable.Id_tip) instanceof Text) {\n tip = (Text) findComponentById(ResourceTable.Id_tip);\n }\n if (findComponentById(ResourceTable.Id_list_answers) instanceof ListContainer) {\n ans_list = (ListContainer) findComponentById(ResourceTable.Id_list_answers);\n }\n if (findComponentById(ResourceTable.Id_show_score) instanceof Text) {\n show_score = (Text) findComponentById(ResourceTable.Id_show_score);\n }\n\n if (isLocal) {\n if (findComponentById(ResourceTable.Id_red) instanceof Button) {\n drawl.addButton((Button) findComponentById(ResourceTable.Id_red));\n }\n if (findComponentById(ResourceTable.Id_green) instanceof Button) {\n drawl.addButton((Button) findComponentById(ResourceTable.Id_green));\n }\n if (findComponentById(ResourceTable.Id_blue) instanceof Button) {\n drawl.addButton((Button) findComponentById(ResourceTable.Id_blue));\n }\n if (findComponentById(ResourceTable.Id_yellow) instanceof Button) {\n drawl.addButton((Button) findComponentById(ResourceTable.Id_yellow));\n }\n if (findComponentById(ResourceTable.Id_pink) instanceof Button) {\n drawl.addButton((Button) findComponentById(ResourceTable.Id_pink));\n }\n if (findComponentById(ResourceTable.Id_cyan) instanceof Button) {\n drawl.addButton((Button) findComponentById(ResourceTable.Id_cyan));\n }\n if (findComponentById(ResourceTable.Id_black) instanceof Button) {\n drawl.addButton((Button) findComponentById(ResourceTable.Id_black));\n }\n\n ans.setVisibility(Component.HIDE);\n submit.setVisibility(Component.HIDE);\n } else {\n back.setVisibility(Component.HIDE);\n play.setVisibility(Component.HIDE);\n show_score.setVisibility(Component.VISIBLE);\n change_name.setVisibility(Component.VISIBLE);\n guesser = new Guesser(submit, ans, tip, show_score, this);\n }\n transform.setClickedListener(component -> {\n DeviceSelectDialog dialog = new DeviceSelectDialog(MainAbilitySlice.this);\n dialog.setListener(deviceIds -> {\n if (deviceIds != null && !deviceIds.isEmpty()) {\n // 启动远程页面\n startRemoteFas(deviceIds);\n // 同步远程数据库\n pointsSingleKvStore.sync(deviceIds, SyncMode.PUSH_ONLY);\n ansSingleKvStore.sync(deviceIds, SyncMode.PUSH_ONLY);\n nameSingleKvStore.sync(deviceIds, SyncMode.PUSH_ONLY);\n }\n dialog.hide();\n });\n dialog.show();\n });\n play.setClickedListener(component -> {\n WordSelectDialog dialog = new WordSelectDialog(MainAbilitySlice.this, main_game.getWords());\n dialog.setListener(word -> {\n if (!word.isEmpty()) {\n newGame(word);\n }\n dialog.hide();\n });\n dialog.show();\n });\n change_name.setClickedListener(component -> {\n ChangeName dialog = new ChangeName(MainAbilitySlice.this, local_name);\n dialog.setListener(name -> {\n if (!name.isEmpty()) {\n setName(name);\n }\n dialog.hide();\n });\n dialog.show();\n });\n }\n\n\n\n /**\n * Initialize art boards\n *\n * @param intent Intent\n */\n private void initDraw(Intent intent) {\n boolean isLocal = !intent.getBooleanParam(IS_FORM_LOCAL_KEY, false);\n\n //int colorIndex = switchcolor.getColorIndex();\n\n drawl.setWidth(MATCH_PARENT);\n drawl.setWidth(MATCH_PARENT);\n canvas.addComponent(drawl);\n\n drawPoints();\n drawl.setOnDrawBack(points -> {\n if (points != null && points.size() > 1) {\n String pointsString = GsonUtil.objectToString(points);\n LogUtils.info(TAG, \"pointsString::\" + pointsString);\n if (pointsSingleKvStore != null) {\n pointsSingleKvStore.putString(POINTS_KEY, pointsString);\n }\n }\n });\n\n back.setClickedListener(component -> {\n List<MyPoint> points = drawl.getPoints();\n if (points == null || points.size() <= 1) {\n return;\n }\n points.remove(points.size() - 1);\n for (int i = points.size() - 1; i >= 0; i--) {\n if (points.get(i).isLastPoint()) {\n break;\n }\n points.remove(i);\n }\n drawl.setDrawParams(points);\n String pointsString = GsonUtil.objectToString(points);\n if (pointsSingleKvStore != null) {\n pointsSingleKvStore.putString(POINTS_KEY, pointsString);\n }\n });\n }\n\n public boolean getIslocal() {\n return isLocal;\n }\n\n /**\n * 设置昵称\n * @param name 昵称\n */\n private void setName(String name) {\n title.setText(name);\n local_name = name;\n nameSingleKvStore.putString(Tools.getDeviceId(this), name);\n }\n\n /**\n * 添加答案元素\n * @param ans\n */\n public void addAnswer(AnswerItem ans) {\n ans.setDeviceId(Tools.getDeviceId(this));\n ansData.add(0, ans);\n String ansString = GsonUtil.objectToString(ansData);\n if (ansSingleKvStore != null) {\n ansSingleKvStore.putString(ANS_KEY, ansString);\n }\n }\n\n /**\n * 开始新游戏\n * @param word 新词语\n */\n private void newGame(String word) {\n ansData.clear();\n AnswerItem a = new AnswerItem(\"开始第 \" + main_game.getRoundnum() +\" 轮游戏了!\", 4);\n a.setWord(word);\n addAnswer(a);\n //answerItemProvider.notifyDataChanged();\n main_game.setWord(word);\n main_game.generateWords();\n title.setText(word);\n clearBoard();\n }\n\n /**\n * 展示答案消息列表\n * @param answers 答案消息数据\n */\n private void showAns(List<AnswerItem> answers) {\n if (!isLocal) {\n guesser.checkEnable(answers);\n }\n ansData.clear();\n ansData.addAll(answers);\n answerItemProvider.notifyDataChanged();\n }\n\n /**\n * 清空画板\n */\n private void clearBoard() {\n List<MyPoint> points = new ArrayList<>(0);\n drawl.setDrawParams(points);\n String pointsString = GsonUtil.objectToString(points);\n if (pointsSingleKvStore != null) {\n pointsSingleKvStore.putString(POINTS_KEY, pointsString);\n }\n }\n\n /**\n * 获取数据库中的点数据,并在画布上画出来\n */\n private void drawPoints() {\n List<Entry> points = pointsSingleKvStore.getEntries(POINTS_KEY);\n for (Entry entry : points) {\n if (entry.getKey().equals(POINTS_KEY)) {\n List<MyPoint> remotePoints = GsonUtil.jsonToList(pointsSingleKvStore.getString(POINTS_KEY), MyPoint.class);\n getUITaskDispatcher().delayDispatch(() -> drawl.setDrawParams(remotePoints), DELAY_TIME);\n }\n }\n }\n\n /**\n * 更新答案消息列表\n */\n private void updateAnsShow() {\n List<Entry> ans = ansSingleKvStore.getEntries(ANS_KEY);\n for (Entry entry : ans) {\n if (entry.getKey().equals(ANS_KEY)) {\n List<AnswerItem> remoteAns= GsonUtil.jsonToList(ansSingleKvStore.getString(ANS_KEY), AnswerItem.class);\n getUITaskDispatcher().delayDispatch(() -> {showAns(remoteAns);}, DELAY_TIME);\n }\n }\n }\n\n /**\n * 获取昵称\n * @param deviceId 设备id\n * @return 昵称\n */\n public String getName(String deviceId) {\n if (Tools.getDeviceId(this).equals(deviceId)) {\n if (isLocal) {\n return \"系统\";\n }\n return local_name;\n }\n String ret;\n try {\n ret = nameSingleKvStore.getString(deviceId);\n }catch (KvStoreException e) {\n ret = deviceId.substring(0, 6);\n }\n if (ret == null || ret.isEmpty()) {\n ret = deviceId.substring(0, 6);\n }\n return ret;\n }\n /**\n * Receive database messages\n */\n private class pointsKvStoreObserverClient implements KvStoreObserver {\n @Override\n public void onChange(ChangeNotification notification) {\n LogUtils.info(TAG, \"data changed......\");\n drawPoints();\n }\n }\n\n private class ansKvStoreObserverClient implements KvStoreObserver {\n @Override\n public void onChange(ChangeNotification notification) {\n LogUtils.info(TAG, \"ans changed......\");\n updateAnsShow();\n }\n }\n\n private class nameKvStoreObserverClient implements KvStoreObserver {\n @Override\n public void onChange(ChangeNotification notification) {\n LogUtils.info(TAG, \"name changed......\");\n getUITaskDispatcher().delayDispatch(() -> {answerItemProvider.notifyDataChanged();}, DELAY_TIME);\n }\n }\n\n /**\n * 创建分布式数据库\n */\n private void initDatabase() {\n // 创建分布式数据库管理对象\n KvManagerConfig config = new KvManagerConfig(this);\n kvManager = KvManagerFactory.getInstance().createKvManager(config);\n // 创建分布式数据库\n Options options = new Options();\n options.setCreateIfMissing(true).setEncrypt(false).setKvStoreType(KvStoreType.SINGLE_VERSION);\n pointsSingleKvStore = kvManager.getKvStore(options, storeId);\n // 订阅分布式数据变化\n KvStoreObserver kvStoreObserverClient = new pointsKvStoreObserverClient();\n pointsSingleKvStore.subscribe(SubscribeType.SUBSCRIBE_TYPE_ALL, kvStoreObserverClient);\n\n // 创建分布式数据库\n ansSingleKvStore = kvManager.getKvStore(options, storeId);\n // 订阅分布式数据变化\n KvStoreObserver kvStoreObserverClient1 = new ansKvStoreObserverClient();\n ansSingleKvStore.subscribe(SubscribeType.SUBSCRIBE_TYPE_ALL, kvStoreObserverClient1);\n\n // 创建分布式数据库\n nameSingleKvStore = kvManager.getKvStore(options, storeId);\n // 订阅分布式数据变化\n KvStoreObserver kvStoreObserverClient2 = new nameKvStoreObserverClient();\n nameSingleKvStore.subscribe(SubscribeType.SUBSCRIBE_TYPE_ALL, kvStoreObserverClient2);\n\n }\n\n /**\n * Starting Multiple Remote Fas\n *\n * @param deviceIds deviceIds\n */\n private void startRemoteFas(List<String> deviceIds) {\n Intent[] intents = new Intent[deviceIds.size()];\n for (int i = 0; i < deviceIds.size(); i++) {\n Intent intent = new Intent();\n intent.setParam(IS_FORM_LOCAL_KEY, true);\n intent.setParam(COLOR_INDEX_KEY, i + 1);\n intent.setParam(STORE_ID_KEY, storeId);\n Operation operation = new Intent.OperationBuilder()\n .withDeviceId(deviceIds.get(i))\n .withBundleName(getBundleName())\n .withAbilityName(MainAbility.class.getName())\n .withFlags(Intent.FLAG_ABILITYSLICE_MULTI_DEVICE)\n .build();\n intent.setOperation(operation);\n intents[i] = intent;\n }\n startAbilities(intents);\n }\n\n\n\n @Override\n protected void onStop() {\n super.onStop();\n kvManager.closeKvStore(pointsSingleKvStore);\n }\n\n}"
},
{
"identifier": "Tools",
"path": "entry/src/main/java/com/tuxiaobei/drawandguess/util/Tools.java",
"snippet": "public class Tools {\n /**\n * 获取设备Id\n */\n public static String getDeviceId(Context mContext){\n return KvManagerFactory.getInstance().createKvManager(new KvManagerConfig(mContext)).getLocalDeviceInfo().getId();\n }\n\n public static String getRandom() {\n return String.valueOf(System.currentTimeMillis()) + String.valueOf(new Random().nextInt(1000));\n }\n}"
},
{
"identifier": "AnswerItem",
"path": "entry/src/main/java/com/tuxiaobei/drawandguess/bean/AnswerItem.java",
"snippet": "public class AnswerItem {\n private String device_id;\n private String ans; //用户的答案\n private int status; //0 未检查, 1 错误, 2 接近, 3 正确, 4 系统消息\n private String rid;\n private String word; //实际答案\n public AnswerItem(String ans, int status) {\n this.ans = ans;\n this.status = status;\n rid = Tools.getRandom();\n }\n public String getDeviceId() {\n return device_id;\n }\n public String getAns() {\n return ans;\n }\n public String getRid() {\n return rid;\n }\n\n public String getWord() {\n return word;\n }\n public int getStatus() {\n return status;\n }\n\n public void setStatus(int status) {\n this.status = status;\n }\n public void setWord(String word) {\n this.word = word;\n }\n public void setDeviceId(String device_id) {\n this.device_id = device_id;\n }\n}"
}
] | import com.tuxiaobei.drawandguess.ResourceTable;
import com.tuxiaobei.drawandguess.slice.MainAbilitySlice;
import com.tuxiaobei.drawandguess.util.Tools;
import ohos.aafwk.ability.AbilitySlice;
import ohos.agp.components.*;
import com.tuxiaobei.drawandguess.bean.AnswerItem;
import ohos.agp.components.element.Element;
import java.util.List; | 5,898 | package com.tuxiaobei.drawandguess.provider;
public class AnswerItemProvider extends BaseItemProvider{
private List<AnswerItem> list; | package com.tuxiaobei.drawandguess.provider;
public class AnswerItemProvider extends BaseItemProvider{
private List<AnswerItem> list; | private MainAbilitySlice slice; | 1 | 2023-12-03 13:36:00+00:00 | 8k |
godheaven/klib-data-jdbc | src/test/java/cl/kanopus/jdbc/example/AbstractBaseDAO.java | [
{
"identifier": "Mapping",
"path": "src/main/java/cl/kanopus/jdbc/entity/Mapping.java",
"snippet": "public abstract class Mapping implements Serializable {\r\n\r\n private static final Logger LOGGER = LoggerFactory.getLogger(Mapping.class);\r\n\r\n @Override\r\n public String toString() {\r\n\r\n Class<?> clase = this.getClass();\r\n Method[] methods = clase.getMethods();\r\n String result;\r\n Method method;\r\n\r\n StringBuilder aux = new StringBuilder(\"Class : [\" + this.getClass().getName() + \"]\\n\");\r\n Object obj;\r\n for (int i = 0; i < methods.length; i++) {\r\n if (methods[i].getName().startsWith(\"get\") && !methods[i].getName().equals(\"getClass\")) {\r\n try {\r\n method = methods[i];\r\n obj = method.invoke(this, (Object[]) null);\r\n if (obj != null) {\r\n result = obj.toString();\r\n } else {\r\n result = null;\r\n }\r\n aux.append(method.getName().substring(3)).append(\" : [\").append(result).append(\"]\\n\");\r\n\r\n } catch (SecurityException | IllegalArgumentException | InvocationTargetException | IllegalAccessException ex) {\r\n LOGGER.error(ex.getMessage(), ex);\r\n }\r\n }\r\n }\r\n\r\n return aux.toString();\r\n\r\n }\r\n\r\n}\r"
},
{
"identifier": "AbstractDAO",
"path": "src/main/java/cl/kanopus/jdbc/impl/AbstractDAO.java",
"snippet": "@SuppressWarnings(\"all\")\r\npublic abstract class AbstractDAO<T extends Mapping, ID> implements DAOInterface<T, ID> {\r\n\r\n enum Operation {\r\n UPDATE,\r\n PERSIST\r\n }\r\n\r\n private final Class<T> genericTypeClass;\r\n\r\n protected AbstractDAO() {\r\n Type type = getClass().getGenericSuperclass();\r\n ParameterizedType paramType = (ParameterizedType) type;\r\n genericTypeClass = (Class<T>) paramType.getActualTypeArguments()[0];\r\n }\r\n\r\n protected abstract NamedParameterJdbcTemplate getJdbcTemplate();\r\n\r\n private static final Charset DEFAULT_CHARSET = StandardCharsets.ISO_8859_1;\r\n\r\n protected abstract Engine getEngine();\r\n\r\n private String createSqlPagination2Engine(SQLQueryDynamic sqlQuery) {\r\n String sql = getCustom().prepareSQL2Engine(sqlQuery.getSQL());\r\n if (sqlQuery.isLimited()) {\r\n return getCustom().createSqlPagination(sql, sqlQuery.getLimit(), sqlQuery.getOffset()).toString();\r\n } else {\r\n return sql;\r\n }\r\n }\r\n\r\n private String createSqlPagination(String sql, int limit, int offset) {\r\n return getCustom().createSqlPagination(sql, limit, offset).toString();\r\n }\r\n\r\n @Override\r\n public int deleteByID(ID id) throws DataException {\r\n return deleteByID(getGenericTypeClass(), id);\r\n }\r\n\r\n protected int deleteByID(Class clazz, ID key) throws DataException {\r\n return deleteByID(clazz, isArray(key) ? ((Object[]) key) : new Object[]{key});\r\n }\r\n\r\n protected int deleteByID(Class clazz, Object... keys) throws DataException {\r\n Table table = getTableName(clazz);\r\n if (table.keys() == null || table.keys().length == 0) {\r\n throw new DataException(\"It is necessary to specify the primary keys for the entity: \" + table.getClass().getCanonicalName());\r\n }\r\n if (table.keys().length != keys.length) {\r\n throw new DataException(\"It is necessary to specify the same amount keys to remove the entity: \" + table.getClass().getCanonicalName());\r\n }\r\n\r\n StringBuilder sql = new StringBuilder();\r\n sql.append(\"DELETE FROM \").append(table.name()).append(\" WHERE \");\r\n HashMap<String, Object> params = new HashMap<>();\r\n for (int i = 0; i < keys.length; i++) {\r\n params.put(table.keys()[i], keys[i]);\r\n sql.append(i == 0 ? \"\" : \" AND \");\r\n sql.append(table.keys()[i]).append(\"=:\").append(table.keys()[i]);\r\n }\r\n\r\n return update(sql.toString(), params);\r\n }\r\n\r\n protected <T> List<T> executeProcedure(String name, SqlParameter[] parameters, Map<String, Object> params, Class<T> returnType) {\r\n SimpleJdbcCall sjc = new SimpleJdbcCall((JdbcTemplate) getJdbcTemplate().getJdbcOperations()).withoutProcedureColumnMetaDataAccess().withProcedureName(name).declareParameters(parameters);\r\n\r\n SqlParameterSource in = new MapSqlParameterSource().addValues(params);\r\n Map<String, Object> out = sjc.execute(in);\r\n Map.Entry<String, Object> entry = out.entrySet().iterator().next();\r\n\r\n if (entry.getValue() instanceof List<?>) {\r\n List<?> tempList = (List<?>) entry.getValue();\r\n if (!tempList.isEmpty() && tempList.get(0).getClass().equals(returnType)) {\r\n return (List<T>) entry.getValue();\r\n }\r\n }\r\n return new ArrayList<>();\r\n }\r\n\r\n protected void executeProcedure(String name, SqlParameter[] parameters, Map<String, Object> params) {\r\n SimpleJdbcCall sjc = new SimpleJdbcCall((JdbcTemplate) getJdbcTemplate().getJdbcOperations()).withoutProcedureColumnMetaDataAccess().withProcedureName(name).declareParameters(parameters);\r\n\r\n SqlParameterSource in = new MapSqlParameterSource().addValues(params);\r\n sjc.execute(in);\r\n }\r\n\r\n protected T executeProcedure(String name, SqlParameter[] parameters, MapSqlParameterSource params, Class<T> returnType) {\r\n SimpleJdbcCall sjc = new SimpleJdbcCall((JdbcTemplate) getJdbcTemplate().getJdbcOperations());\r\n sjc.withProcedureName(name);\r\n sjc.withoutProcedureColumnMetaDataAccess();\r\n sjc.declareParameters(parameters);\r\n return sjc.executeFunction(returnType, params);\r\n }\r\n\r\n protected void executeProcedure(String name, SqlParameter[] parameters, MapSqlParameterSource params) {\r\n SimpleJdbcCall sjc = new SimpleJdbcCall((JdbcTemplate) getJdbcTemplate().getJdbcOperations());\r\n sjc.withProcedureName(name);\r\n sjc.withoutProcedureColumnMetaDataAccess();\r\n sjc.declareParameters(parameters);\r\n sjc.execute(params);\r\n }\r\n\r\n protected Map<String, Object> executeProcedureOut(String name, SqlParameter[] parameters, MapSqlParameterSource params) {\r\n SimpleJdbcCall sjc = new SimpleJdbcCall((JdbcTemplate) getJdbcTemplate().getJdbcOperations());\r\n sjc.withProcedureName(name);\r\n sjc.withoutProcedureColumnMetaDataAccess();\r\n sjc.declareParameters(parameters);\r\n Map<String, Object> out = sjc.execute(params);\r\n return out;\r\n }\r\n\r\n @Override\r\n public List<T> findAll() throws DataException {\r\n Table table = getTableName(getGenericTypeClass());\r\n\r\n SQLQueryDynamic sqlQuery = new SQLQueryDynamic(getGenericTypeClass());\r\n if (!\"[unassigned]\".equals(table.defaultOrderBy())) {\r\n sqlQuery.setOrderBy(table.defaultOrderBy(), SortOrder.ASCENDING);\r\n }\r\n return (List<T>) AbstractDAO.this.find(sqlQuery);\r\n }\r\n\r\n public List findAll(Class<? extends Mapping> aClass) throws DataException {\r\n return findAll(aClass, false);\r\n }\r\n\r\n public List findAll(Class<? extends Mapping> aClass, boolean loadAll) throws DataException {\r\n //@TODO: implementar defaultOrderBy\r\n List list;\r\n try {\r\n String sql = JdbcCache.sqlBase(aClass, loadAll);\r\n list = getJdbcTemplate().query(sql, rowMapper(aClass, loadAll));\r\n } catch (EmptyResultDataAccessException e) {\r\n list = new ArrayList();\r\n } catch (DataException de) {\r\n throw de;\r\n } catch (Exception ex) {\r\n throw new DataException(ex.getMessage(), ex);\r\n }\r\n return list;\r\n }\r\n\r\n @Override\r\n public List<T> findTop(int limit, SortOrder sortOrder) throws DataException {\r\n Table table = getTableName(getGenericTypeClass());\r\n StringBuilder sql = new StringBuilder();\r\n sql.append(JdbcCache.sqlBase(getGenericTypeClass()));\r\n if (table.keys() != null) {\r\n sql.append(\" ORDER BY \");\r\n for (String s : table.keys()) {\r\n sql.append(s);\r\n }\r\n sql.append(sortOrder == SortOrder.DESCENDING ? \" DESC\" : \" ASC\");\r\n }\r\n\r\n StringBuilder customSql = getCustom().createSqlPagination(sql.toString(), limit, 0);\r\n return AbstractDAO.this.find(customSql.toString());\r\n }\r\n\r\n public Iterator findQueryIterator(SQLQueryDynamic sqlQuery) {\r\n int limit = Utils.defaultValue(sqlQuery.getLimit(), 2500);\r\n if (!sqlQuery.isSorted()) {\r\n throw new DataException(\"It is necessary to specify a sort with identifier to be able to iterate over the records.\");\r\n }\r\n return new QueryIterator<Map<String, Object>>(limit) {\r\n\r\n @Override\r\n public List getData(int limit, int offset) {\r\n sqlQuery.setLimit(limit);\r\n sqlQuery.setOffset(offset);\r\n\r\n List records = null;\r\n if (sqlQuery.getClazz() != null) {\r\n records = getJdbcTemplate().query(createSqlPagination2Engine(sqlQuery), sqlQuery.getParams(), rowMapper(sqlQuery.getClazz(), sqlQuery.isLoadAll()));\r\n } else {\r\n records = getJdbcTemplate().queryForList(createSqlPagination2Engine(sqlQuery), sqlQuery.getParams());\r\n }\r\n\r\n sqlQuery.setTotalResultCount(sqlQuery.getTotalResultCount() + records.size());\r\n return records;\r\n }\r\n };\r\n }\r\n\r\n protected List<T> find(String sql) throws DataException {\r\n List list;\r\n try {\r\n list = getJdbcTemplate().query(sql, rowMapper(getGenericTypeClass()));\r\n } catch (EmptyResultDataAccessException e) {\r\n list = new ArrayList();\r\n }\r\n return list;\r\n }\r\n\r\n protected List<T> find(String sql, HashMap<String, ?> params) throws DataException {\r\n List list;\r\n try {\r\n list = getJdbcTemplate().query(sql, params, rowMapper(getGenericTypeClass()));\r\n } catch (EmptyResultDataAccessException e) {\r\n list = new ArrayList();\r\n }\r\n return list;\r\n }\r\n\r\n protected List<?> find(String sql, HashMap<String, ?> params, Class<? extends Mapping> clazz) throws DataException {\r\n List list;\r\n try {\r\n list = getJdbcTemplate().query(sql, params, rowMapper(clazz));\r\n } catch (EmptyResultDataAccessException e) {\r\n list = new ArrayList();\r\n }\r\n return list;\r\n }\r\n\r\n protected List<?> find(String sql, HashMap<String, ?> params, Class<? extends Mapping> clazz, int limit, int offset) throws DataException {\r\n List list;\r\n try {\r\n String sqlPagination = createSqlPagination(sql, limit, offset);\r\n list = getJdbcTemplate().query(sqlPagination, params, rowMapper(clazz));\r\n } catch (EmptyResultDataAccessException e) {\r\n list = new ArrayList();\r\n }\r\n return list;\r\n }\r\n\r\n protected List<?> find(SQLQueryDynamic sqlQuery) throws DataException {\r\n return find(sqlQuery, sqlQuery.getClazz());\r\n }\r\n\r\n protected List find(SQLQueryDynamic sqlQuery, Class<? extends Mapping> clazz) throws DataException {\r\n List records = getJdbcTemplate().query(createSqlPagination2Engine(sqlQuery), sqlQuery.getParams(), rowMapper(clazz, sqlQuery.isLoadAll()));\r\n if (sqlQuery.isLimited()) {\r\n long count = getJdbcTemplate().queryForObject(getCustom().prepareSQL2Engine(sqlQuery.getSQLCount()), sqlQuery.getParams(), Long.class);\r\n sqlQuery.setTotalResultCount(count);\r\n } else {\r\n sqlQuery.setTotalResultCount(records.size());\r\n }\r\n return records;\r\n }\r\n\r\n protected Paginator findPaginator(SQLQueryDynamic sqlQuery) throws DataException {\r\n List records = find(sqlQuery, sqlQuery.getClazz());\r\n Paginator paginator = new Paginator();\r\n paginator.setRecords(records);\r\n paginator.setTotalRecords(sqlQuery.getTotalResultCount());\r\n return paginator;\r\n }\r\n\r\n protected Paginator<Map<String, Object>> findMaps(SQLQueryDynamic sqlQuery) throws DataException {\r\n Paginator paginator = new Paginator();\r\n try {\r\n List records = getJdbcTemplate().queryForList(createSqlPagination2Engine(sqlQuery), sqlQuery.getParams());\r\n if (sqlQuery.isLimited()) {\r\n long count = getJdbcTemplate().queryForObject(getCustom().prepareSQL2Engine(sqlQuery.getSQLCount()), sqlQuery.getParams(), Long.class);\r\n sqlQuery.setTotalResultCount(count);\r\n } else {\r\n sqlQuery.setTotalResultCount(records.size());\r\n }\r\n\r\n paginator.setRecords(records);\r\n paginator.setTotalRecords(sqlQuery.getTotalResultCount());\r\n } catch (EmptyResultDataAccessException e) {\r\n paginator.setRecords(new ArrayList<>());\r\n paginator.setTotalRecords(0);\r\n }\r\n return paginator;\r\n }\r\n\r\n protected List<Map<String, Object>> findMaps(String sql, Map<String, ?> params) throws DataException {\r\n List list;\r\n try {\r\n list = getJdbcTemplate().queryForList(sql, params);\r\n } catch (EmptyResultDataAccessException e) {\r\n list = new ArrayList<>();\r\n }\r\n return list;\r\n }\r\n\r\n protected List<Map<String, Object>> findMaps(String sql, Map<String, ?> params, int limit, int offset) throws DataException {\r\n List list;\r\n try {\r\n String sqlPagination = createSqlPagination(sql, limit, offset);\r\n list = getJdbcTemplate().queryForList(sqlPagination, params);\r\n } catch (EmptyResultDataAccessException e) {\r\n list = new ArrayList<>();\r\n }\r\n return list;\r\n }\r\n\r\n protected List<String> findStrings(String sql, Map<String, ?> params) throws DataException {\r\n List list;\r\n try {\r\n list = getJdbcTemplate().queryForList(sql, params, String.class);\r\n } catch (EmptyResultDataAccessException e) {\r\n list = new ArrayList<>();\r\n }\r\n return list;\r\n }\r\n\r\n protected List<String> findStrings(String sql, Map<String, ?> params, int limit, int offset) throws DataException {\r\n List list;\r\n try {\r\n String sqlPagination = createSqlPagination(sql, limit, offset);\r\n list = getJdbcTemplate().queryForList(sqlPagination, params, String.class);\r\n } catch (EmptyResultDataAccessException e) {\r\n list = new ArrayList<>();\r\n }\r\n return list;\r\n }\r\n\r\n protected List<Long> findLongs(String sql, Map<String, ?> params) throws DataException {\r\n List list;\r\n try {\r\n list = getJdbcTemplate().queryForList(sql, params, Long.class);\r\n } catch (EmptyResultDataAccessException e) {\r\n list = new ArrayList<>();\r\n }\r\n return list;\r\n }\r\n\r\n @Override\r\n public long generateID() throws DataException {\r\n Table table = getTableName(getGenericTypeClass());\r\n if (table.sequence() == null) {\r\n throw new DataException(\"It is necessary to specify the sequence related to the entity:\");\r\n }\r\n\r\n String customSql = getCustom().createSqlNextval(table.sequence());\r\n return queryForLong(customSql);\r\n }\r\n\r\n protected long generateAnyID(Class<? extends Mapping> clazz) throws DataException {\r\n Table table = getTableName(clazz);\r\n if (table.sequence() == null) {\r\n throw new DataException(\"It is necessary to specify the sequence related to the entity:\");\r\n }\r\n String customSql = getCustom().createSqlNextval(table.sequence());\r\n return queryForLong(customSql);\r\n }\r\n\r\n @Override\r\n public T getByID(ID id) throws DataException {\r\n return (T) getByID(getGenericTypeClass(), id);\r\n }\r\n\r\n @Override\r\n public T getByID(ID key, boolean loadAll) throws DataException {\r\n return (T) getByID(getGenericTypeClass(), loadAll, isArray(key) ? ((Object[]) key) : new Object[]{key});\r\n }\r\n\r\n protected <T extends Mapping> T getByID(Class<T> clazz, ID key) throws DataException {\r\n return getByID(clazz, isArray(key) ? ((Object[]) key) : new Object[]{key});\r\n }\r\n\r\n protected <T extends Mapping> T getByID(Class<T> clazz, Object... keys) throws DataException {\r\n return getByID(clazz, false, keys);\r\n }\r\n\r\n protected <T extends Mapping> T getByID(Class<T> clazz, boolean loadAll, Object... keys) throws DataException {\r\n Table table = getTableName(clazz);\r\n if (table.keys() == null || table.keys().length == 0) {\r\n throw new DataException(\"It is necessary to specify the primary keys for the entity: \" + table.getClass().getCanonicalName());\r\n }\r\n if (table.keys().length != keys.length) {\r\n throw new DataException(\"It is necessary to specify the same keys to identify the entity: \" + table.getClass().getCanonicalName());\r\n }\r\n\r\n StringBuilder sql = new StringBuilder();\r\n sql.append(JdbcCache.sqlBase(clazz, true)).append(\" WHERE \");\r\n HashMap<String, Object> params = new HashMap<>();\r\n for (int i = 0; i < keys.length; i++) {\r\n params.put(table.keys()[i], keys[i]);\r\n sql.append(i == 0 ? \"\" : \" AND \");\r\n sql.append(table.keys()[i]).append(\"=:\").append(table.keys()[i]);\r\n }\r\n\r\n return (T) queryForObject(sql.toString(), params, rowMapper(clazz, loadAll));\r\n }\r\n\r\n private Class<T> getGenericTypeClass() {\r\n return genericTypeClass;\r\n }\r\n\r\n @Override\r\n public void persist(T object) throws DataException {\r\n persistAny(object);\r\n }\r\n\r\n protected void persistAny(Mapping object) throws DataException {\r\n\r\n Table table = getTableName(object.getClass());\r\n HashMap<String, Object> params = prepareParams(Operation.PERSIST, object);\r\n\r\n StringBuilder sql = new StringBuilder();\r\n sql.append(\"INSERT INTO \").append(table.name());\r\n sql.append(\"(\");\r\n boolean firstElement = true;\r\n for (String key : params.keySet()) {\r\n sql.append(!firstElement ? \",\" : \"\");\r\n sql.append(key);\r\n firstElement = false;\r\n }\r\n sql.append(\") VALUES\");\r\n sql.append(\"(\");\r\n firstElement = true;\r\n for (String key : params.keySet()) {\r\n sql.append(!firstElement ? \",\" : \"\");\r\n sql.append(\":\").append(key);\r\n firstElement = false;\r\n }\r\n sql.append(\")\");\r\n\r\n update(sql.toString(), params);\r\n }\r\n\r\n protected String queryForString(String sql, HashMap<String, ?> params) throws DataException {\r\n String object;\r\n try {\r\n object = getJdbcTemplate().queryForObject(sql, params, String.class);\r\n } catch (EmptyResultDataAccessException e) {\r\n object = null;\r\n }\r\n return object;\r\n }\r\n\r\n protected byte[] queryForBytes(String sql, HashMap<String, ?> params) throws DataException {\r\n return getJdbcTemplate().queryForObject(sql, params, byte[].class);\r\n }\r\n\r\n protected Integer queryForInteger(String sql) throws DataException {\r\n return queryForInteger(sql, null);\r\n }\r\n\r\n protected Integer queryForInteger(String sql, HashMap<String, ?> params) throws DataException {\r\n Integer object;\r\n try {\r\n object = getJdbcTemplate().queryForObject(sql, params, Integer.class);\r\n } catch (EmptyResultDataAccessException e) {\r\n object = null;\r\n }\r\n return object;\r\n }\r\n\r\n protected Long queryForLong(String sql) throws DataException {\r\n return queryForLong(sql, null);\r\n }\r\n\r\n protected Long queryForLong(String sql, HashMap<String, ?> params) throws DataException {\r\n Long object;\r\n try {\r\n object = getJdbcTemplate().queryForObject(sql, params, Long.class);\r\n } catch (EmptyResultDataAccessException e) {\r\n object = null;\r\n }\r\n return object;\r\n }\r\n\r\n private T queryForObject(String sql, HashMap<String, ?> params, AbstractRowMapper<T> rowMapper) throws DataException {\r\n T mapping;\r\n try {\r\n mapping = getJdbcTemplate().queryForObject(sql, params, rowMapper);\r\n } catch (EmptyResultDataAccessException e) {\r\n mapping = null;\r\n }\r\n return mapping;\r\n }\r\n\r\n protected T queryForObject(String sql, HashMap<String, ?> params) throws DataException {\r\n return queryForObject(sql, params, true);\r\n }\r\n\r\n protected T queryForObject(String sql, HashMap<String, ?> params, boolean loadAll) throws DataException {\r\n T object;\r\n try {\r\n object = (T) queryForObject(sql, params, rowMapper(getGenericTypeClass(), loadAll));\r\n } catch (EmptyResultDataAccessException e) {\r\n object = null;\r\n }\r\n return object;\r\n }\r\n\r\n protected <I extends Mapping> I queryForObject(SQLQueryDynamic sqlQuery) throws DataException {\r\n return queryForObject(createSqlPagination2Engine(sqlQuery), sqlQuery.getParams(), (Class<I>) sqlQuery.getClazz());\r\n }\r\n\r\n protected <I extends Mapping> I queryForObject(String sql, HashMap<String, ?> params, Class<I> clazz) throws DataException {\r\n return queryForObject(sql, params, clazz, true);\r\n }\r\n\r\n protected <I extends Mapping> I queryForObject(String sql, HashMap<String, ?> params, Class<I> clazz, boolean loadAll) throws DataException {\r\n Object object;\r\n try {\r\n object = getJdbcTemplate().queryForObject(sql, params, rowMapper(clazz, loadAll));\r\n } catch (EmptyResultDataAccessException e) {\r\n object = null;\r\n }\r\n return (I) object;\r\n }\r\n\r\n private AbstractRowMapper rowMapper(final Class clazz) {\r\n return JdbcCache.rowMapper(clazz, false);\r\n }\r\n\r\n private AbstractRowMapper rowMapper(final Class clazz, boolean loadAll) {\r\n return JdbcCache.rowMapper(clazz, loadAll);\r\n }\r\n\r\n protected int update(String sql, HashMap<String, ?> params) throws DataException {\r\n return getJdbcTemplate().update(sql, params);\r\n }\r\n\r\n @Override\r\n public int update(T object) throws DataException {\r\n return updateAny(object);\r\n }\r\n\r\n protected int updateAny(Mapping object) throws DataException {\r\n\r\n Table table = getTableName(object.getClass());\r\n if (table.keys() == null || table.keys().length == 0) {\r\n throw new DataException(\"It is necessary to specify the primary keys for the entity: \" + table.getClass().getCanonicalName());\r\n }\r\n\r\n List<String> primaryKeys = Arrays.asList(table.keys());\r\n HashMap<String, Object> params = prepareParams(Operation.UPDATE, object);\r\n StringBuilder sql = new StringBuilder();\r\n sql.append(\"UPDATE \").append(table.name());\r\n sql.append(\" SET \");\r\n boolean firstElement = true;\r\n for (String key : params.keySet()) {\r\n if (primaryKeys.contains(key)) {\r\n continue;\r\n }\r\n sql.append(!firstElement ? \",\" : \"\");\r\n sql.append(key).append(\"=:\").append(key);\r\n firstElement = false;\r\n }\r\n sql.append(\" WHERE \");\r\n\r\n firstElement = true;\r\n for (String key : primaryKeys) {\r\n sql.append(!firstElement ? \" AND \" : \"\");\r\n sql.append(key).append(\"=:\").append(key);\r\n firstElement = false;\r\n }\r\n return update(sql.toString(), params);\r\n }\r\n\r\n private Table getTableName(Class clazz) throws DataException {\r\n Table table = (Table) clazz.getAnnotation(Table.class);\r\n if (table == null) {\r\n throw new DataException(\"There is no annotation @Table into the class: \" + clazz.getCanonicalName());\r\n }\r\n return table;\r\n }\r\n\r\n private boolean isPrimaryKey(Table table, String field) {\r\n boolean isPrimary = false;\r\n if (table != null) {\r\n for (String key : table.keys()) {\r\n if (key.equals(field)) {\r\n isPrimary = true;\r\n break;\r\n }\r\n }\r\n\r\n }\r\n return isPrimary;\r\n }\r\n\r\n private HashMap<String, Object> prepareParams(Operation operation, Object object) throws DataException {\r\n HashMap<String, Object> params = new HashMap<>();\r\n try {\r\n if (object != null) {\r\n\r\n Table table = object.getClass().getAnnotation(Table.class);\r\n for (Field field : object.getClass().getDeclaredFields()) {\r\n // this is for private scope\r\n field.setAccessible(true);\r\n Object value = field.get(object);\r\n\r\n Column column = field.getAnnotation(Column.class);\r\n if (column != null && ((operation == Operation.PERSIST && column.insertable()) || (operation == Operation.UPDATE && column.updatable()) || isPrimaryKey(table, column.name()))) {\r\n if (column.parser() == EnumParser.class && value instanceof EnumIdentifiable) {\r\n params.put(column.name(), ((EnumIdentifiable) value).getId());\r\n } else if (column.parser() == EnumParser.class && value instanceof Enum) {\r\n params.put(column.name(), ((Enum) value).name());\r\n } else if (column.parser() == JsonParser.class || column.parser() == JsonListParser.class) {\r\n PGobject jsonbObj = new PGobject();\r\n jsonbObj.setType(\"json\");\r\n jsonbObj.setValue(GsonUtils.custom.toJson(value));\r\n params.put(column.name(), jsonbObj);\r\n } else if (column.parser() == ByteaJsonParser.class || column.parser() == ByteaJsonListParser.class) {\r\n byte[] bytes = GsonUtils.custom.toJson(value).getBytes(DEFAULT_CHARSET);\r\n params.put(column.name(), bytes);\r\n } else if (value instanceof StringWriter) {\r\n //TODO: Hacer un conversor generico\r\n byte[] bytes = ((StringWriter) value).toString().getBytes(DEFAULT_CHARSET);\r\n params.put(column.name(), bytes);\r\n } else if (value instanceof String) {\r\n String text = ((String) value).trim();\r\n text = (column.length() > 0 && text.length() > column.length()) ? text.substring(0, column.length()) : text;\r\n params.put(column.name(), column.encrypted() ? CryptographyUtils.encrypt(text) : text);\r\n } else {\r\n boolean isZeroOrNull = (value == null || (value instanceof Long && ((Long) value) == 0) || (value instanceof Integer && ((Integer) value) == 0));\r\n if (!column.serial() || (column.serial() && !isZeroOrNull)) {\r\n params.put(column.name(), value);\r\n }\r\n\r\n }\r\n } else {\r\n ColumnGroup columnMapping = field.getAnnotation(ColumnGroup.class);\r\n if (columnMapping != null) {\r\n params.putAll(prepareParams(operation, value));\r\n } else {\r\n JoinTable joinTable = field.getAnnotation(JoinTable.class);\r\n if (joinTable != null) {\r\n Object tableValue = field.get(object);\r\n if (tableValue != null) {\r\n params.put(joinTable.foreignKey(), extractPrimaryKey(tableValue));\r\n }\r\n }\r\n }\r\n }\r\n\r\n }\r\n }\r\n } catch (Exception ex) {\r\n throw new DataException(\"Error preparing parameter of the Object\", ex);\r\n }\r\n return params;\r\n }\r\n\r\n private Object extractPrimaryKey(Object entity) throws IllegalArgumentException, IllegalAccessException {\r\n Table table = entity.getClass().getAnnotation(Table.class);\r\n String key = table.keys()[0];\r\n Object value = null;\r\n for (Field field : entity.getClass().getDeclaredFields()) {\r\n Column column = field.getAnnotation(Column.class);\r\n if (column != null && column.name().equals(key)) {\r\n // this is for private scope\r\n field.setAccessible(true);\r\n value = field.get(entity);\r\n if (column.parser() == EnumParser.class && value instanceof EnumIdentifiable) {\r\n value = ((EnumIdentifiable) value).getId();\r\n } else if (column.parser() == EnumParser.class && value instanceof Enum) {\r\n value = ((Enum) value).name();\r\n }\r\n\r\n break;\r\n }\r\n }\r\n\r\n return value;\r\n }\r\n\r\n private CustomEngine getCustom() {\r\n if (null == getEngine()) {\r\n throw new DataException(\"Engine not supported\");\r\n } else {\r\n switch (getEngine()) {\r\n case ORACLE:\r\n return OracleEngine.getInstance();\r\n case POSTGRES:\r\n return PostgresEngine.getInstance();\r\n case SQLSERVER:\r\n return SQLServerEngine.getInstance();\r\n default:\r\n throw new DataException(\"Engine not supported\");\r\n }\r\n }\r\n }\r\n\r\n private boolean isArray(Object obj) {\r\n return obj != null && obj.getClass().isArray();\r\n }\r\n\r\n}\r"
},
{
"identifier": "Engine",
"path": "src/main/java/cl/kanopus/jdbc/impl/engine/Engine.java",
"snippet": "public enum Engine {\n ORACLE,\n POSTGRES,\n SQLSERVER\n}"
}
] | import cl.kanopus.jdbc.entity.Mapping;
import cl.kanopus.jdbc.impl.AbstractDAO;
import cl.kanopus.jdbc.impl.engine.Engine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; | 6,879 | package cl.kanopus.jdbc.example;
/**
* This abstract class defines methods for data access that are common,
* generally, all kinds of data access DAO must implement this class.Thus it is
* given safely access the Connection database.The JdbcTemplate property is kept
* private and gives access to the database through the methods implemented in
* this AbstractDAO.
*
* @author Pablo Diaz Saavedra
* @param <T>
* @param <ID>
* @email [email protected]
*/
public abstract class AbstractBaseDAO<T extends Mapping, ID> extends AbstractDAO<T, ID> {
@Autowired
private NamedParameterJdbcTemplate jdbcTemplate;
@Override
protected NamedParameterJdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}
@Override | package cl.kanopus.jdbc.example;
/**
* This abstract class defines methods for data access that are common,
* generally, all kinds of data access DAO must implement this class.Thus it is
* given safely access the Connection database.The JdbcTemplate property is kept
* private and gives access to the database through the methods implemented in
* this AbstractDAO.
*
* @author Pablo Diaz Saavedra
* @param <T>
* @param <ID>
* @email [email protected]
*/
public abstract class AbstractBaseDAO<T extends Mapping, ID> extends AbstractDAO<T, ID> {
@Autowired
private NamedParameterJdbcTemplate jdbcTemplate;
@Override
protected NamedParameterJdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}
@Override | protected Engine getEngine() { | 2 | 2023-11-27 18:25:00+00:00 | 8k |
andre111/voxedit | src/client/java/me/andre111/voxedit/client/gui/screen/EditBlockPaletteScreen.java | [
{
"identifier": "BlockStateWidget",
"path": "src/client/java/me/andre111/voxedit/client/gui/widget/BlockStateWidget.java",
"snippet": "@Environment(value=EnvType.CLIENT)\npublic class BlockStateWidget extends TextFieldWidget {\n\tpublic static final MatrixStack.Entry BLOCK_POSE;\n\tstatic {\n\t\tMatrixStack matrices = new MatrixStack();\n\t\tmatrices.translate(-0.7f, 0.4f, 0);\n\t\tmatrices.multiply(new AxisAngle4f((float) Math.PI, 1, 0, 0).get(new Quaternionf()), 0, 0, 0);\n\t\tmatrices.multiply(new AxisAngle4f((float) (30 * Math.PI / 180), 1, 0, 0).get(new Quaternionf()), 0, 0, 0);\n\t\tmatrices.multiply(new AxisAngle4f((float) (45 * Math.PI / 180), 0, 1, 0).get(new Quaternionf()), 0, 0, 0);\n\t\tBLOCK_POSE = matrices.peek();\n\t}\n\t\n\tprivate BlockState value;\n\tprivate String suggestion;\n\tprivate final boolean includeProperties;\n\tprivate final Consumer<BlockState> consumer;\n\n public BlockStateWidget(TextRenderer textRenderer, int x, int y, int width, int height, boolean includeProperties, BlockState initialValue, Consumer<BlockState> consumer) {\n\t\tsuper(textRenderer, x, y, width, height, Text.empty());\n\t\tthis.includeProperties = includeProperties;\n\t\tthis.consumer = consumer;\n\t\tthis.value = initialValue;\n\t\t\n\t\tthis.setMaxLength(200);\n\t\tif(this.includeProperties) {\n\t\t\tthis.setText(BlockArgumentParser.stringifyBlockState(value));\n\t\t} else {\n\t\t\tthis.setText(value.getRegistryEntry().getKey().map(key -> key.getValue().toString()).orElse(\"air\"));\n\t\t}\n\t\t\n\t\tthis.setChangedListener((string) -> {\n\t\t\ttry {\n\t\t\t\tvar wrapper = Registries.BLOCK.getReadOnlyWrapper();\n\t\t\t\tvar builder = new SuggestionsBuilder(string, string.toLowerCase(Locale.ROOT), string.length());\n\t\t\t\tBlockArgumentParser.getSuggestions(wrapper, builder, false, false).thenAccept((suggestions) -> {\n\t\t\t\t\tsetSuggestion(\"\");\n\t\t\t\t\tfor(Suggestion suggestion : suggestions.getList()) {\n\t\t\t\t\t\tif(suggestion.getText().startsWith(string)) {\n\t\t\t\t\t\t\tsetSuggestion(suggestion.getText().substring(string.length()));\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\t\n\t\t\t\tBlockResult result = BlockArgumentParser.block(wrapper, string, false);\n\t\t\t\tthis.setEditableColor(0xFFFFFF);\n\t\t\t\tthis.consumer.accept(value = result.blockState());\n\t\t\t} catch (CommandSyntaxException e) {\n\t\t\t\tthis.setEditableColor(0xFF0000);\n\t\t\t}\n\t\t});\n\t}\n\t\n\tpublic BlockState getValue() {\n\t\treturn value;\n\t}\n\t\n\t@Override\n public void setSuggestion(String suggestion) {\n\t\tthis.suggestion = suggestion;\n\t\tsuper.setSuggestion(suggestion);\n\t}\n\n @Override\n public boolean keyPressed(int keyCode, int scanCode, int modifiers) {\n \tif(isFocused()) {\n \t\tif(keyCode == GLFW.GLFW_KEY_TAB) {\n \t\t\tif(suggestion != null && !suggestion.isEmpty() && getCursor() == getText().length()) {\n \t\t\t\tsetText(getText() + suggestion);\n \t\t\t\treturn true;\n \t\t\t}\n \t\t}\n \t}\n \treturn super.keyPressed(keyCode, scanCode, modifiers);\n }\n\n @Override\n public void renderWidget(DrawContext context, int mouseX, int mouseY, float delta) {\n \tsuper.renderWidget(context, mouseX, mouseY, delta);\n \t\n context.setShaderColor(1.0f, 1.0f, 1.0f, this.alpha);\n RenderSystem.enableBlend();\n RenderSystem.defaultBlendFunc();\n RenderSystem.enableDepthTest();\n RenderSystem.depthMask(false);\n context.drawGuiTexture(Textures.SLOT, this.getX()+width, this.getY(), height, height);\n context.setShaderColor(1.0f, 1.0f, 1.0f, 1.0f);\n\n if(value.isAir()) {\n context.drawGuiTexture(Textures.AIR, this.getX()+width+2, this.getY()+2, height-4, height-4);\n } else {\n\t\t\tMatrixStack matrices = context.getMatrices();\n\t\t\tmatrices.push();\n\t\t\tmatrices.translate(getX()+width+height/2, getY()+height/2, 200);\n\t\t\tfloat scale = 10 * (20.0f / Math.min(width, height));\n\t\t\tmatrices.scale(scale, scale, scale);\n\t\t\tmatrices.multiplyPositionMatrix(BLOCK_POSE.getPositionMatrix());\n\t MinecraftClient.getInstance().getBlockRenderManager().renderBlockAsEntity(value, matrices, context.getVertexConsumers(), LightmapTextureManager.MAX_LIGHT_COORDINATE, OverlayTexture.DEFAULT_UV);\n\t matrices.pop();\n }\n\t}\n}"
},
{
"identifier": "IntSliderWidget",
"path": "src/client/java/me/andre111/voxedit/client/gui/widget/IntSliderWidget.java",
"snippet": "@Environment(value=EnvType.CLIENT)\npublic class IntSliderWidget extends SliderWidget {\n\tprivate final Text text;\n\tprivate final int min;\n\tprivate final int max;\n\tprivate final Consumer<Integer> valueConsumer;\n\t\n\tpublic IntSliderWidget(int x, int y, int width, int height, Text text, int min, int max, int value, Consumer<Integer> valueConsumer) {\n\t\tsuper(x, y, width, height, text, (value - min) / (double) (max - min));\n\t\t\n\t\tthis.text = text;\n\t\tthis.min = min;\n\t\tthis.max = max;\n\t\tthis.valueConsumer = valueConsumer;\n\t\t\n\t\tthis.setIntValue(value);\n\t}\n\n\tpublic int getIntValue() {\n\t\treturn MathHelper.floor(MathHelper.clampedLerp(min, max, value));\n\t}\n\t\n\tpublic void setIntValue(int intValue) {\n\t\tintValue = MathHelper.clamp(intValue, min, max);\n\t\tvalue = MathHelper.clamp((intValue-min) / (double) (max - min), 0.0, 1.0);\n\t\tupdateMessage();\n\t}\n\n\t@Override\n\tprotected void updateMessage() {\n\t\tsetMessage(text.copy().append(\": \"+getIntValue()));\n\t}\n\n\t@Override\n\tprotected void applyValue() {\n\t\tvalueConsumer.accept(getIntValue());\n\t}\n}"
},
{
"identifier": "ModListWidget",
"path": "src/client/java/me/andre111/voxedit/client/gui/widget/ModListWidget.java",
"snippet": "@Environment(value=EnvType.CLIENT)\npublic abstract class ModListWidget<E extends me.andre111.voxedit.client.gui.widget.ModListWidget.Entry<E>> extends ContainerWidget implements LayoutWidget {\n private static final Identifier SCROLLER_TEXTURE = new Identifier(\"widget/scroller\");\n protected final MinecraftClient client;\n private final List<E> children = new ArrayList<>();\n private int padding;\n private double scrollAmount;\n private boolean scrolling;\n private E selected;\n private boolean renderBackground = true;\n private E hoveredEntry;\n\n public ModListWidget(MinecraftClient client, int width, int height, int y, int padding) {\n super(0, y, width, height, ScreenTexts.EMPTY);\n this.client = client;\n this.padding = padding;\n }\n\t\n\t@Override\n\tpublic int getHeight() {\n\t\tint defHeight = super.getHeight();\n\t\treturn defHeight > 0 ? defHeight : this.getMaxPosition();\n\t}\n\n public int getRowWidth() {\n return width-20;\n }\n\n public E getSelectedOrNull() {\n return this.selected;\n }\n\n public void setSelected(@Nullable E entry) {\n this.selected = entry;\n }\n\n public E getFirst() {\n return children.get(0);\n }\n\n public void setRenderBackground(boolean renderBackground) {\n this.renderBackground = renderBackground;\n }\n\n public final List<E> children() {\n return this.children;\n }\n\n protected void clearEntries() {\n this.children.clear();\n this.selected = null;\n }\n\n protected E getEntry(int index) {\n return children().get(index);\n }\n\n protected int addEntry(E entry) {\n \tentry.parentList = this;\n this.children.add(entry);\n this.refreshPositions();\n return this.children.size() - 1;\n }\n\n protected void addEntryToTop(E entry) {\n \tentry.parentList = this;\n double d = this.getMaxScroll() - this.getScrollAmount();\n this.children.add(0, entry);\n this.refreshPositions();\n this.setScrollAmount(this.getMaxScroll() - d);\n }\n\n protected boolean removeEntryWithoutScrolling(E entry) {\n double d = this.getMaxScroll() - this.getScrollAmount();\n boolean bl = this.removeEntry(entry);\n this.setScrollAmount(this.getMaxScroll() - d);\n return bl;\n }\n\n protected int getEntryCount() {\n return this.children().size();\n }\n\n protected boolean isSelectedEntry(E entry) {\n return Objects.equals(this.getSelectedOrNull(), entry);\n }\n\n protected final E getEntryAtPosition(double x, double y) {\n for(E child : children) {\n \tif(child.getX() < x && x < child.getX() + child.getWidth() && child.getY() < y && y < child.getY() + child.getHeight()) return child;\n }\n return null;\n }\n\n protected int getMaxPosition() {\n \tint height = padding;\n \tfor(E child : children) height += child.getHeight()+1;\n return height;\n }\n\n protected void renderDecorations(DrawContext context, int mouseX, int mouseY) {\n }\n\n @Override\n public void renderWidget(DrawContext context, int mouseX, int mouseY, float delta) {\n int j;\n int i;\n hoveredEntry = isMouseOver(mouseX, mouseY) ? getEntryAtPosition(mouseX, mouseY) : null;\n if (renderBackground) {\n context.setShaderColor(0.125f, 0.125f, 0.125f, 1.0f);\n i = 32;\n context.drawTexture(Screen.OPTIONS_BACKGROUND_TEXTURE, getX(), getY(), getRight(), getBottom() + (int) getScrollAmount(), getWidth(), getHeight(), 32, 32);\n context.setShaderColor(1.0f, 1.0f, 1.0f, 1.0f);\n }\n this.enableScissor(context);\n this.renderList(context, mouseX, mouseY, delta);\n context.disableScissor();\n if (renderBackground) {\n i = 4;\n context.fillGradient(RenderLayer.getGuiOverlay(), getX(), getY(), getRight(), getY() + 4, Colors.BLACK, 0, 0);\n context.fillGradient(RenderLayer.getGuiOverlay(), getX(), getBottom() - 4, getRight(), getBottom(), 0, Colors.BLACK, 0);\n }\n if (super.getHeight() > 0 && (i = this.getMaxScroll()) > 0) {\n j = this.getScrollbarPositionX();\n int k = (int)((getHeight() * getHeight()) / (float) getMaxPosition());\n k = MathHelper.clamp(k, 32, getHeight() - 8);\n int l = (int)this.getScrollAmount() * (getHeight() - k) / i + this.getY();\n if (l < this.getY()) {\n l = this.getY();\n }\n context.fill(j, this.getY(), j + 6, this.getBottom(), -16777216);\n context.drawGuiTexture(SCROLLER_TEXTURE, j, l, 6, k);\n }\n this.renderDecorations(context, mouseX, mouseY);\n RenderSystem.disableBlend();\n }\n\n protected void enableScissor(DrawContext context) {\n context.enableScissor(getX(), getY(), getRight(), getBottom());\n }\n\n protected void centerScrollOn(E entry) {\n this.setScrollAmount(entry.getY() + entry.getHeight() / 2 - getHeight() / 2);\n }\n\n protected void ensureVisible(E entry) {\n if(entry.getY() < getY()) {\n scroll(getY()-entry.getY());\n } else if(entry.getY() + entry.getHeight() > getY() + getHeight()) {\n scroll(-(entry.getY() + entry.getHeight() - (getY() + getHeight())));\n }\n }\n\n private void scroll(int amount) {\n setScrollAmount(getScrollAmount() + amount);\n }\n\n public double getScrollAmount() {\n return this.scrollAmount;\n }\n\n public void setScrollAmount(double amount) {\n scrollAmount = MathHelper.clamp(amount, 0.0, getMaxScroll());\n refreshPositions();\n }\n\n public int getMaxScroll() {\n return Math.max(0, getMaxPosition() - (height - 4));\n }\n\n protected void updateScrollingState(double mouseX, double mouseY, int button) {\n this.scrolling = button == 0 && mouseX >= getScrollbarPositionX() && mouseX < (getScrollbarPositionX() + 6);\n }\n\n protected int getScrollbarPositionX() {\n return getWidth()-5;\n }\n\n protected boolean isSelectButton(int button) {\n return button == 0;\n }\n\n @Override\n public boolean mouseClicked(double mouseX, double mouseY, int button) {\n if (!this.isSelectButton(button)) {\n return false;\n }\n this.updateScrollingState(mouseX, mouseY, button);\n if (!this.isMouseOver(mouseX, mouseY)) {\n return false;\n }\n E entry = this.getEntryAtPosition(mouseX, mouseY);\n if (entry != null) {\n if (entry.mouseClicked(mouseX, mouseY, button)) {\n Element entry2 = this.getFocused();\n if (entry2 != entry && entry2 instanceof ParentElement) {\n ParentElement parentElement = (ParentElement)entry2;\n parentElement.setFocused(null);\n }\n this.setFocused(entry);\n this.setDragging(true);\n return true;\n }\n }\n return this.scrolling;\n }\n\n @Override\n public boolean mouseReleased(double mouseX, double mouseY, int button) {\n if (this.getFocused() != null) {\n this.getFocused().mouseReleased(mouseX, mouseY, button);\n }\n return false;\n }\n\n @Override\n public boolean mouseDragged(double mouseX, double mouseY, int button, double deltaX, double deltaY) {\n if (super.mouseDragged(mouseX, mouseY, button, deltaX, deltaY)) {\n return true;\n }\n if (button != 0 || !this.scrolling) {\n return false;\n }\n if (mouseY < (double)this.getY()) {\n this.setScrollAmount(0.0);\n } else if (mouseY > (double)this.getBottom()) {\n this.setScrollAmount(this.getMaxScroll());\n } else {\n double d = Math.max(1, this.getMaxScroll());\n int i = getHeight();\n int j = MathHelper.clamp((int)((float)(i * i) / (float)this.getMaxPosition()), 32, i - 8);\n double e = Math.max(1.0, d / (double)(i - j));\n this.setScrollAmount(this.getScrollAmount() + deltaY * e);\n }\n return true;\n }\n\n @Override\n public boolean mouseScrolled(double mouseX, double mouseY, double horizontalAmount, double verticalAmount) {\n setScrollAmount(getScrollAmount() - verticalAmount * 20);\n return true;\n }\n\n @Override\n public void setFocused(Element focused) {\n super.setFocused(focused);\n int i = children.indexOf(focused);\n if (i >= 0) {\n \tE entry = children.get(i);\n setSelected(entry);\n if (client.getNavigationType().isKeyboard()) {\n \tensureVisible(entry);\n }\n } else {\n \tsetSelected(null);\n }\n }\n\n @Nullable\n protected E getNeighboringEntry(NavigationDirection direction) {\n return getNeighboringEntry(direction, entry -> true);\n }\n\n @Nullable\n protected E getNeighboringEntry(NavigationDirection direction, Predicate<E> predicate) {\n return getNeighboringEntry(direction, predicate, this.getSelectedOrNull());\n }\n\n @Nullable\n protected E getNeighboringEntry(NavigationDirection direction, Predicate<E> predicate, @Nullable E selected) {\n int offset = switch(direction) {\n case RIGHT, LEFT -> 0;\n case UP -> -1;\n case DOWN -> 1;\n };\n if(!this.children().isEmpty() && offset != 0) {\n int startIndex = selected == null ? (offset > 0 ? 0 : children().size() - 1) : children().indexOf(selected) + offset;\n for (int index = startIndex; index >= 0 && index < children.size(); index += offset) {\n E entry = children().get(index);\n if (!predicate.test(entry)) continue;\n return entry;\n }\n }\n return null;\n }\n\n @Override\n public boolean isMouseOver(double mouseX, double mouseY) {\n return mouseY >= this.getY() && mouseY <= this.getBottom() && mouseX >= this.getX() && mouseX <= this.getRight();\n }\n\n protected void renderList(DrawContext context, int mouseX, int mouseY, float delta) {\n for(E child : children) {\n \tif(child.getY() + child.getHeight() < getY()) continue;\n \tif(child.getY() > getY() + getHeight()) return;\n \t\n \tif(child.isFocused()) {\n this.drawSelectionHighlight(context, child.getX(), child.getY(), child.getWidth(), child.getHeight(), 0xFFFFFFFF, -16777216);\n \t}\n \tchild.render(context, mouseX, mouseY, delta);\n }\n }\n\n protected void drawSelectionHighlight(DrawContext context, int entryX, int entryY, int entryWidth, int entryHeight, int borderColor, int fillColor) {\n context.fill(entryX-2, entryY-2, entryX+entryWidth+2, entryY+entryHeight-1, borderColor);\n context.fill(entryX-1, entryY-1, entryX+entryWidth+1, entryY+entryHeight-2, fillColor);\n }\n\n public int getRowLeft() {\n return getX() + getWidth() / 2 - getRowWidth() / 2 + 2;\n }\n\n public int getRowRight() {\n return this.getRowLeft() + this.getRowWidth();\n }\n\n @Override\n public Selectable.SelectionType getType() {\n if (this.isFocused()) {\n return Selectable.SelectionType.FOCUSED;\n }\n if (this.hoveredEntry != null) {\n return Selectable.SelectionType.HOVERED;\n }\n return Selectable.SelectionType.NONE;\n }\n\n @Nullable\n protected E remove(int index) {\n \tE entry = children.get(index);\n if (this.removeEntry(children.get(index))) {\n return entry;\n }\n return null;\n }\n\n protected boolean removeEntry(E entry) {\n boolean bl = this.children.remove(entry);\n if (bl && entry == this.getSelectedOrNull()) {\n this.setSelected(null);\n }\n return bl;\n }\n\n @Nullable\n protected E getHoveredEntry() {\n return this.hoveredEntry;\n }\n\n\t@Override\n\tprotected void appendClickableNarrations(NarrationMessageBuilder builder) {\n\t}\n\n protected void appendNarrations(NarrationMessageBuilder builder, E entry) {\n int i;\n List<E> list = this.children();\n if (list.size() > 1 && (i = list.indexOf(entry)) != -1) {\n builder.put(NarrationPart.POSITION, (Text)Text.translatable(\"narrator.position.list\", i + 1, list.size()));\n }\n }\n\n\t@Override\n\tpublic void forEachElement(Consumer<Widget> consumer) {\n\t\tfor(E child : children) consumer.accept(child);\n\t}\n\t\n\t@Override\n\tpublic void refreshPositions() {\n\t\tint currentX = getX() + (width-getRowWidth()) / 2;\n\t\tint currentY = (int) (getY() + padding - getScrollAmount());\n\t\tfor(E child : children) {\n\t\t\tchild.setPosition(currentX, currentY);\n\t\t\tchild.setWidth(getRowWidth());\n\t\t\tcurrentY += child.getHeight()+1;\n\t\t}\n\t\tLayoutWidget.super.refreshPositions();\n\t}\n\n @Environment(value=EnvType.CLIENT)\n public abstract static class Entry<E extends Entry<E>> extends ContainerWidget implements LayoutWidget {\n public Entry() {\n\t\t\tsuper(0, 0, 0, 11, Text.empty());\n\t\t}\n\n ModListWidget<E> parentList;\n\n @Override\n public void setFocused(boolean focused) {\n }\n\n @Override\n public boolean isFocused() {\n return this.parentList.getFocused() == this;\n }\n \n\t @Override\n\t public boolean mouseClicked(double mouseX, double mouseY, int button) {\n\t \tboolean child = super.mouseClicked(mouseX, mouseY, button);\n\t \treturn child || (getX() <= mouseX && mouseX <= getX() + getWidth() && getY() <= mouseY && mouseY <= getY() + getHeight()); \n\t }\n\n\t\t@Override\n\t\tpublic void forEachElement(Consumer<Widget> consumer) {\n\t\t\tfor(Element child : children()) {\n\t\t\t\tif(child instanceof Widget widget) consumer.accept(widget);\n\t\t\t}\n\t\t}\n\t\t\n\t\t@Override\n\t\tpublic void refreshPositions() {\n\t\t\tpositionChildren();\n\t\t\tLayoutWidget.super.refreshPositions();\n\t\t}\n \n public abstract int getHeight();\n \n public abstract void positionChildren();\n }\n}"
},
{
"identifier": "BlockPalette",
"path": "src/main/java/me/andre111/voxedit/tool/data/BlockPalette.java",
"snippet": "public class BlockPalette {\n\tpublic static final Codec<BlockPalette> CODEC = RecordCodecBuilder.create(instance -> instance\n\t\t\t.group(\n\t\t\t\t\tEntry.CODEC.listOf().fieldOf(\"entries\").forGetter(bp -> bp.entries)\n\t\t\t)\n\t\t\t.apply(instance, BlockPalette::new));\n\tpublic static final BlockPalette DEFAULT = new BlockPalette(Blocks.STONE.getDefaultState());\n\t\n\tprivate List<Entry> entries = new ArrayList<>();\n\n\tpublic BlockPalette() {\n\t}\n\tpublic BlockPalette(BlockState state) {\n\t\tentries.add(new Entry(state, 1));\n\t}\n\tpublic BlockPalette(List<Entry> entries) {\n\t\tthis.entries = entries;\n\t}\n\t\n\tpublic int size() {\n\t\treturn entries.size();\n\t}\n\t\n\tpublic boolean has(Block block) {\n\t\tfor(Entry entry : entries) {\n\t\t\tif(entry.state.getBlock() == block) return true;\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tpublic BlockState get(int index) {\n\t\treturn entries.get(index).state;\n\t}\n\t\n\tpublic BlockState getRandom(Random random) {\n\t\tint totalWeight = entries.stream().mapToInt(Entry::weight).sum();\n\t\tint value = random.nextInt(totalWeight);\n\t\tfor(Entry entry : entries) {\n\t\t\tif(value < entry.weight) return entry.state;\n\t\t\tvalue -= entry.weight;\n\t\t}\n\t\treturn Blocks.AIR.getDefaultState();\n\t}\n\t\n\tpublic Entry getEntry(int index) {\n\t\treturn entries.get(index);\n\t}\n\t\n\tpublic void setEntry(int index, Entry entry) {\n\t\tentries.set(index, entry);\n\t}\n\t\n\tpublic List<Entry> getEntries() {\n\t\treturn new ArrayList<>(entries);\n\t}\n\t\n\t@Override\n\tpublic boolean equals(Object other) {\n\t\tif(other == null) return false;\n\t\tif(other instanceof BlockPalette otherPallete) return entries.equals(otherPallete.entries);\n\t\treturn false;\n\t}\n\t\n\tpublic static Builder builder() {\n\t\treturn new Builder();\n\t}\n\t\n\tpublic static record Entry(BlockState state, int weight) {\n\t\tprivate static final Codec<Entry> CODEC = RecordCodecBuilder.create(instance -> instance\n\t\t\t\t.group(\n\t\t\t\t\t\tBlockState.CODEC.fieldOf(\"state\").forGetter(e -> e.state),\n\t\t\t\t\t\tCodec.INT.fieldOf(\"weight\").forGetter(e -> e.weight)\n\t\t\t\t)\n\t\t\t\t.apply(instance, Entry::new));\n\t}\n\t\n\tpublic static class Builder {\n\t\tprivate List<Entry> entries = new ArrayList<>();\n\t\t\n\t\tpublic Builder add(Block block) {\n\t\t\treturn add(block, 1);\n\t\t}\n\t\t\n\t\tpublic Builder add(Block block, int weight) {\n\t\t\treturn add(block.getDefaultState(), weight);\n\t\t}\n\t\t\n\t\tpublic Builder add(BlockState state) {\n\t\t\treturn add(state, 1);\n\t\t}\n\t\t\n\t\tpublic Builder add(BlockState state, int weight) {\n\t\t\tentries.add(new Entry(state, weight));\n\t\t\treturn this;\n\t\t}\n\t\t\n\t\tpublic BlockPalette build() {\n\t\t\treturn new BlockPalette(new ArrayList<>(entries));\n\t\t}\n\t}\n}"
}
] | import net.minecraft.client.gui.widget.ButtonWidget;
import net.minecraft.screen.ScreenTexts;
import net.minecraft.text.Text;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import me.andre111.voxedit.client.gui.widget.BlockStateWidget;
import me.andre111.voxedit.client.gui.widget.IntSliderWidget;
import me.andre111.voxedit.client.gui.widget.ModListWidget;
import me.andre111.voxedit.tool.data.BlockPalette;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.minecraft.block.Blocks;
import net.minecraft.client.gui.DrawContext;
import net.minecraft.client.gui.Element;
import net.minecraft.client.gui.screen.Screen;
import net.minecraft.client.gui.screen.narration.NarrationMessageBuilder; | 6,277 | /*
* Copyright (c) 2023 André Schweiger
*
* 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 me.andre111.voxedit.client.gui.screen;
@Environment(value=EnvType.CLIENT)
public class EditBlockPaletteScreen extends Screen {
private final Screen parent;
private final int minSize;
private final boolean includeProperties;
private final boolean showWeights; | /*
* Copyright (c) 2023 André Schweiger
*
* 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 me.andre111.voxedit.client.gui.screen;
@Environment(value=EnvType.CLIENT)
public class EditBlockPaletteScreen extends Screen {
private final Screen parent;
private final int minSize;
private final boolean includeProperties;
private final boolean showWeights; | private final Consumer<BlockPalette> callback; | 3 | 2023-12-01 15:12:26+00:00 | 8k |
victor-vilar/coleta | backend/src/main/java/com/victorvilar/projetoempresa/controllers/AddressController.java | [
{
"identifier": "AddressCreateDto",
"path": "backend/src/main/java/com/victorvilar/projetoempresa/dto/adress/AddressCreateDto.java",
"snippet": "public class AddressCreateDto {\n\n\n private String addressName;\n private String addressNumber;\n private String complement;\n private String zipCode;\n private String city;\n private String state;\n private boolean requiresCollection;\n @NotBlank(message=\"An address must have a customer\")\n private String customerId;\n\n\n public AddressCreateDto() {\n\n }\n\n public AddressCreateDto(\n String addressName,\n String addressNumber,\n String complement,\n String zipCode,\n String city,\n String state,\n boolean requiresCollection,\n String customerId) {\n\n this.addressName = addressName;\n this.addressNumber = addressNumber;\n this.complement = complement;\n this.zipCode = zipCode;\n this.city = city;\n this.state = state;\n this.requiresCollection = requiresCollection;\n this.customerId = customerId;\n }\n\n\n //getters e setters - addressName\n public String getAddressName() {\n return addressName;\n }\n public void setAddressName(String addressName) {\n this.addressName = addressName;\n }\n //--------------\n\n //getters e setters - addressNumber\n public String getAddressNumber() {\n return addressNumber;\n }\n public void setAddressNumber(String addressNumber) {\n this.addressNumber = addressNumber;\n }\n //--------------\n\n //getters e setters - complement\n public String getComplement() {\n return complement;\n }\n public void setComplement(String complement) {\n this.complement = complement;\n }\n //--------------\n\n //getters e setters - requiredCollection\n public String getZipCode() {\n return zipCode;\n }\n public void setZipCode(String zipCode) {\n this.zipCode = zipCode;\n }\n //--------------\n\n //getters e setters - city\n public String getCity() {\n return city;\n }\n public void setCity(String city) {\n this.city = city;\n }\n //--------------\n\n //getters e setters - state\n public String getState() {\n return state;\n }\n public void setState(String state) {\n this.state = state;\n }\n //--------------\n\n //getters e setters - requiredCollection\n public boolean isRequiresCollection() {\n return requiresCollection;\n }\n public void setRequiresCollection(boolean requiresCollection) {\n this.requiresCollection = requiresCollection;\n }\n //--------------\n\n //getters and setters - customerId\n public String getCustomerId() {\n return customerId;\n }\n public void setCustomerId(String customerId) {\n this.customerId = customerId;\n }\n //--------------\n\n public static AddressCreateBuilder builder(){\n return new AddressCreateBuilder();\n }\n\n public static class AddressCreateBuilder{\n\n private String addressName;\n private String addressNumber;\n private String complement;\n private String zipCode;\n private String city;\n private String state;\n private boolean requiresCollection;\n private String customerId;\n\n public AddressCreateBuilder addressName(String addressName){\n this.addressName = addressName;\n return this;\n }\n\n public AddressCreateBuilder addressNumber(String addressNumber){\n this.addressNumber = addressNumber;\n return this;\n }\n\n public AddressCreateBuilder complement(String complement){\n this.complement = complement;\n return this;\n }\n\n public AddressCreateBuilder zipCode(String zipCode){\n this.zipCode = zipCode;\n return this;\n }\n\n public AddressCreateBuilder city(String city){\n this.city = city;\n return this;\n }\n\n public AddressCreateBuilder state(String state){\n this.state = state;\n return this;\n }\n\n public AddressCreateBuilder requiresCollection(boolean requiresCollection){\n this.requiresCollection = requiresCollection;\n return this;\n }\n\n public AddressCreateBuilder customerId(String customerId){\n this.customerId = customerId;\n return this;\n }\n\n public AddressCreateDto build(){\n AddressCreateDto address= new AddressCreateDto();\n address.setAddressName(this.addressName);\n address.setAddressNumber(this.addressNumber);\n address.setComplement(this.complement);\n address.setZipCode(this.zipCode);\n address.setCity(this.city);\n address.setState(this.state);\n address.setRequiresCollection(this.requiresCollection);\n address.setCustomerId(this.customerId);\n return address;\n }\n }\n\n\n}"
},
{
"identifier": "AddressResponseDto",
"path": "backend/src/main/java/com/victorvilar/projetoempresa/dto/adress/AddressResponseDto.java",
"snippet": "public class AddressResponseDto {\n\n private Long id;\n private String addressName;\n private String addressNumber;\n private String complement;\n private String zipCode;\n private String city;\n private String state;\n private String customerId;\n private boolean requiresCollection;\n\n public AddressResponseDto() {\n }\n\n public AddressResponseDto(Long id,String addressName, String addressNumber, String complement, String zipCode, String city, String state, String clientId, boolean requiresCollection) {\n this.addressName = addressName;\n this.addressNumber = addressNumber;\n this.complement = complement;\n this.zipCode = zipCode;\n this.city = city;\n this.state = state;\n this.customerId = clientId;\n this.id = id;\n this.requiresCollection = requiresCollection;\n }\n\n public Long getId() {\n return id;\n }\n\n public void setId(Long id) {\n this.id = id;\n }\n\n public String getAddressName() {\n return addressName;\n }\n\n public void setAddressName(String addressName) {\n this.addressName = addressName;\n }\n\n public String getAddressNumber() {\n return addressNumber;\n }\n\n public void setAddressNumber(String addressNumber) {\n this.addressNumber = addressNumber;\n }\n\n public String getComplement() {\n return complement;\n }\n\n public void setComplement(String complement) {\n this.complement = complement;\n }\n\n public String getZipCode() {\n return zipCode;\n }\n\n public void setZipCode(String zipCode) {\n this.zipCode = zipCode;\n }\n\n public String getCity() {\n return city;\n }\n\n public void setCity(String city) {\n this.city = city;\n }\n\n public String getState() {\n return state;\n }\n\n public void setState(String state) {\n this.state = state;\n }\n\n public String getCustomerId() {\n return customerId;\n }\n\n public void setCustomerId(String clientId) {\n this.customerId = clientId;\n }\n\n public boolean isRequiresCollection() {\n return requiresCollection;\n }\n\n public void setRequiresCollection(boolean requiresCollection) {\n this.requiresCollection = requiresCollection;\n }\n}"
},
{
"identifier": "AddressUpdateDto",
"path": "backend/src/main/java/com/victorvilar/projetoempresa/dto/adress/AddressUpdateDto.java",
"snippet": "public class AddressUpdateDto {\n\n @NotNull(message=\"An address to update must have an id\")\n private Long id;\n private String addressName;\n private String addressNumber;\n private String complement;\n private String zipCode;\n private String city;\n private String state;\n private boolean requiresCollection;\n @NotBlank(message=\"An address must have a customer\")\n private String customerId;\n\n public AddressUpdateDto() {\n }\n\n public AddressUpdateDto(Long id, String addressName, String addressNumber, String complement, String zipCode, String city, String state, boolean requiresCollection, String customerId) {\n this.id = id;\n this.addressName = addressName;\n this.addressNumber = addressNumber;\n this.complement = complement;\n this.zipCode = zipCode;\n this.city = city;\n this.state = state;\n this.requiresCollection = requiresCollection;\n this.customerId = customerId;\n }\n\n public Long getId() {\n return id;\n }\n\n public void setId(Long id) {\n this.id = id;\n }\n\n public String getAddressName() {\n return addressName;\n }\n\n public void setAddressName(String addressName) {\n this.addressName = addressName;\n }\n\n public String getAddressNumber() {\n return addressNumber;\n }\n\n public void setAddressNumber(String addressNumber) {\n this.addressNumber = addressNumber;\n }\n\n public String getComplement() {\n return complement;\n }\n\n public void setComplement(String complement) {\n this.complement = complement;\n }\n\n public String getZipCode() {\n return zipCode;\n }\n\n public void setZipCode(String zipCode) {\n this.zipCode = zipCode;\n }\n\n public String getCity() {\n return city;\n }\n\n public void setCity(String city) {\n this.city = city;\n }\n\n public String getState() {\n return state;\n }\n\n public void setState(String state) {\n this.state = state;\n }\n\n public boolean isRequiresCollection() {\n return requiresCollection;\n }\n\n public void setRequiresCollection(boolean requiresCollection) {\n this.requiresCollection = requiresCollection;\n }\n\n public String getCustomerId() {\n return customerId;\n }\n\n public void setCustomerId(String customerId) {\n this.customerId = customerId;\n }\n\n public AddressUpdateDtoBuilder builder(){\n return new AddressUpdateDtoBuilder();\n }\n\n public static class AddressUpdateDtoBuilder{\n\n private String addressName;\n private String addressNumber;\n private String complement;\n private String zipCode;\n private String city;\n private String state;\n private boolean requiresCollection;\n private String customerId;\n\n public AddressUpdateDtoBuilder addressName(String addressName){\n this.addressName = addressName;\n return this;\n }\n\n public AddressUpdateDtoBuilder addressNumber(String addressNumber){\n this.addressNumber = addressNumber;\n return this;\n }\n\n public AddressUpdateDtoBuilder complement(String complement){\n this.complement = complement;\n return this;\n }\n\n public AddressUpdateDtoBuilder zipCode(String zipCode){\n this.zipCode = zipCode;\n return this;\n }\n\n public AddressUpdateDtoBuilder city(String city){\n this.city = city;\n return this;\n }\n\n public AddressUpdateDtoBuilder state(String state){\n this.state = state;\n return this;\n }\n\n public AddressUpdateDtoBuilder requiresCollection(boolean requiresCollection){\n this.requiresCollection = requiresCollection;\n return this;\n }\n\n public AddressUpdateDtoBuilder customerId(String customerId){\n this.customerId = customerId;\n return this;\n }\n\n public AddressUpdateDto build(){\n AddressUpdateDto address= new AddressUpdateDto();\n address.setAddressName(this.addressName);\n address.setAddressNumber(this.addressNumber);\n address.setComplement(this.complement);\n address.setZipCode(this.zipCode);\n address.setCity(this.city);\n address.setState(this.state);\n address.setRequiresCollection(this.requiresCollection);\n address.setCustomerId(this.customerId);\n return address;\n }\n }\n\n}"
},
{
"identifier": "AddressService",
"path": "backend/src/main/java/com/victorvilar/projetoempresa/services/AddressService.java",
"snippet": "@Service\npublic class AddressService {\n\n private final AddressRepository addressRepository;\n private final AddressMapper addressMapper;\n private final CustomerService customerService;\n private final CustomerRepository customerRepository;\n\n @Autowired\n //constructor\n public AddressService(AddressRepository addressRepository, AddressMapper mapper, CustomerService customerService\n ,CustomerRepository customerRepository) {\n this.addressRepository = addressRepository;\n this.addressMapper = mapper;\n this.customerService = customerService;\n this.customerRepository = customerRepository;\n }\n //------------\n\n /**\n * get all address\n * @return all address\n */\n public List<AddressResponseDto> getAll(){\n return this.addressMapper.toAddressResponseDtoList(this.addressRepository.findAll());\n }\n\n /**\n * get all address of a client\n * @param clientId\n * @return\n */\n public List<AddressResponseDto> getAllByCustomerId(String clientId){\n return this.addressMapper.toAddressResponseDtoList(this.addressRepository.findByCustomerCpfCnpj(clientId));\n }\n\n /**\n * get a Address Object without mapping\n * @return Address Object\n */\n public Address findAddressById(Long id){\n return this.addressRepository.findById(id).orElseThrow(() -> new AddressNotFoundException(\"Address Not found\"));\n }\n\n /**\n * get an address by id\n * @param id\n * @return\n */\n public AddressResponseDto getById(Long id){\n return this.addressMapper.toAddressResponseDto(this.findAddressById(id));\n }\n\n /**\n * create a new address\n * @param addressCreateDto\n */\n public AddressResponseDto save(AddressCreateDto addressCreateDto){\n Address address = this.addressMapper.toAddress(addressCreateDto);\n Customer customer = this.customerService.findCustomerById(addressCreateDto.getCustomerId());\n customer.addNewAddress(address);\n return this.addressMapper.toAddressResponseDto(this.addressRepository.save(address));\n }\n\n\n /**\n * delete an address\n * @param id\n */\n public void delete(Long id){\n Address address = this.findAddressById(id);\n this.addressRepository.deleteById(id);\n }\n\n\n /**\n * update an address\n * @param addressUpdateDto\n * @return saved contract\n */\n public AddressResponseDto update(AddressUpdateDto addressUpdateDto){\n Address addressToUpdate = this.addressRepository.findById(addressUpdateDto.getId()).orElseThrow(() -> new AddressNotFoundException(\"Address Not found\"));\n addressToUpdate.setAddressName(addressUpdateDto.getAddressName());\n addressToUpdate.setAddressNumber(addressUpdateDto.getAddressNumber());\n addressToUpdate.setCity(addressUpdateDto.getCity());\n addressToUpdate.setComplement(addressUpdateDto.getComplement());\n addressToUpdate.setState(addressUpdateDto.getState());\n addressToUpdate.setZipCode(addressUpdateDto.getZipCode());\n addressToUpdate.setRequiresCollection(addressUpdateDto.isRequiresCollection());\n this.addressRepository.save(addressToUpdate);\n return this.addressMapper.toAddressResponseDto(addressToUpdate);\n }\n\n\n\n}"
}
] | import com.victorvilar.projetoempresa.dto.adress.AddressCreateDto;
import com.victorvilar.projetoempresa.dto.adress.AddressResponseDto;
import com.victorvilar.projetoempresa.dto.adress.AddressUpdateDto;
import com.victorvilar.projetoempresa.services.AddressService;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List; | 4,084 | package com.victorvilar.projetoempresa.controllers;
/**
* Address controller
* @author Victor Vilar
* @since 05/01/2023
*/
@RestController
@RequestMapping("/address")
public class AddressController {
private final AddressService addressService;
@Autowired
public AddressController(AddressService service){
this.addressService = service;
}
/**
* get all address
* @return list of address
*/
@GetMapping()
public ResponseEntity<List<AddressResponseDto>> getAll(){
return ResponseEntity.status(HttpStatus.OK).body(this.addressService.getAll());
}
/**
* get all address of a client
* @param clientId id of a client
* @return a list of address of a client
*/
@GetMapping("by-customer/{clientId}")
public ResponseEntity<List<AddressResponseDto>> getAllByCustomerId(@PathVariable String clientId){
return ResponseEntity.status(HttpStatus.OK).body(this.addressService.getAllByCustomerId(clientId));
}
/**
* get an address by id
* @param id
* @return address
*/
@GetMapping("/{id}")
public ResponseEntity<AddressResponseDto> getById(@PathVariable Long id){
return ResponseEntity.status(HttpStatus.OK).body(this.addressService.getById(id));
}
/**
* create a new addresss
* @param addressCreateDto address body to save
* @return saved address
*/
@PostMapping()
public ResponseEntity<AddressResponseDto> save(@Valid @RequestBody AddressCreateDto addressCreateDto){
return ResponseEntity.status(HttpStatus.OK).body(this.addressService.save(addressCreateDto));
}
/**
* delete an address
* @param id of an address
* @return
*/
@DeleteMapping("/{id}")
public ResponseEntity<?> delete(@PathVariable Long id){
this.addressService.delete(id);
return new ResponseEntity<>(HttpStatus.OK);
}
/**
* update an address
* @return
*/
@PutMapping() | package com.victorvilar.projetoempresa.controllers;
/**
* Address controller
* @author Victor Vilar
* @since 05/01/2023
*/
@RestController
@RequestMapping("/address")
public class AddressController {
private final AddressService addressService;
@Autowired
public AddressController(AddressService service){
this.addressService = service;
}
/**
* get all address
* @return list of address
*/
@GetMapping()
public ResponseEntity<List<AddressResponseDto>> getAll(){
return ResponseEntity.status(HttpStatus.OK).body(this.addressService.getAll());
}
/**
* get all address of a client
* @param clientId id of a client
* @return a list of address of a client
*/
@GetMapping("by-customer/{clientId}")
public ResponseEntity<List<AddressResponseDto>> getAllByCustomerId(@PathVariable String clientId){
return ResponseEntity.status(HttpStatus.OK).body(this.addressService.getAllByCustomerId(clientId));
}
/**
* get an address by id
* @param id
* @return address
*/
@GetMapping("/{id}")
public ResponseEntity<AddressResponseDto> getById(@PathVariable Long id){
return ResponseEntity.status(HttpStatus.OK).body(this.addressService.getById(id));
}
/**
* create a new addresss
* @param addressCreateDto address body to save
* @return saved address
*/
@PostMapping()
public ResponseEntity<AddressResponseDto> save(@Valid @RequestBody AddressCreateDto addressCreateDto){
return ResponseEntity.status(HttpStatus.OK).body(this.addressService.save(addressCreateDto));
}
/**
* delete an address
* @param id of an address
* @return
*/
@DeleteMapping("/{id}")
public ResponseEntity<?> delete(@PathVariable Long id){
this.addressService.delete(id);
return new ResponseEntity<>(HttpStatus.OK);
}
/**
* update an address
* @return
*/
@PutMapping() | public ResponseEntity<AddressResponseDto> update(@RequestBody AddressUpdateDto addressUpdateDto){ | 2 | 2023-12-02 21:29:33+00:00 | 8k |
aliyun/aliyun-pairec-config-java-sdk | src/main/java/com/aliyun/openservices/pairec/api/ExperimentRoomApi.java | [
{
"identifier": "Constants",
"path": "src/main/java/com/aliyun/openservices/pairec/common/Constants.java",
"snippet": "public class Constants {\n public static final String CODE_OK = \"OK\";\n public static final String Environment_Daily_Desc = \"daily\";\n public static final String Environment_Prepub_Desc = \"prepub\";\n\n public static final String Environment_Product_Desc = \"product\";\n\n public static int ExpRoom_Status_Offline = 1;\n public static int ExpRoom_Status_Online = 2;\n\n public static int ExpGroup_Status_Offline = 1;\n public static int ExpGroup_Status_Online = 2;\n\n public static final int ExpGroup_Distribution_Type_User = 1;\n\n public static final int ExpGroup_Distribution_Type_TimeDuration = 2;\n\n public static int Experiment_Status_Offline = 1;\n public static int Experiment_Status_Online = 2;\n\n public static int Bucket_Type_UID = 1;\n public static int Bucket_Type_UID_HASH = 2;\n public static int Bucket_Type_Custom = 3;\n public static int Bucket_Type_Filter = 4;\n\n public static int ExpRoom_Type_Base = 1;\n public static int ExpRoom_Type_Normal = 2;\n\n public static final int Experiment_Type_Base = 1;\n public static final int Experiment_Type_Test = 2;\n public static final int Experiment_Type_Default = 3;\n\n public static String environmentDesc2OpenApiString(String environment) {\n if (environment.equals(Environment_Daily_Desc)) {\n return \"Daily\";\n } else if (environment.equals(Environment_Prepub_Desc)) {\n return \"Pre\";\n } else if (environment.equals(Environment_Product_Desc)) {\n return \"Prod\";\n }\n\n return \"\";\n }\n\n}"
},
{
"identifier": "ExperimentRoom",
"path": "src/main/java/com/aliyun/openservices/pairec/model/ExperimentRoom.java",
"snippet": "public class ExperimentRoom {\n @SerializedName(\"exp_room_id\")\n private Long expRoomId = null;\n\n @SerializedName(\"scene_id\")\n private Long sceneId = null;\n\n @SerializedName(\"exp_room_name\")\n private String expRoomName = null;\n\n @SerializedName(\"exp_room_info\")\n private String expRoomInfo = null;\n\n @SerializedName(\"debug_users\")\n private String debugUsers = null;\n\n @SerializedName(\"bucket_count\")\n private Integer bucketCount = null;\n\n @SerializedName(\"exp_room_buckets\")\n private String expRoomBuckets = null;\n\n @SerializedName(\"bucket_type\")\n private Integer bucketType = null;\n\n @SerializedName(\"filter\")\n private String filter = null;\n\n @SerializedName(\"exp_room_config\")\n private String expRoomConfig = null;\n\n @SerializedName(\"environment\")\n private String environment = null;\n\n @SerializedName(\"type\")\n private Integer type = null;\n\n @SerializedName(\"status\")\n private Integer status = null;\n\n private Integer debugCrowdId = null;\n\n private List<String> debugCrowdIdUsers = null;\n private Map<String, Boolean> debugUserMap = new HashMap<>();\n\n DiversionBucket diversionBucket = null;\n\n private List<Layer> layerList = new ArrayList<>();\n\n public ExperimentRoom expRoomId(Long expRoomId) {\n this.expRoomId = expRoomId;\n return this;\n }\n\n /**\n * Get expRoomId\n *\n * @return expRoomId\n **/\n public Long getExpRoomId() {\n return expRoomId;\n }\n\n public void setExpRoomId(Long expRoomId) {\n this.expRoomId = expRoomId;\n }\n\n public ExperimentRoom sceneId(Long sceneId) {\n this.sceneId = sceneId;\n return this;\n }\n\n /**\n * Get sceneId\n *\n * @return sceneId\n **/\n public Long getSceneId() {\n return sceneId;\n }\n\n public void setSceneId(Long sceneId) {\n this.sceneId = sceneId;\n }\n\n public ExperimentRoom expRoomName(String expRoomName) {\n this.expRoomName = expRoomName;\n return this;\n }\n\n /**\n * Get expRoomName\n *\n * @return expRoomName\n **/\n public String getExpRoomName() {\n return expRoomName;\n }\n\n public void setExpRoomName(String expRoomName) {\n this.expRoomName = expRoomName;\n }\n\n public ExperimentRoom expRoomInfo(String expRoomInfo) {\n this.expRoomInfo = expRoomInfo;\n return this;\n }\n\n /**\n * Get expRoomInfo\n *\n * @return expRoomInfo\n **/\n public String getExpRoomInfo() {\n return expRoomInfo;\n }\n\n public void setExpRoomInfo(String expRoomInfo) {\n this.expRoomInfo = expRoomInfo;\n }\n\n public ExperimentRoom debugUsers(String debugUsers) {\n this.debugUsers = debugUsers;\n return this;\n }\n\n /**\n * Get debugUsers\n *\n * @return debugUsers\n **/\n public String getDebugUsers() {\n return debugUsers;\n }\n\n public void setDebugUsers(String debugUsers) {\n this.debugUsers = debugUsers;\n }\n\n public ExperimentRoom bucketCount(Integer bucketCount) {\n this.bucketCount = bucketCount;\n return this;\n }\n\n /**\n * Get bucketCount\n *\n * @return bucketCount\n **/\n public Integer getBucketCount() {\n return bucketCount;\n }\n\n public void setBucketCount(Integer bucketCount) {\n this.bucketCount = bucketCount;\n }\n\n public ExperimentRoom expRoomBuckets(String expRoomBuckets) {\n this.expRoomBuckets = expRoomBuckets;\n return this;\n }\n\n /**\n * Get expRoomBuckets\n *\n * @return expRoomBuckets\n **/\n public String getExpRoomBuckets() {\n return expRoomBuckets;\n }\n\n public void setExpRoomBuckets(String expRoomBuckets) {\n this.expRoomBuckets = expRoomBuckets;\n }\n\n public ExperimentRoom bucketType(Integer bucketType) {\n this.bucketType = bucketType;\n return this;\n }\n\n /**\n * Get bucketType\n *\n * @return bucketType\n **/\n public Integer getBucketType() {\n return bucketType;\n }\n\n public void setBucketType(Integer bucketType) {\n this.bucketType = bucketType;\n }\n\n public ExperimentRoom filter(String filter) {\n this.filter = filter;\n return this;\n }\n\n /**\n * Get filter\n *\n * @return filter\n **/\n public String getFilter() {\n return filter;\n }\n\n public void setFilter(String filter) {\n this.filter = filter;\n }\n\n public ExperimentRoom expRoomConfig(String expRoomConfig) {\n this.expRoomConfig = expRoomConfig;\n return this;\n }\n\n /**\n * Get expRoomConfig\n *\n * @return expRoomConfig\n **/\n public String getExpRoomConfig() {\n return expRoomConfig;\n }\n\n public void setExpRoomConfig(String expRoomConfig) {\n this.expRoomConfig = expRoomConfig;\n }\n\n public ExperimentRoom environment(String environment) {\n this.environment = environment;\n return this;\n }\n\n /**\n * Get environment\n *\n * @return environment\n **/\n public String getEnvironment() {\n return environment;\n }\n\n public void setEnvironment(String environment) {\n this.environment = environment;\n }\n\n public ExperimentRoom type(Integer type) {\n this.type = type;\n return this;\n }\n\n /**\n * Get type\n *\n * @return type\n **/\n public Integer getType() {\n return type;\n }\n\n public void setType(Integer type) {\n this.type = type;\n }\n\n public ExperimentRoom status(Integer status) {\n this.status = status;\n return this;\n }\n\n /**\n * Get status\n *\n * @return status\n **/\n public Integer getStatus() {\n return status;\n }\n\n public void setStatus(Integer status) {\n this.status = status;\n }\n\n public Integer getDebugCrowdId() {\n return debugCrowdId;\n }\n\n public void setDebugCrowdId(Integer debugCrowdId) {\n this.debugCrowdId = debugCrowdId;\n }\n\n public List<String> getDebugCrowdIdUsers() {\n return debugCrowdIdUsers;\n }\n\n public void setDebugCrowdIdUsers(List<String> debugCrowdIdUsers) {\n this.debugCrowdIdUsers = debugCrowdIdUsers;\n }\n\n @Override\n public boolean equals(java.lang.Object o) {\n if (this == o) {\n return true;\n }\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n ExperimentRoom experimentRoom = (ExperimentRoom) o;\n return Objects.equals(this.expRoomId, experimentRoom.expRoomId) &&\n Objects.equals(this.sceneId, experimentRoom.sceneId) &&\n Objects.equals(this.expRoomName, experimentRoom.expRoomName) &&\n Objects.equals(this.expRoomInfo, experimentRoom.expRoomInfo) &&\n Objects.equals(this.debugUsers, experimentRoom.debugUsers) &&\n Objects.equals(this.bucketCount, experimentRoom.bucketCount) &&\n Objects.equals(this.expRoomBuckets, experimentRoom.expRoomBuckets) &&\n Objects.equals(this.bucketType, experimentRoom.bucketType) &&\n Objects.equals(this.filter, experimentRoom.filter) &&\n Objects.equals(this.expRoomConfig, experimentRoom.expRoomConfig) &&\n Objects.equals(this.environment, experimentRoom.environment) &&\n Objects.equals(this.type, experimentRoom.type) &&\n Objects.equals(this.debugCrowdId, experimentRoom.debugCrowdId) &&\n Objects.equals(this.debugCrowdIdUsers, experimentRoom.debugCrowdIdUsers) &&\n Objects.equals(this.status, experimentRoom.status);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(expRoomId, sceneId, expRoomName, expRoomInfo, debugUsers, bucketCount, expRoomBuckets, bucketType, filter, expRoomConfig, environment,\n type, status, debugCrowdId, debugCrowdIdUsers);\n }\n\n\n @Override\n public String toString() {\n StringBuilder sb = new StringBuilder();\n sb.append(\"class ExperimentRoom {\\n\");\n\n sb.append(\" expRoomId: \").append(toIndentedString(expRoomId)).append(\"\\n\");\n sb.append(\" sceneId: \").append(toIndentedString(sceneId)).append(\"\\n\");\n sb.append(\" expRoomName: \").append(toIndentedString(expRoomName)).append(\"\\n\");\n sb.append(\" expRoomInfo: \").append(toIndentedString(expRoomInfo)).append(\"\\n\");\n sb.append(\" debugUsers: \").append(toIndentedString(debugUsers)).append(\"\\n\");\n sb.append(\" bucketCount: \").append(toIndentedString(bucketCount)).append(\"\\n\");\n sb.append(\" expRoomBuckets: \").append(toIndentedString(expRoomBuckets)).append(\"\\n\");\n sb.append(\" bucketType: \").append(toIndentedString(bucketType)).append(\"\\n\");\n sb.append(\" filter: \").append(toIndentedString(filter)).append(\"\\n\");\n sb.append(\" expRoomConfig: \").append(toIndentedString(expRoomConfig)).append(\"\\n\");\n sb.append(\" environment: \").append(toIndentedString(environment)).append(\"\\n\");\n sb.append(\" type: \").append(toIndentedString(type)).append(\"\\n\");\n sb.append(\" status: \").append(toIndentedString(status)).append(\"\\n\");\n sb.append(\" debugCrowdId: \").append(toIndentedString(debugCrowdId)).append(\"\\n\");\n sb.append(\" debugCrowdIdUsers: \").append(toIndentedString(debugCrowdIdUsers)).append(\"\\n\");\n sb.append(\"}\");\n return sb.toString();\n }\n\n /**\n * Convert the given object to string with each line indented by 4 spaces\n * (except the first line).\n */\n private String toIndentedString(java.lang.Object o) {\n if (o == null) {\n return \"null\";\n }\n return o.toString().replace(\"\\n\", \"\\n \");\n }\n\n /**\n * Experiment Room init function\n */\n public void init() {\n if (!StringUtils.isEmpty(this.debugUsers)) {\n String[] users = this.debugUsers.split(\",\");\n for (String user : users) {\n this.debugUserMap.put(user, true);\n }\n }\n if (this.debugCrowdIdUsers != null && this.debugCrowdIdUsers.size() > 0) {\n for(String user : this.debugCrowdIdUsers) {\n this.debugUserMap.put(user, true);\n }\n }\n\n if (diversionBucket == null) {\n if (bucketType == Constants.Bucket_Type_UID) {\n diversionBucket = new UidDiversionBucket(this.bucketCount, this.expRoomBuckets);\n } else if (bucketType == Constants.Bucket_Type_UID_HASH) {\n diversionBucket = new UidHashDiversionBucket(this.bucketCount, this.expRoomBuckets);\n } else if (bucketType == Constants.Bucket_Type_Custom) {\n diversionBucket = new CustomDiversionBucket();\n } else if (bucketType == Constants.Bucket_Type_Filter) {\n diversionBucket = new FilterDiversionBucket(this.filter);\n }\n }\n }\n\n public void addLayer(Layer layer) {\n this.layerList.add(layer);\n }\n\n public boolean matchDebugUsers(ExperimentContext experimentContext) {\n return this.debugUserMap.containsKey(experimentContext.getUid());\n }\n public boolean match(ExperimentContext experimentContext) {\n if (this.debugUserMap.containsKey(experimentContext.getUid())) {\n return true;\n }\n\n if (null != this.diversionBucket) {\n return this.diversionBucket.match(experimentContext);\n }\n return false;\n }\n\n public List<Layer> getLayerList() {\n return layerList;\n }\n}"
}
] | import com.aliyun.openservices.pairec.common.Constants;
import com.aliyun.openservices.pairec.model.ExperimentRoom;
import com.aliyun.pairecservice20221213.models.ListLaboratoriesRequest;
import com.aliyun.pairecservice20221213.models.ListLaboratoriesResponse;
import com.aliyun.pairecservice20221213.models.ListLaboratoriesResponseBody;
import com.aliyun.tea.utils.StringUtils;
import java.util.ArrayList;
import java.util.List; | 3,655 | package com.aliyun.openservices.pairec.api;
public class ExperimentRoomApi extends BaseApi {
public ExperimentRoomApi(ApiClient apiClient) {
super(apiClient);
}
| package com.aliyun.openservices.pairec.api;
public class ExperimentRoomApi extends BaseApi {
public ExperimentRoomApi(ApiClient apiClient) {
super(apiClient);
}
| public List<ExperimentRoom> listExperimentRooms(String environment, Long sceneId, Integer status) throws Exception { | 1 | 2023-11-29 06:27:36+00:00 | 8k |
bioastroiner/Minetweaker-Gregtech6-Addon | src/main/java/mods/bio/gttweaker/mods/minetweaker/CTIOreDictExpansion.java | [
{
"identifier": "IMaterialData",
"path": "src/main/java/mods/bio/gttweaker/api/mods/gregtech/oredict/IMaterialData.java",
"snippet": "@ZenClass(\"mods.gregtech.oredict.IMaterialData\")\npublic interface IMaterialData {\n\t@ZenMethod\n\tpublic static IMaterialData association(IItemStack item) {\n\t\tOreDictItemData data = OreDictManager.INSTANCE.getAssociation(MineTweakerMC.getItemStack(item), F);\n\t\tif (data != null) return new CTMaterialData(data);\n\t\tMineTweakerAPI.logError(item + \" dose not have a GT Association!\");\n\t\treturn null;\n\t}\n\n\t@ZenMethod\n\tpublic static IMaterialData association(ILiquidStack iLiquidStack) {\n\t\tOreDictMaterialStack stack = OreDictMaterial.FLUID_MAP.get(MineTweakerMC.getLiquidStack(iLiquidStack).getFluid().getName());\n\t\tif (stack != null) {\n\t\t\tOreDictItemData data = new OreDictItemData(stack);\n\t\t\treturn new CTMaterialData(data);\n\t\t}\n\t\tMineTweakerAPI.logError(iLiquidStack + \" dose not have a GT Association!\");\n\t\treturn null;\n\t}\n\n\t@ZenMethod\n\tpublic static IMaterialData association(IOreDictEntry ore) {\n\t\tOreDictItemData data = OreDictManager.INSTANCE.getAutomaticItemData(ore.getName());\n\t\tif (data != null) return new CTMaterialData(data);\n\t\tMineTweakerAPI.logError(ore + \" dose not have a GT Association!\");\n\t\treturn null;\n\t}\n\n\t@ZenGetter\n\tIMaterialStack material();\n\n\t@ZenGetter\n\tIPrefix prefix();\n\n\t@ZenGetter\n\tList<IMaterialStack> byProducts();\n\n\t@ZenGetter\n\tList<IMaterialStack> materials();\n}"
},
{
"identifier": "IPrefix",
"path": "src/main/java/mods/bio/gttweaker/api/mods/gregtech/oredict/IPrefix.java",
"snippet": "public interface IPrefix {\n\t@ZenGetter\n\tlong amount();\n\n\t@ZenMethod\n\tIItemStack withMaterial(IMaterial aMaterial);\n\n\t@ZenMethod\n\tIItemStack mat(IMaterial aMaterial);\n\n\t@ZenMethod\n\tIItemStack material(IMaterial aMaterial);\n\n\t@ZenMethod\n\tIPrefix disableItemGeneration();\n\n\t@ZenMethod\n\tIPrefix forceItemGeneration();\n\n\t@ZenMethod\n\tboolean contains(IItemStack aIItemStack);\n\n\t@ZenMethod\n\tboolean contains(IItemStack... aIItemStacks);\n\n\t@ZenMethod\n\t\t// TODO there is more to this visit later, but it's rather ready for production\n\tIPrefix contains(int stackSize);\n\n\t// TODO: to be implemented\n\tboolean contains(IOreDictEntry aIOreDictEntry);\n}"
},
{
"identifier": "CTMaterial",
"path": "src/main/java/mods/bio/gttweaker/mods/gregtech/oredict/CTMaterial.java",
"snippet": "public class CTMaterial implements mods.bio.gttweaker.api.mods.gregtech.oredict.IMaterial {\n\tprivate final OreDictMaterial material_internal;\n\n\t@Override\n\tpublic OreDictMaterial getMaterial(){\n\t\treturn material_internal;\n\t}\n\n\t@Override\n\tpublic IMaterialStack multiply(long amount) {\n\t\treturn new CTMaterialStack(new OreDictMaterialStack(getMaterial(),amount));\n\t}\n\n\tpublic CTMaterial(OreDictMaterial aMaterial){\n\t\tif (aMaterial == null){\n\t\t\tMineTweakerAPI.logError(\"Null Material was provided unable to create a new <material:>\");\n\t\t}\n\t\tmaterial_internal = aMaterial;\n\t}\n\n\t/**\n\t * @return formatted string as it is formatted in bracketHandler\n\t */\n\t@Override\n\tpublic String toString() {\n\t\treturn String.format(\"<material:%s>\",material_internal.mNameInternal);\n\t}\n\n\t@Override\n\tpublic boolean equals(Object o) {\n\t\tif (this == o) return true;\n\t\tif (o == null || getClass() != o.getClass()) return false;\n\t\tCTMaterial that = (CTMaterial) o;\n\t\treturn Objects.equals(material_internal, that.material_internal);\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn Objects.hash(material_internal);\n\t}\n}"
},
{
"identifier": "CTMaterialData",
"path": "src/main/java/mods/bio/gttweaker/mods/gregtech/oredict/CTMaterialData.java",
"snippet": "public class CTMaterialData implements mods.bio.gttweaker.api.mods.gregtech.oredict.IMaterialData {\n\tpublic final OreDictItemData backingData;\n\t@Override\n\t@ZenGetter\n\tpublic IMaterialStack material(){\n\t\tif(backingData.mMaterial != null) return new CTMaterialStack(backingData.mMaterial);\n\t\tMineTweakerAPI.logError(this + \" dose not have any Main Material\");\n\t\treturn null;\n\t}\n\t@Override\n\t@ZenGetter\n\tpublic IPrefix prefix(){\n\t\tif(backingData.mPrefix != null) return new CTPrefix(backingData.mPrefix);\n\t\tMineTweakerAPI.logError(this + \" dose not have any GT prefix\");\n\t\treturn null;\n\t}\n\t@Override\n\tpublic List<IMaterialStack> byProducts(){\n\t\tif(backingData.mByProducts.length < 1) {\n\t\t\tMineTweakerAPI.logError(this + \" dose not have any GT byproduct\");\n\t\t\treturn new ArrayList<>();\n\t\t}\n\t\treturn Arrays.stream(backingData.mByProducts).map(CTMaterialStack::new).collect(Collectors.toList());\n\t}\n\t@Override\n\t@ZenGetter\n\tpublic List<IMaterialStack> materials(){\n\t\tList<IMaterialStack> list = new ArrayList<>();\n\t\tlist.add(material());\n\t\tlist.addAll(byProducts());\n\t\treturn list;\n\t}\n\n\tpublic CTMaterialData(OreDictItemData backingData) {\n\t\tthis.backingData = backingData;\n\t\tif(backingData==null) {\n\t\t\tMineTweakerAPI.logError(\"Material Data cannot be null\",new NullPointerException(\"Not a valid Material Data.\"));\n\t\t}\n\t}\n\n\t/**\n\t * @return a very JSON like CTMaterialData Representation tough it's not ready for json parsing at all\n\t * but is human readable.\n\t * {\n\t * MainMaterial: <material:name> * amount U ,\n\t * ByProducts: [\n\t * 1: <material:name> * amount U,\n\t * 2 :<material:name> * amount U,\n\t * 3: <material:name> * amount U\n\t * ]\n\t * }\n\t *\n\t */\n\t@Override\n\tpublic String toString() {\n\t\tStringBuilder builder = new StringBuilder();\n\t\tif(material() != null) builder.append(\"{MainMaterial:\").append(material());\n\t\telse builder.append(\"{NULL\");\n\t\tList<IMaterialStack> list = byProducts();\n\t\tif(!list.isEmpty()) builder.append(\",ByProducts:[\");\n\t\tlist.forEach(s->builder.append(String.format(\"%d: %s,\",list.indexOf(s),s)));\n\t\tif (!list.isEmpty()) builder.reverse().deleteCharAt(0).reverse().append(\"]}\");\n\t\treturn builder.toString();\n\t}\n}"
},
{
"identifier": "CTPrefix",
"path": "src/main/java/mods/bio/gttweaker/mods/gregtech/oredict/CTPrefix.java",
"snippet": "@ZenClass(\"mods.gregtech.oredict.Prefix\")\npublic class CTPrefix implements mods.bio.gttweaker.api.mods.gregtech.oredict.IPrefix {\n\tpublic final OreDictPrefix prefix_internal;\n\n\tpublic CTPrefix(OreDictPrefix aPrefix) {\n\t\tprefix_internal = aPrefix;\n\t}\n\n\t/**\n\t * @return formatted string as it is formatted in bracketHandler\n\t */\n\t@Override\n\tpublic String toString() {\n\t\treturn String.format(\"<prefix:%s>\", prefix_internal.mNameInternal);\n\t}\n\n\t@Override\n\tpublic boolean equals(Object o) {\n\t\tif (this == o) return true;\n\t\tif (o == null || getClass() != o.getClass()) return false;\n\t\tCTPrefix ctPrefix = (CTPrefix) o;\n\t\treturn Objects.equals(prefix_internal, ctPrefix.prefix_internal);\n\t}\n\n\t@Override\n\tpublic int hashCode() {\n\t\treturn Objects.hash(prefix_internal);\n\t}\n\n\t/* GETTERS */\n\n\t/**\n\t * @return gets a qualified amount on terms of U, its a float TODO we need to work on Unit System and make it a bit unified\n\t */\n\t@Override\n\t@ZenGetter\n\tpublic long amount() {\n\t\treturn prefix_internal.mAmount;\n\t}\n\n\t/* METHODS */\n\n\t@Override\n\t@ZenMethod\n\tpublic IItemStack withMaterial(IMaterial aMaterial) {\n\t\tIItemStack aStack = MineTweakerMC.getIItemStack(prefix_internal.mat(aMaterial.getMaterial(), 1));\n\t\tif (aStack == null)\n\t\t\tMineTweakerAPI.logError(String.format(\"%s dose not return a valid Item in %s.\", aMaterial, this));\n\t\treturn aStack;\n\t}\n\n\t@Override\n\t@ZenMethod\n\tpublic IItemStack mat(IMaterial aMaterial) {\n\t\treturn withMaterial(aMaterial);\n\t}\n\n\t@Override\n\t@ZenMethod\n\tpublic IItemStack material(IMaterial aMaterial) {\n\t\treturn withMaterial(aMaterial);\n\t}\n\n\t@Override\n\t@ZenMethod\n\tpublic IPrefix disableItemGeneration() {\n\t\tprefix_internal.disableItemGeneration();\n\t\tMineTweakerAPI.logInfo(String.format(\"ItemGeneration for %s has been disabled.\", this));\n\t\treturn this;\n\t}\n\n\t@Override\n\t@ZenMethod\n\tpublic IPrefix forceItemGeneration() {\n\t\tprefix_internal.forceItemGeneration();\n\t\tMineTweakerAPI.logInfo(String.format(\"ItemGeneration for %s has been Forced to be generated.\", this));\n\t\treturn this;\n\t}\n\n\t@Override\n\t@ZenMethod\n\tpublic boolean contains(IItemStack aIItemStack) {\n\t\treturn prefix_internal.contains(MineTweakerMC.getItemStack(aIItemStack));\n\t}\n\n\t@Override\n\t@ZenMethod\n\tpublic boolean contains(IItemStack... aIItemStacks) {\n\t\treturn prefix_internal.contains(MineTweakerMC.getItemStacks(aIItemStacks));\n\t}\n\n\t@Override\n\t@ZenMethod\n\t// TODO there is more to this visit later, but it's rather ready for production\n\tpublic IPrefix contains(int stackSize) {\n\t\tMineTweakerAPI.logInfo(String.format(\"New StackSize has been set for %s from %d to %d\", this, prefix_internal.mDefaultStackSize, stackSize));\n\t\tprefix_internal.setStacksize(stackSize);\n\t\treturn this;\n\t}\n\n\t// TODO: to be implemented\n\t@Override\n\tpublic boolean contains(IOreDictEntry aIOreDictEntry) {\n\t\treturn false;\n\t}\n\n}"
},
{
"identifier": "CTUnifier",
"path": "src/main/java/mods/bio/gttweaker/mods/gregtech/oredict/CTUnifier.java",
"snippet": "@ZenClass(\"mods.gregtech.oredict.Unifier\")\n// TODO: Zen Expansion for IOreDict#unify\npublic class CTUnifier {\n\tpublic static final Map<ItemStackContainer, OreDictItemData> REMOVED_DATA = new HashMap<>();\n\n\t@ZenGetter\n\tpublic static long U() {\n\t\treturn U;\n\t}\n\n\t@ZenMethod(\"unify\")\n\tpublic static IItemStack unifyItem(IOreDictEntry ore) {\n\t\treturn MineTweakerMC.getIItemStack(OreDictManager.INSTANCE.getStack(ore.getName(), ore.getAmount()));\n\t}\n\n\t@ZenMethod(\"unify\")\n\tpublic static IItemStack unifyItem(IItemStack stack) {\n\t\treturn MineTweakerMC.getIItemStack(OreDictManager.INSTANCE.getStack(T, MineTweakerMC.getItemStack(stack)));\n\t}\n\n\tpublic static boolean removeItemData(ItemStack aStack) {\n\t\tMap<ItemStackContainer, OreDictItemData> sItemStack2DataMap = null;\n\t\ttry {\n\t\t\tsItemStack2DataMap = (Map<ItemStackContainer, OreDictItemData>) UT.Reflection.getField(OreDictManager.INSTANCE, \"sItemStack2DataMap\", true, true).get(OreDictManager.INSTANCE);\n\t\t} catch (Exception e) {\n\t\t\tMineTweakerAPI.logError(String.format(\"Unexpected Exception at removing ItemData for %s: \", MineTweakerMC.getIItemStack(aStack)),e);\n\t\t}\n\t\tOreDictItemData rData = null;\n\t\tItemStackContainer container = new ItemStackContainer(aStack);\n\t\tif (sItemStack2DataMap == null) return F;\n\t\trData = sItemStack2DataMap.get(container);\n\t\tif (rData == null) container = new ItemStackContainer(aStack, W);\n\t\trData = sItemStack2DataMap.get(container);\n\t\tif (rData == null && aStack.getItem().isDamageable()) {\n\t\t\tcontainer = new ItemStackContainer(aStack, 0);\n\t\t\trData = sItemStack2DataMap.get(container);\n\t\t}\n\t\tif (rData != null) {\n\t\t\tREMOVED_DATA.put(container, rData);\n\t\t\tsItemStack2DataMap.remove(container);\n\t\t\treturn true;\n\t\t}\n\t\tMineTweakerAPI.logError(String.format(\"%s dose not have Any Associated Material contained.\", MineTweakerMC.getIItemStack(aStack)));\n\t\treturn false;\n\t}\n\n\t@ZenMethod\n\tpublic static boolean remove(IItemStack aStack) {\n\t\treturn removeItemData(MineTweakerMC.getItemStack(aStack));\n\t}\n\n\t// removes recycling for an itemstack without wiping its oredict material info\n\t@ZenMethod(\"removeRecycling\")\n\tpublic static boolean removeRecyclingCT(IItemStack aStack) {\n\t\treturn removeRecycling(MineTweakerMC.getItemStack(aStack));\n\t}\n\n\tpublic static boolean removeRecycling(ItemStack aStack) {\n\t\treturn new CTRecipeMap(RM.Smelter).removeRecipeCT(MineTweakerMC.getIItemStacks(aStack)) || new CTRecipeMap(RM.Mortar).removeRecipeCT(MineTweakerMC.getIItemStacks(aStack));\n\t}\n}"
}
] | import gregapi.oredict.OreDictManager;
import minetweaker.api.item.IItemStack;
import minetweaker.api.oredict.IOreDictEntry;
import mods.bio.gttweaker.api.mods.gregtech.oredict.IMaterialData;
import mods.bio.gttweaker.api.mods.gregtech.oredict.IPrefix;
import mods.bio.gttweaker.mods.gregtech.oredict.CTMaterial;
import mods.bio.gttweaker.mods.gregtech.oredict.CTMaterialData;
import mods.bio.gttweaker.mods.gregtech.oredict.CTPrefix;
import mods.bio.gttweaker.mods.gregtech.oredict.CTUnifier;
import stanhebben.zenscript.annotations.ZenExpansion;
import stanhebben.zenscript.annotations.ZenGetter; | 3,761 | package mods.bio.gttweaker.mods.minetweaker;
@ZenExpansion("minetweaker.oredict.IOreDictEntry")
public class CTIOreDictExpansion {
@ZenGetter
public static IItemStack unified(IOreDictEntry oreDictEntry){
return CTUnifier.unifyItem(oreDictEntry);
}
@ZenGetter
public static CTMaterial material(IOreDictEntry oreDictEntry){
return new CTMaterial(OreDictManager.INSTANCE.getAutomaticItemData(oreDictEntry.getName()).mMaterial.mMaterial);
}
@ZenGetter
public static IPrefix prefix(IOreDictEntry oreDictEntry){ | package mods.bio.gttweaker.mods.minetweaker;
@ZenExpansion("minetweaker.oredict.IOreDictEntry")
public class CTIOreDictExpansion {
@ZenGetter
public static IItemStack unified(IOreDictEntry oreDictEntry){
return CTUnifier.unifyItem(oreDictEntry);
}
@ZenGetter
public static CTMaterial material(IOreDictEntry oreDictEntry){
return new CTMaterial(OreDictManager.INSTANCE.getAutomaticItemData(oreDictEntry.getName()).mMaterial.mMaterial);
}
@ZenGetter
public static IPrefix prefix(IOreDictEntry oreDictEntry){ | return new CTPrefix(OreDictManager.INSTANCE.getAutomaticItemData(oreDictEntry.getName()).mPrefix); | 4 | 2023-12-03 11:55:49+00:00 | 8k |
ariel-mitchell/404-found | server/src/main/java/org/launchcode/fourohfourfound/finalproject/controllers/ApiController.java | [
{
"identifier": "CharacterDTO",
"path": "server/src/main/java/org/launchcode/fourohfourfound/finalproject/dtos/CharacterDTO.java",
"snippet": "@Valid\npublic class CharacterDTO {\n\n @NotNull(message = \"Owner ID cannot be null\")\n private int ownerId;\n\n @NotNull(message = \"Choose a name for your character\")\n @Size(min = 3, max = 50, message = \"Character name must be between 3 and 50 characters\")\n @NotBlank(message = \"Choose a name for your character\")\n private String characterName;\n\n @NotBlank(message = \"Choose an alignment\")\n @Size(min = 3, max = 50, message = \"Alignment must be between 3 and 50 characters\")\n @NotNull(message = \"Choose an alignment\")\n private String alignment;\n\n @NotNull(message = \"Choose a class from the list\")\n @NotBlank(message = \"Choose a class from the list\")\n private String characterClass;\n\n @NotNull(message = \"Choose a race\")\n @NotBlank\n private String race;\n\n @NotBlank(message = \"Enter a custom background\")\n @Size(max = 1000)\n private String background;\n private String proficiencyOne;\n private String proficiencyTwo;\n private String spellOne;\n private String spellTwo;\n private String armorChoice;\n private String magicArmor;\n private String weapon;\n private String magicWeapon;\n private String equipment;\n private String treasure;\n\n public CharacterDTO( int ownerId,\n String characterName, String alignment,\n String characterClass, String race,\n String background, String proficiencyOne, String proficiencyTwo,\n String spellOne,String spellTwo,String weapon,\n String magicWeapon, String armorChoice, String magicArmor,\n String equipment, String treasure) {\n\n this.ownerId = ownerId;\n this.characterName = characterName;\n this.alignment = alignment;\n this.characterClass = characterClass;\n this.race = race;\n this.background = background;\n this.proficiencyOne = proficiencyOne;\n this.proficiencyTwo = proficiencyTwo;\n this.spellOne = spellOne;\n this.spellTwo = spellTwo;\n this.weapon = weapon;\n this.magicWeapon = magicWeapon;\n this.armorChoice = armorChoice;\n this.magicArmor = magicArmor;\n this.equipment = equipment;\n this.treasure = treasure;\n\n }\n\n public CharacterDTO() {\n }\n\n public int getOwnerId() {\n return ownerId;\n }\n\n public void setOwnerId(int ownerId) {\n this.ownerId = ownerId;\n }\n\n public String getCharacterName() {\n return characterName;\n }\n\n public void setCharacterName(String characterName) {\n this.characterName = characterName;\n }\n\n public String getAlignment() {\n return alignment;\n }\n\n public void setAlignment(String alignment) {\n this.alignment = alignment;\n }\n\n public String getCharacterClass() {\n return characterClass;\n }\n\n public void setCharacterClass(String characterClass) {\n this.characterClass = characterClass;\n }\n\n public String getRace() {\n return race;\n }\n\n public void setRace(String race) {\n this.race = race;\n }\n\n public String getBackground() {\n return background;\n }\n\n public void setBackground(String background) {\n this.background = background;\n }\n\n public String getProficiencyOne() {\n return proficiencyOne;\n }\n\n public void setProficiencyOne(String proficiencyOne) {\n this.proficiencyOne = proficiencyOne;\n }\n\n public String getProficiencyTwo() {\n return proficiencyTwo;\n }\n\n public void setProficiencyTwo(String proficiencyTwo) {\n this.proficiencyTwo = proficiencyTwo;\n }\n\n public String getSpellOne() {\n return spellOne;\n }\n\n public void setSpellOne(String spellOne) {\n this.spellOne = spellOne;\n }\n\n public String getSpellTwo() {\n return spellTwo;\n }\n\n public void setSpellTwo(String spellTwo) {\n this.spellTwo = spellTwo;\n }\n\n public String getArmorChoice() {\n return armorChoice;\n }\n\n public void setArmorChoice(String armorChoice) {\n this.armorChoice = armorChoice;\n }\n\n public String getMagicArmor() {\n return magicArmor;\n }\n\n public void setMagicArmor(String magicArmor) {\n this.magicArmor = magicArmor;\n }\n\n public String getWeapon() {\n return weapon;\n }\n\n public void setWeapon(String weapon) {\n this.weapon = weapon;\n }\n\n public String getMagicWeapon() {\n return magicWeapon;\n }\n\n public void setMagicWeapon(String magicWeapon) {\n this.magicWeapon = magicWeapon;\n }\n\n public String getEquipment() {\n return equipment;\n }\n\n public void setEquipment(String equipment) {\n this.equipment = equipment;\n }\n\n public String getTreasure() {\n return treasure;\n }\n\n public void setTreasure(String treasure) {\n this.treasure = treasure;\n }\n}"
},
{
"identifier": "LoginFormDTO",
"path": "server/src/main/java/org/launchcode/fourohfourfound/finalproject/dtos/LoginFormDTO.java",
"snippet": "public class LoginFormDTO {\n @NotNull\n @NotBlank\n private String username;\n\n @NotNull\n @NotBlank\n @Size(min = 2, max = 30, message = \"Invalid password. Must be between 2 and 30 characters.\")\n private String password;\n\n\n public String getUsername() {\n return username;\n }\n\n public void setUsername(String username) {\n this.username = username;\n }\n\n\n public String getPassword() {\n return password;\n }\n\n public void setPassword(String password) {\n this.password = password;\n }\n\n}"
},
{
"identifier": "RegisterFormDTO",
"path": "server/src/main/java/org/launchcode/fourohfourfound/finalproject/dtos/RegisterFormDTO.java",
"snippet": "public class RegisterFormDTO extends LoginFormDTO {\n\n\n\n @Email(message = \"Invalid email. Try again.\")\n @NotBlank(message = \"Email is required.\")\n private String email;\n\n @NotNull(message = \"Passwords do not match\")\n private String verifyPassword;\n\n\n\n public String getVerifyPassword() {\n return verifyPassword;\n }\n\n public void setVerifyPassword(String verifyPassword) {\n this.verifyPassword = verifyPassword;\n }\n\n public String getEmail() {\n return email;\n }\n public void setEmail(String email) {\n this.email = email;\n }\n}"
},
{
"identifier": "CharacterRepository",
"path": "server/src/main/java/org/launchcode/fourohfourfound/finalproject/repositories/CharacterRepository.java",
"snippet": "@Repository\npublic interface CharacterRepository extends JpaRepository<Character, Integer> {\n List<Character> findByOwner(User owner);\n\n}"
},
{
"identifier": "UserRepository",
"path": "server/src/main/java/org/launchcode/fourohfourfound/finalproject/repositories/UserRepository.java",
"snippet": "@Repository\npublic interface UserRepository extends JpaRepository<User, Integer> {\n\n User findByUsernameIgnoreCase(String username);\n User findByEmail(String email);\n\n boolean existsByUsername(String username);\n}"
},
{
"identifier": "User",
"path": "server/src/main/java/org/launchcode/fourohfourfound/finalproject/models/User.java",
"snippet": "@Entity\n@Table(name = \"users\")\npublic class User extends AbstractIdentifiableModel{\n\n @Column\n private String username;\n @Column\n private String email;\n\n @Column\n private String password;\n\n public User() {}\n\n\n\n public User(String username, String email, String password) {\n super();\n this.username = username;\n this.email = email;\n setPassword(password);\n\n }\n\n public String getUserName() {\n return username;\n }\n\n public void setUsername(String username) {\n this.username = username;\n }\n\n public String getEmail() {\n return email;\n }\n\n public void setEmail(String email) {\n this.email = email;\n }\n\n public void setPassword(String password) {\n this.password = password;\n }\n @JsonIgnore\n public String getPassword() {\n return password;\n }\n\n public static BCryptPasswordEncoder getEncoder() {\n return new BCryptPasswordEncoder();\n }\n\n public boolean isPasswordEmpty() {\n return password == null || password.isEmpty();\n }\n\n public boolean isMatchingPassword(String password) {\n return getEncoder().matches(password, this.password);\n }\n}"
},
{
"identifier": "Character",
"path": "server/src/main/java/org/launchcode/fourohfourfound/finalproject/models/Character.java",
"snippet": "@Entity\n@Table(name = \"characters\")\npublic class Character extends AbstractIdentifiableModel{\n @ManyToOne\n @JoinColumn(name = \"owner_id\")\n private User owner;\n private String characterName;\n private String alignment;\n private String characterClass;\n private String race;\n private String background;\n private String armorChoice;\n private String magicArmor;\n private String weapon;\n private String magicWeapon;\n private String equipment;\n private String treasure;\n private String proficiencyOne;\n private String proficiencyTwo;\n private String spellOne;\n private String spellTwo;\n\n public Character() {\n }\n\n public Character(User owner, String characterName,String alignment, String aBackground,String armorChoice,\n String magicArmor, String weapon, String magicWeapon, String equipment, String treasure,\n String aClass, String aRace, String proficiencyOne, String proficiencyTwo,\n String spellOne, String spellTwo) {\n super();\n this.owner = owner;\n this.characterName = characterName;\n this.alignment = alignment;\n this.background = aBackground;\n this.armorChoice = armorChoice;\n this.magicArmor = magicArmor;\n this.weapon = weapon;\n this.magicWeapon = magicWeapon;\n this.equipment = equipment;\n this.treasure = treasure;\n this.characterClass = aClass;\n this.race = aRace;\n this.proficiencyOne = proficiencyOne;\n this.proficiencyTwo = proficiencyTwo;\n this.spellOne = spellOne;\n this.spellTwo = spellTwo;\n }\n\n public int getId() {\n return super.getId();\n }\n\n public String getCharacterName() {\n return characterName;\n }\n\n public void setCharacterName(String characterName) {\n this.characterName = characterName;\n }\n\n public String getAlignment() {\n return alignment;\n }\n\n public void setAlignment(String alignment) {\n this.alignment = alignment;\n }\n\n public String getCharacterClass() {\n return characterClass;\n }\n\n public void setCharacterClass(String classInfo) {\n this.characterClass = classInfo;\n }\n\n public String getRace() {\n return race;\n }\n\n public void setRace(String race) {\n this.race = race;\n }\n\n public String getBackground() {\n return background;\n }\n\n public void setBackground(String background) {\n this.background = background;\n }\n\n public String getArmorChoice() {\n return armorChoice;\n }\n\n public void setArmorChoice(String armorChoice) {\n this.armorChoice = armorChoice;\n }\n\n public String getMagicArmor() {\n return magicArmor;\n }\n\n public void setMagicArmor(String magicArmor) {\n this.magicArmor = magicArmor;\n }\n\n public String getWeapon() {\n return weapon;\n }\n\n public void setWeapon(String weapon) {\n this.weapon = weapon;\n }\n\n public String getMagicWeapon() {\n return magicWeapon;\n }\n\n public void setMagicWeapon(String magicWeapon) {\n this.magicWeapon = magicWeapon;\n }\n\n public String getEquipment() {\n return equipment;\n }\n\n public void setEquipment(String equipment) {\n this.equipment = equipment;\n }\n\n public String getTreasure() {\n return treasure;\n }\n\n public void setTreasure(String treasure) {\n this.treasure = treasure;\n }\n\n public String getProficiencyOne() {\n return proficiencyOne;\n }\n\n public void setProficiencyOne(String proficiencyOne) {\n this.proficiencyOne = proficiencyOne;\n }\n\n public String getProficiencyTwo() {\n return proficiencyTwo;\n }\n\n public void setProficiencyTwo(String proficiencyTwo) {\n this.proficiencyTwo = proficiencyTwo;\n }\n\n public String getSpellOne() {\n return spellOne;\n }\n\n public void setSpellOne(String spellOne) {\n this.spellOne = spellOne;\n }\n\n public String getSpellTwo() {\n return spellTwo;\n }\n\n public void setSpellTwo(String spellTwo) {\n this.spellTwo = spellTwo;\n }\n\n public User getOwner() {\n return owner;\n }\n\n public void setOwner(User owner) {\n this.owner = owner;\n }\n}"
}
] | import ch.qos.logback.core.net.SyslogOutputStream;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import jakarta.validation.Valid;
import org.launchcode.fourohfourfound.finalproject.dtos.CharacterDTO;
import org.launchcode.fourohfourfound.finalproject.dtos.LoginFormDTO;
import org.launchcode.fourohfourfound.finalproject.dtos.RegisterFormDTO;
import org.launchcode.fourohfourfound.finalproject.repositories.CharacterRepository;
import org.launchcode.fourohfourfound.finalproject.repositories.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.launchcode.fourohfourfound.finalproject.models.User;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.*;
import org.launchcode.fourohfourfound.finalproject.models.Character;
import org.springframework.http.HttpStatus;
import org.springframework.web.server.ResponseStatusException;
import java.util.Optional; | 4,021 | package org.launchcode.fourohfourfound.finalproject.controllers;
@RestController
@CrossOrigin(origins = "http://localhost:5173")
@RequestMapping("/api")
public class ApiController {
private final CharacterRepository characterRepository;
private final UserRepository userRepository;
private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
@Autowired
public ApiController(CharacterRepository characterRepository, UserRepository userRepository) {
this.characterRepository = characterRepository;
this.userRepository = userRepository;
}
private static final String userSessionKey = "user";
public User getUserFromSession(HttpSession session) {
Integer userId = (Integer) session.getAttribute(userSessionKey);
if (userId == null) {
return null;
}
Optional<User> user = userRepository.findById(userId);
if (user.isEmpty()) {
return null;
}
return user.get();
}
private static void setUserInSession(HttpSession session, User user) {
session.setAttribute(userSessionKey, user.getId());
}
public ResponseEntity<User> getCurrentUser(HttpSession session) {
User user = getUserFromSession(session);
if (user == null) {
return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
}
return new ResponseEntity<>(user, HttpStatus.OK);
}
@GetMapping("/currentUserId")
public ResponseEntity<Integer> getCurrentUserId (HttpSession session) {
User user = getUserFromSession(session);
if (user == null) {
return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
}
return new ResponseEntity<>(user.getId(),HttpStatus.OK);
}
@PostMapping("/register")
public ResponseEntity<?> registerUser(@RequestBody @Valid RegisterFormDTO registerFormDTO, Errors errors, HttpServletRequest request) {
if (errors.hasErrors()) {
System.out.println(errors.getAllErrors());
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
User existingUser = userRepository.findByUsernameIgnoreCase(registerFormDTO.getUsername());
if (existingUser != null) {
return new ResponseEntity<String>("Username already exists", HttpStatus.CONFLICT);
}
String password = registerFormDTO.getPassword();
String verifyPassword = registerFormDTO.getVerifyPassword();
if (!password.equals(verifyPassword)) {
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
User newUser = new User(registerFormDTO.getUsername(), registerFormDTO.getEmail(),passwordEncoder.encode(password));
userRepository.save(newUser);
setUserInSession(request.getSession(), newUser);
return new ResponseEntity<>(newUser, HttpStatus.CREATED);
}
@GetMapping("/login")
public ResponseEntity<String> displayLoginForm() {
return new ResponseEntity<>("Please log in", HttpStatus.OK);
}
@PostMapping("/login") | package org.launchcode.fourohfourfound.finalproject.controllers;
@RestController
@CrossOrigin(origins = "http://localhost:5173")
@RequestMapping("/api")
public class ApiController {
private final CharacterRepository characterRepository;
private final UserRepository userRepository;
private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
@Autowired
public ApiController(CharacterRepository characterRepository, UserRepository userRepository) {
this.characterRepository = characterRepository;
this.userRepository = userRepository;
}
private static final String userSessionKey = "user";
public User getUserFromSession(HttpSession session) {
Integer userId = (Integer) session.getAttribute(userSessionKey);
if (userId == null) {
return null;
}
Optional<User> user = userRepository.findById(userId);
if (user.isEmpty()) {
return null;
}
return user.get();
}
private static void setUserInSession(HttpSession session, User user) {
session.setAttribute(userSessionKey, user.getId());
}
public ResponseEntity<User> getCurrentUser(HttpSession session) {
User user = getUserFromSession(session);
if (user == null) {
return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
}
return new ResponseEntity<>(user, HttpStatus.OK);
}
@GetMapping("/currentUserId")
public ResponseEntity<Integer> getCurrentUserId (HttpSession session) {
User user = getUserFromSession(session);
if (user == null) {
return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
}
return new ResponseEntity<>(user.getId(),HttpStatus.OK);
}
@PostMapping("/register")
public ResponseEntity<?> registerUser(@RequestBody @Valid RegisterFormDTO registerFormDTO, Errors errors, HttpServletRequest request) {
if (errors.hasErrors()) {
System.out.println(errors.getAllErrors());
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
User existingUser = userRepository.findByUsernameIgnoreCase(registerFormDTO.getUsername());
if (existingUser != null) {
return new ResponseEntity<String>("Username already exists", HttpStatus.CONFLICT);
}
String password = registerFormDTO.getPassword();
String verifyPassword = registerFormDTO.getVerifyPassword();
if (!password.equals(verifyPassword)) {
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
User newUser = new User(registerFormDTO.getUsername(), registerFormDTO.getEmail(),passwordEncoder.encode(password));
userRepository.save(newUser);
setUserInSession(request.getSession(), newUser);
return new ResponseEntity<>(newUser, HttpStatus.CREATED);
}
@GetMapping("/login")
public ResponseEntity<String> displayLoginForm() {
return new ResponseEntity<>("Please log in", HttpStatus.OK);
}
@PostMapping("/login") | public ResponseEntity<User> processLoginForm(@RequestBody @Valid LoginFormDTO loginFormDTO, Errors errors, HttpServletRequest request) { | 1 | 2023-11-28 01:32:31+00:00 | 8k |
perfree/perfree-cms | perfree-system/perfree-system-biz/src/main/java/com/perfree/system/service/user/UserServiceImpl.java | [
{
"identifier": "CaptchaCacheService",
"path": "perfree-core/src/main/java/com/perfree/cache/CaptchaCacheService.java",
"snippet": "@Service\npublic class CaptchaCacheService {\n private final Cache<String, String> verificationCodeCache;\n\n public CaptchaCacheService() {\n verificationCodeCache = CacheBuilder.newBuilder()\n .expireAfterWrite(2, TimeUnit.MINUTES) // 设置过期时间为2分钟\n .build();\n }\n\n public void putCaptcha(String key, String captchaCode) {\n verificationCodeCache.put(key, captchaCode);\n }\n\n public String getCaptcha(String key) {\n return verificationCodeCache.getIfPresent(key);\n }\n\n public void removeCaptcha(String key) {\n verificationCodeCache.invalidate(key);\n }\n}"
},
{
"identifier": "ErrorCode",
"path": "perfree-system/perfree-system-api/src/main/java/com/perfree/enums/ErrorCode.java",
"snippet": "@Getter\npublic enum ErrorCode {\n ACCOUNT_NOT_FOUNT(100000001,\"账号不存在!\"),\n ACCOUNT_PASSWORD_ERROR(100000002,\"账号或密码错误!\"),\n CAPTCHA_IMAGE_ERROR(100000004,\"验证码生成失败!\"),\n CAPTCHA_EXPIRE(100000005,\"验证码已过期!\"),\n CAPTCHA_VALID_ERROR(100000006,\"验证码错误!\"),\n MENU_EXISTS_CHILDREN(100000007, \"存在子菜单,无法删除!\");\n private final Integer code;\n\n private final String msg;\n\n ErrorCode(Integer code, String msg) {\n this.code = code;\n this.msg = msg;\n }\n\n}"
},
{
"identifier": "ServiceException",
"path": "perfree-core/src/main/java/com/perfree/commons/exception/ServiceException.java",
"snippet": "@Data\n@EqualsAndHashCode(callSuper = true)\npublic final class ServiceException extends RuntimeException {\n\n /**\n * 业务错误码\n */\n private Integer code;\n /**\n * 错误提示\n */\n private String message;\n\n /**\n * 空构造方法,避免反序列化问题\n */\n public ServiceException() {\n }\n\n public ServiceException(ErrorCode serviceErrorCode) {\n this.code = serviceErrorCode.getCode();\n this.message = serviceErrorCode.getMsg();\n }\n\n public ServiceException(Integer code, String message) {\n this.code = code;\n this.message = message;\n }\n\n public Integer getCode() {\n return code;\n }\n\n public ServiceException setCode(Integer code) {\n this.code = code;\n return this;\n }\n\n @Override\n public String getMessage() {\n return message;\n }\n\n public ServiceException setMessage(String message) {\n this.message = message;\n return this;\n }\n\n}"
},
{
"identifier": "SecurityFrameworkUtils",
"path": "perfree-core/src/main/java/com/perfree/security/SecurityFrameworkUtils.java",
"snippet": "public class SecurityFrameworkUtils {\n\n /**\n * 获得当前认证信息\n * @return 认证信息\n */\n public static Authentication getAuthentication() {\n SecurityContext context = SecurityContextHolder.getContext();\n if (context == null) {\n return null;\n }\n return context.getAuthentication();\n }\n\n\n /**\n * 获取当前登录用户\n * @return User\n */\n @Nullable\n public static LoginUserVO getLoginUser() {\n Authentication authentication = getAuthentication();\n if (authentication == null) {\n return null;\n }\n return (LoginUserVO) authentication.getPrincipal();\n }\n}"
},
{
"identifier": "JwtUtil",
"path": "perfree-core/src/main/java/com/perfree/security/util/JwtUtil.java",
"snippet": "@Component\n@RequiredArgsConstructor\npublic class JwtUtil {\n private static final byte[] secretKey = DatatypeConverter.parseBase64Binary(SecurityConstants.JWT_SECRET_KEY);\n\n private static final byte[] refreshKey = DatatypeConverter.parseBase64Binary(SecurityConstants.JWT_REFRESH_KEY);\n\n private static UserApi userApi;\n private static RoleApi roleApi;\n\n @Autowired\n public JwtUtil(UserApi userApi, RoleApi roleApi) {\n JwtUtil.userApi = userApi;\n JwtUtil.roleApi = roleApi;\n }\n\n /**\n * @param account 账户\n * @param isRemember 是否记住账户\n * @return java.lang.String\n * @author Perfree\n * @description 根据用户生成 token\n * @date 15:14 2023/9/28\n */\n public static String generateToken(String account, Boolean isRemember) {\n // 过期时间\n long expirationTime = isRemember ? SecurityConstants.TOKEN_EXPIRATION_REMEMBER_TIME : SecurityConstants.TOKEN_EXPIRATION_TIME;\n // 生成token\n return Jwts.builder()\n // 生成签证信息\n .setHeaderParam(\"typ\", SecurityConstants.TOKEN_TYPE)\n .signWith(Keys.hmacShaKeyFor(secretKey))\n // 所有人\n .setSubject(account)\n // JWT主体\n .setIssuer(SecurityConstants.TOKEN_ISSUER)\n // 签发时间\n .setIssuedAt(new Date())\n .setAudience(SecurityConstants.TOKEN_AUDIENCE)\n // 设置有效时间\n .setExpiration(new Date(System.currentTimeMillis() + expirationTime * 1000))\n .compact();\n }\n\n /**\n * @param account 账号\n * @return java.lang.String\n * @author Perfree\n * @description 生成refresh_token\n * @date 15:15 2023/9/28\n */\n public static String getRefreshToken(String account, Date expiration) {\n return Jwts.builder()\n .signWith(Keys.hmacShaKeyFor(refreshKey))\n .setSubject(account)\n .setExpiration(expiration)\n .compact();\n }\n\n /**\n * @param token token\n * @return boolean\n * @author Perfree\n * @description 校验token是否有效\n * @date 15:15 2023/9/28\n */\n public static boolean verifyToken(String token) {\n getTokenBody(token);\n return true;\n }\n\n /**\n * @param token token\n * @return org.springframework.security.core.Authentication\n * @author Perfree\n * @description 根据token获取用户认证信息\n * @date 15:15 2023/9/28\n */\n public static Authentication getAuthentication(String token) {\n Claims claims;\n try {\n claims = getTokenBody(token);\n } catch (ExpiredJwtException e) {\n e.printStackTrace();\n claims = e.getClaims();\n }\n // 获取用户角色 TODO 老数据为单角色不分权限,这里在考虑要不要升级为多角色加权限的方式\n UserRespDTO byAccount = userApi.findByAccount(claims.getSubject());\n LoginUserVO loginUser = new LoginUserVO();\n loginUser.setId(byAccount.getId());\n loginUser.setAccount(byAccount.getAccount());\n loginUser.setRoleId(byAccount.getRoleId());\n RoleRespDTO role = roleApi.getById(loginUser.getRoleId());\n List<String> roles = new ArrayList<>();\n // roles.add(role.getCode().startsWith(\"ROLE_\") ? role.getCode(): \"ROLE_\" + role.getCode());\n roles.add(role.getCode());\n List<SimpleGrantedAuthority> authorities = roles.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());\n return new UsernamePasswordAuthenticationToken(loginUser, token, authorities);\n }\n\n /**\n * @param token token\n * @return io.jsonwebtoken.Claims\n * @author Perfree\n * @description 从token中获取用户信息\n * @date 15:16 2023/9/28\n */\n private static Claims getTokenBody(String token) {\n return Jwts.parserBuilder()\n .setSigningKey(secretKey)\n .build()\n .parseClaimsJws(token)\n .getBody();\n }\n\n /**\n * @param refreshToken refreshToken\n * @return io.jsonwebtoken.Claims\n * @author Perfree\n * @description 从refreshToken中获取用户信息\n * @date 15:16 2023/9/28\n */\n public static Claims getRefreshTokenBody(String refreshToken) {\n return Jwts.parserBuilder()\n .setSigningKey(refreshKey)\n .build()\n .parseClaimsJws(refreshToken)\n .getBody();\n }\n}"
},
{
"identifier": "LoginUserVO",
"path": "perfree-core/src/main/java/com/perfree/security/vo/LoginUserVO.java",
"snippet": "@Getter\n@Setter\npublic class LoginUserVO implements Serializable {\n\n @Serial\n private static final long serialVersionUID = 1L;\n\n /**\n * 主键\n */\n private Integer id;\n\n /**\n * 用户账号\n */\n private String account;\n\n /**\n * 角色ID\n */\n private Long roleId;\n}"
},
{
"identifier": "UserConvert",
"path": "perfree-system/perfree-system-biz/src/main/java/com/perfree/system/convert/user/UserConvert.java",
"snippet": "@Mapper(componentModel = \"spring\")\npublic interface UserConvert {\n\n UserConvert INSTANCE = Mappers.getMapper(UserConvert.class);\n\n User convert(LoginUserReqVO bean);\n\n LoginUserRespVO convert(User bean);\n\n List<LoginUserRespVO> convertList(List<User> list);\n\n LoginUserInfoRespVO convertLoginInfo(User loginUser);\n\n UserRespDTO convertDto(User byAccount);\n\n}"
},
{
"identifier": "RoleMapper",
"path": "perfree-system/perfree-system-biz/src/main/java/com/perfree/system/mapper/RoleMapper.java",
"snippet": "@Mapper\npublic interface RoleMapper extends BaseMapperX<Role> {\n\n default PageResult<Role> selectPage(RolePageReqVO pageVO) {\n return selectPage(pageVO, new LambdaQueryWrapper<Role>()\n .like(StringUtils.isNotBlank(pageVO.getName()), Role::getName, pageVO.getName()));\n }\n\n}"
},
{
"identifier": "UserMapper",
"path": "perfree-system/perfree-system-biz/src/main/java/com/perfree/system/mapper/UserMapper.java",
"snippet": "@Mapper\npublic interface UserMapper extends BaseMapperX<User> {\n\n default User findByAccount(String account){\n return selectOne(new LambdaQueryWrapper<User>().eq(User::getAccount, account));\n }\n}"
},
{
"identifier": "Role",
"path": "perfree-system/perfree-system-biz/src/main/java/com/perfree/system/model/Role.java",
"snippet": "@Getter\n@Setter\n@TableName(\"p_role\")\npublic class Role implements Serializable {\n\n @Serial\n private static final long serialVersionUID = 1L;\n\n /**\n * 主键\n */\n @TableId(value = \"id\", type = IdType.AUTO)\n private Integer id;\n\n /**\n * 角色名\n */\n private String name;\n\n /**\n * 角色描述\n */\n private String description;\n\n /**\n * 角色编码\n */\n private String code;\n\n private Date createTime;\n\n private Date updateTime;\n}"
},
{
"identifier": "User",
"path": "perfree-system/perfree-system-biz/src/main/java/com/perfree/system/model/User.java",
"snippet": "@Getter\n@Setter\n@TableName(\"p_user\")\n@NoArgsConstructor\n@AllArgsConstructor\npublic class User implements Serializable {\n\n @Serial\n private static final long serialVersionUID = 1L;\n\n /**\n * 主键\n */\n @TableId(value = \"id\", type = IdType.AUTO)\n private Integer id;\n\n /**\n * 用户账号\n */\n private String account;\n\n /**\n * 用户名\n */\n private String userName;\n\n /**\n * 用户登录密码\n */\n private String password;\n\n /**\n * 盐值\n */\n private String salt;\n\n /**\n * 状态\n */\n private Integer status;\n\n /**\n * 头像\n */\n private String avatar;\n\n /**\n * 角色ID\n */\n private Long roleId;\n\n /**\n * 邮箱\n */\n private String email;\n\n /**\n * 网站\n */\n private String website;\n\n private Date createTime;\n\n private Date updateTime;\n}"
},
{
"identifier": "LoginUserInfoRespVO",
"path": "perfree-system/perfree-system-biz/src/main/java/com/perfree/system/vo/system/LoginUserInfoRespVO.java",
"snippet": "@Schema(description = \"登录用户信息 Response VO\")\n@Data\n@EqualsAndHashCode(callSuper = true)\npublic class LoginUserInfoRespVO extends UserBaseVO {\n\n @Schema(description = \"用户id\")\n private Integer id;\n\n @Schema(description = \"角色编码集合\")\n private List<String> roles = new ArrayList<>();\n\n @Schema(description = \"权限编码集合\")\n private List<String> permissions = new ArrayList<>();\n}"
},
{
"identifier": "LoginUserReqVO",
"path": "perfree-system/perfree-system-biz/src/main/java/com/perfree/system/vo/system/LoginUserReqVO.java",
"snippet": "@Schema(description = \"账号密码登录 Request VO\")\n@Data\npublic class LoginUserReqVO {\n\n @Schema(description = \"账号\", example = \"admin\")\n @NotEmpty(message = \"登录账号不能为空\")\n @Length(min = 1, max = 16, message = \"账号长度为 1-16 位\")\n @Pattern(regexp = \"^[A-Za-z0-9]+$\", message = \"账号格式为数字以及字母\")\n private String username;\n\n @Schema(description = \"密码\", example = \"123456\")\n @NotEmpty(message = \"密码不能为空\")\n @Length(min = 4, max = 16, message = \"密码长度为 4-16 位\")\n private String password;\n\n @Schema(description = \"验证码uuid\", example = \"123456\")\n @NotEmpty(message = \"验证码uuid不能为空\")\n private String uuid;\n\n @Schema(description = \"验证码\", example = \"123456\")\n @NotEmpty(message = \"验证码不能为空\")\n private String code;\n\n}"
},
{
"identifier": "LoginUserRespVO",
"path": "perfree-system/perfree-system-biz/src/main/java/com/perfree/system/vo/system/LoginUserRespVO.java",
"snippet": "@Schema(description = \"登录 Response VO\")\n@Data\n@NoArgsConstructor\n@AllArgsConstructor\n@Builder\npublic class LoginUserRespVO {\n @Schema(description = \"用户编号\", example = \"1024\")\n private Integer userId;\n\n @Schema(description = \"访问令牌\", example = \"happy\")\n private String accessToken;\n\n @Schema(description = \"刷新令牌\", example = \"nice\")\n private String refreshToken;\n\n @Schema(description = \"过期时间\")\n private LocalDateTime expiresTime;\n}"
},
{
"identifier": "SecurityConstants",
"path": "perfree-core/src/main/java/com/perfree/security/SecurityConstants.java",
"snippet": "public class SecurityConstants {\n\n /**\n * JWT签名密钥,用的512-bit Encryption key\n */\n public static final String JWT_SECRET_KEY = \"B?E(H+MbQeShVmYq3t6w9z$C&F)J@NcRfUjWnZr4u7x!A%D*G-KaPdSgVkYp3s5v\";\n\n /**\n * 刷新refresh_token的密钥\n */\n public static final String JWT_REFRESH_KEY = \"q3t6w9z$C&F)H@McQfTjWnZr4u7x!A%D*G-KaNdRgUkXp2s5v8y/B?E(H+MbQeSh\";\n\n /**\n * token前缀,用在请求头里Authorization\n */\n public static final String TOKEN_PREFIX = \"Bearer \";\n\n /**\n * 请求头\n */\n public static final String TOKEN_HEADER = \"Authorization\";\n\n /**\n * token类型\n */\n public static final String TOKEN_TYPE = \"JWT\";\n\n /**\n * token颁发者身份标识\n */\n public static final String TOKEN_ISSUER = \"security\";\n\n /**\n * token覆盖范围\n */\n public static final String TOKEN_AUDIENCE = \"security-all\";\n\n /**\n * token有效期2小时(当remember为false时)\n */\n public static final Long TOKEN_EXPIRATION_TIME = 60 * 60 * 2L;\n\n /**\n * token有效期为7天(当remember为true时)\n */\n public static final Long TOKEN_EXPIRATION_REMEMBER_TIME = 60 * 60 * 24 * 7L;\n}"
}
] | import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.perfree.cache.CaptchaCacheService;
import com.perfree.enums.ErrorCode;
import com.perfree.commons.exception.ServiceException;
import com.perfree.security.SecurityFrameworkUtils;
import com.perfree.security.util.JwtUtil;
import com.perfree.security.vo.LoginUserVO;
import com.perfree.system.convert.user.UserConvert;
import com.perfree.system.mapper.RoleMapper;
import com.perfree.system.mapper.UserMapper;
import com.perfree.system.model.Role;
import com.perfree.system.model.User;
import com.perfree.system.vo.system.LoginUserInfoRespVO;
import com.perfree.system.vo.system.LoginUserReqVO;
import com.perfree.system.vo.system.LoginUserRespVO;
import com.perfree.security.SecurityConstants;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import java.time.ZoneId;
import java.util.Date; | 4,316 | package com.perfree.system.service.user;
/**
* <p>
* 服务实现类
* </p>
*
* @author perfree
* @since 2023-09-27
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
@Resource
private UserMapper userMapper;
@Resource
private RoleMapper roleMapper;
@Resource
private CaptchaCacheService captchaCacheService;
@Override | package com.perfree.system.service.user;
/**
* <p>
* 服务实现类
* </p>
*
* @author perfree
* @since 2023-09-27
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
@Resource
private UserMapper userMapper;
@Resource
private RoleMapper roleMapper;
@Resource
private CaptchaCacheService captchaCacheService;
@Override | public LoginUserRespVO login(LoginUserReqVO loginUserVO) { | 12 | 2023-12-01 23:37:25+00:00 | 8k |
tuxiaobei-scu/SCU-CCSOJ-Backend | JudgeServer/src/main/java/top/hcode/hoj/dao/impl/JudgeServerEntityServiceImpl.java | [
{
"identifier": "SandboxRun",
"path": "JudgeServer/src/main/java/top/hcode/hoj/judge/SandboxRun.java",
"snippet": "@Slf4j(topic = \"hoj\")\npublic class SandboxRun {\n\n private static final RestTemplate restTemplate;\n\n // 单例模式\n private static final SandboxRun instance = new SandboxRun();\n\n private static final String SANDBOX_BASE_URL = \"http://1.13.23.80:5050\";\n\n public static final HashMap<String, Integer> RESULT_MAP_STATUS = new HashMap<>();\n\n private static final int maxProcessNumber = 128;\n\n private static final int TIME_LIMIT_MS = 16000;\n\n private static final int MEMORY_LIMIT_MB = 512;\n\n private static final int STACK_LIMIT_MB = 256;\n\n private static final int STDIO_SIZE_MB = 32;\n\n private SandboxRun() {\n\n }\n\n static {\n SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();\n requestFactory.setConnectTimeout(20000);\n requestFactory.setReadTimeout(180000);\n restTemplate = new RestTemplate(requestFactory);\n }\n\n static {\n RESULT_MAP_STATUS.put(\"Time Limit Exceeded\", Constants.Judge.STATUS_TIME_LIMIT_EXCEEDED.getStatus());\n RESULT_MAP_STATUS.put(\"Memory Limit Exceeded\", Constants.Judge.STATUS_MEMORY_LIMIT_EXCEEDED.getStatus());\n RESULT_MAP_STATUS.put(\"Output Limit Exceeded\", Constants.Judge.STATUS_RUNTIME_ERROR.getStatus());\n RESULT_MAP_STATUS.put(\"Accepted\", Constants.Judge.STATUS_ACCEPTED.getStatus());\n RESULT_MAP_STATUS.put(\"Nonzero Exit Status\", Constants.Judge.STATUS_RUNTIME_ERROR.getStatus());\n RESULT_MAP_STATUS.put(\"Internal Error\", Constants.Judge.STATUS_SYSTEM_ERROR.getStatus());\n RESULT_MAP_STATUS.put(\"File Error\", Constants.Judge.STATUS_SYSTEM_ERROR.getStatus());\n RESULT_MAP_STATUS.put(\"Signalled\", Constants.Judge.STATUS_RUNTIME_ERROR.getStatus());\n }\n\n public static RestTemplate getRestTemplate() {\n return restTemplate;\n }\n\n public static String getSandboxBaseUrl() {\n return SANDBOX_BASE_URL;\n }\n\n public static final List<String> signals = Arrays.asList(\n \"\", // 0\n \"Hangup\", // 1\n \"Interrupt\", // 2\n \"Quit\", // 3\n \"Illegal instruction\", // 4\n \"Trace/breakpoint trap\", // 5\n \"Aborted\", // 6\n \"Bus error\", // 7\n \"Floating point exception\", // 8\n \"Killed\", // 9\n \"User defined signal 1\", // 10\n \"Segmentation fault\", // 11\n \"User defined signal 2\", // 12\n \"Broken pipe\", // 13\n \"Alarm clock\", // 14\n \"Terminated\", // 15\n \"Stack fault\", // 16\n \"Child exited\", // 17\n \"Continued\", // 18\n \"Stopped (signal)\", // 19\n \"Stopped\", // 20\n \"Stopped (tty input)\", // 21\n \"Stopped (tty output)\", // 22\n \"Urgent I/O condition\", // 23\n \"CPU time limit exceeded\", // 24\n \"File size limit exceeded\", // 25\n \"Virtual timer expired\", // 26\n \"Profiling timer expired\", // 27\n \"Window changed\", // 28\n \"I/O possible\", // 29\n \"Power failure\", // 30\n \"Bad system call\" // 31\n );\n\n public JSONArray run(String uri, JSONObject param) throws SystemError {\n HttpHeaders headers = new HttpHeaders();\n headers.setContentType(MediaType.APPLICATION_JSON);\n HttpEntity<String> request = new HttpEntity<>(JSONUtil.toJsonStr(param), headers);\n ResponseEntity<String> postForEntity;\n try {\n postForEntity = restTemplate.postForEntity(SANDBOX_BASE_URL + uri, request, String.class);\n return JSONUtil.parseArray(postForEntity.getBody());\n } catch (RestClientResponseException ex) {\n if (ex.getRawStatusCode() != 200) {\n throw new SystemError(\"Cannot connect to sandbox service.\", null, ex.getResponseBodyAsString());\n }\n } catch (Exception e) {\n throw new SystemError(\"Call SandBox Error.\", null, e.getMessage());\n }\n return null;\n }\n\n public static void delFile(String fileId) {\n\n try {\n restTemplate.delete(SANDBOX_BASE_URL + \"/file/{0}\", fileId);\n } catch (RestClientResponseException ex) {\n if (ex.getRawStatusCode() != 200) {\n log.error(\"安全沙箱判题的删除内存中的文件缓存操作异常----------------->{}\", ex.getResponseBodyAsString());\n }\n }\n\n }\n\n /**\n * \"files\": [{\n * \"content\": \"\"\n * }, {\n * \"name\": \"stdout\",\n * \"max\": 1024 * 1024 * 32\n * }, {\n * \"name\": \"stderr\",\n * \"max\": 1024 * 1024 * 32\n * }]\n */\n private static final JSONArray COMPILE_FILES = new JSONArray();\n\n static {\n JSONObject content = new JSONObject();\n content.set(\"content\", \"\");\n\n JSONObject stdout = new JSONObject();\n stdout.set(\"name\", \"stdout\");\n stdout.set(\"max\", 1024 * 1024 * STDIO_SIZE_MB);\n\n JSONObject stderr = new JSONObject();\n stderr.set(\"name\", \"stderr\");\n stderr.set(\"max\", 1024 * 1024 * STDIO_SIZE_MB);\n COMPILE_FILES.put(content);\n COMPILE_FILES.put(stdout);\n COMPILE_FILES.put(stderr);\n }\n\n /**\n * @param maxCpuTime 最大编译的cpu时间 ms\n * @param maxRealTime 最大编译的真实时间 ms\n * @param maxMemory 最大编译的空间 b\n * @param maxStack 最大编译的栈空间 b\n * @param srcName 编译的源文件名字\n * @param exeName 编译生成的exe文件名字\n * @param args 编译的cmd参数\n * @param envs 编译的环境变量\n * @param code 编译的源代码\n * @param extraFiles 编译所需的额外文件 key:文件名,value:文件内容\n * @param needCopyOutCached 是否需要生成编译后的用户程序exe文件\n * @param needCopyOutExe 是否需要生成用户程序的缓存文件,即生成用户程序id\n * @param copyOutDir 生成编译后的用户程序exe文件的指定路径\n * @MethodName compile\n * @Description 编译运行\n * @Return\n * @Since 2022/1/3\n */\n public static JSONArray compile(Long maxCpuTime,\n Long maxRealTime,\n Long maxMemory,\n Long maxStack,\n String srcName,\n String exeName,\n List<String> args,\n List<String> envs,\n String code,\n HashMap<String, String> extraFiles,\n Boolean needCopyOutCached,\n Boolean needCopyOutExe,\n String copyOutDir) throws SystemError {\n JSONObject cmd = new JSONObject();\n cmd.set(\"args\", args);\n cmd.set(\"env\", envs);\n cmd.set(\"files\", COMPILE_FILES);\n // ms-->ns\n cmd.set(\"cpuLimit\", maxCpuTime * 1000 * 1000L);\n cmd.set(\"clockLimit\", maxRealTime * 1000 * 1000L);\n // byte\n cmd.set(\"memoryLimit\", maxMemory);\n cmd.set(\"procLimit\", maxProcessNumber);\n cmd.set(\"stackLimit\", maxStack);\n\n JSONObject fileContent = new JSONObject();\n fileContent.set(\"content\", code);\n\n JSONObject copyIn = new JSONObject();\n copyIn.set(srcName, fileContent);\n\n if (extraFiles != null) {\n for (Map.Entry<String, String> entry : extraFiles.entrySet()) {\n if (!StringUtils.isEmpty(entry.getKey()) && !StringUtils.isEmpty(entry.getValue())) {\n JSONObject content = new JSONObject();\n content.set(\"content\", entry.getValue());\n copyIn.set(entry.getKey(), content);\n }\n }\n }\n\n cmd.set(\"copyIn\", copyIn);\n cmd.set(\"copyOut\", new JSONArray().put(\"stdout\").put(\"stderr\"));\n\n if (needCopyOutCached) {\n cmd.set(\"copyOutCached\", new JSONArray().put(exeName));\n }\n\n if (needCopyOutExe) {\n cmd.set(\"copyOutDir\", copyOutDir);\n }\n\n JSONObject param = new JSONObject();\n param.set(\"cmd\", new JSONArray().put(cmd));\n\n JSONArray result = instance.run(\"/run\", param);\n JSONObject tmp = (JSONObject) result.get(0);\n ((JSONObject) result.get(0)).set(\"status\", RESULT_MAP_STATUS.get(tmp.getStr(\"status\")));\n return result;\n }\n\n\n /**\n * @param args 普通评测运行cmd的命令参数\n * @param envs 普通评测运行的环境变量\n * @param testCasePath 题目数据的输入文件路径\n * @param testCaseContent 题目数据的输入数据(与testCasePath二者选一)\n * @param maxTime 评测的最大限制时间 ms\n * @param maxOutputSize 评测的最大输出大小 kb\n * @param maxStack 评测的最大限制栈空间 mb\n * @param exeName 评测的用户程序名称\n * @param fileId 评测的用户程序文件id\n * @param fileContent 评测的用户程序文件内容,如果userFileId存在则为null\n * @MethodName testCase\n * @Description 普通评测\n * @Return JSONArray\n * @Since 2022/1/3\n */\n public static JSONArray testCase(List<String> args,\n List<String> envs,\n String testCasePath,\n String testCaseContent,\n Long maxTime,\n Long maxMemory,\n Long maxOutputSize,\n Integer maxStack,\n String exeName,\n String fileId,\n String fileContent) throws SystemError {\n\n JSONObject cmd = new JSONObject();\n cmd.set(\"args\", args);\n cmd.set(\"env\", envs);\n\n JSONArray files = new JSONArray();\n JSONObject content = new JSONObject();\n if (StringUtils.isEmpty(testCasePath)) {\n content.set(\"content\", testCaseContent);\n } else {\n content.set(\"src\", testCasePath);\n }\n\n JSONObject stdout = new JSONObject();\n stdout.set(\"name\", \"stdout\");\n stdout.set(\"max\", maxOutputSize);\n\n JSONObject stderr = new JSONObject();\n stderr.set(\"name\", \"stderr\");\n stderr.set(\"max\", 1024 * 1024 * 16);\n files.put(content);\n files.put(stdout);\n files.put(stderr);\n\n cmd.set(\"files\", files);\n\n // ms-->ns\n cmd.set(\"cpuLimit\", maxTime * 1000 * 1000L);\n cmd.set(\"clockLimit\", maxTime * 1000 * 1000L * 3);\n // byte\n if (maxMemory >= MEMORY_LIMIT_MB) {\n cmd.set(\"memoryLimit\", (maxMemory + 100) * 1024 * 1024L);\n } else {\n cmd.set(\"memoryLimit\", MEMORY_LIMIT_MB * 1024 * 1024L);\n }\n cmd.set(\"procLimit\", maxProcessNumber);\n cmd.set(\"stackLimit\", maxStack * 1024 * 1024L);\n\n JSONObject exeFile = new JSONObject();\n if (!StringUtils.isEmpty(fileId)) {\n exeFile.set(\"fileId\", fileId);\n } else {\n exeFile.set(\"content\", fileContent);\n }\n JSONObject copyIn = new JSONObject();\n copyIn.set(exeName, exeFile);\n\n cmd.set(\"copyIn\", copyIn);\n cmd.set(\"copyOut\", new JSONArray().put(\"stdout\").put(\"stderr\"));\n\n JSONObject param = new JSONObject();\n param.set(\"cmd\", new JSONArray().put(cmd));\n\n // 调用判题安全沙箱\n JSONArray result = instance.run(\"/run\", param);\n\n JSONObject tmp = (JSONObject) result.get(0);\n ((JSONObject) result.get(0)).set(\"status\", RESULT_MAP_STATUS.get(tmp.getStr(\"status\")));\n return result;\n }\n\n\n /**\n * @param args 特殊判题的运行cmd命令参数\n * @param envs 特殊判题的运行环境变量\n * @param userOutputFilePath 用户程序输出文件的路径\n * @param userOutputFileName 用户程序输出文件的名字\n * @param testCaseInputFilePath 题目数据的输入文件的路径\n * @param testCaseInputFileName 题目数据的输入文件的名字\n * @param testCaseOutputFilePath 题目数据的输出文件的路径\n * @param testCaseOutputFileName 题目数据的输出文件的路径\n * @param spjExeSrc 特殊判题的exe文件的路径\n * @param spjExeName 特殊判题的exe文件的名字\n * @MethodName spjCheckResult\n * @Description 特殊判题的评测\n * @Return JSONArray\n * @Since 2022/1/3\n */\n public static JSONArray spjCheckResult(List<String> args,\n List<String> envs,\n String userOutputFilePath,\n String userOutputFileName,\n String testCaseInputFilePath,\n String testCaseInputFileName,\n String testCaseOutputFilePath,\n String testCaseOutputFileName,\n String spjExeSrc,\n String spjExeName) throws SystemError {\n\n JSONObject cmd = new JSONObject();\n cmd.set(\"args\", args);\n cmd.set(\"env\", envs);\n\n JSONArray outFiles = new JSONArray();\n\n JSONObject content = new JSONObject();\n content.set(\"content\", \"\");\n\n JSONObject outStdout = new JSONObject();\n outStdout.set(\"name\", \"stdout\");\n outStdout.set(\"max\", 1024 * 1024 * 16);\n\n JSONObject outStderr = new JSONObject();\n outStderr.set(\"name\", \"stderr\");\n outStderr.set(\"max\", 1024 * 1024 * 16);\n\n outFiles.put(content);\n outFiles.put(outStdout);\n outFiles.put(outStderr);\n cmd.set(\"files\", outFiles);\n\n // ms-->ns\n cmd.set(\"cpuLimit\", TIME_LIMIT_MS * 1000 * 1000L);\n cmd.set(\"clockLimit\", TIME_LIMIT_MS * 1000 * 1000L * 3);\n // byte\n cmd.set(\"memoryLimit\", MEMORY_LIMIT_MB * 1024 * 1024L);\n cmd.set(\"procLimit\", maxProcessNumber);\n cmd.set(\"stackLimit\", STACK_LIMIT_MB * 1024 * 1024L);\n\n\n JSONObject spjExeFile = new JSONObject();\n spjExeFile.set(\"src\", spjExeSrc);\n\n JSONObject useOutputFileSrc = new JSONObject();\n useOutputFileSrc.set(\"src\", userOutputFilePath);\n\n JSONObject stdInputFileSrc = new JSONObject();\n stdInputFileSrc.set(\"src\", testCaseInputFilePath);\n\n JSONObject stdOutFileSrc = new JSONObject();\n stdOutFileSrc.set(\"src\", testCaseOutputFilePath);\n\n JSONObject spjCopyIn = new JSONObject();\n\n spjCopyIn.set(spjExeName, spjExeFile);\n spjCopyIn.set(userOutputFileName, useOutputFileSrc);\n spjCopyIn.set(testCaseInputFileName, stdInputFileSrc);\n spjCopyIn.set(testCaseOutputFileName, stdOutFileSrc);\n\n\n cmd.set(\"copyIn\", spjCopyIn);\n cmd.set(\"copyOut\", new JSONArray().put(\"stdout\").put(\"stderr\"));\n\n JSONObject param = new JSONObject();\n\n param.set(\"cmd\", new JSONArray().put(cmd));\n\n // 调用判题安全沙箱\n JSONArray result = instance.run(\"/run\", param);\n\n JSONObject tmp = (JSONObject) result.get(0);\n ((JSONObject) result.get(0)).set(\"status\", RESULT_MAP_STATUS.get(tmp.getStr(\"status\")));\n return result;\n }\n\n\n /**\n * @param args cmd的命令参数 评测运行的命令\n * @param envs 测评的环境变量\n * @param userExeName 用户程序的名字\n * @param userFileId 用户程序在编译后返回的id,主要是对应内存中已编译后的文件\n * @param userFileContent 用户程序文件的内容,如果userFileId存在则为null\n * @param userMaxTime 用户程序的最大测评时间 ms\n * @param userMaxStack 用户程序的最大测评栈空间 mb\n * @param testCaseInputPath 题目数据的输入文件路径\n * @param testCaseInputFileName 题目数据的输入文件名字\n * @param testCaseOutputFilePath 题目数据的输出文件路径\n * @param testCaseOutputFileName 题目数据的输出文件名字\n * @param userOutputFileName 用户程序的输出文件名字\n * @param interactArgs 交互程序运行的cmd命令参数\n * @param interactEnvs 交互程序运行的环境变量\n * @param interactExeSrc 交互程序的exe文件路径\n * @param interactExeName 交互程序的exe文件名字\n * @MethodName interactTestCase\n * @Description 交互评测\n * @Return JSONArray\n * @Since 2022/1/3\n */\n public static JSONArray interactTestCase(List<String> args,\n List<String> envs,\n String userExeName,\n String userFileId,\n String userFileContent,\n Long userMaxTime,\n Long userMaxMemory,\n Integer userMaxStack,\n String testCaseInputPath,\n String testCaseInputFileName,\n String testCaseOutputFilePath,\n String testCaseOutputFileName,\n String userOutputFileName,\n List<String> interactArgs,\n List<String> interactEnvs,\n String interactExeSrc,\n String interactExeName) throws SystemError {\n\n /**\n * 注意:用户源代码需要先编译,若是通过编译需要先将文件存入内存,再利用管道判题,同时特殊判题程序必须已编译且存在(否则判题失败,系统错误)!\n */\n\n JSONObject pipeInputCmd = new JSONObject();\n pipeInputCmd.set(\"args\", args);\n pipeInputCmd.set(\"env\", envs);\n\n JSONArray files = new JSONArray();\n\n JSONObject stderr = new JSONObject();\n stderr.set(\"name\", \"stderr\");\n stderr.set(\"max\", 1024 * 1024 * STDIO_SIZE_MB);\n\n files.put(new JSONObject());\n files.put(new JSONObject());\n files.put(stderr);\n\n String inTmp = files.toString().replace(\"{}\", \"null\");\n pipeInputCmd.set(\"files\", JSONUtil.parseArray(inTmp, false));\n\n // ms-->ns\n pipeInputCmd.set(\"cpuLimit\", userMaxTime * 1000 * 1000L);\n pipeInputCmd.set(\"clockLimit\", userMaxTime * 1000 * 1000L * 3);\n\n // byte\n\n pipeInputCmd.set(\"memoryLimit\", (userMaxMemory + 100) * 1024 * 1024L);\n pipeInputCmd.set(\"procLimit\", maxProcessNumber);\n pipeInputCmd.set(\"stackLimit\", userMaxStack * 1024 * 1024L);\n\n JSONObject exeFile = new JSONObject();\n if (!StringUtils.isEmpty(userFileId)) {\n exeFile.set(\"fileId\", userFileId);\n } else {\n exeFile.set(\"content\", userFileContent);\n }\n JSONObject copyIn = new JSONObject();\n copyIn.set(userExeName, exeFile);\n\n pipeInputCmd.set(\"copyIn\", copyIn);\n pipeInputCmd.set(\"copyOut\", new JSONArray());\n\n\n // 管道输出,用户程序输出数据经过特殊判题程序后,得到的最终输出结果。\n JSONObject pipeOutputCmd = new JSONObject();\n pipeOutputCmd.set(\"args\", interactArgs);\n pipeOutputCmd.set(\"env\", interactEnvs);\n\n JSONArray outFiles = new JSONArray();\n\n\n JSONObject outStderr = new JSONObject();\n outStderr.set(\"name\", \"stderr\");\n outStderr.set(\"max\", 1024 * 1024 * STDIO_SIZE_MB);\n outFiles.put(new JSONObject());\n outFiles.put(new JSONObject());\n outFiles.put(outStderr);\n String outTmp = outFiles.toString().replace(\"{}\", \"null\");\n pipeOutputCmd.set(\"files\", JSONUtil.parseArray(outTmp, false));\n\n // ms-->ns\n pipeOutputCmd.set(\"cpuLimit\", userMaxTime * 1000 * 1000L * 2);\n pipeOutputCmd.set(\"clockLimit\", userMaxTime * 1000 * 1000L * 3 * 2);\n // byte\n pipeOutputCmd.set(\"memoryLimit\", (userMaxMemory + 100) * 1024 * 1024L * 2);\n pipeOutputCmd.set(\"procLimit\", maxProcessNumber);\n pipeOutputCmd.set(\"stackLimit\", STACK_LIMIT_MB * 1024 * 1024L);\n\n JSONObject spjExeFile = new JSONObject();\n spjExeFile.set(\"src\", interactExeSrc);\n\n JSONObject stdInputFileSrc = new JSONObject();\n stdInputFileSrc.set(\"src\", testCaseInputPath);\n\n JSONObject stdOutFileSrc = new JSONObject();\n stdOutFileSrc.set(\"src\", testCaseOutputFilePath);\n\n JSONObject interactiveCopyIn = new JSONObject();\n interactiveCopyIn.set(interactExeName, spjExeFile);\n interactiveCopyIn.set(testCaseInputFileName, stdInputFileSrc);\n interactiveCopyIn.set(testCaseOutputFileName, stdOutFileSrc);\n\n\n pipeOutputCmd.set(\"copyIn\", interactiveCopyIn);\n pipeOutputCmd.set(\"copyOut\", new JSONArray().put(userOutputFileName));\n\n JSONArray cmdList = new JSONArray();\n cmdList.put(pipeInputCmd);\n cmdList.put(pipeOutputCmd);\n\n JSONObject param = new JSONObject();\n // 添加cmd指令\n param.set(\"cmd\", cmdList);\n\n // 添加管道映射\n JSONArray pipeMapping = new JSONArray();\n // 用户程序\n JSONObject user = new JSONObject();\n\n JSONObject userIn = new JSONObject();\n userIn.set(\"index\", 0);\n userIn.set(\"fd\", 1);\n\n JSONObject userOut = new JSONObject();\n userOut.set(\"index\", 1);\n userOut.set(\"fd\", 0);\n\n user.set(\"in\", userIn);\n user.set(\"out\", userOut);\n user.set(\"max\", STDIO_SIZE_MB * 1024 * 1024);\n user.set(\"proxy\", true);\n user.set(\"name\", \"stdout\");\n\n // 评测程序\n JSONObject judge = new JSONObject();\n\n JSONObject judgeIn = new JSONObject();\n judgeIn.set(\"index\", 1);\n judgeIn.set(\"fd\", 1);\n\n JSONObject judgeOut = new JSONObject();\n judgeOut.set(\"index\", 0);\n judgeOut.set(\"fd\", 0);\n\n judge.set(\"in\", judgeIn);\n judge.set(\"out\", judgeOut);\n judge.set(\"max\", STDIO_SIZE_MB * 1024 * 1024);\n judge.set(\"proxy\", true);\n judge.set(\"name\", \"stdout\");\n\n\n // 添加到管道映射列表\n pipeMapping.add(user);\n pipeMapping.add(judge);\n\n param.set(\"pipeMapping\", pipeMapping);\n\n // 调用判题安全沙箱\n JSONArray result = instance.run(\"/run\", param);\n JSONObject userRes = (JSONObject) result.get(0);\n JSONObject interactiveRes = (JSONObject) result.get(1);\n userRes.set(\"status\", RESULT_MAP_STATUS.get(userRes.getStr(\"status\")));\n interactiveRes.set(\"status\", RESULT_MAP_STATUS.get(interactiveRes.getStr(\"status\")));\n return result;\n }\n\n}"
},
{
"identifier": "JudgeServerMapper",
"path": "DataBackup/src/main/java/top/hcode/hoj/mapper/JudgeServerMapper.java",
"snippet": "@Mapper\n@Repository\npublic interface JudgeServerMapper extends BaseMapper<JudgeServer> {\n\n}"
},
{
"identifier": "JudgeServer",
"path": "api/src/main/java/top/hcode/hoj/pojo/entity/judge/JudgeServer.java",
"snippet": "@Data\n@EqualsAndHashCode(callSuper = false)\n@Accessors(chain = true)\n@ApiModel(value = \"JudgeServer对象\", description = \"判题服务器配置\")\npublic class JudgeServer {\n private static final long serialVersionUID = 1L;\n\n @TableId(value = \"id\", type = IdType.AUTO)\n private Integer id;\n\n @ApiModelProperty(value = \"判题服务名字\")\n private String name;\n\n @ApiModelProperty(value = \"判题机ip\")\n private String ip;\n\n @ApiModelProperty(value = \"判题机端口号\")\n private Integer port;\n\n @ApiModelProperty(value = \"ip:port\")\n private String url;\n\n @ApiModelProperty(value = \"判题机所在服务器cpu核心数\")\n private Integer cpuCore;\n\n @ApiModelProperty(value = \"当前判题数\")\n private Integer taskNumber;\n\n @ApiModelProperty(value = \"判题并发最大数\")\n private Integer maxTaskNumber;\n\n @ApiModelProperty(value = \"0可用,1不可用\")\n private Integer status;\n\n @ApiModelProperty(value = \"是否为远程判题vj\")\n private Boolean isRemote;\n\n @ApiModelProperty(value = \"是否可提交CF\")\n private Boolean cfSubmittable;\n\n @TableField(fill = FieldFill.INSERT)\n private Date gmtCreate;\n\n @TableField(fill = FieldFill.INSERT_UPDATE)\n private Date gmtModified;\n\n}"
},
{
"identifier": "JudgeServerEntityService",
"path": "JudgeServer/src/main/java/top/hcode/hoj/dao/JudgeServerEntityService.java",
"snippet": "public interface JudgeServerEntityService extends IService<JudgeServer> {\n\n public HashMap<String, Object> getJudgeServerInfo();\n}"
}
] | import cn.hutool.core.map.MapUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;
import top.hcode.hoj.judge.SandboxRun;
import top.hcode.hoj.mapper.JudgeServerMapper;
import top.hcode.hoj.pojo.entity.judge.JudgeServer;
import top.hcode.hoj.dao.JudgeServerEntityService;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap; | 6,782 | package top.hcode.hoj.dao.impl;
/**
* @Author: Himit_ZH
* @Date: 2021/4/15 11:27
* @Description:
*/
@Service
@Slf4j(topic = "hoj")
@RefreshScope | package top.hcode.hoj.dao.impl;
/**
* @Author: Himit_ZH
* @Date: 2021/4/15 11:27
* @Description:
*/
@Service
@Slf4j(topic = "hoj")
@RefreshScope | public class JudgeServerEntityServiceImpl extends ServiceImpl<JudgeServerMapper, JudgeServer> implements JudgeServerEntityService { | 2 | 2023-12-03 14:15:51+00:00 | 8k |
FIREBOTICS/SwerveBot | src/main/java/frc/robot/RobotContainer.java | [
{
"identifier": "ControllerConstants",
"path": "src/main/java/frc/robot/Constants.java",
"snippet": "public static final class ControllerConstants {\n\n public static final int driverGamepadPort = 0;\n\n public static final double joystickDeadband = 0.15;\n\n public static final double triggerPressedThreshhold = 0.25;\n}"
},
{
"identifier": "IncreaseSpdCmd",
"path": "src/main/java/frc/robot/commands/drivetrain/IncreaseSpdCmd.java",
"snippet": "public class IncreaseSpdCmd extends Command {\n\n private final SwerveSys swerveSys;\n\n private final double difference;\n\n public IncreaseSpdCmd(double difference, SwerveSys swerveSys) {\n this.swerveSys = swerveSys;\n this.difference = difference;\n }\n\n @Override\n public void initialize() {\n\n }\n\n @Override\n public void execute() {\n swerveSys.increaseSpeedFactor(difference);\n }\n\n @Override\n public void end(boolean interrupted) {\n\n }\n\n @Override\n public boolean isFinished() {\n\n return true;\n\n }\n \n}"
},
{
"identifier": "DecreaseSpdCmd",
"path": "src/main/java/frc/robot/commands/drivetrain/DecreaseSpdCmd.java",
"snippet": "public class DecreaseSpdCmd extends Command {\n\n private final SwerveSys swerveSys;\n\n\n private final double difference;\n\n public DecreaseSpdCmd(double difference, SwerveSys swerveSys) {\n this.swerveSys = swerveSys;\n this.difference = difference;\n }\n\n @Override\n public void initialize() {\n }\n\n @Override\n public void execute() {\n swerveSys.decreaseSpeedFactor(difference);\n }\n\n @Override\n public void end(boolean interrupted) {\n\n }\n\n @Override\n public boolean isFinished() {\n\n return true;\n\n }\n \n}"
},
{
"identifier": "LockCmd",
"path": "src/main/java/frc/robot/commands/drivetrain/LockCmd.java",
"snippet": "public class LockCmd extends Command {\n\n private final SwerveSys swerveSys;\n\n /**\n * Constructs a new SetLockedCmd.\n * \n * <p>SetLockedCmd is used to set whether the drive base will lock, forming an X-pattern with the wheels.\n * \n * <p>The command finishes instantly.\n * \n * @param swerveSys The SwerveSys to modify.\n */\n public LockCmd(SwerveSys swerveSys) {\n this.swerveSys = swerveSys;\n }\n\n // Called when the command is initially scheduled.\n @Override\n public void initialize() {\n \n }\n\n // Called every time the scheduler runs while the command is scheduled.\n @Override\n public void execute() {\n swerveSys.lock();\n }\n \n // Called once the command ends or is interrupted.\n @Override\n public void end(boolean interrupted) {\n \n }\n \n // Returns true when the command should end.\n @Override\n public boolean isFinished() {\n return false;\n }\n\n // Whether the command should run when robot is disabled.\n @Override\n public boolean runsWhenDisabled() {\n return false;\n }\n}"
},
{
"identifier": "ResetHeadingCmd",
"path": "src/main/java/frc/robot/commands/drivetrain/ResetHeadingCmd.java",
"snippet": "public class ResetHeadingCmd extends Command {\n\n private final SwerveSys swerveSys;\n\n\n public ResetHeadingCmd(SwerveSys swerveSys) {\n\n this.swerveSys = swerveSys;\n\n }\n\n @Override\n public void initialize() {\n\n }\n\n @Override\n public void execute() {\n\n swerveSys.resetHeading();\n\n }\n\n @Override\n public void end(boolean interrupted) {\n\n }\n\n @Override\n public boolean isFinished() {\n\n return true;\n\n }\n \n}"
},
{
"identifier": "SwerveDriveCmd",
"path": "src/main/java/frc/robot/commands/drivetrain/SwerveDriveCmd.java",
"snippet": "public class SwerveDriveCmd extends Command {\n\n /**\n * Command to allow for driver input in teleop\n * Can't be inlined efficiently if we want to edit the inputs in any way (deadband, square, etc.)\n */\n\n private final SwerveSys swerveSys;\n\n /**\n * Joysticks return DoubleSuppliers when the get methods are called\n * This is so that joystick getter methods can be passed in as a parameter but will continuously update, \n * versus using a double which would only update when the constructor is called\n */\n private final DoubleSupplier drive;\n private final DoubleSupplier strafe;\n private final DoubleSupplier rot;\n \n private final boolean isFieldRelative;\n\n /**\n * Constructs a new SwerveDriveCmd.\n * \n * <p>SwerveDriveCmd is used to control the swerve drive base with arcade drive.\n * \n * @param drive The commanded forward/backward lateral motion.\n * @param strafe The commanded left/right lateral motion.\n * @param rot The commanded rotational motion.\n * @param isFieldRelative Whether the commanded inputs are field- or robot-oriented.\n * @param swerveSys The required SwerveSys.\n */\n public SwerveDriveCmd(\n DoubleSupplier drive, \n DoubleSupplier strafe, \n DoubleSupplier rot,\n boolean isFieldRelative,\n SwerveSys swerveSys\n ) {\n\n this.swerveSys = swerveSys;\n\n this.drive = drive;\n this.strafe = strafe;\n this.rot = rot;\n\n this.isFieldRelative = isFieldRelative;\n\n addRequirements(swerveSys);\n\n }\n \n @Override\n public void execute() {\n\n /**\n * Units are given in meters per second radians per second\n * Since joysticks give output from -1 to 1, we multiply the outputs by the max speed\n * Otherwise, our max speed would be 1 meter per second and 1 radian per second\n */\n\n double drive = this.drive.getAsDouble();\n drive *= Math.abs(drive);\n\n double strafe = this.strafe.getAsDouble();\n strafe *= Math.abs(strafe);\n\n double rot = this.rot.getAsDouble();\n rot *= Math.abs(rot);\n\n swerveSys.drive(\n -drive,\n -strafe,\n -rot,\n isFieldRelative\n );\n\n }\n\n}"
},
{
"identifier": "SwerveSys",
"path": "src/main/java/frc/robot/subsystems/SwerveSys.java",
"snippet": "public class SwerveSys extends SubsystemBase {\n\n // Initializes swerve module objects\n private final SwerveModule frontLeftMod = \n new SwerveModule(\n CANDevices.frontLeftDriveMotorId,\n CANDevices.frontLeftSteerMotorId,\n CANDevices.frontLeftSteerEncoderId,\n DriveConstants.frontLeftModOffset,\n CANDevices.frontLeftReversed\n );\n\n private final SwerveModule frontRightMod = \n new SwerveModule(\n CANDevices.frontRightDriveMotorId,\n CANDevices.frontRightSteerMotorId,\n CANDevices.frontRightSteerEncoderId,\n DriveConstants.frontRightModOffset,\n CANDevices.frontRightReversed\n );\n\n private final SwerveModule rearLeftMod = \n new SwerveModule(\n CANDevices.rearLeftDriveMotorId,\n CANDevices.rearLeftSteerMotorId,\n CANDevices.rearLeftSteerEncoderId,\n DriveConstants.rearLeftModOffset,\n CANDevices.rearLeftReversed\n );\n\n private final SwerveModule rearRightMod = \n new SwerveModule(\n CANDevices.rearRightDriveMotorId,\n CANDevices.rearRightSteerMotorId,\n CANDevices.rearRightSteerEncoderId,\n DriveConstants.rearRightModOffset,\n CANDevices.rearRightReversed\n );\n\n private boolean isLocked = false;\n public boolean isLocked() {\n return isLocked;\n }\n\n private boolean isFieldOriented = false;\n public boolean isFieldOriented() {\n return isFieldOriented;\n }\n\n private double speedFactor = 0.3; //Speed\n private boolean speedChanged = false;\n public double getSpeedFactor() {\n return speedFactor;\n }\n public void setSpeedFactor(double newSpeedFactor) {\n speedChanged = true;\n this.speedFactor = newSpeedFactor;\n SmartDashboard.updateValues();\n }\n public void increaseSpeedFactor(double difference) {\n setSpeedFactor(speedFactor + difference);\n }\n public void decreaseSpeedFactor(double difference) {\n System.out.println(speedFactor);\n setSpeedFactor(speedFactor - difference);\n System.out.println(speedFactor);\n }\n\n private boolean isTracking = false;\n public boolean isTracking() {\n return isTracking;\n }\n public void setIsTracking(boolean isTracking) {\n this.isTracking = isTracking;\n }\n\n private final AHRS navX = new AHRS(SPI.Port.kMXP);\n\n // Odometry for the robot, measured in meters for linear motion and radians for rotational motion\n // Takes in kinematics and robot angle for parameters\n\n private SwerveDrivePoseEstimator odometry = \n new SwerveDrivePoseEstimator(\n DriveConstants.kinematics,\n getHeading(),\n getModulePositions(),\n new Pose2d()\n );\n\n /**\n * Constructs a new SwerveSys.\n * \n * <p>SwerveCmd contains 4 {@link SwerveModule}, a gyro, and methods to control the drive base and odometry.\n */\n public SwerveSys() {\n // Resets the measured distance driven for each module\n resetDriveDistances();\n\n resetPose();\n SmartDashboard.putNumber(\"Speed Percent\", speedFactor);\n\n }\n \n // This method will be called once per scheduler run\n @Override\n public void periodic() {\n // Updates the odometry every 20ms\n odometry.update(getHeading(), getModulePositions());\n\n SmartDashboard.putNumber(\"front left CANcoder\", frontLeftMod.getCanCoderAngle().getDegrees());\n SmartDashboard.putNumber(\"front right CANcoder\", frontRightMod.getCanCoderAngle().getDegrees());\n SmartDashboard.putNumber(\"rear left CANcoder\", rearLeftMod.getCanCoderAngle().getDegrees());\n SmartDashboard.putNumber(\"rear right CANcoder\", rearRightMod.getCanCoderAngle().getDegrees());\n\n if (speedChanged) speedChanged = false;\n else speedFactor = SmartDashboard.getNumber(\"Speed Percent\", speedFactor);\n }\n \n /**\n * Inputs drive values into the swerve drive base.\n * \n * @param driveX The desired forward/backward lateral motion, in meters per second.\n * @param driveY The desired left/right lateral motion, in meters per second.\n * @param rotation The desired rotational motion, in radians per second.\n * @param isFieldOriented whether driving is field- or robot-oriented.\n */\n public void drive(double driveX, double driveY, double rotation, boolean isFieldRelative) { \n if(driveX != 0.0 || driveY != 0.0 || rotation != 0.0) isLocked = false;\n isFieldOriented = isFieldRelative;\n \n if(isLocked) {\n setModuleStates(new SwerveModuleState[] {\n new SwerveModuleState(0.0, new Rotation2d(0.25 * Math.PI)),\n new SwerveModuleState(0.0, new Rotation2d(-0.25 * Math.PI)),\n new SwerveModuleState(0.0, new Rotation2d(-0.25 * Math.PI)),\n new SwerveModuleState(0.0, new Rotation2d(0.25 * Math.PI))\n });\n }\n else {\n // Reduces the speed of the drive base for \"turtle\" or \"sprint\" modes.\n driveX *= speedFactor;\n driveY *= speedFactor;\n rotation *= speedFactor; //TODO: make individually modifiable\n\n // Represents the overall state of the drive base.\n ChassisSpeeds speeds =\n isFieldRelative\n ? ChassisSpeeds.fromFieldRelativeSpeeds(\n driveX, driveY, rotation, getHeading())\n : new ChassisSpeeds(driveX, driveY, rotation); //If you put - on rotation it the wheels goes backwards not the angle\n\n // Uses kinematics (wheel placements) to convert overall robot state to array of individual module states.\n SwerveModuleState[] states = DriveConstants.kinematics.toSwerveModuleStates(speeds);\n \n // Makes sure the wheels don't try to spin faster than the maximum speed possible\n SwerveDriveKinematics.desaturateWheelSpeeds(states, DriveConstants.maxDriveSpeedMetersPerSec);\n\n setModuleStates(states);\n }\n }\n\n /**\n * Stops the driving of the robot.\n * <p>Sets the drive power of each module to zero while maintaining module headings.\n */\n public void stop() {\n drive(0.0, 0.0, 0.0, isFieldOriented);\n }\n\n // TODO: javadoc\n public void lock() {\n isLocked = true;\n }\n\n /**\n * Sets the desired state for each swerve module.\n * <p>Uses PID and feedforward control (closed-loop) to control the linear and rotational values for the modules.\n * \n * @param moduleStates the module states to set.\n */\n public void setModuleStates(SwerveModuleState[] moduleStates) {\n frontLeftMod.setDesiredState(moduleStates[0], false);\n frontRightMod.setDesiredState(moduleStates[1], false);\n rearLeftMod.setDesiredState(moduleStates[2], false);\n rearRightMod.setDesiredState(moduleStates[3], false);\n }\n\n /**\n * Sets the desired state for each swerve module.\n * <p>Uses PID and feedforward control to control the linear and rotational values for the modules.\n * \n * @param moduleStates the module states to set.\n */\n public void setModuleStatesAuto(SwerveModuleState[] moduleStates) {\n frontLeftMod.setDesiredState(moduleStates[0], true);\n frontRightMod.setDesiredState(moduleStates[1], true);\n rearLeftMod.setDesiredState(moduleStates[2], true);\n rearRightMod.setDesiredState(moduleStates[3], true);\n }\n\n public void setChassisSpeeds(ChassisSpeeds chassisSpeeds) {\n setModuleStatesAuto(DriveConstants.kinematics.toSwerveModuleStates(chassisSpeeds));\n }\n \n\n /**\n * Returns an array of module states.\n * \n * @return An array of SwerveModuleState.\n */\n public SwerveModuleState[] getModuleStates() {\n return new SwerveModuleState[] {\n new SwerveModuleState(frontLeftMod.getCurrentVelocityMetersPerSecond(), frontLeftMod.getSteerEncAngle()),\n new SwerveModuleState(frontRightMod.getCurrentVelocityMetersPerSecond(), frontRightMod.getSteerEncAngle()),\n new SwerveModuleState(rearLeftMod.getCurrentVelocityMetersPerSecond(), rearLeftMod.getSteerEncAngle()),\n new SwerveModuleState(rearRightMod.getCurrentVelocityMetersPerSecond(), rearRightMod.getSteerEncAngle())\n };\n }\n\n /**\n * Returns an array of module positions.\n * \n * @return An array of SwerveModulePosition.\n */\n public SwerveModulePosition[] getModulePositions() {\n return new SwerveModulePosition[] {\n frontLeftMod.getPosition(),\n frontRightMod.getPosition(),\n rearLeftMod.getPosition(),\n rearRightMod.getPosition()\n };\n }\n\n /**\n * @return The current estimated position of the robot on the field\n * based on drive encoder and gyro readings.\n */\n public Pose2d getPose() {\n return odometry.getEstimatedPosition();\n }\n\n /**\n * Resets the current pose.\n */\n public void resetPose() {\n resetDriveDistances();\n resetHeading();\n\n odometry = new SwerveDrivePoseEstimator(\n DriveConstants.kinematics,\n new Rotation2d(),\n getModulePositions(),\n new Pose2d()\n );\n }\n\n public void setHeading(Rotation2d heading) {\n double desiredYaw = Math.abs(heading.getDegrees() % 360.0);\n navX.setAngleAdjustment(-desiredYaw);\n \n }\n\n /**\n * Sets the pose of the robot.\n * \n * @param pose The pose to set the robot to.\n */\n public void setPose(Pose2d pose) {\n setHeading(pose.getRotation());\n\n odometry = new SwerveDrivePoseEstimator(\n DriveConstants.kinematics,\n pose.getRotation(),\n getModulePositions(),\n pose\n );\n }\n\n /**\n * Resets the measured distance driven for each module.\n */\n public void resetDriveDistances() {\n frontLeftMod.resetDistance();\n frontRightMod.resetDistance();\n rearLeftMod.resetDistance();\n rearRightMod.resetDistance();\n }\n\n /**\n * Returns the average distance driven of each module to get an overall distance driven by the robot.\n * \n * @return The overall distance driven by the robot in meters.\n */\n public double getAverageDriveDistanceMeters() {\n return (\n (frontLeftMod.getDriveDistanceMeters()\n + frontRightMod.getDriveDistanceMeters()\n + rearLeftMod.getDriveDistanceMeters()\n + rearRightMod.getDriveDistanceMeters())\n / 4.0\n );\n }\n\n /**\n * Returns the average velocity of each module to get an overall velocity of the robot.\n * \n * @return The overall velocity of the robot in meters per second.\n */\n public double getAverageDriveVelocityMetersPerSecond() {\n return (\n (Math.abs(frontLeftMod.getCurrentVelocityMetersPerSecond())\n + Math.abs(frontRightMod.getCurrentVelocityMetersPerSecond())\n + Math.abs(rearLeftMod.getCurrentVelocityMetersPerSecond() )\n + Math.abs(rearRightMod.getCurrentVelocityMetersPerSecond()))\n / 4.0\n );\n }\n\n /**\n * Returns the average direction of each module to get an overall direction of travel of the robot.\n * \n * @return The overall direction of travel of the robot\n */\n public Rotation2d getDirectionOfTravel() {\n return new Rotation2d(\n (frontLeftMod.getCanCoderAngle().plus(new Rotation2d(frontLeftMod.getCurrentVelocityMetersPerSecond() < 0.0 ? Math.PI : 0.0)).getRadians()\n + frontRightMod.getCanCoderAngle().plus(new Rotation2d(frontRightMod.getCurrentVelocityMetersPerSecond() < 0.0 ? Math.PI : 0.0)).getRadians()\n + rearLeftMod.getCanCoderAngle().plus(new Rotation2d(rearLeftMod.getCurrentVelocityMetersPerSecond() < 0.0 ? Math.PI : 0.0)).getRadians()\n + rearRightMod.getCanCoderAngle().plus(new Rotation2d(rearRightMod.getCurrentVelocityMetersPerSecond() < 0.0 ? Math.PI : 0.0)).getRadians()\n ) / 4.0\n );\n }\n\n /**\n * Returns the average velocity in the forward direction.\n * \n * @return The velocity in the forward direction of the robot in meters per second.\n */\n public double getForwardVelocityMetersPerSecond() {\n double rel = Math.abs(getDirectionOfTravel().getDegrees() % 90.0);\n if(getDirectionOfTravel().getDegrees() > 90.0 || getDirectionOfTravel().getDegrees() < -90.0)\n rel -= 90.0;\n\n return getAverageDriveVelocityMetersPerSecond() * (Math.copySign((90.0 - rel), rel) / 90.0);\n }\n\n /**\n * Returns the current heading of the robot from the gyro.\n * \n * @return The current heading of the robot.\n */\n public Rotation2d getHeading() {\n return Rotation2d.fromDegrees(-navX.getYaw());\n }\n \n\n /**\n * Returns the current pitch of the robot from the gyro.\n * \n * @return The current pitch of the robot.\n */\n public double getPitchDegrees() {\n // IMU is turned 90 degrees, so pitch and roll are flipped.\n return navX.getPitch();\n }\n\n /**\n * Returns the current roll of the robot from the gyro.\n * \n * @return The current roll of the robot.\n */\n public double getRollDegrees() {\n // IMU is turned 90 degrees, so pitch and roll are flipped.\n return navX.getRoll();\n }\n\n /**\n * Sets the gyro heading to zero.\n */\n public void resetHeading() {\n navX.zeroYaw();\n }\n\n public void setDriveCurrentLimit(int amps) {\n frontLeftMod.setDriveCurrentLimit(amps);\n frontRightMod.setDriveCurrentLimit(amps);\n rearLeftMod.setDriveCurrentLimit(amps);\n rearRightMod.setDriveCurrentLimit(amps);\n }\n}"
}
] | import edu.wpi.first.wpilibj.XboxController;
import edu.wpi.first.wpilibj.smartdashboard.SendableChooser;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
import edu.wpi.first.wpilibj2.command.Command;
import edu.wpi.first.wpilibj2.command.button.JoystickButton;
import edu.wpi.first.wpilibj2.command.button.Trigger;
import frc.robot.Constants.ControllerConstants;
import frc.robot.commands.drivetrain.IncreaseSpdCmd;
import frc.robot.commands.drivetrain.DecreaseSpdCmd;
import frc.robot.commands.drivetrain.LockCmd;
import frc.robot.commands.drivetrain.ResetHeadingCmd;
import frc.robot.commands.drivetrain.SwerveDriveCmd;
import frc.robot.subsystems.SwerveSys; | 5,661 | package frc.robot;
public class RobotContainer {
// Initialize subsystems.
private final SwerveSys swerveSys = new SwerveSys();
// Initialize joysticks.
private final XboxController driverController = new XboxController(ControllerConstants.driverGamepadPort);
private final JoystickButton driverMenuBtn = new JoystickButton(driverController, 8);
private final Trigger driverLeftTriggerBtn =
new Trigger(() -> driverController.getLeftTriggerAxis() > ControllerConstants.triggerPressedThreshhold);
private final Trigger driverSpeedUpButton =
new Trigger(() -> driverController.getXButtonPressed());
private final Trigger driverSlowDownButton =
new Trigger(() -> driverController.getAButtonPressed());
// Initialize auto selector.
SendableChooser<Command> autoSelector = new SendableChooser<Command>();
public RobotContainer() {
SmartDashboard.putData("auto selector", autoSelector);
configDriverBindings();
}
public void configDriverBindings() {
swerveSys.setDefaultCommand(
new SwerveDriveCmd(
() -> deadband(driverController.getLeftY()),
() -> deadband(driverController.getLeftX()),
() -> deadband(driverController.getRightX()),
true, //Switch to False for Chairbot Mode
swerveSys
)
); | package frc.robot;
public class RobotContainer {
// Initialize subsystems.
private final SwerveSys swerveSys = new SwerveSys();
// Initialize joysticks.
private final XboxController driverController = new XboxController(ControllerConstants.driverGamepadPort);
private final JoystickButton driverMenuBtn = new JoystickButton(driverController, 8);
private final Trigger driverLeftTriggerBtn =
new Trigger(() -> driverController.getLeftTriggerAxis() > ControllerConstants.triggerPressedThreshhold);
private final Trigger driverSpeedUpButton =
new Trigger(() -> driverController.getXButtonPressed());
private final Trigger driverSlowDownButton =
new Trigger(() -> driverController.getAButtonPressed());
// Initialize auto selector.
SendableChooser<Command> autoSelector = new SendableChooser<Command>();
public RobotContainer() {
SmartDashboard.putData("auto selector", autoSelector);
configDriverBindings();
}
public void configDriverBindings() {
swerveSys.setDefaultCommand(
new SwerveDriveCmd(
() -> deadband(driverController.getLeftY()),
() -> deadband(driverController.getLeftX()),
() -> deadband(driverController.getRightX()),
true, //Switch to False for Chairbot Mode
swerveSys
)
); | driverMenuBtn.onTrue(new ResetHeadingCmd(swerveSys)); | 4 | 2023-11-30 00:00:43+00:00 | 8k |
yichenhsiaonz/EscAIpe-room-final | src/main/java/nz/ac/auckland/se206/TextToSpeechManager.java | [
{
"identifier": "SharedElements",
"path": "src/main/java/nz/ac/auckland/se206/controllers/SharedElements.java",
"snippet": "public class SharedElements {\n\n private static SharedElements instance;\n private static HBox[] taskBarHorizontalBoxList = new HBox[3];\n private static VBox[] inventoryVBoxList = new VBox[3];\n private static TextArea[] chatBoxList = new TextArea[3];\n private static TextArea[] hintBoxList = new TextArea[3];\n private static Button[] hintButtonList = new Button[3];\n private static HBox[] chatBubbleList = new HBox[3];\n\n /**\n * This method should be called when a new game is started. It will clear all previous instances\n * of the SharedElements class and create new instances for the new game.\n */\n public static void newGame() throws ApiProxyException {\n // clear all previous instances\n taskBarHorizontalBoxList = new HBox[3];\n inventoryVBoxList = new VBox[3];\n chatBoxList = new TextArea[3];\n hintBoxList = new TextArea[3];\n hintButtonList = new Button[3];\n chatBubbleList = new HBox[3];\n // create new instances\n instance = new SharedElements();\n }\n\n /**\n * Returns the master mute button text.\n *\n * @return Text containing the mute button text\n */\n public static Text getMuteText() {\n return instance.muteText;\n }\n\n /** Toggles the master mute button text between mute and unmute. */\n public static void toggleMuteText() {\n if (instance.muteText.getText().equals(\"MUTE\")) {\n instance.muteText.setText(\"UNMUTE\");\n } else {\n instance.muteText.setText(\"MUTE\");\n }\n }\n\n /**\n * Allocates an instance of a child ChatBox. Should not be called again until\n * incremnetLoadedScenes() is called.\n *\n * @return TextArea containing the chat box\n */\n public static TextArea getChatBox() {\n // allocate a dialogue box instance to each scene\n return chatBoxList[instance.loadedScenes];\n }\n\n /**\n * Allocates an instance of a child HintBox. Should not be called again until\n * incremnetLoadedScenes() is called.\n *\n * @return TextArea containing the hint box\n */\n public static TextArea getHintBox() {\n // allocate a dialogue box instance to each scene\n return hintBoxList[instance.loadedScenes];\n }\n\n /**\n * Allocates an instance of a child taskBarHorizontalBox. Should not be called again until\n * incremnetLoadedScenes() is called. This is the task bar at the bottom of the screen. It\n * contains the hint list, send message box, the buttons to show the chat history and hint list,\n * and the button to use a hint.\n *\n * @return HBox containing the task bar\n */\n public static HBox getTaskBarBox() {\n // allocate a task bar instance to each scene\n return taskBarHorizontalBoxList[instance.loadedScenes];\n }\n\n /**\n * Allocates an instance of a child inventoryVBox. Should not be called again until\n * incremnetLoadedScenes() is called. This is the inventory box on the right of the screen. It\n * contains the items the player has collected.\n *\n * @return VBox containing the inventory box\n */\n public static VBox getInventoryBox() {\n // allocate an inventory instance to each scene\n return inventoryVBoxList[instance.loadedScenes];\n }\n\n /**\n * Allocates an instance of a child hintButton. Should not be called again until\n * incremnetLoadedScenes() is called This is the button to use a hint.\n *\n * @return Button containing the hint button\n */\n public static Button getHintButton() {\n return hintButtonList[instance.loadedScenes];\n }\n\n /**\n * Allocates an instance of a child chatBubble. Should not be called again until\n * incremnetLoadedScenes() is called. This is the chat bubble that appears when the AI speaks.\n *\n * @return HBox containing the chat bubble\n */\n public static HBox getChatBubble() {\n return chatBubbleList[instance.loadedScenes];\n }\n\n /**\n * Increments the number of scenes that have been loaded Should be called after each scene is\n * loaded. This is used to determine which set of children to allocate to each scene.\n */\n public static void incremnetLoadedScenes() {\n instance.loadedScenes++;\n }\n\n /**\n * Returns the master message box This is the box where the player types their message to send to\n * the AI.\n *\n * @return TextField containing the message box\n */\n public static TextField getMessageBox() {\n return instance.messageBox;\n }\n\n /**\n * Adds items to each inventory child instance.\n *\n * @param item ImageView array containing three copies of the items to add to each inventory child\n * instance\n */\n public static void addInventoryItem(ImageView[] item) {\n // add item to each inventory instance\n for (int i = 0; i < 3; i++) {\n inventoryVBoxList[i].getChildren().add(item[i]);\n item[i].setFitWidth(100);\n item[i].setFitHeight(100);\n }\n }\n\n /**\n * Removes items from each inventory child instance.\n *\n * @param item ImageView array containing three copies of the items to remove from each inventory\n * child instance\n */\n public static void removeInventoryItem(ImageView[] item) {\n // remove item from each inventory instance\n for (int i = 0; i < 3; i++) {\n inventoryVBoxList[i].getChildren().remove(item[i]);\n }\n }\n\n /**\n * Adds text to the master chat box and scrolls each child chat box to the bottom.\n *\n * @param message String containing the message to add to the master chat box\n */\n public static void appendChat(String message) {\n // append message to master chat box with a newline below\n instance.chatBox.appendText(message + \"\\n\\n\");\n }\n\n /**\n * Adds text to the master hint box and scrolls each child hint box to the bottom.\n *\n * @param message String containing the message to add to the master hint box\n */\n public static void appendHint(String message) {\n // append message to master chat box with a newline below\n instance.hintBox.appendText(message + \"\\n\\n\");\n for (int i = 0; i < 3; i++) {\n hintBoxList[i].setScrollTop(Double.MAX_VALUE);\n }\n }\n\n /**\n * Sets the text of the master chat bubble label and shows each child chat bubble. If the game is\n * not muted, calls the TextToSpeechManager to speak the message and hides each child chat bubble\n * when the message is finished. If the game is muted, hides each child chat bubble after 4\n * seconds.\n *\n * @param message String containing the message to set the master chat box to\n */\n public static void chatBubbleSpeak(String message) {\n for (int i = 0; i < 3; i++) {\n chatBubbleList[i].setVisible(true);\n }\n\n // text roll on animation for bubble\n Platform.runLater(\n () -> {\n final IntegerProperty i = new SimpleIntegerProperty(0);\n Timeline timeline = new Timeline();\n KeyFrame keyFrame =\n new KeyFrame(\n // sets the duration of the text roll\n Duration.seconds(0.01),\n event -> {\n if (i.get() < message.length()) {\n instance.chatLabel.setText(message.substring(0, i.get() + 1));\n i.set(i.get() + 1);\n } else {\n timeline.stop();\n }\n });\n timeline.getKeyFrames().add(keyFrame);\n timeline.setCycleCount(message.length() + 1);\n timeline.play();\n });\n\n // if game is not muted, speak message, play without speaking otherwise\n if (!GameState.getMuted()) {\n TextToSpeechManager.speak(message);\n } else {\n // hide chat bubble after 4 seconds\n GameState.delayRun(\n () -> {\n for (int i = 0; i < 3; i++) {\n chatBubbleList[i].setVisible(false);\n }\n },\n 4);\n }\n }\n\n /** This method hides the chat bubble for the user. */\n public static void hideChatBubble() {\n for (int i = 0; i < 3; i++) {\n chatBubbleList[i].setVisible(false);\n }\n }\n\n /**\n * Sets the text of the hints button to the number of hints left.\n *\n * @param hints The number of hints left\n */\n public static void setHintsText(int hints) {\n // set master hint button text\n if (hints == 0) {\n // disable hints button if no hints left\n instance.hintButton.setText(\"NO HINTS LEFT\");\n instance.hintButton.setDisable(true);\n } else if (hints < 0) {\n // set hints to unlimited if on easy mode\n instance.hintButton.setText(\"USE HINT: INFINITE\");\n } else {\n instance.hintButton.setText(\"USE HINT: \" + hints);\n }\n }\n\n public static void disableHintsButton() {\n instance.hintButton.setDisable(true);\n }\n\n public static void enableHintsButton() {\n instance.hintButton.setDisable(false);\n }\n\n public static void disableSendButton() {\n instance.sendMessage.setDisable(true);\n }\n\n public static void enableSendButton() {\n instance.sendMessage.setDisable(false);\n }\n\n public static void printPaper() {\n instance.isPaperPrinted = true;\n }\n\n public static void takePaper() {\n instance.isPaperPrinted = false;\n }\n\n public static boolean isPaperPrinted() {\n return instance.isPaperPrinted;\n }\n\n /**\n * This method is called to initalize the different rooms. It fits the elements to the screen\n * size.\n *\n * @param room The room to initialize\n * @param bottomVerticalBox The task bar box\n * @param inventoryPane The inventory box\n * @param dialogueHorizontalBox The chat bubble\n * @param muteButton The mute button\n * @param contentPane The content pane\n */\n public static void initialize(\n AnchorPane room,\n VBox bottomVerticalBox,\n Pane inventoryPane,\n HBox dialogueHorizontalBox,\n Button muteButton,\n AnchorPane contentPane) {\n // get shared elements from the SharedElements class\n HBox bottom = SharedElements.getTaskBarBox();\n TextArea chatBox = SharedElements.getChatBox();\n TextArea hintBox = SharedElements.getHintBox();\n VBox inventory = SharedElements.getInventoryBox();\n HBox chatBubble = SharedElements.getChatBubble();\n\n // add shared elements to the correct places\n room.getChildren().addAll(chatBox, hintBox);\n AnchorPane.setBottomAnchor(chatBox, 0.0);\n AnchorPane.setLeftAnchor(chatBox, 0.0);\n AnchorPane.setBottomAnchor(hintBox, 0.0);\n AnchorPane.setLeftAnchor(hintBox, 0.0);\n bottomVerticalBox.getChildren().add(bottom);\n inventoryPane.getChildren().add(inventory);\n dialogueHorizontalBox.getChildren().add(chatBubble);\n SharedElements.incremnetLoadedScenes();\n // scale the room to the screen size\n GameState.scaleToScreen(contentPane);\n\n // bind the mute button to the GameState muted property\n muteButton.textProperty().bind(SharedElements.getMuteText().textProperty());\n }\n\n @FXML private VBox dialogueBox;\n @FXML private HBox sendBox;\n @FXML private Label timerLabel;\n @FXML private Label powerLabel;\n @FXML private ProgressBar timerProgressBar;\n @FXML private TextField messageBox;\n @FXML private TextArea hintBox;\n @FXML private TextArea chatBox;\n @FXML private Button sendMessage;\n @FXML private Button hintButton;\n @FXML private Button showChatBox;\n @FXML private Button showHintBox;\n @FXML private Text muteText;\n @FXML private Label chatLabel;\n @FXML private SimpleDoubleProperty chatScrolDoubleProperty;\n @FXML private SimpleDoubleProperty hintScrolDoubleProperty;\n\n private int loadedScenes;\n private boolean isPaperPrinted = false;\n\n private SharedElements() throws ApiProxyException {\n\n // create master mute button text\n muteText = new Text();\n muteText.setText(\"MUTE\");\n\n // create new master timer label and progress bar\n timerLabel = new Label();\n timerProgressBar = new ProgressBar();\n\n // bind master timer label and progress bar to game state timer\n Task<Void> timerTask = GameState.getTimer();\n\n timerLabel.textProperty().bind(timerTask.messageProperty());\n timerProgressBar.progressProperty().bind(timerTask.progressProperty());\n\n // create new master send message field\n messageBox = new TextField();\n messageBox.setOnKeyPressed(\n new EventHandler<KeyEvent>() {\n @Override\n public void handle(KeyEvent ke) {\n if (ke.getCode().equals(KeyCode.ENTER)) {\n try {\n GameState.onMessageSent();\n } catch (ApiProxyException e) {\n e.printStackTrace();\n }\n }\n }\n });\n\n // create new master hint box\n hintBox = new TextArea();\n hintBox.setVisible(false);\n\n // create new hint scroll property\n hintScrolDoubleProperty = new SimpleDoubleProperty(0.0);\n\n // create new master chat box\n chatBox = new TextArea();\n chatBox.setVisible(false);\n\n // create new chat scroll property\n chatScrolDoubleProperty = new SimpleDoubleProperty(0.0);\n\n // create new master hint button\n hintButton = new Button();\n // assign script to hint button\n hintButton.setOnAction(\n event -> {\n try {\n\n GameState.getPuzzleHint();\n } catch (ApiProxyException e) {\n e.printStackTrace();\n }\n });\n // create new master send button\n sendMessage = new Button();\n // assign script to send button\n sendMessage.setOnAction(\n event -> {\n try {\n GameState.onMessageSent();\n } catch (ApiProxyException e) {\n e.printStackTrace();\n }\n });\n\n // create master chat label\n chatLabel = new Label();\n\n // create master show chatBox button\n showChatBox = new Button();\n showChatBox.setOnAction(\n event -> {\n if (chatBox.isVisible()) {\n chatBox.setVisible(false);\n } else {\n chatBox.setVisible(true);\n }\n hintBox.setVisible(false);\n });\n\n // create master show hintBox button\n showHintBox = new Button();\n showHintBox.setOnAction(\n event -> {\n if (hintBox.isVisible()) {\n hintBox.setVisible(false);\n } else {\n hintBox.setVisible(true);\n }\n chatBox.setVisible(false);\n });\n\n loadedScenes = 0;\n for (int i = 0; i < 3; i++) {\n // use HBox to place elements side by side\n // use VBox to place elements on top of each other\n VBox inventoryVerticalBoxChild = new VBox();\n inventoryVerticalBoxChild.setPrefWidth(180);\n inventoryVerticalBoxChild.setPrefHeight(400);\n inventoryVerticalBoxChild.setSpacing(30);\n inventoryVerticalBoxChild.setAlignment(Pos.TOP_CENTER);\n inventoryVerticalBoxChild.setLayoutY(5);\n\n inventoryVBoxList[i] = inventoryVerticalBoxChild;\n\n // create new child chat box\n // bind child chat box text to master chat box\n TextArea chatBoxChild = new TextArea();\n chatBoxChild.setPrefWidth(350);\n chatBoxChild.setPrefHeight(700);\n chatBoxChild.setEditable(false);\n chatBoxChild.setWrapText(true);\n chatBoxChild.setFocusTraversable(false);\n chatBoxChild.textProperty().bind(chatBox.textProperty());\n chatBoxChild.visibleProperty().bind(chatBox.visibleProperty());\n chatBoxChild.scrollLeftProperty().bindBidirectional(chatScrolDoubleProperty);\n chatBoxChild.setPromptText(\"Chat history will appear here\");\n\n // auto scroll to the bottom when new text added to chat box\n chatBox\n .textProperty()\n .addListener(\n (observable, oldValue, newValue) -> {\n chatBoxChild.selectPositionCaret(chatBoxChild.getLength());\n chatBoxChild.deselect();\n });\n\n // add css to chat box\n chatBoxChild.getStyleClass().add(\"text-box\");\n\n chatBoxList[i] = chatBoxChild;\n\n // create new child hint box\n // bind child hint box text to master hint box\n TextArea hintBoxChild = new TextArea();\n hintBoxChild.setPrefWidth(350);\n hintBoxChild.setPrefHeight(700);\n hintBoxChild.setEditable(false);\n hintBoxChild.setWrapText(true);\n hintBoxChild.setFocusTraversable(false);\n hintBoxChild.textProperty().bind(hintBox.textProperty());\n hintBoxChild.visibleProperty().bind(hintBox.visibleProperty());\n hintBoxChild.scrollTopProperty().bindBidirectional(hintScrolDoubleProperty);\n hintBoxChild.setPromptText(\"Hints given will appear here\");\n\n // auto scroll to the bottom when new text added to hint box\n hintBox\n .textProperty()\n .addListener(\n (observable, oldValue, newValue) -> {\n hintBoxChild.selectPositionCaret(hintBoxChild.getLength());\n hintBoxChild.deselect();\n });\n\n // add css to hint box\n hintBoxChild.getStyleClass().add(\"text-box\");\n\n hintBoxList[i] = hintBoxChild;\n\n // create new child hint button\n // bind child hint button click behaviour to master hint button\n // bind child hint button disable property to master hint button\n Button hintButtonChild = new Button();\n hintButtonChild.setPrefWidth(330);\n hintButtonChild.setPrefHeight(25);\n hintButtonChild.textProperty().bind(hintButton.textProperty());\n hintButtonChild.onActionProperty().bind(hintButton.onActionProperty());\n hintButtonChild.disableProperty().bind(hintButton.disableProperty());\n\n // add css to hint button\n hintButtonChild.getStyleClass().add(\"hint-button\");\n\n // create new child chat label\n Label chatBubbleLabelChild = new Label();\n chatBubbleLabelChild.setWrapText(true);\n chatBubbleLabelChild.setPrefWidth(1200);\n chatBubbleLabelChild.setMaxWidth(1200);\n chatBubbleLabelChild.setMaxHeight(200);\n chatBubbleLabelChild.setAlignment(Pos.CENTER);\n chatBubbleLabelChild.textProperty().bind(chatLabel.textProperty());\n\n // add css to bubble label\n chatBubbleLabelChild.getStyleClass().add(\"bubble-label\");\n\n StackPane chatBubbleLabelPaneChild = new StackPane();\n chatBubbleLabelPaneChild.setPrefHeight(200);\n chatBubbleLabelPaneChild.setAlignment(Pos.CENTER);\n Image backgroundImage =\n new Image(\"images/ChatBubble/middle-bubble.png\", 216, 200, false, true);\n chatBubbleLabelPaneChild.setBackground(\n new Background(\n new BackgroundImage(\n backgroundImage,\n null,\n BackgroundRepeat.NO_REPEAT,\n BackgroundPosition.CENTER,\n null)));\n chatBubbleLabelPaneChild.setMaxWidth(1200);\n\n // add css to middle bubble pane\n chatBubbleLabelPaneChild.getChildren().add(chatBubbleLabelChild);\n\n ImageView leftChatImage = new ImageView(\"images/ChatBubble/left-bubble.png\");\n leftChatImage.setPreserveRatio(true);\n leftChatImage.setFitHeight(200);\n\n ImageView rightChatImage = new ImageView(\"images/ChatBubble/right-bubble.png\");\n rightChatImage.setPreserveRatio(true);\n rightChatImage.setFitHeight(200);\n\n HBox chatBubbleHorizontalBoxChild = new HBox();\n chatBubbleHorizontalBoxChild.setAlignment(Pos.CENTER_LEFT);\n chatBubbleHorizontalBoxChild\n .getChildren()\n .addAll(leftChatImage, chatBubbleLabelPaneChild, rightChatImage);\n chatBubbleHorizontalBoxChild.setVisible(false);\n chatBubbleList[i] = chatBubbleHorizontalBoxChild;\n\n // create buttons for showing hint and chat history\n\n Button showChatButtonChild = new Button();\n showChatButtonChild.setPrefWidth(165);\n showChatButtonChild.setPrefHeight(25);\n showChatButtonChild.setText(\"HISTORY\");\n showChatButtonChild.onActionProperty().bind(showChatBox.onActionProperty());\n\n // add css to show chat button\n showChatButtonChild.getStyleClass().add(\"chat-button\");\n\n Button showHintButtonChild = new Button();\n showHintButtonChild.setPrefWidth(165);\n showHintButtonChild.setPrefHeight(25);\n showHintButtonChild.setText(\"HINT LIST\");\n showHintButtonChild.onActionProperty().bind(showHintBox.onActionProperty());\n\n // add css to show hint button\n showHintButtonChild.getStyleClass().add(\"chat-button\");\n\n // Power left label\n Label powerLabelChild = new Label();\n powerLabelChild.setText(\"Power Left:\");\n powerLabelChild.setFont(new javafx.scene.text.Font(\"System\", 24));\n\n // add css to power left label\n powerLabelChild.getStyleClass().add(\"power-label\");\n\n // create new child timer label and progress bar\n ProgressBar timerProgressBarChild = new ProgressBar();\n timerProgressBarChild.setPrefWidth(609);\n timerProgressBarChild.setPrefHeight(35);\n Label timerLabelChild = new Label();\n timerLabelChild.setFont(new javafx.scene.text.Font(\"System\", 24));\n\n // add css to progress bar\n timerProgressBarChild.getStyleClass().add(\"progress-bar\");\n\n // bind child timer label and progress bar to master timer label and progress bar\n timerLabelChild.textProperty().bind(timerLabel.textProperty());\n timerProgressBarChild.progressProperty().bind(timerProgressBar.progressProperty());\n\n // add css to timer label\n timerLabelChild.getStyleClass().add(\"timer-label\");\n\n HBox buttonBoxChild = new HBox();\n HBox timerHorizontalBoxChild = new HBox();\n VBox timerVerticalBoxChild = new VBox();\n\n // place buttons side by side\n buttonBoxChild.getChildren().addAll(showChatButtonChild, showHintButtonChild);\n\n // add css to button box holding chat history and show hint buttons\n buttonBoxChild.getStyleClass().add(\"button-box\");\n\n // place progress bar and label side by side\n timerHorizontalBoxChild.getChildren().addAll(timerProgressBarChild, timerLabelChild);\n // place buttons above header and headver above progress bar and label\n timerVerticalBoxChild\n .getChildren()\n .addAll(buttonBoxChild, powerLabelChild, timerHorizontalBoxChild);\n\n // timer / history buttons container anchor box\n // use this to position the timer / history buttons\n AnchorPane timerAnchorPane = new AnchorPane(timerVerticalBoxChild);\n timerAnchorPane.setPrefHeight(133);\n\n // create new child message box\n // bidirectionally bind child message box text to master message box\n TextField messageBoxChild = new TextField();\n messageBoxChild.textProperty().bindBidirectional(messageBox.textProperty());\n messageBoxChild.setPrefWidth(400);\n messageBoxChild.setPrefHeight(40);\n messageBoxChild.setPromptText(\"Talk to AI-23...\");\n\n // add css to message box\n messageBoxChild.getStyleClass().add(\"message-box\");\n\n messageBoxChild.onKeyPressedProperty().bind(messageBox.onKeyPressedProperty());\n\n // create new child send button\n // bind child send button click behaviour to master send button\n // bind child send button disable property to master send button\n Button sendMessageChild = new Button();\n sendMessageChild.setText(\"SUBMIT\");\n sendMessageChild.setPrefWidth(60);\n sendMessageChild.setPrefHeight(25);\n sendMessageChild.onActionProperty().bind(sendMessage.onActionProperty());\n sendMessageChild.disableProperty().bind(sendMessage.disableProperty());\n\n // add css to send button\n sendMessageChild.getStyleClass().add(\"send-button\");\n\n // place chat box and send button side by side\n HBox sendBoxChild = new HBox();\n sendBoxChild.getChildren().addAll(messageBoxChild, sendMessageChild, hintButtonChild);\n\n // add css to send message hbox\n sendBoxChild.getStyleClass().add(\"send-box\");\n\n // Place timer / history buttons next to the send message box\n HBox taskBarHorizontalBoxChild = new HBox();\n taskBarHorizontalBoxChild.setPrefSize(1920, 133);\n taskBarHorizontalBoxChild.setBackground(\n new Background(new BackgroundFill(Color.web(\"010a1a\"), null, null)));\n taskBarHorizontalBoxChild.getChildren().addAll(timerAnchorPane, sendBoxChild);\n\n // add css to task bar\n taskBarHorizontalBoxChild.getStyleClass().add(\"task-bar\");\n\n // add new instance to list\n taskBarHorizontalBoxList[i] = taskBarHorizontalBoxChild;\n }\n }\n}"
},
{
"identifier": "TextToSpeech",
"path": "src/main/java/nz/ac/auckland/se206/speech/TextToSpeech.java",
"snippet": "public class TextToSpeech {\n /** Custom unchecked exception for Text-to-speech issues. */\n static class TextToSpeechException extends RuntimeException {\n public TextToSpeechException(final String message) {\n super(message);\n }\n }\n\n /**\n * Main function to speak the given list of sentences.\n *\n * @param args A sequence of strings to speak.\n */\n public static void main(final String[] args) {\n if (args.length == 0) {\n throw new IllegalArgumentException(\n \"You are not providing any arguments. You need to provide one or more sentences.\");\n }\n\n final TextToSpeech textToSpeech = new TextToSpeech();\n\n textToSpeech.speak(args);\n textToSpeech.terminate();\n }\n\n private final Synthesizer synthesizer;\n\n /**\n * Constructs the TextToSpeech object creating and allocating the speech synthesizer. English\n * voice: com.sun.speech.freetts.en.us.cmu_us_kal.KevinVoiceDirectory\n */\n public TextToSpeech() {\n try {\n System.setProperty(\n \"freetts.voices\", \"com.sun.speech.freetts.en.us.cmu_us_kal.KevinVoiceDirectory\");\n Central.registerEngineCentral(\"com.sun.speech.freetts.jsapi.FreeTTSEngineCentral\");\n\n synthesizer = Central.createSynthesizer(new SynthesizerModeDesc(java.util.Locale.ENGLISH));\n\n synthesizer.allocate();\n } catch (final EngineException e) {\n throw new TextToSpeechException(e.getMessage());\n }\n }\n\n /**\n * Speaks the given list of sentences.\n *\n * @param sentences A sequence of strings to speak.\n */\n public void speak(final String... sentences) {\n boolean isFirst = true;\n\n for (final String sentence : sentences) {\n if (isFirst) {\n isFirst = false;\n } else {\n // Add a pause between sentences.\n sleep();\n }\n\n speak(sentence);\n }\n }\n\n /**\n * Speaks the given sentence in input.\n *\n * @param sentence A string to speak.\n */\n public void speak(final String sentence) {\n if (sentence == null) {\n throw new IllegalArgumentException(\"Text cannot be null.\");\n }\n\n try {\n synthesizer.resume();\n synthesizer.speakPlainText(sentence, null);\n synthesizer.waitEngineState(Synthesizer.QUEUE_EMPTY);\n } catch (final AudioException | InterruptedException e) {\n throw new TextToSpeechException(e.getMessage());\n }\n }\n\n /** Sleeps a while to add some pause between sentences. */\n private void sleep() {\n try {\n Thread.sleep(100);\n } catch (final InterruptedException e) {\n e.printStackTrace();\n }\n }\n\n /**\n * It deallocates the speech synthesizer. If you are experiencing an IllegalThreadStateException,\n * avoid using this method and run the speak method without terminating.\n */\n public void terminate() {\n try {\n synthesizer.deallocate();\n } catch (final EngineException e) {\n throw new TextToSpeechException(e.getMessage());\n }\n }\n\n public void stop() {\n synthesizer.cancelAll();\n }\n}"
}
] | import javafx.concurrent.Task;
import nz.ac.auckland.se206.controllers.SharedElements;
import nz.ac.auckland.se206.speech.TextToSpeech; | 7,143 | package nz.ac.auckland.se206;
/** This class manages the text to speech that plays for the user. */
public class TextToSpeechManager {
private static TextToSpeech textToSpeech = new TextToSpeech();
private static Task<Void> task;
public static boolean hideOnComplete = false;
/**
* Speaks the given sentences, and hides the chat bubble when complete.
*
* @param sentences sentences to speak
*/
public static void speak(String... sentences) {
hideOnComplete = false;
cutOff();
hideOnComplete = true;
// Run in a separate thread to avoid blocking the UI thread
task =
new Task<Void>() {
@Override
protected Void call() throws InterruptedException {
textToSpeech.speak(sentences);
if (hideOnComplete) { | package nz.ac.auckland.se206;
/** This class manages the text to speech that plays for the user. */
public class TextToSpeechManager {
private static TextToSpeech textToSpeech = new TextToSpeech();
private static Task<Void> task;
public static boolean hideOnComplete = false;
/**
* Speaks the given sentences, and hides the chat bubble when complete.
*
* @param sentences sentences to speak
*/
public static void speak(String... sentences) {
hideOnComplete = false;
cutOff();
hideOnComplete = true;
// Run in a separate thread to avoid blocking the UI thread
task =
new Task<Void>() {
@Override
protected Void call() throws InterruptedException {
textToSpeech.speak(sentences);
if (hideOnComplete) { | SharedElements.hideChatBubble(); | 0 | 2023-12-02 04:57:43+00:00 | 8k |
SverreNystad/board-master | backend/src/test/java/board/master/service/GameServiceTest.java | [
{
"identifier": "GameResponse",
"path": "backend/src/main/java/board/master/model/communication/GameResponse.java",
"snippet": "public class GameResponse {\n private final String gameId;\n private final String status;\n private final Board board;\n\n public GameResponse(String gameId, String status, Board board) {\n this.gameId = gameId;\n this.status = status;\n this.board = board;\n }\n\n public String getGameId() {\n return gameId;\n }\n\n public String getStatus() {\n return status;\n }\n\n public Board getBoard() {\n return board;\n }\n\n}"
},
{
"identifier": "GameStartRequest",
"path": "backend/src/main/java/board/master/model/communication/GameStartRequest.java",
"snippet": "public class GameStartRequest {\n private final String botType;\n private final String gameType;\n\n public GameStartRequest(String botType, String gameType) {\n this.botType = botType;\n this.gameType = gameType;\n }\n\n public String getBotType() {\n return botType;\n }\n\n public String getGameType() {\n return gameType;\n }\n}"
},
{
"identifier": "MoveRequest",
"path": "backend/src/main/java/board/master/model/communication/MoveRequest.java",
"snippet": "public class MoveRequest {\n private final String gameId;\n private final Move move;\n\n public MoveRequest(String gameId, int x, int y) {\n this.gameId = gameId;\n this.move = new Move(x, y);\n }\n\n public String getGameId() {\n return gameId;\n }\n\n public Move getMove() {\n return move;\n }\n}"
},
{
"identifier": "Board",
"path": "backend/src/main/java/board/master/model/games/Board.java",
"snippet": "public class Board {\n private List<List<String>> grid;\n private int rows;\n private int columns;\n\n public Board(int rows, int columns) {\n this.rows = rows;\n this.columns = columns;\n this.grid = initializeBoard(rows, columns);\n }\n\n /** \n * Initialize the board with empty strings or a default value\n * @param rows The number of rows in the board\n * @param columns The number of columns in the board\n */\n private static List<List<String>> initializeBoard(int rows, int columns) {\n List<List<String>> cells = new ArrayList<>();\n for (int r = 0; r < rows; r++) {\n List<String> row = new ArrayList<>();\n for (int c = 0; c < columns; c++) {\n row.add(\"\");\n }\n cells.add(row);\n }\n return cells;\n }\n\n public List<List<String>> getGrid() {\n return this.grid;\n }\n\n public int getRows() {\n return rows;\n }\n\n public int getColumns() {\n return columns;\n }\n\n public String getPosition(int x, int y) {\n return this.grid.get(x).get(y);\n }\n\n public void setPosition(int x, int y, String value) {\n List<String> row = this.grid.get(x);\n row.set(y, value);\n this.grid.set(x, row);\n }\n\n public boolean equals(Object other) {\n if (this == other) {\n return true;\n }\n if (!(other instanceof Board)) {\n return false;\n }\n Board otherBoard = (Board) other;\n for (int r = 0; r < this.rows; r++) {\n for (int c = 0; c < this.columns; c++) {\n if (!this.getPosition(r, c).equals(otherBoard.getPosition(r, c))) {\n return false;\n }\n }\n }\n return true;\n }\n}"
},
{
"identifier": "Chess",
"path": "backend/src/main/java/board/master/model/games/chess/Chess.java",
"snippet": "public class Chess implements StateHandler {\n \n private Board board;\n private int toMove;\n private Map<String, Piece> pieces;\n\n \n public Chess() {\n this.toMove = 1;\n this.board = CreateInitialBoard();\n this.pieces = new HashMap<String, Piece>();\n initializePieces();\n\n pieces.forEach((key, value) -> {\n this.board.setPosition(value.row, value.column, key);\n } );\n\n }\n \n private static Board CreateInitialBoard() {\n return new Board(8,8);\n }\n\n private void initializePieces() { \n for (int i = 0; i < 8; i++) { // Pawns\n Pawn whitePawn = new Pawn(Color.WHITE, 6, i);\n Pawn blackPawn = new Pawn(Color.BLACK, 1, i);\n this.pieces.put(whitePawn.getSymbol() + i, whitePawn);\n this.pieces.put(blackPawn.getSymbol() + i, blackPawn);\n }\n\n int[] RookColumns = {0, 7};\n for (int i : RookColumns) { // Rooks\n Piece whiteRook = new Rook(Color.WHITE, 7, i);\n Piece blackRook = new Rook(Color.BLACK, 0, i);\n this.pieces.put(whiteRook.getSymbol() + i, whiteRook);\n this.pieces.put(blackRook.getSymbol() + i, blackRook);\n }\n\n int[] KnightColumns = {1, 6};\n for (int i : KnightColumns) { // Knights\n Piece whiteKnight = new Knight(Color.WHITE, 7, i);\n Piece blackKnight = new Knight(Color.BLACK, 0, i);\n this.pieces.put(whiteKnight.getSymbol() + i, whiteKnight);\n this.pieces.put(blackKnight.getSymbol() + i, blackKnight);\n }\n\n int[] BishopColumns = {2, 5};\n for (int i : BishopColumns) { // Bishops\n Piece whiteBishop = new Bishop(Color.WHITE, 7, i);\n Piece blackBishop = new Bishop(Color.BLACK, 0, i);\n this.pieces.put(whiteBishop.getSymbol() + i, whiteBishop);\n this.pieces.put(blackBishop.getSymbol() + i, blackBishop);\n }\n\n // Queens and Kings\n Piece whiteQueen = new Queen(Color.WHITE, 7, 3);\n Piece blackQueen = new Queen(Color.BLACK, 0, 3); \n this.pieces.put(whiteQueen.getSymbol(), whiteQueen);\n this.pieces.put(blackQueen.getSymbol(), blackQueen);\n \n Piece whiteKing = new King(Color.WHITE, 7, 4);\n Piece blackKing = new King(Color.BLACK, 0, 4);\n this.pieces.put(whiteKing.getSymbol(), whiteKing);\n this.pieces.put(blackKing.getSymbol(), blackKing);\n }\n\n protected Chess(Board board, int toMove, Map<String, Piece> pieces) {\n Board newBoard = new Board(board.getRows(), board.getColumns());\n \n Map<String, Piece> newPieces = new HashMap<String, Piece>();\n pieces.forEach((key, value) -> {\n newPieces.put(key, value.copy());\n } );\n\n newPieces.forEach((key, value) -> {\n newBoard.setPosition(value.row, value.column, key);\n } );\n\n this.pieces = newPieces;\n this.board = newBoard;\n this.toMove = toMove;\n }\n \n /**\n * {@inheritDoc}\n */\n public int toMove() {\n // Should be -1 for black, 1 for white\n return this.toMove;\n }\n\n /**\n * {@inheritDoc}\n */\n public List<Action> getActions() {\n List<Action> actions = new ArrayList<Action>();\n for (Piece piece : this.pieces.values()) {\n if (toMove() == 1 && piece.getColor() == Color.BLACK) {\n piece.getValidMoves(this.board).forEach(action -> actions.add(action));\n } else if (toMove() == -1 && piece.getColor() == Color.WHITE) {\n piece.getValidMoves(this.board).forEach(action -> actions.add(action));\n } \n }\n return actions;\n }\n\n /**\n * {@inheritDoc}\n * Assumes that the action is valid and that Action is a Move.\n */\n public StateHandler result(Action action) {\n // Make a copy of the board\n Chess newState = new Chess(this.board, this.toMove, this.pieces);\n\n\n // Find piece to move\n Move move = (Move) action;\n String currentPos = move.getX();\n Piece toMovePiece = newState.getPiece(currentPos);\n \n // Change its position \n String newPos = move.getY();\n int toX = Character.getNumericValue(newPos.charAt(0));\n int toY = Character.getNumericValue(newPos.charAt(1));\n if (newState.getPiece(newPos) != null) {\n newState.pieces.remove(newState.getPiece(newPos).getSymbol());\n }\n toMovePiece.move(toX, toY, this.board);\n\n // Change turn\n newState.toMove *= -1;\n return newState;\n }\n\n private Piece getPiece(String position) {\n // Position is of from \"xy\" where x is the row and y is the column\n if (position.length() != 2) {\n throw new IllegalArgumentException(\"Position must be of length 2\");\n }\n int x = Character.getNumericValue(position.charAt(0));\n int y = Character.getNumericValue(position.charAt(1));\n String pieceSymbol = this.board.getPosition(x, y);\n return this.pieces.getOrDefault(pieceSymbol, null);\n }\n\n /**\n * {@inheritDoc}\n */\n public boolean isTerminal() {\n // Check for checkmate\n Piece whiteKing = this.pieces.get(\"KW\");\n Piece blackKing = this.pieces.get(\"KB\");\n\n boolean whiteKingInCheck = isKingInCheck(whiteKing);\n boolean blackKingInCheck = isKingInCheck(blackKing);\n\n if (whiteKingInCheck) {\n return isKingInCheckMate(whiteKing);\n \n } else if (blackKingInCheck) {\n return isKingInCheckMate(blackKing);\n } else {\n return false;\n }\n }\n\n private boolean isKingInCheck(Piece king) {\n String kingPosition = String.valueOf(king.getRow()) +\n String.valueOf(king.getColumn());\n \n List<Action> actions = getActions();\n\n for (Action action : actions) {\n Move move = (Move) action;\n String newPos = move.getY();\n\n if (newPos.equals(kingPosition)) {\n return true;\n }\n }\n return false;\n }\n\n private boolean isKingInCheckMate(Piece king) {\n // King is in check\n List<Action> whiteActions = king.getValidMoves(this.board);\n if (whiteActions.isEmpty()) {\n return true;\n }\n for (Action action : whiteActions) {\n Chess newState = (Chess) result(action);\n Piece newKing = newState.pieces.get(king.getSymbol());\n\n //if there is a move that gets the king out of check, then it is not checkmate\n if (!newState.isKingInCheck(newKing)) {\n return false;\n }\n }\n // White is in checkmate\n return true;\n }\n\n /**\n * {@inheritDoc}\n */\n public int utility(int player) {\n Map<Color, Integer> analysis = analyzeBoard();\n\n if (analysis.containsKey(Color.WHITE)) {\n return (player == 1) ? analysis.get(Color.WHITE) : -analysis.get(Color.WHITE);\n }\n else {\n return (player == -1) ? analysis.get(Color.BLACK) : -analysis.get(Color.BLACK);\n }\n }\n\n private Map<Color, Integer> analyzeBoard() {\n Map<Color, Integer> analysis = new HashMap<Color, Integer>();\n\n if (isTerminal()) {\n if (isKingInCheck(this.pieces.get(\"KW\"))) {\n analysis.put(Color.BLACK, 1000);\n } else {\n analysis.put(Color.WHITE, 1000);\n }\n }\n\n int value = 0;\n\n for (Piece piece : this.pieces.values()) {\n if (piece.getColor() == Color.WHITE) {\n value += piece.getValue();\n } else {\n value -= piece.getValue();\n }\n }\n\n if (value >= 0) {\n analysis.put(Color.WHITE, value);\n } else {\n analysis.put(Color.BLACK, value);\n }\n return analysis;\n }\n\n /**\n * {@inheritDoc}\n */\n public Board getBoard() {\n return this.board;\n }\n}"
},
{
"identifier": "TicTacToe",
"path": "backend/src/main/java/board/master/model/games/tictactoe/TicTacToe.java",
"snippet": "public class TicTacToe implements StateHandler {\n\n // Game board representation, player turn, and other necessary state variables\n // TODO: Define the game board and other state variables\n private Board board;\n \n /**\n * Constructs a new TicTacToe game with an empty board and sets the starting\n * player.\n */\n public TicTacToe() {\n this.board = new Board(3, 3);\n // TODO: Initialize the game board and set the starting player\n }\n\n public TicTacToe(TicTacToe ticTacToe) {\n this.board = new Board(ticTacToe.getBoard().getRows(), \n ticTacToe.getBoard().getColumns());\n for (int x = 0; x < ticTacToe.getBoard().getRows(); x++) {\n for (int y = 0; y < ticTacToe.getBoard().getColumns(); y++) {\n this.board.setPosition(x, y, ticTacToe.getBoard().getPosition(x, y));\n }\n }\n //this.board.setGrid(ticTacToe.getBoard().getGrid()); !!!DONT DO THIS!!!\n // TODO: Initialize the game board and set the starting player\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public int toMove() {\n int emptySpaces = 0;\n for (int x = 0; x < this.board.getRows(); x++) {\n for (int y = 0; y < this.board.getColumns(); y++) {\n if (this.board.getPosition(x, y).equals(\"\")) {\n emptySpaces++;\n }\n }\n }\n //In this code, X always goes first\n if (emptySpaces == 0) {\n return 0;\n }\n if (emptySpaces % 2 == 0) { //if even, it's O's turn\n return -1;\n }\n else { //if odd, it's X's turn\n return 1;\n }\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public List<Action> getActions() {\n if (checkWin() != \"\") {\n return new ArrayList<Action>();\n }\n // current state\n List<Action> actions = new ArrayList<Action>();\n for (int x = 0; x < this.board.getRows(); x++) {\n for (int y = 0; y < this.board.getColumns(); y++) {\n if (this.board.getPosition(x, y).equals(\"\")) {\n actions.add((Action) new Move(x, y));\n }\n }\n }\n return actions;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public StateHandler result(Action action) {\n Move move = (Move) action;\n String value = (this.toMove() == 1) ? \"X\" : \"O\";\n TicTacToe newState = new TicTacToe(this);\n newState.setPosition(Integer.parseInt(move.getX()), Integer.parseInt(move.getY()), value);\n \n return newState;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public boolean isTerminal() {\n //if board is full \n if (getActions().size() == 0) {\n return true;\n }\n \n return false;\n }\n\n /**\n * {@inheritDoc}\n */\n // // @Override\n // public int utility(int player) {\n // //String checkWin = checkWin();\n // switch (checkWin()) {\n // case \"X\":\n // return (player == 1) ? 1 : -1;\n // case \"O\":\n // return (player == -1) ? 1 : -1;\n // default:\n // return 0;\n // }\n // }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public int utility(int player) {\n Map<String, Integer> analysis = analyzeBoard();\n if (analysis.containsKey(\"X\")) {\n return (player == 1) ? analysis.get(\"X\") : -analysis.get(\"X\");\n }\n else {\n return (player == -1) ? analysis.get(\"O\") : -analysis.get(\"O\");\n }\n }\n\n public String getPosition(int x, int y) {\n return board.getPosition(x, y);\n }\n\n private void setPosition(int x, int y, String value) {\n board.setPosition(x, y, value);\n }\n\n public Board getBoard() {\n return this.board;\n }\n\n /**\n * Checks for a win in the current state of the game. \n * Returns the symbol of the winning player if there is a win, \n * or null if there is no win yet or the game is a draw.\n * @return\n */\n private String checkWin() {\n String checkWin = \"\";\n //check for win in rows and columns\n for (int i = 0; i < 3; i++) {\n Boolean isNotEmpty = !board.getPosition(i, i).isEmpty();\n \n Boolean sameSignCol = board.getPosition(i, 0).equals(board.getPosition(i, 1)) \n && board.getPosition(i, 1).equals(board.getPosition(i, 2));\n \n Boolean sameSignRow = board.getPosition(0, i).equals(board.getPosition(1, i)) \n && board.getPosition(1, i).equals(board.getPosition(2, i));\n \n if (sameSignCol && isNotEmpty) {\n return board.getPosition(i, 0);\n }\n\n if (sameSignRow && isNotEmpty) {\n return board.getPosition(0, i);\n }\n }\n\n Boolean isNotEmpty = !board.getPosition(1, 1).isEmpty();\n\n //check for win in diagonals\n if (board.getPosition(0, 0).equals(board.getPosition(1, 1)) \n && board.getPosition(1, 1).equals(board.getPosition(2, 2)) \n && isNotEmpty) {\n return board.getPosition(1, 1);\n }\n\n if(board.getPosition(0, 2).equals(board.getPosition(1, 1))\n && board.getPosition(1, 1).equals(board.getPosition(2, 0))\n && isNotEmpty) {\n return board.getPosition(1, 1);\n }\n return checkWin;\n }\n\n private Map<String, Integer> analyzeBoard() {\n HashMap<String, Integer> analysis = new HashMap<String, Integer>();\n\n String checkWin = checkWin();\n\n if (!checkWin.isEmpty()) {\n analysis.put(checkWin, 100);\n return analysis;\n \n }\n\n int count = 0;\n\n // int xCount = 0;\n // int oCount = 0;\n\n for (int i = 0; i < 3; i++) {\n Boolean isNotEmpty = !board.getPosition(i, i).isEmpty();\n \n Boolean sameSignCol = board.getPosition(i, 0).equals(board.getPosition(i, 1)) \n || board.getPosition(i, 1).equals(board.getPosition(i, 2));\n \n Boolean sameSignRow = board.getPosition(0, i).equals(board.getPosition(1, i)) \n || board.getPosition(1, i).equals(board.getPosition(2, i));\n \n if (sameSignCol && isNotEmpty) {\n count += board.getPosition(i, 0).equals(\"X\") ? 10 : -10;\n // if (board.getPosition(i, 1).equals(\"X\")) {\n // xCount += 10;\n // }\n // else {\n // oCount += 10;\n \n // }\n }\n\n if (sameSignRow && isNotEmpty) {\n count += board.getPosition(i, 0).equals(\"X\") ? 10 : -10;\n // if (board.getPosition(i, 1).equals(\"X\")) {\n // xCount += 10;\n // }\n // else {\n // oCount += 10;\n // }\n }\n }\n\n Boolean isNotEmpty = !board.getPosition(1, 1).isEmpty();\n\n if (board.getPosition(0, 0).equals(board.getPosition(1, 1)) \n || board.getPosition(1, 1).equals(board.getPosition(2, 2)) \n && isNotEmpty) {\n count += board.getPosition(1, 1).equals(\"X\") ? 10 : -10;\n // if (board.getPosition(1, 1).equals(\"X\")) {\n // xCount += 10;\n // }\n // else {\n // oCount += 10;\n // }\n }\n\n if(board.getPosition(0, 2).equals(board.getPosition(1, 1))\n || board.getPosition(1, 1).equals(board.getPosition(2, 0))\n && isNotEmpty) {\n count += board.getPosition(1, 1).equals(\"X\") ? 10 : -10;\n // if (board.getPosition(1, 1).equals(\"X\")) {\n // xCount += 15;\n // }\n // else {\n // oCount += 15;\n // }\n }\n\n if (count > 0) {\n analysis.put(\"X\", count);\n }\n else {\n analysis.put(\"O\", -count);\n }\n return analysis;\n }\n}"
}
] | import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import board.master.model.communication.GameResponse;
import board.master.model.communication.GameStartRequest;
import board.master.model.communication.MoveRequest;
import board.master.model.games.Board;
import board.master.model.games.chess.Chess;
import board.master.model.games.tictactoe.TicTacToe; | 5,659 | package board.master.service;
public class GameServiceTest {
private GameService gameService;
private String gameIdOfGameInService;
private Board boardOfGameInService;
private final String nonUsedGameId = "nonUsedGameId";
@BeforeEach
void GameServiceSetup() {
gameService = new GameService();
// Make a game to be used in tests
String gameType = "tic-tac-toe";
String botType = "random";
GameStartRequest request = new GameStartRequest(botType, gameType);
GameResponse response = gameService.startGame(request);
gameIdOfGameInService = response.getGameId();
}
@Nested
@DisplayName("Test of startGame")
class CreationOfGames {
@Test
@DisplayName("Test of startGame with chess")
void testStartGameChess() {
String gameType = "chess";
String botType = "random"; | package board.master.service;
public class GameServiceTest {
private GameService gameService;
private String gameIdOfGameInService;
private Board boardOfGameInService;
private final String nonUsedGameId = "nonUsedGameId";
@BeforeEach
void GameServiceSetup() {
gameService = new GameService();
// Make a game to be used in tests
String gameType = "tic-tac-toe";
String botType = "random";
GameStartRequest request = new GameStartRequest(botType, gameType);
GameResponse response = gameService.startGame(request);
gameIdOfGameInService = response.getGameId();
}
@Nested
@DisplayName("Test of startGame")
class CreationOfGames {
@Test
@DisplayName("Test of startGame with chess")
void testStartGameChess() {
String gameType = "chess";
String botType = "random"; | Board expectedBoard = new Chess().getBoard(); | 4 | 2023-11-30 21:27:22+00:00 | 8k |
nageoffer/shortlink | admin/src/main/java/com/nageoffer/shortlink/admin/controller/RecycleBinController.java | [
{
"identifier": "Result",
"path": "admin/src/main/java/com/nageoffer/shortlink/admin/common/convention/result/Result.java",
"snippet": "@Data\n@Accessors(chain = true)\npublic class Result<T> implements Serializable {\n\n @Serial\n private static final long serialVersionUID = 5679018624309023727L;\n\n /**\n * 正确返回码\n */\n public static final String SUCCESS_CODE = \"0\";\n\n /**\n * 返回码\n */\n private String code;\n\n /**\n * 返回消息\n */\n private String message;\n\n /**\n * 响应数据\n */\n private T data;\n\n /**\n * 请求ID\n */\n private String requestId;\n\n public boolean isSuccess() {\n return SUCCESS_CODE.equals(code);\n }\n}"
},
{
"identifier": "Results",
"path": "admin/src/main/java/com/nageoffer/shortlink/admin/common/convention/result/Results.java",
"snippet": "public final class Results {\n\n /**\n * 构造成功响应\n */\n public static Result<Void> success() {\n return new Result<Void>()\n .setCode(Result.SUCCESS_CODE);\n }\n\n /**\n * 构造带返回数据的成功响应\n */\n public static <T> Result<T> success(T data) {\n return new Result<T>()\n .setCode(Result.SUCCESS_CODE)\n .setData(data);\n }\n\n /**\n * 构建服务端失败响应\n */\n public static Result<Void> failure() {\n return new Result<Void>()\n .setCode(BaseErrorCode.SERVICE_ERROR.code())\n .setMessage(BaseErrorCode.SERVICE_ERROR.message());\n }\n\n /**\n * 通过 {@link AbstractException} 构建失败响应\n */\n public static Result<Void> failure(AbstractException abstractException) {\n String errorCode = Optional.ofNullable(abstractException.getErrorCode())\n .orElse(BaseErrorCode.SERVICE_ERROR.code());\n String errorMessage = Optional.ofNullable(abstractException.getErrorMessage())\n .orElse(BaseErrorCode.SERVICE_ERROR.message());\n return new Result<Void>()\n .setCode(errorCode)\n .setMessage(errorMessage);\n }\n\n /**\n * 通过 errorCode、errorMessage 构建失败响应\n */\n public static Result<Void> failure(String errorCode, String errorMessage) {\n return new Result<Void>()\n .setCode(errorCode)\n .setMessage(errorMessage);\n }\n}"
},
{
"identifier": "RecycleBinRecoverReqDTO",
"path": "admin/src/main/java/com/nageoffer/shortlink/admin/dto/req/RecycleBinRecoverReqDTO.java",
"snippet": "@Data\npublic class RecycleBinRecoverReqDTO {\n\n /**\n * 分组标识\n */\n private String gid;\n\n /**\n * 全部短链接\n */\n private String fullShortUrl;\n}"
},
{
"identifier": "RecycleBinRemoveReqDTO",
"path": "admin/src/main/java/com/nageoffer/shortlink/admin/dto/req/RecycleBinRemoveReqDTO.java",
"snippet": "@Data\npublic class RecycleBinRemoveReqDTO {\n\n /**\n * 分组标识\n */\n private String gid;\n\n /**\n * 全部短链接\n */\n private String fullShortUrl;\n}"
},
{
"identifier": "RecycleBinSaveReqDTO",
"path": "admin/src/main/java/com/nageoffer/shortlink/admin/dto/req/RecycleBinSaveReqDTO.java",
"snippet": "@Data\npublic class RecycleBinSaveReqDTO {\n\n /**\n * 分组标识\n */\n private String gid;\n\n /**\n * 全部短链接\n */\n private String fullShortUrl;\n}"
},
{
"identifier": "ShortLinkRemoteService",
"path": "admin/src/main/java/com/nageoffer/shortlink/admin/remote/ShortLinkRemoteService.java",
"snippet": "public interface ShortLinkRemoteService {\n\n /**\n * 创建短链接\n *\n * @param requestParam 创建短链接请求参数\n * @return 短链接创建响应\n */\n default Result<ShortLinkCreateRespDTO> createShortLink(ShortLinkCreateReqDTO requestParam) {\n String resultBodyStr = HttpUtil.post(\"http://127.0.0.1:8001/api/short-link/v1/create\", JSON.toJSONString(requestParam));\n return JSON.parseObject(resultBodyStr, new TypeReference<>() {\n });\n }\n\n /**\n * 批量创建短链接\n *\n * @param requestParam 批量创建短链接请求参数\n * @return 短链接批量创建响应\n */\n default Result<ShortLinkBatchCreateRespDTO> batchCreateShortLink(ShortLinkBatchCreateReqDTO requestParam) {\n String resultBodyStr = HttpUtil.post(\"http://127.0.0.1:8001/api/short-link/v1/create/batch\", JSON.toJSONString(requestParam));\n return JSON.parseObject(resultBodyStr, new TypeReference<>() {\n });\n }\n\n /**\n * 修改短链接\n *\n * @param requestParam 修改短链接请求参数\n */\n default void updateShortLink(ShortLinkUpdateReqDTO requestParam) {\n HttpUtil.post(\"http://127.0.0.1:8001/api/short-link/v1/update\", JSON.toJSONString(requestParam));\n }\n\n /**\n * 分页查询短链接\n *\n * @param requestParam 分页短链接请求参数\n * @return 查询短链接响应\n */\n default Result<IPage<ShortLinkPageRespDTO>> pageShortLink(ShortLinkPageReqDTO requestParam) {\n Map<String, Object> requestMap = new HashMap<>();\n requestMap.put(\"gid\", requestParam.getGid());\n requestMap.put(\"orderTag\", requestParam.getOrderTag());\n requestMap.put(\"current\", requestParam.getCurrent());\n requestMap.put(\"size\", requestParam.getSize());\n String resultPageStr = HttpUtil.get(\"http://127.0.0.1:8001/api/short-link/v1/page\", requestMap);\n return JSON.parseObject(resultPageStr, new TypeReference<>() {\n });\n }\n\n /**\n * 查询分组短链接总量\n *\n * @param requestParam 分组短链接总量请求参数\n * @return 查询分组短链接总量响应\n */\n default Result<List<ShortLinkGroupCountQueryRespDTO>> listGroupShortLinkCount(List<String> requestParam) {\n Map<String, Object> requestMap = new HashMap<>();\n requestMap.put(\"requestParam\", requestParam);\n String resultPageStr = HttpUtil.get(\"http://127.0.0.1:8001/api/short-link/v1/count\", requestMap);\n return JSON.parseObject(resultPageStr, new TypeReference<>() {\n });\n }\n\n /**\n * 根据 URL 获取标题\n *\n * @param url 目标网站地址\n * @return 网站标题\n */\n default Result<String> getTitleByUrl(@RequestParam(\"url\") String url) {\n String resultStr = HttpUtil.get(\"http://127.0.0.1:8001/api/short-link/v1/title?url=\" + url);\n return JSON.parseObject(resultStr, new TypeReference<>() {\n });\n }\n\n /**\n * 保存回收站\n *\n * @param requestParam 请求参数\n */\n default void saveRecycleBin(RecycleBinSaveReqDTO requestParam) {\n HttpUtil.post(\"http://127.0.0.1:8001/api/short-link/v1/recycle-bin/save\", JSON.toJSONString(requestParam));\n }\n\n /**\n * 分页查询回收站短链接\n *\n * @param requestParam 分页短链接请求参数\n * @return 查询短链接响应\n */\n default Result<IPage<ShortLinkPageRespDTO>> pageRecycleBinShortLink(ShortLinkRecycleBinPageReqDTO requestParam) {\n Map<String, Object> requestMap = new HashMap<>();\n requestMap.put(\"gidList\", requestParam.getGidList());\n requestMap.put(\"current\", requestParam.getCurrent());\n requestMap.put(\"size\", requestParam.getSize());\n String resultPageStr = HttpUtil.get(\"http://127.0.0.1:8001/api/short-link/v1/recycle-bin/page\", requestMap);\n return JSON.parseObject(resultPageStr, new TypeReference<>() {\n });\n }\n\n /**\n * 恢复短链接\n *\n * @param requestParam 短链接恢复请求参数\n */\n default void recoverRecycleBin(RecycleBinRecoverReqDTO requestParam) {\n HttpUtil.post(\"http://127.0.0.1:8001/api/short-link/v1/recycle-bin/recover\", JSON.toJSONString(requestParam));\n }\n\n /**\n * 移除短链接\n *\n * @param requestParam 短链接移除请求参数\n */\n default void removeRecycleBin(RecycleBinRemoveReqDTO requestParam) {\n HttpUtil.post(\"http://127.0.0.1:8001/api/short-link/v1/recycle-bin/remove\", JSON.toJSONString(requestParam));\n }\n\n /**\n * 访问单个短链接指定时间内监控数据\n *\n * @param requestParam 访问短链接监控请求参数\n * @return 短链接监控信息\n */\n default Result<ShortLinkStatsRespDTO> oneShortLinkStats(ShortLinkStatsReqDTO requestParam) {\n String resultBodyStr = HttpUtil.get(\"http://127.0.0.1:8001/api/short-link/v1/stats\", BeanUtil.beanToMap(requestParam));\n return JSON.parseObject(resultBodyStr, new TypeReference<>() {\n });\n }\n\n /**\n * 访问分组短链接指定时间内监控数据\n *\n * @param requestParam 访分组问短链接监控请求参数\n * @return 分组短链接监控信息\n */\n default Result<ShortLinkStatsRespDTO> groupShortLinkStats(ShortLinkGroupStatsReqDTO requestParam) {\n String resultBodyStr = HttpUtil.get(\"http://127.0.0.1:8001/api/short-link/v1/stats/group\", BeanUtil.beanToMap(requestParam));\n return JSON.parseObject(resultBodyStr, new TypeReference<>() {\n });\n }\n\n /**\n * 访问单个短链接指定时间内监控访问记录数据\n *\n * @param requestParam 访问短链接监控访问记录请求参数\n * @return 短链接监控访问记录信息\n */\n default Result<IPage<ShortLinkStatsAccessRecordRespDTO>> shortLinkStatsAccessRecord(ShortLinkStatsAccessRecordReqDTO requestParam) {\n Map<String, Object> stringObjectMap = BeanUtil.beanToMap(requestParam, false, true);\n stringObjectMap.remove(\"orders\");\n stringObjectMap.remove(\"records\");\n String resultBodyStr = HttpUtil.get(\"http://127.0.0.1:8001/api/short-link/v1/stats/access-record\", stringObjectMap);\n return JSON.parseObject(resultBodyStr, new TypeReference<>() {\n });\n }\n\n /**\n * 访问分组短链接指定时间内监控访问记录数据\n *\n * @param requestParam 访问分组短链接监控访问记录请求参数\n * @return 分组短链接监控访问记录信息\n */\n default Result<IPage<ShortLinkStatsAccessRecordRespDTO>> groupShortLinkStatsAccessRecord(ShortLinkGroupStatsAccessRecordReqDTO requestParam) {\n Map<String, Object> stringObjectMap = BeanUtil.beanToMap(requestParam, false, true);\n stringObjectMap.remove(\"orders\");\n stringObjectMap.remove(\"records\");\n String resultBodyStr = HttpUtil.get(\"http://127.0.0.1:8001/api/short-link/v1/stats/access-record/group\", stringObjectMap);\n return JSON.parseObject(resultBodyStr, new TypeReference<>() {\n });\n }\n}"
},
{
"identifier": "ShortLinkRecycleBinPageReqDTO",
"path": "admin/src/main/java/com/nageoffer/shortlink/admin/remote/dto/req/ShortLinkRecycleBinPageReqDTO.java",
"snippet": "@Data\npublic class ShortLinkRecycleBinPageReqDTO extends Page {\n\n /**\n * 分组标识\n */\n private List<String> gidList;\n}"
},
{
"identifier": "ShortLinkPageRespDTO",
"path": "admin/src/main/java/com/nageoffer/shortlink/admin/remote/dto/resp/ShortLinkPageRespDTO.java",
"snippet": "@Data\npublic class ShortLinkPageRespDTO {\n\n /**\n * id\n */\n private Long id;\n\n /**\n * 域名\n */\n private String domain;\n\n /**\n * 短链接\n */\n private String shortUri;\n\n /**\n * 完整短链接\n */\n private String fullShortUrl;\n\n /**\n * 原始链接\n */\n private String originUrl;\n\n /**\n * 分组标识\n */\n private String gid;\n\n /**\n * 有效期类型 0:永久有效 1:自定义\n */\n private Integer validDateType;\n\n /**\n * 有效期\n */\n @JsonFormat(pattern = \"yyyy-MM-dd HH:mm:ss\", timezone = \"GMT+8\")\n private Date validDate;\n\n /**\n * 创建时间\n */\n @JsonFormat(pattern = \"yyyy-MM-dd HH:mm:ss\", timezone = \"GMT+8\")\n private Date createTime;\n\n /**\n * 描述\n */\n private String describe;\n\n /**\n * 网站标识\n */\n private String favicon;\n\n\n /**\n * 历史PV\n */\n private Integer totalPv;\n\n /**\n * 今日PV\n */\n private Integer todayPv;\n\n /**\n * 历史UV\n */\n private Integer totalUv;\n\n /**\n * 今日UV\n */\n private Integer todayUv;\n\n /**\n * 历史UIP\n */\n private Integer totalUip;\n\n /**\n * 今日UIP\n */\n private Integer todayUip;\n}"
},
{
"identifier": "RecycleBinService",
"path": "admin/src/main/java/com/nageoffer/shortlink/admin/service/RecycleBinService.java",
"snippet": "public interface RecycleBinService {\n\n /**\n * 分页查询回收站短链接\n *\n * @param requestParam 请求参数\n * @return 返回参数包装\n */\n Result<IPage<ShortLinkPageRespDTO>> pageRecycleBinShortLink(ShortLinkRecycleBinPageReqDTO requestParam);\n}"
}
] | import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.nageoffer.shortlink.admin.common.convention.result.Result;
import com.nageoffer.shortlink.admin.common.convention.result.Results;
import com.nageoffer.shortlink.admin.dto.req.RecycleBinRecoverReqDTO;
import com.nageoffer.shortlink.admin.dto.req.RecycleBinRemoveReqDTO;
import com.nageoffer.shortlink.admin.dto.req.RecycleBinSaveReqDTO;
import com.nageoffer.shortlink.admin.remote.ShortLinkRemoteService;
import com.nageoffer.shortlink.admin.remote.dto.req.ShortLinkRecycleBinPageReqDTO;
import com.nageoffer.shortlink.admin.remote.dto.resp.ShortLinkPageRespDTO;
import com.nageoffer.shortlink.admin.service.RecycleBinService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping; | 4,192 | /*
* 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 com.nageoffer.shortlink.admin.controller;
/**
* 回收站管理控制层
* 公众号:马丁玩编程,回复:加群,添加马哥微信(备注:link)获取项目资料
*/
@RestController
@RequiredArgsConstructor
public class RecycleBinController {
private final RecycleBinService recycleBinService;
/**
* 后续重构为 SpringCloud Feign 调用
*/
ShortLinkRemoteService shortLinkRemoteService = new ShortLinkRemoteService() {
};
/**
* 保存回收站
*/
@PostMapping("/api/short-link/admin/v1/recycle-bin/save") | /*
* 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 com.nageoffer.shortlink.admin.controller;
/**
* 回收站管理控制层
* 公众号:马丁玩编程,回复:加群,添加马哥微信(备注:link)获取项目资料
*/
@RestController
@RequiredArgsConstructor
public class RecycleBinController {
private final RecycleBinService recycleBinService;
/**
* 后续重构为 SpringCloud Feign 调用
*/
ShortLinkRemoteService shortLinkRemoteService = new ShortLinkRemoteService() {
};
/**
* 保存回收站
*/
@PostMapping("/api/short-link/admin/v1/recycle-bin/save") | public Result<Void> saveRecycleBin(@RequestBody RecycleBinSaveReqDTO requestParam) { | 0 | 2023-11-19 16:04:32+00:00 | 8k |
NEWCIH2023/galois | src/main/java/io/liuguangsheng/galois/service/MethodAdapter.java | [
{
"identifier": "GlobalConfiguration",
"path": "src/main/java/io/liuguangsheng/galois/conf/GlobalConfiguration.java",
"snippet": "public class GlobalConfiguration {\n\n private static final String GALOIS_PROPERTIES = \"galois.properties\";\n private static final Properties configuration = new Properties();\n\n private static class GlobalConfigurationHolder {\n private static final GlobalConfiguration globalConfiguration = new GlobalConfiguration();\n }\n\n private GlobalConfiguration() {\n ClassLoader loader = Thread.currentThread().getContextClassLoader();\n try (InputStream is = loader.getResourceAsStream(GALOIS_PROPERTIES)) {\n configuration.load(is);\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n /**\n * get instance\n *\n * @return {@link GlobalConfiguration}\n * @see GlobalConfiguration\n */\n public static GlobalConfiguration getInstance() {\n return GlobalConfigurationHolder.globalConfiguration;\n }\n\n /**\n * get string\n *\n * @param key key\n * @return {@link String}\n * @see String\n */\n public String getStr(String key) {\n return getStr(key, Constant.EMPTY);\n }\n\n /**\n * get string\n *\n * @param key key\n * @param defaultValue defaultValue\n * @return {@link String}\n * @see String\n */\n public String getStr(String key, String defaultValue) {\n if (StringUtil.isBlank(key)) {\n return defaultValue;\n }\n\n String result = configuration.getProperty(key);\n\n if (StringUtil.isBlank(result)) {\n return System.getProperty(key, defaultValue);\n }\n\n return result;\n }\n\n /**\n * get boolean\n *\n * @param key key\n * @return {@link boolean}\n */\n public boolean getBool(String key) {\n return getBool(key, false);\n }\n\n /**\n * get boolean\n *\n * @param key key\n * @param defaultValue defaultValue\n * @return {@link boolean}\n */\n public boolean getBool(String key, boolean defaultValue) {\n String result = getStr(key, defaultValue ? Constant.TRUE : Constant.FALSE);\n return Constant.TRUE.equalsIgnoreCase(result);\n }\n\n /**\n * get long\n *\n * @param key key\n * @return {@link long}\n */\n public long getLong(String key) {\n return getLong(key, 0L);\n }\n\n /**\n * get long\n *\n * @param key key\n * @param defaultValue defaultValue\n * @return {@link long}\n */\n public long getLong(String key, long defaultValue) {\n String result = getStr(key, String.valueOf(defaultValue));\n try {\n return Long.parseLong(result);\n } catch (Exception e) {\n return -1L;\n }\n }\n\n /**\n * get integer\n *\n * @param key key\n * @return {@link int}\n */\n public int getInt(String key) {\n return getInt(key, 0);\n }\n\n /**\n * get integer\n *\n * @param key key\n * @param defaultValue defaultValue\n * @return {@link int}\n */\n public int getInt(String key, int defaultValue) {\n String result = getStr(key, String.valueOf(defaultValue));\n try {\n return Integer.parseInt(result);\n } catch (Exception e) {\n return -1;\n }\n }\n\n}"
},
{
"identifier": "GaloisLog",
"path": "src/main/java/io/liuguangsheng/galois/utils/GaloisLog.java",
"snippet": "public class GaloisLog implements Logger {\n\n private final Logger logger;\n private static final GlobalConfiguration config = GlobalConfiguration.getInstance();\n private final boolean isReleaseVersion = RELEASE.equals(config.getStr(BUILD_TYPE));\n private static final Marker marker = MarkerFactory.getMarker(\"[Galois]\");\n\n /**\n * Instantiates a new Galois log.\n *\n * @param clazz the clazz\n */\n public GaloisLog(Class<?> clazz) {\n logger = LoggerFactory.getLogger(clazz);\n }\n\n /**\n * Instantiates a new Galois log.\n *\n * @param name the name\n */\n public GaloisLog(String name) {\n logger = LoggerFactory.getLogger(name);\n }\n\n @Override\n public String getName() {\n return logger.getName();\n }\n\n @Override\n public boolean isTraceEnabled() {\n return logger.isTraceEnabled();\n }\n\n @Override\n public void trace(String msg) {\n logger.trace(marker, msg);\n }\n\n @Override\n public void trace(String format, Object arg) {\n logger.trace(marker, format, arg);\n }\n\n @Override\n public void trace(String format, Object arg1, Object arg2) {\n logger.trace(marker, format, arg1, arg2);\n }\n\n @Override\n public void trace(String format, Object... arguments) {\n logger.trace(marker, format, arguments);\n }\n\n @Override\n public void trace(String msg, Throwable t) {\n if (isReleaseVersion) {\n logger.trace(msg, t);\n } else {\n logger.trace(msg);\n }\n }\n\n @Override\n public boolean isTraceEnabled(Marker marker) {\n return logger.isTraceEnabled(marker);\n }\n\n @Override\n public void trace(Marker marker, String msg) {\n logger.trace(marker, msg);\n\n }\n\n @Override\n public void trace(Marker marker, String format, Object arg) {\n logger.trace(marker, format, arg);\n\n }\n\n @Override\n public void trace(Marker marker, String format, Object arg1, Object arg2) {\n logger.trace(marker, format, arg1, arg2);\n\n }\n\n @Override\n public void trace(Marker marker, String format, Object... argArray) {\n logger.trace(marker, format, argArray);\n\n }\n\n @Override\n public void trace(Marker marker, String msg, Throwable t) {\n if (isReleaseVersion) {\n logger.trace(marker, msg, t);\n } else {\n logger.trace(marker, msg);\n }\n\n }\n\n @Override\n public boolean isDebugEnabled() {\n return logger.isDebugEnabled();\n }\n\n @Override\n public void debug(String msg) {\n logger.debug(msg);\n }\n\n @Override\n public void debug(String format, Object arg) {\n logger.debug(format, arg);\n\n }\n\n @Override\n public void debug(String format, Object arg1, Object arg2) {\n logger.debug(format, arg1, arg2);\n\n }\n\n @Override\n public void debug(String format, Object... arguments) {\n logger.debug(format, arguments);\n\n }\n\n @Override\n public void debug(String msg, Throwable t) {\n if (isReleaseVersion) {\n logger.debug(msg, t);\n } else {\n logger.debug(msg);\n }\n }\n\n @Override\n public boolean isDebugEnabled(Marker marker) {\n return logger.isDebugEnabled(marker);\n }\n\n @Override\n public void debug(Marker marker, String msg) {\n logger.debug(marker, msg);\n\n }\n\n @Override\n public void debug(Marker marker, String format, Object arg) {\n logger.debug(marker, format, arg);\n\n }\n\n @Override\n public void debug(Marker marker, String format, Object arg1, Object arg2) {\n logger.debug(marker, format, arg1, arg2);\n\n }\n\n @Override\n public void debug(Marker marker, String format, Object... arguments) {\n logger.debug(marker, format, arguments);\n\n }\n\n @Override\n public void debug(Marker marker, String msg, Throwable t) {\n if (isReleaseVersion) {\n logger.debug(marker, msg, t);\n } else {\n logger.debug(marker, msg);\n }\n }\n\n @Override\n public boolean isInfoEnabled() {\n return logger.isInfoEnabled();\n }\n\n @Override\n public void info(String msg) {\n logger.info(marker, msg);\n\n }\n\n @Override\n public void info(String format, Object arg) {\n logger.info(marker, format, arg);\n\n }\n\n @Override\n public void info(String format, Object arg1, Object arg2) {\n logger.info(marker, format, arg1, arg2);\n\n }\n\n @Override\n public void info(String format, Object... arguments) {\n logger.info(marker, format, arguments);\n }\n\n @Override\n public void info(String msg, Throwable t) {\n if (isReleaseVersion) {\n logger.info(marker, msg, t);\n } else {\n logger.info(marker, msg);\n }\n }\n\n @Override\n public boolean isInfoEnabled(Marker marker) {\n return logger.isInfoEnabled(marker);\n }\n\n @Override\n public void info(Marker marker, String msg) {\n logger.info(marker, msg);\n }\n\n @Override\n public void info(Marker marker, String format, Object arg) {\n logger.info(marker, format, arg);\n }\n\n @Override\n public void info(Marker marker, String format, Object arg1, Object arg2) {\n logger.info(marker, format, arg1, arg2);\n }\n\n @Override\n public void info(Marker marker, String format, Object... arguments) {\n logger.info(marker, format, arguments);\n }\n\n @Override\n public void info(Marker marker, String msg, Throwable t) {\n if (isReleaseVersion) {\n logger.info(marker, msg, t);\n } else {\n logger.info(marker, msg);\n }\n }\n\n @Override\n public boolean isWarnEnabled() {\n return logger.isWarnEnabled();\n }\n\n @Override\n public void warn(String msg) {\n logger.warn(msg);\n }\n\n @Override\n public void warn(String format, Object arg) {\n logger.warn(format, arg);\n }\n\n @Override\n public void warn(String format, Object... arguments) {\n logger.warn(format, arguments);\n }\n\n @Override\n public void warn(String format, Object arg1, Object arg2) {\n logger.warn(format, arg1, arg2);\n }\n\n @Override\n public void warn(String msg, Throwable t) {\n if (isReleaseVersion) {\n logger.warn(msg, t);\n } else {\n logger.warn(msg);\n }\n }\n\n @Override\n public boolean isWarnEnabled(Marker marker) {\n return logger.isWarnEnabled(marker);\n }\n\n @Override\n public void warn(Marker marker, String msg) {\n logger.warn(marker, msg);\n }\n\n @Override\n public void warn(Marker marker, String format, Object arg) {\n logger.warn(marker, format, arg);\n }\n\n @Override\n public void warn(Marker marker, String format, Object arg1, Object arg2) {\n logger.warn(marker, format, arg1, arg2);\n }\n\n @Override\n public void warn(Marker marker, String format, Object... arguments) {\n logger.warn(marker, format, arguments);\n }\n\n @Override\n public void warn(Marker marker, String msg, Throwable t) {\n if (isReleaseVersion) {\n logger.warn(marker, msg, t);\n } else {\n logger.warn(marker, msg);\n }\n }\n\n @Override\n public boolean isErrorEnabled() {\n return logger.isErrorEnabled();\n }\n\n @Override\n public void error(String msg) {\n logger.error(msg);\n }\n\n @Override\n public void error(String format, Object arg) {\n logger.error(format, arg);\n }\n\n @Override\n public void error(String format, Object arg1, Object arg2) {\n logger.error(format, arg1, arg2);\n }\n\n @Override\n public void error(String format, Object... arguments) {\n logger.error(format, arguments);\n }\n\n @Override\n public void error(String msg, Throwable t) {\n logger.error(msg, t);\n }\n\n @Override\n public boolean isErrorEnabled(Marker marker) {\n return logger.isErrorEnabled(marker);\n }\n\n @Override\n public void error(Marker marker, String msg) {\n logger.error(marker, msg);\n }\n\n @Override\n public void error(Marker marker, String format, Object arg) {\n logger.error(marker, format, arg);\n }\n\n @Override\n public void error(Marker marker, String format, Object arg1, Object arg2) {\n logger.error(marker, format, arg1, arg2);\n }\n\n @Override\n public void error(Marker marker, String format, Object... arguments) {\n logger.error(marker, format, arguments);\n }\n\n @Override\n public void error(Marker marker, String msg, Throwable t) {\n logger.error(marker, msg, t);\n }\n}"
},
{
"identifier": "PRINT_ASM_CODE_ENABLE",
"path": "src/main/java/io/liuguangsheng/galois/constants/ConfConstant.java",
"snippet": "public static final String PRINT_ASM_CODE_ENABLE = \"print-asm-code.enable\";"
},
{
"identifier": "DOT",
"path": "src/main/java/io/liuguangsheng/galois/constants/Constant.java",
"snippet": "public static final String DOT = \".\";"
},
{
"identifier": "USER_DIR",
"path": "src/main/java/io/liuguangsheng/galois/constants/Constant.java",
"snippet": "public static final String USER_DIR = \"user.dir\";"
}
] | import java.io.File;
import java.io.FileOutputStream;
import java.util.Arrays;
import java.util.Optional;
import static io.liuguangsheng.galois.constants.ConfConstant.PRINT_ASM_CODE_ENABLE;
import static io.liuguangsheng.galois.constants.Constant.DOT;
import static io.liuguangsheng.galois.constants.Constant.USER_DIR;
import static io.liuguangsheng.galois.constants.FileType.CLASS_FILE;
import static jdk.internal.org.objectweb.asm.Opcodes.ASM5;
import io.liuguangsheng.galois.conf.GlobalConfiguration;
import io.liuguangsheng.galois.utils.GaloisLog;
import jdk.internal.org.objectweb.asm.ClassReader;
import jdk.internal.org.objectweb.asm.ClassVisitor;
import jdk.internal.org.objectweb.asm.ClassWriter;
import org.slf4j.Logger; | 3,899 | /*
* MIT License
*
* Copyright (c) [2023] [liuguangsheng]
*
* 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 io.liuguangsheng.galois.service;
/**
* method adapter
*
* @author liuguangsheng
* @since 1.0.0
*/
public abstract class MethodAdapter extends ClassVisitor {
private static final Logger logger = new GaloisLog(MethodAdapter.class); | /*
* MIT License
*
* Copyright (c) [2023] [liuguangsheng]
*
* 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 io.liuguangsheng.galois.service;
/**
* method adapter
*
* @author liuguangsheng
* @since 1.0.0
*/
public abstract class MethodAdapter extends ClassVisitor {
private static final Logger logger = new GaloisLog(MethodAdapter.class); | private static final GlobalConfiguration config = GlobalConfiguration.getInstance(); | 0 | 2023-11-22 04:51:35+00:00 | 8k |
TongchengOpenSource/ckibana | src/main/java/com/ly/ckibana/parser/MsearchQueryTask.java | [
{
"identifier": "CKNotSupportException",
"path": "src/main/java/com/ly/ckibana/model/exception/CKNotSupportException.java",
"snippet": "public class CKNotSupportException extends UiException {\n\n public CKNotSupportException(String message) {\n super(\"ckNotSupport \" + message);\n }\n}"
},
{
"identifier": "UiException",
"path": "src/main/java/com/ly/ckibana/model/exception/UiException.java",
"snippet": "public class UiException extends RuntimeException {\n\n public UiException(String message) {\n super(message);\n }\n\n public String getUiShow() {\n return this.getMessage();\n }\n}"
},
{
"identifier": "CkRequestContext",
"path": "src/main/java/com/ly/ckibana/model/request/CkRequestContext.java",
"snippet": "@Data\npublic class CkRequestContext {\n\n private IndexPattern indexPattern;\n\n private String tableName;\n\n private Map<String, String> columns = new HashMap<>();\n\n private int size;\n\n private String sort;\n\n /**\n * response hits使用 使用原始字段名.\n */\n private List<DocValue> docValues;\n\n private List<SortedField> sortingFields;\n\n private String querySqlWithoutTimeRange;\n\n private String query;\n\n /**\n * 聚合参数.\n */\n private List<Aggregation> aggs;\n\n /**\n * 采样参数.\n */\n private SampleParam sampleParam;\n /**\n * 最大结果条数。若大于或等于此阈值,抛出异常,否则可能引发oom.\n */\n private int maxResultRow;\n\n /**\n * 时间范围参数.\n */\n private Range timeRange;\n\n /**\n * 记录耗时使用.\n */\n private long beginTime;\n\n private String database;\n\n private String clientIp;\n\n public CkRequestContext() {\n }\n\n public CkRequestContext(String clientIp, IndexPattern indexPattern, int maxResultRow) {\n this.clientIp = clientIp;\n this.indexPattern = indexPattern;\n this.maxResultRow = maxResultRow;\n database = indexPattern.getDatabase();\n beginTime = System.currentTimeMillis();\n }\n\n @Data\n @AllArgsConstructor\n public static class SampleParam {\n\n /**\n * 优化策略,一个msearch查询第一个的count,确定本次查询的采样参数.\n */\n private long sampleTotalCount;\n\n /**\n * sampleTotalCount数据量超过这个阈值,才会使用采样查询.\n */\n private int sampleCountMaxThreshold;\n\n }\n}"
},
{
"identifier": "Response",
"path": "src/main/java/com/ly/ckibana/model/response/Response.java",
"snippet": "@Data\npublic class Response {\n\n @JsonProperty(\"timed_out\")\n private boolean timedOut;\n\n @JsonProperty(\"_shards\")\n private Shards shards = new Shards();\n\n private Hits hits = new Hits();\n\n private int took;\n\n private boolean cache;\n\n /**\n * 聚合名-{buckets信息}.\n */\n private Map<String, Map<String, Object>> aggregations;\n\n private Integer status;\n\n private Object error;\n\n private List<String> sqls = new ArrayList<>();\n}"
},
{
"identifier": "ProxyUtils",
"path": "src/main/java/com/ly/ckibana/util/ProxyUtils.java",
"snippet": "@Slf4j\npublic class ProxyUtils {\n\n public static final long MILLISECOND = 1;\n\n public static final String TIME_FIELD_OPTION_MATCH_NAME = \"time\";\n\n private static final Map<String, Long> TIME_UNIT_MAP = new LinkedHashMap<>();\n\n private static final List<String> NUMBER_TYPE = Arrays.asList(\"UInt8\", \"UInt16\", \"UInt32\", \"UInt64\",\n \"Int8\", \"Int16\", \"Int32\", \"Int64\", \"Float32\", \"Float64\", \"Decimal\");\n\n /**\n * 从es的interval str(30s)中解析数字和单位(30,s).\n * 本系统默认时间戳到 MICROSECOND\n */\n public static Interval parseInterval(String intervalStr) {\n Interval result = null;\n if (TIME_UNIT_MAP.isEmpty()) {\n TIME_UNIT_MAP.put(\"ms\", MILLISECOND);\n TIME_UNIT_MAP.put(\"s\", 1000 * MILLISECOND);\n TIME_UNIT_MAP.put(\"m\", 60 * 1000 * MILLISECOND);\n TIME_UNIT_MAP.put(\"h\", 60 * 60 * 1000 * MILLISECOND);\n TIME_UNIT_MAP.put(\"d\", 24 * 60 * 60 * 1000 * MILLISECOND);\n TIME_UNIT_MAP.put(\"w\", 7 * 24 * 60 * 60 * 1000 * MILLISECOND);\n }\n for (Map.Entry<String, Long> each : TIME_UNIT_MAP.entrySet()) {\n if (intervalStr.endsWith(each.getKey())) {\n result = new Interval();\n result.setTimeUnit(each.getValue());\n result.setValue(Integer.parseInt(Utils.trimSuffix(intervalStr, each.getKey())));\n break;\n }\n }\n return result;\n }\n\n /**\n * ck基础类型,排查封装类型.\n *\n * @param type ck类型\n * @return 基础类型\n */\n public static String parseCkBaseType(String type) {\n String result = Utils.trimPrefix(type, \"Array\");\n result = Utils.trimPrefix(result, \"Nullable\");\n result = Utils.trimPrefix(result, \"LowCardinality\");\n result = Utils.trimByPrefixAndSuffixChars(result, \"(\", \")\");\n return result;\n }\n\n /**\n * 值转换。若时间字段的utc时间和gmt时间转换为时间戳参数.\n *\n * @param ckFieldType ck字段类型\n * @param ckFieldName ck字段名\n * @param value 值\n * @param timeFieldName 时间字段\n * @return 转换后的值\n */\n public static Object convertValue(String ckFieldType, String ckFieldName, Object value, String timeFieldName) {\n Object result = value;\n if (ProxyUtils.isString(ckFieldType) && StringUtils.equals(timeFieldName, ckFieldName)) {\n Object timeValue = DateUtils.toEpochMilli(result.toString());\n if (timeValue != null) {\n result = timeValue;\n }\n }\n\n return result;\n }\n\n /**\n * 解析ck字段类型,扩展字段和和默认字段为String类型.\n */\n public static String getCkFieldTypeByName(String ckFieldName, Map<String, String> columns) {\n if (columns.containsKey(ckFieldName)) {\n return columns.get(ckFieldName);\n } else if (!checkIfExtensionInnerField(ckFieldName)) {\n log.error(\"unknown ck field: {}, columns:{}\", ckFieldName, columns);\n }\n return \"String\";\n }\n\n /**\n * ck类型是否为数值类.\n */\n public static boolean isNumeric(String type) {\n return NUMBER_TYPE.contains(parseCkBaseType(type));\n }\n\n /**\n * ck类型是否为float或decimal类型.\n */\n public static boolean isDouble(String type) {\n return isNumeric(type) && (SqlConstants.TYPE_FLOAT.equals(parseCkBaseType(type))\n || SqlConstants.TYPE_DECIMAL.equals(parseCkBaseType(type)));\n }\n\n /**\n * ck类型数值类型转为es识别的类型.\n */\n public static String convertCkNumberTypeToEsType(String type) {\n String ckBaseType = parseCkBaseType(type);\n if (ckBaseType.endsWith(\"Int8\")) {\n return \"byte\";\n } else if (ckBaseType.endsWith(\"Int16\")) {\n return \"short\";\n } else if (ckBaseType.endsWith(\"Int32\")) {\n return \"integer\";\n } else if (ckBaseType.endsWith(\"Int64\")) {\n return \"long\";\n } else if (ckBaseType.startsWith(\"Float\")) {\n return \"float\";\n } else {\n return \"double\";\n }\n }\n\n /**\n * 基于值正则或基于ck字段类型判断是否为IPV4类查询.\n * 目前仅支持 string类型ipv4\n */\n public static IPType getIpType(String ckFieldType, String value) {\n IPType ipType = null;\n if (IPType.IPV4.getCkType().equals(ckFieldType)) {\n ipType = IPType.IPV4;\n } else if (IPType.IPV6.getCkType().equals(ckFieldType)) {\n ipType = IPType.IPV6;\n } else if (StringUtils.isNotBlank(value)) {\n if (Utils.isIPv4Value(value) && IPType.IPV4_STRING.getCkType().equals(ckFieldType)) {\n ipType = IPType.IPV4_STRING;\n } else if (Utils.isIPv6Value(value) && IPType.IPV6_STRING.getCkType().equals(ckFieldType)) {\n ipType = IPType.IPV6_STRING;\n }\n }\n return ipType;\n }\n\n /**\n * 是否为数组类字段,目前暂未实际使用.\n * 基于数据类型决定转换语法 https://clickhouse.tech/docs/zh/sql-reference/data-types/\n */\n public static boolean isArrayType(String type) {\n return type.startsWith(\"Array\");\n }\n\n /**\n * 是否为字符串类型字段.\n */\n public static boolean isString(String type) {\n return SqlConstants.TYPE_STRING.equals(parseCkBaseType(type));\n }\n\n /**\n * 是否为date类型字段.\n */\n public static boolean isDate(String type) {\n return parseCkBaseType(type).startsWith(\"Date\");\n }\n\n /**\n * 构建kibana exception.\n */\n public static Response newKibanaException(String error) {\n Map<String, Object> searchError = new HashMap<>(2, 1);\n searchError.put(\"name\", \"SearchError\");\n searchError.put(\"message\", error);\n Response result = new Response();\n result.setAggregations(null);\n result.setHits(null);\n result.setShards(null);\n result.setError(searchError);\n return result;\n }\n\n public static Map<String, Object> newKibanaExceptionV8(String error) {\n return Map.of(\n \"response\", Map.of(\n \"hits\", new Hits(),\n \"_shards\", new Shards()\n ),\n \"error\", Map.of(\n \"type\", \"status_exception\",\n \"reason\", error\n ));\n }\n\n public static String getErrorResponse(Exception e) {\n return getErrorResponse(e.getMessage());\n }\n\n public static String getErrorResponse(String message) {\n return String.format(\"{\\\"status\\\":400, \\\"error\\\":\\\"%s\\\"}\", message);\n }\n\n /**\n * 时间查询sql转换,支持字符串(耗性能,不推荐)和数值类型,DateTime64类型.\n */\n public static String generateTimeFieldSqlWithFormatUnixTimestamp64Milli(String ckFieldName, String ckFieldType) {\n if (isDateTime64Ms(ckFieldType)) {\n return String.format(\"toUnixTimestamp64Milli(%s)\", getFieldSqlPart(ckFieldName));\n } else {\n return getFieldSqlPart(ckFieldName);\n }\n }\n\n /**\n * range请求包装。用于:将不支持range的原始字段转换为支持range的ck function包装后的值.\n * 时间字段:支持数值型timestamp 和DateTime64存储类型 =>,其中DateTime64类型利用toDateTime64()语法实现range\n * ip字段:支持字符串存储类型=> 利用IPv4StringToNum()语法实现range\n * 普通数值字段:支持数值型存储类型=> 无需额外转换\n *\n * @param isTimeField 是否为indexPattern的时间字段\n */\n public static Range getRangeWrappedBySqlFunction(Range orgRange, boolean isTimeField) {\n String ckFieldName = orgRange.getCkFieldName();\n Range rangeConverted = new Range(ckFieldName, orgRange.getCkFieldType(), orgRange.getHigh(), orgRange.getLow());\n if (isTimeField && !isNumeric(orgRange.getCkFieldType())) {\n //时间字段且为非数值类型\n rangeConverted.setCkFieldName(generateTimeFieldSqlWithFormatDateTime64ZoneShangHai(ckFieldName, false));\n rangeConverted.setHigh(generateTimeFieldSqlWithFormatDateTime64ZoneShangHai(orgRange.getHigh(), true));\n rangeConverted.setLow(generateTimeFieldSqlWithFormatDateTime64ZoneShangHai(orgRange.getLow(), true));\n } else {\n //ip\n IPType ipType = ProxyUtils.getIpType(orgRange.getCkFieldType(), orgRange.getLow().toString());\n if (null != ipType) {\n rangeConverted.setCkFieldName(SqlUtils.generateIpSql(ckFieldName, ipType, false));\n rangeConverted.setHigh(SqlUtils.generateIpSql(orgRange.getHigh(), ipType, true));\n rangeConverted.setLow(SqlUtils.generateIpSql(orgRange.getLow(), ipType, true));\n }\n\n }\n return rangeConverted;\n }\n\n /**\n * 是否为DateTime64时间类型.\n *\n * @param ckFieldType ck字段类型\n * @return true:是DateTime64类型\n */\n public static boolean isDateTime64Ms(String ckFieldType) {\n return StringUtils.startsWith(ckFieldType, SqlConstants.TYPE_DATETIME64);\n }\n\n /**\n * 时间字段转换。作为值 or 字段.\n */\n public static String generateTimeFieldSqlWithFormatDateTime64ZoneShangHai(Object value, boolean isValue) {\n if (isValue) {\n return value.toString();\n } else {\n return String.format(\"toUnixTimestamp64Milli(%s)\", getFieldSqlPart(value.toString()));\n }\n\n }\n\n public static Object trimNull(Object body) {\n return null == body || Strings.isNullOrEmpty(body.toString()) ? \"\" : body.toString();\n }\n\n /**\n * 代理自定义语法 忽略大小写.\n */\n public static boolean isCaseIgnoreQuery(String field) {\n return field.endsWith(Constants.UI_PHRASE_CASE_IGNORE);\n }\n\n /**\n * 代理自定义语法 忽略大小写.\n */\n public static boolean isCaseIgnoreKeywordStringQuery(String field) {\n return field.endsWith(Constants.UI_PHRASE_CASE_IGNORE + Constants.ES_KEYWORD);\n }\n\n /**\n * ck类型转为es类型,供kibana 识别.\n */\n public static String convertCkTypeToEsType(String ckName, String ckType, boolean isForSelectTimeField) {\n String result = \"string\";\n if (null != getIpType(ckType, StringUtils.EMPTY)) {\n result = \"ip\";\n } else if (\"_source\".equals(ckName)) {\n result = \"_source\";\n } else if (isDate(ckType) || isTimeFieldOptionByName(ckName, isForSelectTimeField)) {\n result = \"date\";\n } else if (isString(ckType)) {\n result = \"string\";\n } else if (isNumeric(ckType)) {\n result = convertCkNumberTypeToEsType(ckType);\n }\n return result;\n }\n\n /**\n * 除了DateTime64类型,其他可作为时间字段的字段列表。如采样时用的UInt类型等.\n */\n private static boolean isTimeFieldOptionByName(String ckName, boolean isForSelectTimeField) {\n return isForSelectTimeField && ckName.contains(TIME_FIELD_OPTION_MATCH_NAME);\n }\n\n /**\n * ui字段名 转为es字段名.\n */\n public static String convertUiFieldToEsField(String orgField) {\n String result = orgField;\n if (isCaseIgnoreQuery(orgField) || isCaseIgnoreKeywordStringQuery(orgField)) {\n result = result.replace(Constants.UI_PHRASE_CASE_IGNORE, StringUtils.EMPTY);\n }\n result = result.replace(Constants.ES_KEYWORD, StringUtils.EMPTY);\n return result;\n }\n\n /**\n * get no symbol value name.\n * 'A' -> A\n * (A) -> A\n * \"A\" -> A\n *\n * @param confusedValue 混淆的值\n * @return java.lang.String\n * @author quzhihao\n * @date 2023/9/26 20:30\n */\n public static String getPurValue(String confusedValue) {\n String pureColumnName = confusedValue.replace(Constants.Symbol.DOUBLE_QUOTA, StringUtils.EMPTY);\n pureColumnName = pureColumnName.replace(Constants.Symbol.SINGLE_QUOTA, StringUtils.EMPTY);\n pureColumnName = pureColumnName.replace(Constants.Symbol.LEFT_PARENTHESIS, StringUtils.EMPTY);\n pureColumnName = pureColumnName.replace(Constants.Symbol.RIGHT_PARENTHESIS, StringUtils.EMPTY);\n return StringUtils.trim(pureColumnName);\n }\n\n /**\n * get no symbol column name.\n * A.keyword => A\n * A.caseIgnore => A\n * A.caseIgnore.keyword => A\n *\n * @param confusedColumnName ui语法\n * @return java.lang.String\n */\n public static String getPureColumnName(String confusedColumnName) {\n String pureColumnName = confusedColumnName.replace(Constants.UI_PHRASE_CASE_IGNORE, StringUtils.EMPTY);\n pureColumnName = pureColumnName.replace(Constants.ES_KEYWORD, StringUtils.EMPTY);\n return StringUtils.trim(pureColumnName);\n }\n\n /**\n * 是否为创建indexpattern的页面初始查询.\n */\n public static boolean matchAllIndex(String index) {\n return Constants.INDEX_PATTERN_ALL.contains(index);\n }\n\n /**\n * 是否为查询extension内动态字段.\n */\n public static boolean checkIfExtensionInnerField(String ckField) {\n return ckField.startsWith(Constants.CK_EXTENSION_QUERY_FUNCTION);\n }\n\n /**\n * 将字段名转换为sql中拼接的格式,添加符转义或json内解析函数.\n */\n public static String getFieldSqlPart(String ckField) {\n String fieldExpr = (checkIfExtensionInnerField(ckField) || ckField.startsWith(Constants.Symbol.BACK_QUOTE_CHAR)) ? \"%s\" : \"`%s`\";\n return String.format(fieldExpr, ckField);\n }\n\n /**\n * es索引转换为表名.\n * 表名规范替换-换成_\n */\n public static CkRequest buildCkRequest(CkRequestContext ckRequestContext) {\n String ckTableName = ckRequestContext.getTableName();\n return buildRequest(ckTableName, \"*\");\n }\n\n public static CkRequest buildRequest(String table, String... selectParam) {\n CkRequest result = new CkRequest();\n String escapeTable = table;\n if (!escapeTable.startsWith(\"`\")) {\n escapeTable = SqlUtils.escape(escapeTable);\n }\n result.setTable(escapeTable);\n if (selectParam.length > 0) {\n result.setSelect(selectParam[0]);\n }\n return result;\n }\n\n public static boolean isPreciseField(String field) {\n return field.endsWith(Constants.ES_KEYWORD);\n }\n\n public static boolean isRangeQuery(String condition) {\n return condition.startsWith(Constants.Symbol.LEFT_PARENTHESIS) && condition.endsWith(Constants.Symbol.RIGHT_PARENTHESIS);\n }\n\n public static String trimRemoteCluster(String originalIndex) {\n // trim remote cluster\n if (!StringUtils.isEmpty(originalIndex) && originalIndex.contains(Constants.QUERY_CLUSTER_SPLIT)) {\n return originalIndex.substring(originalIndex.indexOf(Constants.QUERY_CLUSTER_SPLIT) + 1);\n }\n return originalIndex;\n }\n}"
}
] | import com.alibaba.fastjson2.JSONObject;
import com.ly.ckibana.model.exception.CKNotSupportException;
import com.ly.ckibana.model.exception.UiException;
import com.ly.ckibana.model.request.CkRequestContext;
import com.ly.ckibana.model.response.Response;
import com.ly.ckibana.util.ProxyUtils;
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.Callable; | 5,213 | /*
* Copyright (c) 2023 LY.com All Rights Reserved.
*
* 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.ly.ckibana.parser;
@Slf4j
public class MsearchQueryTask implements Callable<Response> {
private CkRequestContext ckRequestContext;
private AggResultParser aggsParser;
private JSONObject searchQuery;
public MsearchQueryTask(CkRequestContext ckRequestContext, AggResultParser aggResultParser, JSONObject searchQuery) {
this.ckRequestContext = ckRequestContext;
this.aggsParser = aggResultParser;
this.searchQuery = searchQuery;
}
@Override
public Response call() {
try {
return invoke(ckRequestContext);
} catch (CKNotSupportException ex) {
log.error("call error ", ex);
throw new CKNotSupportException(ex.getMessage());
} catch (Exception ex) { | /*
* Copyright (c) 2023 LY.com All Rights Reserved.
*
* 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.ly.ckibana.parser;
@Slf4j
public class MsearchQueryTask implements Callable<Response> {
private CkRequestContext ckRequestContext;
private AggResultParser aggsParser;
private JSONObject searchQuery;
public MsearchQueryTask(CkRequestContext ckRequestContext, AggResultParser aggResultParser, JSONObject searchQuery) {
this.ckRequestContext = ckRequestContext;
this.aggsParser = aggResultParser;
this.searchQuery = searchQuery;
}
@Override
public Response call() {
try {
return invoke(ckRequestContext);
} catch (CKNotSupportException ex) {
log.error("call error ", ex);
throw new CKNotSupportException(ex.getMessage());
} catch (Exception ex) { | if (ex instanceof UiException e) { | 1 | 2023-11-21 09:12:07+00:00 | 8k |
libgdx/gdx-particle-editor | core/src/main/java/com/ray3k/stripe/DraggableList.java | [
{
"identifier": "DragAndDrop",
"path": "core/src/main/java/com/badlogic/gdx/scenes/scene2d/utils/DragAndDrop.java",
"snippet": "public class DragAndDrop {\n static final Vector2 tmpVector = new Vector2();\n\n Source dragSource;\n Payload payload;\n Actor dragActor;\n boolean removeDragActor;\n Target target;\n boolean isValidTarget;\n final Array<Target> targets = new Array<>(8);\n final ObjectMap<Source, DragListener> sourceListeners = new ObjectMap<>(8);\n private float tapWidth = 8;\n private float tapHeight = 8;\n private int button;\n float dragActorX = 0, dragActorY = 0;\n float touchOffsetX, touchOffsetY;\n long dragValidTime;\n int dragTime = 250;\n int activePointer = -1;\n boolean cancelTouchFocus = true;\n boolean keepWithinStage = true;\n\n public void addSource (final Source source) {\n DragListener listener = new DragListener() {\n public void dragStart (InputEvent event, float x, float y, int pointer) {\n if (activePointer != -1) {\n event.stop();\n return;\n }\n\n activePointer = pointer;\n\n dragValidTime = System.currentTimeMillis() + dragTime;\n dragSource = source;\n payload = source.dragStart(event, getTouchDownX(), getTouchDownY(), pointer);\n event.stop();\n\n if (cancelTouchFocus && payload != null) {\n Stage stage = source.getActor().getStage();\n if (stage != null) stage.cancelTouchFocusExcept(this, source.getActor());\n }\n }\n\n public void drag (InputEvent event, float x, float y, int pointer) {\n if (payload == null) return;\n if (pointer != activePointer) return;\n\n source.drag(event, x, y, pointer);\n\n Stage stage = event.getStage();\n\n // Move the drag actor away, so it cannot be hit.\n Actor oldDragActor = dragActor;\n float oldDragActorX = 0, oldDragActorY = 0;\n if (oldDragActor != null) {\n oldDragActorX = oldDragActor.getX();\n oldDragActorY = oldDragActor.getY();\n oldDragActor.setPosition(Integer.MAX_VALUE, Integer.MAX_VALUE);\n }\n\n float stageX = event.getStageX() + touchOffsetX, stageY = event.getStageY() + touchOffsetY;\n Actor hit = event.getStage().hit(stageX, stageY, true); // Prefer touchable actors.\n if (hit == null) hit = event.getStage().hit(stageX, stageY, false);\n\n if (oldDragActor != null) oldDragActor.setPosition(oldDragActorX, oldDragActorY);\n\n // Find target.\n Target newTarget = null;\n isValidTarget = false;\n if (hit != null) {\n for (int i = 0, n = targets.size; i < n; i++) {\n Target target = targets.get(i);\n if (!target.actor.isAscendantOf(hit)) continue;\n newTarget = target;\n target.actor.stageToLocalCoordinates(tmpVector.set(stageX, stageY));\n break;\n }\n }\n\n // If over a new target, notify the former target that it's being left behind.\n if (newTarget != target) {\n if (target != null) target.reset(source, payload);\n target = newTarget;\n }\n\n // Notify new target of drag.\n if (newTarget != null) isValidTarget = newTarget.drag(source, payload, tmpVector.x, tmpVector.y, pointer);\n\n // Determine the drag actor, remove the old one if it was added by DragAndDrop, and add the new one.\n Actor actor = null;\n if (target != null) actor = isValidTarget ? payload.validDragActor : payload.invalidDragActor;\n if (actor == null) actor = payload.dragActor;\n if (actor != oldDragActor) {\n if (oldDragActor != null && removeDragActor) oldDragActor.remove();\n dragActor = actor;\n removeDragActor = actor.getStage() == null; // Only remove later if not already in the stage now.\n if (removeDragActor) stage.addActor(actor);\n }\n if (actor == null) return;\n\n // Position the drag actor.\n float actorX = event.getStageX() - actor.getWidth() + dragActorX;\n float actorY = event.getStageY() + dragActorY;\n if (keepWithinStage) {\n if (actorX < 0) actorX = 0;\n if (actorY < 0) actorY = 0;\n if (actorX + actor.getWidth() > stage.getWidth()) actorX = stage.getWidth() - actor.getWidth();\n if (actorY + actor.getHeight() > stage.getHeight()) actorY = stage.getHeight() - actor.getHeight();\n }\n actor.setPosition(actorX, actorY);\n }\n\n public void dragStop (InputEvent event, float x, float y, int pointer) {\n if (pointer != activePointer) return;\n activePointer = -1;\n if (payload == null) return;\n\n if (System.currentTimeMillis() < dragValidTime)\n isValidTarget = false;\n else if (!isValidTarget && target != null) {\n float stageX = event.getStageX() + touchOffsetX, stageY = event.getStageY() + touchOffsetY;\n target.actor.stageToLocalCoordinates(tmpVector.set(stageX, stageY));\n isValidTarget = target.drag(source, payload, tmpVector.x, tmpVector.y, pointer);\n }\n if (dragActor != null && removeDragActor) dragActor.remove();\n if (isValidTarget) {\n float stageX = event.getStageX() + touchOffsetX, stageY = event.getStageY() + touchOffsetY;\n target.actor.stageToLocalCoordinates(tmpVector.set(stageX, stageY));\n target.drop(source, payload, tmpVector.x, tmpVector.y, pointer);\n }\n source.dragStop(event, x, y, pointer, payload, isValidTarget ? target : null);\n if (target != null) target.reset(source, payload);\n dragSource = null;\n payload = null;\n target = null;\n isValidTarget = false;\n dragActor = null;\n }\n };\n listener.setTapWidth(tapWidth);\n listener.setTapHeight(tapHeight);\n listener.setButton(button);\n source.actor.addCaptureListener(listener);\n sourceListeners.put(source, listener);\n }\n\n public void removeSource (Source source) {\n DragListener dragListener = sourceListeners.remove(source);\n source.actor.removeCaptureListener(dragListener);\n }\n\n public void addTarget (Target target) {\n targets.add(target);\n }\n\n public void removeTarget (Target target) {\n targets.removeValue(target, true);\n }\n\n /** Removes all targets and sources. */\n public void clear () {\n targets.clear();\n for (Entry<Source, DragListener> entry : sourceListeners.entries())\n entry.key.actor.removeCaptureListener(entry.value);\n sourceListeners.clear(8);\n }\n\n /** Cancels the touch focus for everything except the specified source. */\n public void cancelTouchFocusExcept (Source except) {\n DragListener listener = sourceListeners.get(except);\n if (listener == null) return;\n Stage stage = except.getActor().getStage();\n if (stage != null) stage.cancelTouchFocusExcept(listener, except.getActor());\n }\n\n /** Sets the horizontal distance a touch must travel before being considered a drag. */\n public void setTapWidth(float halfTapWidthSize) {\n tapWidth = halfTapWidthSize;\n updateTapSize();\n }\n\n /** Sets the vertical distance a touch must travel before being considered a drag. */\n public void setTapHeight(float halfTapHeightSize) {\n tapHeight = halfTapHeightSize;\n updateTapSize();\n }\n\n /** Sets the distance a touch must travel before being considered a drag. */\n public void setTapSquareSize(float halfTapSquareSize) {\n tapWidth = halfTapSquareSize;\n tapHeight = halfTapSquareSize;\n updateTapSize();\n }\n\n private void updateTapSize() {\n for (var listener : sourceListeners.values()) {\n listener.setTapWidth(tapWidth);\n listener.setTapHeight(tapHeight);\n }\n }\n\n /** Sets the button to listen for, all other buttons are ignored. Default is {@link Buttons#LEFT}. Use -1 for any button. */\n public void setButton (int button) {\n this.button = button;\n }\n\n public void setDragActorPosition (float dragActorX, float dragActorY) {\n this.dragActorX = dragActorX;\n this.dragActorY = dragActorY;\n }\n\n /** Sets an offset in stage coordinates from the touch position which is used to determine the drop location. Default is\n * 0,0. */\n public void setTouchOffset (float touchOffsetX, float touchOffsetY) {\n this.touchOffsetX = touchOffsetX;\n this.touchOffsetY = touchOffsetY;\n }\n\n public boolean isDragging () {\n return payload != null;\n }\n\n /** Returns the current drag actor, or null. */\n public @Null Actor getDragActor () {\n return dragActor;\n }\n\n /** Returns the current drag payload, or null. */\n public @Null Payload getDragPayload () {\n return payload;\n }\n\n /** Returns the current drag source, or null. */\n public @Null Source getDragSource () {\n return dragSource;\n }\n\n /** Time in milliseconds that a drag must take before a drop will be considered valid. This ignores an accidental drag and drop\n * that was meant to be a click. Default is 250. */\n public void setDragTime (int dragMillis) {\n this.dragTime = dragMillis;\n }\n\n public int getDragTime () {\n return dragTime;\n }\n\n /** Returns true if a drag is in progress and the {@link #setDragTime(int) drag time} has elapsed since the drag started. */\n public boolean isDragValid () {\n return payload != null && System.currentTimeMillis() >= dragValidTime;\n }\n\n /** When true (default), the {@link Stage#cancelTouchFocus()} touch focus} is cancelled if\n * {@link Source#dragStart(InputEvent, float, float, int) dragStart} returns non-null. This ensures the DragAndDrop is the only\n * touch focus listener, eg when the source is inside a {@link ScrollPane} with flick scroll enabled. */\n public void setCancelTouchFocus (boolean cancelTouchFocus) {\n this.cancelTouchFocus = cancelTouchFocus;\n }\n\n public void setKeepWithinStage (boolean keepWithinStage) {\n this.keepWithinStage = keepWithinStage;\n }\n\n /** A source where a payload can be dragged from.\n * @author Nathan Sweet */\n static abstract public class Source {\n final Actor actor;\n\n public Source (Actor actor) {\n if (actor == null) throw new IllegalArgumentException(\"actor cannot be null.\");\n this.actor = actor;\n }\n\n /** Called when a drag is started on the source. The coordinates are in the source's local coordinate system.\n * @return If null the drag will not affect any targets. */\n abstract public @Null Payload dragStart (InputEvent event, float x, float y, int pointer);\n\n /** Called repeatedly during a drag which started on this source. */\n public void drag (InputEvent event, float x, float y, int pointer) {\n }\n\n /** Called when a drag for the source is stopped. The coordinates are in the source's local coordinate system.\n * @param payload null if dragStart returned null.\n * @param target null if not dropped on a valid target. */\n public void dragStop (InputEvent event, float x, float y, int pointer, @Null Payload payload, @Null Target target) {\n }\n\n public Actor getActor () {\n return actor;\n }\n }\n\n /** A target where a payload can be dropped to.\n * @author Nathan Sweet */\n static abstract public class Target {\n final Actor actor;\n\n public Target (Actor actor) {\n if (actor == null) throw new IllegalArgumentException(\"actor cannot be null.\");\n this.actor = actor;\n Stage stage = actor.getStage();\n if (stage != null && actor == stage.getRoot())\n throw new IllegalArgumentException(\"The stage root cannot be a drag and drop target.\");\n }\n\n /** Called when the payload is dragged over the target. The coordinates are in the target's local coordinate system.\n * @return true if this is a valid target for the payload. */\n abstract public boolean drag (Source source, Payload payload, float x, float y, int pointer);\n\n /** Called when the payload is no longer over the target, whether because the touch was moved or a drop occurred. This is\n * called even if {@link #drag(Source, Payload, float, float, int)} returned false. */\n public void reset (Source source, Payload payload) {\n }\n\n /** Called when the payload is dropped on the target. The coordinates are in the target's local coordinate system. This is\n * not called if {@link #drag(Source, Payload, float, float, int)} returned false. */\n abstract public void drop (Source source, Payload payload, float x, float y, int pointer);\n\n public Actor getActor () {\n return actor;\n }\n }\n\n /** The payload of a drag and drop operation. Actors can be optionally provided to follow the cursor and change when over a\n * target. Such actors will be added the stage automatically during the drag operation as necessary and they will only be\n * removed from the stage if they were added automatically. A source actor can be used as a payload drag actor. */\n static public class Payload {\n @Null Actor dragActor, validDragActor, invalidDragActor;\n @Null Object object;\n\n public void setDragActor (@Null Actor dragActor) {\n this.dragActor = dragActor;\n }\n\n public @Null Actor getDragActor () {\n return dragActor;\n }\n\n public void setValidDragActor (@Null Actor validDragActor) {\n this.validDragActor = validDragActor;\n }\n\n public @Null Actor getValidDragActor () {\n return validDragActor;\n }\n\n public void setInvalidDragActor (@Null Actor invalidDragActor) {\n this.invalidDragActor = invalidDragActor;\n }\n\n public @Null Actor getInvalidDragActor () {\n return invalidDragActor;\n }\n\n public @Null Object getObject () {\n return object;\n }\n\n public void setObject (@Null Object object) {\n this.object = object;\n }\n }\n}"
},
{
"identifier": "Payload",
"path": "core/src/main/java/com/badlogic/gdx/scenes/scene2d/utils/DragAndDrop.java",
"snippet": "static public class Payload {\n @Null Actor dragActor, validDragActor, invalidDragActor;\n @Null Object object;\n\n public void setDragActor (@Null Actor dragActor) {\n this.dragActor = dragActor;\n }\n\n public @Null Actor getDragActor () {\n return dragActor;\n }\n\n public void setValidDragActor (@Null Actor validDragActor) {\n this.validDragActor = validDragActor;\n }\n\n public @Null Actor getValidDragActor () {\n return validDragActor;\n }\n\n public void setInvalidDragActor (@Null Actor invalidDragActor) {\n this.invalidDragActor = invalidDragActor;\n }\n\n public @Null Actor getInvalidDragActor () {\n return invalidDragActor;\n }\n\n public @Null Object getObject () {\n return object;\n }\n\n public void setObject (@Null Object object) {\n this.object = object;\n }\n}"
},
{
"identifier": "Source",
"path": "core/src/main/java/com/badlogic/gdx/scenes/scene2d/utils/DragAndDrop.java",
"snippet": "static abstract public class Source {\n final Actor actor;\n\n public Source (Actor actor) {\n if (actor == null) throw new IllegalArgumentException(\"actor cannot be null.\");\n this.actor = actor;\n }\n\n /** Called when a drag is started on the source. The coordinates are in the source's local coordinate system.\n * @return If null the drag will not affect any targets. */\n abstract public @Null Payload dragStart (InputEvent event, float x, float y, int pointer);\n\n /** Called repeatedly during a drag which started on this source. */\n public void drag (InputEvent event, float x, float y, int pointer) {\n }\n\n /** Called when a drag for the source is stopped. The coordinates are in the source's local coordinate system.\n * @param payload null if dragStart returned null.\n * @param target null if not dropped on a valid target. */\n public void dragStop (InputEvent event, float x, float y, int pointer, @Null Payload payload, @Null Target target) {\n }\n\n public Actor getActor () {\n return actor;\n }\n}"
},
{
"identifier": "Target",
"path": "core/src/main/java/com/badlogic/gdx/scenes/scene2d/utils/DragAndDrop.java",
"snippet": "static abstract public class Target {\n final Actor actor;\n\n public Target (Actor actor) {\n if (actor == null) throw new IllegalArgumentException(\"actor cannot be null.\");\n this.actor = actor;\n Stage stage = actor.getStage();\n if (stage != null && actor == stage.getRoot())\n throw new IllegalArgumentException(\"The stage root cannot be a drag and drop target.\");\n }\n\n /** Called when the payload is dragged over the target. The coordinates are in the target's local coordinate system.\n * @return true if this is a valid target for the payload. */\n abstract public boolean drag (Source source, Payload payload, float x, float y, int pointer);\n\n /** Called when the payload is no longer over the target, whether because the touch was moved or a drop occurred. This is\n * called even if {@link #drag(Source, Payload, float, float, int)} returned false. */\n public void reset (Source source, Payload payload) {\n }\n\n /** Called when the payload is dropped on the target. The coordinates are in the target's local coordinate system. This is\n * not called if {@link #drag(Source, Payload, float, float, int)} returned false. */\n abstract public void drop (Source source, Payload payload, float x, float y, int pointer);\n\n public Actor getActor () {\n return actor;\n }\n}"
}
] | import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.scenes.scene2d.*;
import com.badlogic.gdx.scenes.scene2d.ui.Button;
import com.badlogic.gdx.scenes.scene2d.ui.Button.ButtonStyle;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.scenes.scene2d.ui.WidgetGroup;
import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener.ChangeEvent;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import com.badlogic.gdx.scenes.scene2d.utils.DragAndDrop;
import com.badlogic.gdx.scenes.scene2d.utils.DragAndDrop.Payload;
import com.badlogic.gdx.scenes.scene2d.utils.DragAndDrop.Source;
import com.badlogic.gdx.scenes.scene2d.utils.DragAndDrop.Target;
import com.badlogic.gdx.scenes.scene2d.utils.Drawable;
import com.badlogic.gdx.utils.Align;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.ObjectMap; | 4,754 | package com.ray3k.stripe;
public class DraggableList extends WidgetGroup {
private DraggableListStyle style;
private final Table table;
protected Array<Actor> actors;
private final ObjectMap<Actor, Actor> dragActors;
private final ObjectMap<Actor, Actor> validDragActors;
private final ObjectMap<Actor, Actor> invalidDragActors; | package com.ray3k.stripe;
public class DraggableList extends WidgetGroup {
private DraggableListStyle style;
private final Table table;
protected Array<Actor> actors;
private final ObjectMap<Actor, Actor> dragActors;
private final ObjectMap<Actor, Actor> validDragActors;
private final ObjectMap<Actor, Actor> invalidDragActors; | private final DragAndDrop dragAndDrop; | 0 | 2023-11-24 15:58:20+00:00 | 8k |
373675032/love-charity | src/main/java/com/charity/controller/ArticleController.java | [
{
"identifier": "CheckStatus",
"path": "src/main/java/com/charity/constant/CheckStatus.java",
"snippet": "public class CheckStatus {\n\n /**\n * 等待审核\n */\n public static final int WAIT = 0;\n\n /**\n * 审核通过\n */\n public static final int PASS = 1;\n\n /**\n * 审核未通过\n */\n public static final int NOT_PASS = 2;\n}"
},
{
"identifier": "CommentType",
"path": "src/main/java/com/charity/constant/CommentType.java",
"snippet": "public class CommentType {\n\n /**\n * 文章\n */\n public static final int ARTICLE = 2;\n\n /**\n * 活动\n */\n public static final int ACTIVITY = 2;\n\n /**\n * 公益项目\n */\n public static final int PROJECT = 1;\n}"
},
{
"identifier": "TrashStatus",
"path": "src/main/java/com/charity/constant/TrashStatus.java",
"snippet": "public class TrashStatus {\n\n /**\n * 不在回收站\n */\n public static final int NOT_IN = 1;\n\n /**\n * 在回收站\n */\n public static final int IS_IN = 2;\n}"
},
{
"identifier": "TypeStatus",
"path": "src/main/java/com/charity/constant/TypeStatus.java",
"snippet": "public class TypeStatus {\n\n /**\n * 文章\n */\n public static final int ARTICLE = 1;\n\n /**\n * 活动\n */\n public static final int ACTIVITY = 2;\n}"
},
{
"identifier": "ResponseResult",
"path": "src/main/java/com/charity/dto/ResponseResult.java",
"snippet": "public class ResponseResult {\n\n private int code;\n private int success;\n private String message;\n private Object data;\n private String url;\n\n public ResponseResult() {\n }\n\n public ResponseResult(int code, String message) {\n this.code = code;\n this.message = message;\n }\n\n public ResponseResult(int code, String message, Object data) {\n this.code = code;\n this.message = message;\n this.data = data;\n }\n\n public ResponseResult(int code) {\n this.code = code;\n }\n\n public ResponseResult(int code, String message, String url) {\n this.code = code;\n this.message = message;\n this.url = url;\n }\n\n public int getSuccess() {\n return success;\n }\n\n public void setSuccess(int success) {\n this.success = success;\n }\n\n public int getCode() {\n return code;\n }\n\n public void setCode(int code) {\n this.code = code;\n }\n\n public String getMessage() {\n return message;\n }\n\n public void setMessage(String message) {\n this.message = message;\n }\n\n public Object getData() {\n return data;\n }\n\n public void setData(Object data) {\n this.data = data;\n }\n\n public String getUrl() {\n return url;\n }\n\n public void setUrl(String url) {\n this.url = url;\n }\n\n @Override\n public String toString() {\n return \"ResponseResult{\" +\n \"code=\" + code +\n \", success=\" + success +\n \", message='\" + message + '\\'' +\n \", data=\" + data +\n \", url='\" + url + '\\'' +\n '}';\n }\n}"
},
{
"identifier": "Article",
"path": "src/main/java/com/charity/entity/Article.java",
"snippet": "@Data\n@NoArgsConstructor\n@AllArgsConstructor\n@Builder\npublic class Article implements Serializable {\n\n private static final long serialVersionUID = 591577028509822181L;\n\n /**\n * 文章ID\n */\n private Integer id;\n\n /**\n * 作者用户ID\n */\n private Integer userId;\n\n /**\n * 文章标题\n */\n private String title;\n\n /**\n * 文章正文\n */\n private String content;\n\n /**\n * 文章状态:发布(1),回收站(2)\n */\n private Integer status;\n\n /**\n * 阅读量\n */\n private Integer readCount;\n\n /**\n * 封面图片\n */\n private String img;\n\n /**\n * 类型:文章(1),活动(2)\n */\n private Integer type;\n\n /**\n * 文章审核,0:未审核,1:审核通过,2:审核不通过\n */\n private Integer isChecked;\n\n /**\n * 审核未通过返回的消息\n */\n private String info;\n\n /**\n * 数据插入时间,即发布时间\n */\n private Date gmtCreate;\n\n /**\n * 更新时间\n */\n private Date gmtModified;\n\n}"
},
{
"identifier": "Message",
"path": "src/main/java/com/charity/entity/Message.java",
"snippet": "@Data\n@NoArgsConstructor\n@AllArgsConstructor\n@Builder\npublic class Message implements Serializable {\n\n private static final long serialVersionUID = 170364374295614279L;\n\n /**\n * 主键ID\n */\n private Integer id;\n\n /**\n * 接收消息的用户ID\n */\n private Integer receiveUserId;\n\n /**\n * 发送消息的用户ID\n */\n private Integer sentUserId;\n\n /**\n * 类型:点赞(0)/评论(1)\n */\n private Integer type;\n\n /**\n * 目标ID:公益项目/文章ID\n */\n private Integer targetId;\n\n /**\n * 标题\n */\n private String title;\n\n /**\n * 消息的内容\n */\n private String content;\n\n /**\n * 是否已读:未读(0),已读(1)\n */\n private Integer isRead;\n\n /**\n * 插入数据的时间,即发表评论的时间\n */\n private Date gmtCreate;\n\n /**\n * 更新的时间\n */\n private Date gmtModified;\n\n /**\n * 发送者用户头像\n */\n private String sentUserImg;\n\n}"
},
{
"identifier": "OssUtils",
"path": "src/main/java/com/charity/utils/OssUtils.java",
"snippet": "public class OssUtils {\n\n private static String FILE_URL;\n private static final String BUCKET_NAME = \"su-share\";\n private static final String END_POINT = \"oss-cn-beijing.aliyuncs.com\";\n private static final String ACCESS_KEY_ID = \"\";\n private static final String ACCESS_KEY_SECRET = \"\";\n\n /**\n * 上传文件\n */\n public static String upload(MultipartFile file, String path) throws IOException {\n if (file == null || path == null) {\n return null;\n }\n OSSClient ossClient = new OSSClient(END_POINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);\n if (!ossClient.doesBucketExist(BUCKET_NAME)) {\n ossClient.createBucket(BUCKET_NAME);\n CreateBucketRequest createBucketRequest = new CreateBucketRequest(BUCKET_NAME);\n createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);\n ossClient.createBucket(createBucketRequest);\n }\n String extension = getFileExtension(file);\n //设置文件路径\n String fileUrl = path + \"/\" + IdUtil.simpleUUID() + extension;\n FILE_URL = \"https://\" + BUCKET_NAME + \".\" + END_POINT + \"/\" + fileUrl;\n PutObjectResult result = ossClient.putObject(new PutObjectRequest(BUCKET_NAME, fileUrl, file.getInputStream()));\n //上传文件\n ossClient.setBucketAcl(BUCKET_NAME, CannedAccessControlList.PublicRead);\n return FILE_URL;\n }\n\n /**\n * 获取文件的扩展名\n */\n public static String getFileExtension(MultipartFile file) {\n String filename = file.getOriginalFilename();\n return filename.substring(filename.lastIndexOf(\".\"));\n }\n\n /**\n * 获得随机的头像\n */\n public static String getRandomImg() {\n String[] imgs = {\n \"https://su-share.oss-cn-beijing.aliyuncs.com/1.jpg\",\n \"https://su-share.oss-cn-beijing.aliyuncs.com/2.jpg\",\n \"https://su-share.oss-cn-beijing.aliyuncs.com/3.jpg\",\n \"https://su-share.oss-cn-beijing.aliyuncs.com/4.jpg\",\n \"https://su-share.oss-cn-beijing.aliyuncs.com/5.jpg\",\n };\n return imgs[(int) (Math.random() * 5)];\n }\n\n /**\n * 获得随机的文章封面\n */\n public static String getRandomFace() {\n String[] imgs = {\n \"https://su-share.oss-cn-beijing.aliyuncs.com/1.jpg\",\n \"https://su-share.oss-cn-beijing.aliyuncs.com/2.jpg\",\n \"https://su-share.oss-cn-beijing.aliyuncs.com/3.jpg\",\n \"https://su-share.oss-cn-beijing.aliyuncs.com/4.jpg\",\n \"https://su-share.oss-cn-beijing.aliyuncs.com/5.jpg\",\n\n };\n return imgs[(int) (Math.random() * 5)];\n }\n\n\n public static boolean checkFileSize(Long len, int size, String unit) {\n double fileSize = 0;\n if (\"B\".equalsIgnoreCase(unit)) {\n fileSize = (double) len;\n } else if (\"K\".equalsIgnoreCase(unit)) {\n fileSize = (double) len / 1024;\n } else if (\"M\".equalsIgnoreCase(unit)) {\n fileSize = (double) len / 1048576;\n } else if (\"G\".equalsIgnoreCase(unit)) {\n fileSize = (double) len / 1073741824;\n }\n return !(fileSize > size);\n }\n}"
},
{
"identifier": "LogUtils",
"path": "src/main/java/com/charity/utils/LogUtils.java",
"snippet": "public class LogUtils {\n private static Logger logger;\n\n private LogUtils() {\n }\n\n public static Logger getInstance(Class c) {\n return logger = LoggerFactory.getLogger(c);\n }\n}"
},
{
"identifier": "MessageUtils",
"path": "src/main/java/com/charity/utils/MessageUtils.java",
"snippet": "public class MessageUtils {\n\n /**\n * 文章/项目评论的内容处理\n * name 被评论的文章的名字 userName评论者的用户名 content消息内容 type文章/项目\n */\n public static String CommentHandle(String name, String userName, String content, Integer type) {\n String typeName = \"\";\n if (type == 1) {\n typeName = \"项目\";\n } else {\n typeName = \"文章\";\n }\n String content1 = \"<b>\" + userName + \"</b> 评论了您的\" + typeName + \" <b><<\" + name + \">></b> 内容如下: <b>\" + content + \"</b>\";\n return content1;\n }\n\n /**\n * 文章/项目平路回复的消息处理\n */\n public static String relplyCommentHandle(String articleName, String userName, String content, Integer type) {\n String typeName = \"\";\n if (type == 1) {\n typeName = \"项目\";\n } else {\n typeName = \"文章\";\n }\n String content1 = \"<b>\" + userName + \"</b> 回复了您关于\" + typeName + \" <b><<\" + articleName + \">></b>的评论,内容如下: <b>\" + content + \"</b>\";\n return content1;\n }\n\n /**\n * 文章审核消息处理\n * articleName 文章名字 flag为1表示通过审核,为2表示不通过审核 info处理信息\n */\n public static String articleCheckHandle(String articleName, Integer flag, String info) {\n String content = \"\";\n if (flag == 1) {\n content = \"<b>恭喜您,您的文章</b><b><<\" + articleName + \">>已通过审核!</b>\";\n } else {\n content = \"<b>很遗憾,您的文章</b><b><<\" + articleName + \">>未通过审核!原因为:</b><b>\" + info + \"</b>\";\n }\n return content;\n }\n\n /**\n * 认证审核消息处理\n * flag为1表示通c过审核,为2表示不通过审核 info处理信息\n */\n public static String certificationCheckHandle(Integer flag, String info) {\n String content = \"\";\n if (flag == 1) {\n content = \"<b>恭喜您,您已成功通过认证!</b>\";\n } else {\n content = \"<b>很遗憾,您未能通过认证!原因为:</b><b>\" + info + \"</b>\";\n }\n return content;\n }\n\n\n}"
}
] | import com.alibaba.fastjson.JSONObject;
import com.charity.constant.CheckStatus;
import com.charity.constant.CommentType;
import com.charity.constant.TrashStatus;
import com.charity.constant.TypeStatus;
import com.charity.dto.ResponseResult;
import com.charity.entity.Article;
import com.charity.entity.Message;
import com.charity.utils.OssUtils;
import com.charity.utils.LogUtils;
import com.charity.utils.MessageUtils;
import org.slf4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.Date; | 4,651 | package com.charity.controller;
/**
* 文章控制器
* <p>
* ==========================================================================
* 郑重说明:本项目免费开源!原创作者为:薛伟同学,严禁私自出售。
* ==========================================================================
* B站账号:薛伟同学
* 微信公众号:薛伟同学
* 作者博客:http://xuewei.world
* ==========================================================================
* 陆陆续续总会收到粉丝的提醒,总会有些人为了赚取利益倒卖我的开源项目。
* 不乏有粉丝朋友出现钱付过去,那边只把代码发给他就跑路的,最后还是根据线索找到我。。
* 希望各位朋友擦亮慧眼,谨防上当受骗!
* ==========================================================================
*
* @author <a href="http://xuewei.world/about">XUEW</a>
*/
@Controller
public class ArticleController extends BaseController {
private final Logger logger = LogUtils.getInstance(ArticleController.class);
/**
* 发布求助文章
*/
@PostMapping("/publishArticle")
@ResponseBody
public String publishArticle(String title, String content, String imgPath, Integer activityId) {
// 生成文章对象
Article article = Article.builder()
.title(title).content(content).userId(loginUser.getId())
.type(TypeStatus.ARTICLE).readCount(0).status(TrashStatus.NOT_IN).isChecked(CheckStatus.WAIT)
.gmtCreate(new Date()).gmtModified(new Date())
.build();
// 为文章设置封面,如果为空就生成随机封面
article.setImg(StringUtils.isEmpty(imgPath) ? OssUtils.getRandomFace() : imgPath);
if (articleService.insert(article)) {
if (activityId != -1) {
articleService.insertArticleActivity(article.getId(), activityId);
logger.info("【成功】:添加文章活动");
}
result.setCode(200);
logger.info("【成功】:添加文章");
} else {
result.setCode(500);
logger.info("【失败】:添加文章");
}
return JSONObject.toJSONString(result);
}
/**
* 更新文章
*/
@PostMapping("/updateArticle")
@ResponseBody
public String updateArticle(Integer id, String title, String content, String imgPath, int activityId) {
// 生成文章对象
Article article = Article.builder()
.id(id).title(title).content(content).status(TrashStatus.NOT_IN).isChecked(CheckStatus.WAIT)
.gmtModified(new Date())
.build();
// 为文章设置封面,如果为空就生成随机封面
article.setImg(StringUtils.isEmpty(imgPath) ? OssUtils.getRandomFace() : imgPath);
if (articleService.update(article)) {
if (activityId != -1) {
// 获取原来参加的活动
Article activity = articleService.getActivityByArticleId(id);
if (activity == null || activity.getId() != activityId) {
// 删除参与的活动
articleService.deleteArticleActivity(id);
// 添加新的活动
articleService.insertArticleActivity(article.getId(), activityId);
logger.info("【成功】:更新文章活动");
}
}
result.setCode(200);
logger.info("【成功】:更新文章");
} else {
result.setCode(500);
logger.info("【失败】:更新文章");
}
return JSONObject.toJSONString(result);
}
/**
* 将文章移到回收站
*/
@GetMapping("/putIntoTrash")
public String putIntoTrash(@RequestParam("id") Integer id, @RequestParam("checked") Integer checked) {
// 获取文章
Article article = articleService.getById(id);
if (article.getType() == TypeStatus.ACTIVITY) {
logger.info("【失败】:将文章移到回收站,类型错误");
return "error/400";
}
if (article.getUserId() != loginUser.getId()) {
logger.info("【失败】:将文章移到回收站,无权限");
return "error/401";
}
article.setStatus(TrashStatus.IS_IN);
if (articleService.update(article)) {
logger.info("【成功】:将文字移到回收站");
} else {
logger.info("【失败】:将文字移到回收站");
}
return "redirect:/my-articles?checked=" + checked;
}
/**
* 删除文章
*/
@GetMapping("/deleteArticle")
public String deleteArticle(@RequestParam("id") Integer id) {
Article article = articleService.getById(id);
if (article.getType() == TypeStatus.ACTIVITY) {
logger.info("【失败】:删除文章,类型错误");
return "error/400";
}
if (article.getUserId() != loginUser.getId()) {
logger.info("【失败】:删除文章,无权限");
return "error/401";
}
// 删除文章
if (articleService.deleteById(id)) {
logger.info("【成功】:删除文章");
// 删除文章参加的活动
articleService.deleteArticleActivity(id);
// 删除评论
commentService.deleteByTargetIdAndType(id, CommentType.ARTICLE);
} else {
logger.info("【失败】:删除文章");
}
return "redirect:/trash-article";
}
/**
* 更新文章审核状态
*/
@PostMapping("/updateArticleIsCheck")
@ResponseBody
public ResponseResult updateArticleIsCheck(String isChecked, String info, Integer id) {
Article article = articleService.getById(id);
article.setIsChecked(Integer.parseInt(isChecked));
article.setInfo(info);
if (articleService.update(article)) {
//储存消息 | package com.charity.controller;
/**
* 文章控制器
* <p>
* ==========================================================================
* 郑重说明:本项目免费开源!原创作者为:薛伟同学,严禁私自出售。
* ==========================================================================
* B站账号:薛伟同学
* 微信公众号:薛伟同学
* 作者博客:http://xuewei.world
* ==========================================================================
* 陆陆续续总会收到粉丝的提醒,总会有些人为了赚取利益倒卖我的开源项目。
* 不乏有粉丝朋友出现钱付过去,那边只把代码发给他就跑路的,最后还是根据线索找到我。。
* 希望各位朋友擦亮慧眼,谨防上当受骗!
* ==========================================================================
*
* @author <a href="http://xuewei.world/about">XUEW</a>
*/
@Controller
public class ArticleController extends BaseController {
private final Logger logger = LogUtils.getInstance(ArticleController.class);
/**
* 发布求助文章
*/
@PostMapping("/publishArticle")
@ResponseBody
public String publishArticle(String title, String content, String imgPath, Integer activityId) {
// 生成文章对象
Article article = Article.builder()
.title(title).content(content).userId(loginUser.getId())
.type(TypeStatus.ARTICLE).readCount(0).status(TrashStatus.NOT_IN).isChecked(CheckStatus.WAIT)
.gmtCreate(new Date()).gmtModified(new Date())
.build();
// 为文章设置封面,如果为空就生成随机封面
article.setImg(StringUtils.isEmpty(imgPath) ? OssUtils.getRandomFace() : imgPath);
if (articleService.insert(article)) {
if (activityId != -1) {
articleService.insertArticleActivity(article.getId(), activityId);
logger.info("【成功】:添加文章活动");
}
result.setCode(200);
logger.info("【成功】:添加文章");
} else {
result.setCode(500);
logger.info("【失败】:添加文章");
}
return JSONObject.toJSONString(result);
}
/**
* 更新文章
*/
@PostMapping("/updateArticle")
@ResponseBody
public String updateArticle(Integer id, String title, String content, String imgPath, int activityId) {
// 生成文章对象
Article article = Article.builder()
.id(id).title(title).content(content).status(TrashStatus.NOT_IN).isChecked(CheckStatus.WAIT)
.gmtModified(new Date())
.build();
// 为文章设置封面,如果为空就生成随机封面
article.setImg(StringUtils.isEmpty(imgPath) ? OssUtils.getRandomFace() : imgPath);
if (articleService.update(article)) {
if (activityId != -1) {
// 获取原来参加的活动
Article activity = articleService.getActivityByArticleId(id);
if (activity == null || activity.getId() != activityId) {
// 删除参与的活动
articleService.deleteArticleActivity(id);
// 添加新的活动
articleService.insertArticleActivity(article.getId(), activityId);
logger.info("【成功】:更新文章活动");
}
}
result.setCode(200);
logger.info("【成功】:更新文章");
} else {
result.setCode(500);
logger.info("【失败】:更新文章");
}
return JSONObject.toJSONString(result);
}
/**
* 将文章移到回收站
*/
@GetMapping("/putIntoTrash")
public String putIntoTrash(@RequestParam("id") Integer id, @RequestParam("checked") Integer checked) {
// 获取文章
Article article = articleService.getById(id);
if (article.getType() == TypeStatus.ACTIVITY) {
logger.info("【失败】:将文章移到回收站,类型错误");
return "error/400";
}
if (article.getUserId() != loginUser.getId()) {
logger.info("【失败】:将文章移到回收站,无权限");
return "error/401";
}
article.setStatus(TrashStatus.IS_IN);
if (articleService.update(article)) {
logger.info("【成功】:将文字移到回收站");
} else {
logger.info("【失败】:将文字移到回收站");
}
return "redirect:/my-articles?checked=" + checked;
}
/**
* 删除文章
*/
@GetMapping("/deleteArticle")
public String deleteArticle(@RequestParam("id") Integer id) {
Article article = articleService.getById(id);
if (article.getType() == TypeStatus.ACTIVITY) {
logger.info("【失败】:删除文章,类型错误");
return "error/400";
}
if (article.getUserId() != loginUser.getId()) {
logger.info("【失败】:删除文章,无权限");
return "error/401";
}
// 删除文章
if (articleService.deleteById(id)) {
logger.info("【成功】:删除文章");
// 删除文章参加的活动
articleService.deleteArticleActivity(id);
// 删除评论
commentService.deleteByTargetIdAndType(id, CommentType.ARTICLE);
} else {
logger.info("【失败】:删除文章");
}
return "redirect:/trash-article";
}
/**
* 更新文章审核状态
*/
@PostMapping("/updateArticleIsCheck")
@ResponseBody
public ResponseResult updateArticleIsCheck(String isChecked, String info, Integer id) {
Article article = articleService.getById(id);
article.setIsChecked(Integer.parseInt(isChecked));
article.setInfo(info);
if (articleService.update(article)) {
//储存消息 | String content = MessageUtils.articleCheckHandle(article.getTitle(), Integer.parseInt(isChecked), info); | 9 | 2023-11-26 17:33:02+00:00 | 8k |
siam1026/siam-server | siam-system/system-provider/src/main/java/com/siam/system/modular/package_goods/controller/admin/internal/AdminVipRechargeRecordController.java | [
{
"identifier": "BasicResultCode",
"path": "siam-common/src/main/java/com/siam/package_common/constant/BasicResultCode.java",
"snippet": "public class BasicResultCode {\n public static final int ERR = 0;\n\n public static final int SUCCESS = 1;\n\n public static final int TOKEN_ERR = 2;\n}"
},
{
"identifier": "Quantity",
"path": "siam-common/src/main/java/com/siam/package_common/constant/Quantity.java",
"snippet": "public class Quantity {\n\n public static final byte BYTE_0 = (byte) 0;\n public static final byte BYTE_1 = (byte) 1;\n public static final byte BYTE_2 = (byte) 2;\n public static final byte BYTE_3 = (byte) 3;\n\n public static final int INT_MINUS_1 = -1;\n public static final int INT_MINUS_60 = -60;\n\n public static final int INT_0 = 0;\n public static final int INT_1 = 1;\n public static final int INT_2 = 2;\n public static final int INT_3 = 3;\n public static final int INT_4 = 4;\n public static final int INT_5 = 5;\n public static final int INT_6 = 6;\n public static final int INT_7 = 7;\n public static final int INT_8 = 8;\n public static final int INT_9 = 9;\n public static final int INT_10 = 10;\n public static final int INT_11 = 11;\n public static final int INT_12 = 12;\n public static final int INT_13 = 13;\n public static final int INT_14 = 14;\n public static final int INT_15 = 15;\n public static final int INT_16 = 16;\n public static final int INT_17 = 17;\n public static final int INT_18 = 18;\n public static final int INT_19 = 19;\n\n public static final long LONG_0 = 0;\n public static final long LONG_1 = 1;\n public static final long LONG_2 = 2;\n public static final long LONG_3 = 3;\n public static final long LONG_4 = 4;\n\n}"
},
{
"identifier": "BasicData",
"path": "siam-common/src/main/java/com/siam/package_common/entity/BasicData.java",
"snippet": "public class BasicData extends BasicResult{\n private Object data;\n\n public Object getData() {\n return data;\n }\n\n public void setData(Object data) {\n this.data = data;\n }\n}"
},
{
"identifier": "BasicResult",
"path": "siam-common/src/main/java/com/siam/package_common/entity/BasicResult.java",
"snippet": "@Data\npublic class BasicResult {\n\n public static final Integer CODE_DEFAULT_SUCCESS = 200;\n public static final Integer CODE_DEFAULT_ERROR = 500;\n\n public static final String MESSAGE_DEFAULT_SUCCESS = \"请求成功\";\n public static final String MESSAGE_DEFAULT_ERROR = \"网络异常\";\n\n private Boolean success;\n\n private Integer code;\n\n private String message;\n\n private Object data;\n\n public BasicResult() {\n }\n\n public BasicResult(Boolean success, Integer code, String message, Object data) {\n this.success = success;\n this.code = code;\n this.message = message;\n this.data = data;\n }\n\n public static BasicResult success() {\n return new BasicResult(true, CODE_DEFAULT_SUCCESS, MESSAGE_DEFAULT_SUCCESS, null);\n }\n\n public static BasicResult success(Object data) {\n return new BasicResult(true, CODE_DEFAULT_SUCCESS, MESSAGE_DEFAULT_SUCCESS, data);\n }\n\n public static BasicResult error(String message) {\n return new BasicResult(false, CODE_DEFAULT_ERROR, message, null);\n }\n}"
},
{
"identifier": "VipRechargeRecord",
"path": "siam-system/system-api/src/main/java/com/siam/system/modular/package_goods/entity/internal/VipRechargeRecord.java",
"snippet": "@Data\n@TableName(\"tb_vip_recharge_record\")\n@ApiModel(value = \"会员充值记录表\")\npublic class VipRechargeRecord {\n\n /* ##################################### START 扩展字段 #################################### */\n\n //开始日期\n @TableField(select = false)\n private Date startCreateTime;\n\n //结束日期\n @TableField(select = false)\n private Date endCreateTime;\n\n //充值时长(月)\n @TableField(select = false)\n private int rechargeTime;\n\n public Date getStartCreateTime() {\n return startCreateTime;\n }\n\n public void setStartCreateTime(Date startCreateTime) {\n this.startCreateTime = startCreateTime;\n }\n\n public Date getEndCreateTime() {\n return endCreateTime;\n }\n\n public void setEndCreateTime(Date endCreateTime) {\n this.endCreateTime = endCreateTime;\n }\n\n //页码\n @TableField(select = false)\n private Integer pageNo = 1;\n\n //页面大小\n @TableField(select = false)\n private Integer pageSize = 20;\n\n public Integer getPageNo() {\n return pageNo;\n }\n\n public void setPageNo(Integer pageNo) {\n this.pageNo = pageNo;\n }\n\n /* ##################################### END 扩展字段 #################################### */\n\n @TableId(type = IdType.AUTO)\n private Integer id;\n\n private Integer memberId;\n\n private String orderNo;\n\n private Integer channel;\n\n private Integer denominationId;\n\n private BigDecimal amount;\n\n private String denominationName;\n\n private BigDecimal denominationPrice;\n\n private Boolean denominationIsSale;\n\n private BigDecimal denominationSalePrice;\n\n private Boolean denominationIsGiveBalance;\n\n private BigDecimal denominationGiveBalance;\n\n private Boolean denominationIsGiveCoupons;\n\n private String denominationGiveCouponsDescription;\n\n private String denominationGiveCouponsJson;\n\n private Integer tradeId;\n\n private Integer status;\n\n private Date createTime;\n\n public Integer getId() {\n return id;\n }\n\n public void setId(Integer id) {\n this.id = id;\n }\n\n public Integer getMemberId() {\n return memberId;\n }\n\n public void setMemberId(Integer memberId) {\n this.memberId = memberId;\n }\n\n public String getOrderNo() {\n return orderNo;\n }\n\n public void setOrderNo(String orderNo) {\n this.orderNo = orderNo == null ? null : orderNo.trim();\n }\n\n public Integer getChannel() {\n return channel;\n }\n\n public void setChannel(Integer channel) {\n this.channel = channel;\n }\n\n public Integer getDenominationId() {\n return denominationId;\n }\n\n public void setDenominationId(Integer denominationId) {\n this.denominationId = denominationId;\n }\n\n public BigDecimal getAmount() {\n return amount;\n }\n\n public void setAmount(BigDecimal amount) {\n this.amount = amount;\n }\n\n public String getDenominationName() {\n return denominationName;\n }\n\n public void setDenominationName(String denominationName) {\n this.denominationName = denominationName == null ? null : denominationName.trim();\n }\n\n public BigDecimal getDenominationPrice() {\n return denominationPrice;\n }\n\n public void setDenominationPrice(BigDecimal denominationPrice) {\n this.denominationPrice = denominationPrice;\n }\n\n public Boolean getDenominationIsSale() {\n return denominationIsSale;\n }\n\n public void setDenominationIsSale(Boolean denominationIsSale) {\n this.denominationIsSale = denominationIsSale;\n }\n\n public BigDecimal getDenominationSalePrice() {\n return denominationSalePrice;\n }\n\n public void setDenominationSalePrice(BigDecimal denominationSalePrice) {\n this.denominationSalePrice = denominationSalePrice;\n }\n\n public Boolean getDenominationIsGiveBalance() {\n return denominationIsGiveBalance;\n }\n\n public void setDenominationIsGiveBalance(Boolean denominationIsGiveBalance) {\n this.denominationIsGiveBalance = denominationIsGiveBalance;\n }\n\n public BigDecimal getDenominationGiveBalance() {\n return denominationGiveBalance;\n }\n\n public void setDenominationGiveBalance(BigDecimal denominationGiveBalance) {\n this.denominationGiveBalance = denominationGiveBalance;\n }\n\n public Boolean getDenominationIsGiveCoupons() {\n return denominationIsGiveCoupons;\n }\n\n public void setDenominationIsGiveCoupons(Boolean denominationIsGiveCoupons) {\n this.denominationIsGiveCoupons = denominationIsGiveCoupons;\n }\n\n public String getDenominationGiveCouponsDescription() {\n return denominationGiveCouponsDescription;\n }\n\n public void setDenominationGiveCouponsDescription(String denominationGiveCouponsDescription) {\n this.denominationGiveCouponsDescription = denominationGiveCouponsDescription == null ? null : denominationGiveCouponsDescription.trim();\n }\n\n public String getDenominationGiveCouponsJson() {\n return denominationGiveCouponsJson;\n }\n\n public void setDenominationGiveCouponsJson(String denominationGiveCouponsJson) {\n this.denominationGiveCouponsJson = denominationGiveCouponsJson == null ? null : denominationGiveCouponsJson.trim();\n }\n\n public Integer getTradeId() {\n return tradeId;\n }\n\n public void setTradeId(Integer tradeId) {\n this.tradeId = tradeId;\n }\n\n public Integer getStatus() {\n return status;\n }\n\n public void setStatus(Integer status) {\n this.status = status;\n }\n\n public Date getCreateTime() {\n return createTime;\n }\n\n public void setCreateTime(Date createTime) {\n this.createTime = createTime;\n }\n}"
},
{
"identifier": "VipRechargeRecordService",
"path": "siam-system/system-api/src/main/java/com/siam/system/modular/package_goods/service/internal/VipRechargeRecordService.java",
"snippet": "public interface VipRechargeRecordService {\n\n void deleteByPrimaryKey(Integer id);\n\n void insertSelective(VipRechargeRecord vipRechargeRecord);\n\n VipRechargeRecord selectByPrimaryKey(Integer id);\n\n void updateByPrimaryKeySelective(VipRechargeRecord vipRechargeRecord);\n\n /**\n * 条件查询集合\n * @param vipRechargeRecord 查询条件对象\n * @param pageNo 分页所在页\n * @param pageSize 单页数据量大小\n * @return\n */\n Page getListByPage(int pageNo, int pageSize, VipRechargeRecord vipRechargeRecord);\n\n /**\n * 条件查询集合\n * @param vipRechargeRecord 查询条件对象\n * @param pageNo 分页所在页\n * @param pageSize 单页数据量大小\n * @return\n */\n Page getListByPageJoinMember(int pageNo, int pageSize, VipRechargeRecord vipRechargeRecord);\n\n Map<String, Object> statisticalAmount(VipRechargeRecord vipRechargeRecord);\n\n /**\n * 普通订单回调\n * 支付成功回调时修改订单状态,并且触发一系列关联操作\n * @param outTradeNo 商户单号\n */\n void updateByPayNotify(String outTradeNo);\n\n VipRechargeRecord selectLastestPaid(Integer memberId);\n}"
},
{
"identifier": "Member",
"path": "siam-system/system-api/src/main/java/com/siam/system/modular/package_user/entity/Member.java",
"snippet": "@Data\n@TableName(\"tb_member\")\npublic class Member {\n\n //注册方式 1=微信一键登录 2=手机验证码 3=邀请注册\n public static final int REGISTER_WAY_OF_WECHAT = 1;\n public static final int REGISTER_WAY_OF_MOBILECODE = 2;\n public static final int REGISTER_WAY_OF_INVITE = 3;\n\n @TableId(type = IdType.AUTO)\n private Integer id;\n\n private String username;\n\n private String mobile;\n\n private String password;\n\n private String passwordSalt;\n\n private String nickname;\n\n private BigDecimal balance;\n\n private Integer loginCount;\n\n private String inviteCode;\n\n private String headImg;\n\n private String roles;\n\n private Integer sex;\n\n private String email;\n\n private Boolean isDisabled;\n\n private Boolean isDeleted;\n\n private String openId;\n\n private Boolean isBindWx;\n\n private BigDecimal points;\n\n private Integer vipStatus;\n\n private Integer vipType;\n\n private Date vipStartTime;\n\n private Date vipEndTime;\n\n private Integer type;\n\n private String vipNo;\n\n private Boolean isNewPeople;\n\n private Boolean isRemindNewPeople;\n\n private Date lastUseTime;\n\n private String lastUseAddress;\n\n private Integer registerWay;\n\n private String wxPublicPlatformOpenId;\n\n private Boolean isRequestWxNotify;\n\n private Date lastRequestWxNotifyTime;\n\n private BigDecimal inviteRewardAmount;\n\n private String realName;\n\n private BigDecimal totalBalance;\n\n private BigDecimal totalConsumeBalance;\n\n private BigDecimal totalPoints;\n\n private BigDecimal totalConsumePoints;\n\n private BigDecimal totalWithdrawInviteRewardAmount;\n\n private String paymentPassword;\n\n private String paymentPasswordSalt;\n\n private String inviteSuncode;\n\n private BigDecimal unreceivedPoints;\n\n private BigDecimal unreceivedInviteRewardAmount;\n\n private Date createTime;\n\n private Date updateTime;\n\n private Date lastLoginTime;\n}"
},
{
"identifier": "MemberService",
"path": "siam-system/system-api/src/main/java/com/siam/system/modular/package_user/service/MemberService.java",
"snippet": "public interface MemberService {\n\n// /**\n// * 登录-手机验证码\n// *\n// * @author 暹罗\n// */\n// MemberResult loginByMobile(MemberParam param);\n\n /**\n * 对密码进行盐值加密(废弃)\n *\n * @author 暹罗\n */\n String encryptionBySalt(String password, String passwordSalt);\n\n /**\n * 微信一键登录\n *\n * @author 暹罗\n */\n Integer findMemberByOpenId(String openId);\n\n /**\n * 微信一键登录\n *\n * @author 暹罗\n */\n Member findMemberByOneKeyLogin(Member member) throws Exception;\n\n /**\n * 将新用户的\"是否需要弹出新人引导提示\"字段值改成是\n *\n * @author 暹罗\n */\n String getNextVipNo();\n\n /**\n * 将新用户的\"是否需要弹出新人引导提示\"字段值改成是\n *\n * @author 暹罗\n */\n List<Member> selectAllMemberNoneCoupons();\n\n /**\n * 将新用户的\"是否需要弹出新人引导提示\"字段值改成是\n *\n * @author 暹罗\n */\n List<Member> selectAllMemberNoneCouponsByPointsMall();\n\n /**\n * 将新用户的\"是否需要弹出新人引导提示\"字段值改成是\n *\n * @author 暹罗\n */\n void updateIsRemindNewPeople();\n\n /**\n * 查询普通注册人数(微信一键登录)\n *\n * @author 暹罗\n */\n int selectCountWeChatRegister(Date startTime, Date endTime);\n\n /**\n * 查询普通注册人数(手机验证码注册)\n *\n * @author 暹罗\n */\n int selectCountMobileCodeRegister(Date startTime, Date endTime);\n\n /**\n * 查询普通注册人数(微信一键登录+手机验证码注册)\n *\n * @author 暹罗\n */\n int selectCountGeneralRegister(Date startTime, Date endTime);\n\n /**\n * 查询所有注册人数\n *\n * @author 暹罗\n */\n int selectCountRegister(Date startTime, Date endTime);\n\n /**\n * 查询邀请注册人数\n *\n * @author 暹罗\n */\n int selectCountInviteRegister(Date startTime, Date endTime);\n\n /**\n * 修改用户的是否需要请求授权服务通知状态\n *\n * @author 暹罗\n */\n void updateIsRequestWxNotify();\n\n /**\n *\n *\n * @author 暹罗\n */\n String generateVipNo();\n\n /**\n *\n *\n * @author 暹罗\n */\n void queryWxPublicPlatformOpenId() throws IOException;\n\n /**\n *\n *\n * @author 暹罗\n */\n BasicResult querySingleWxPublicPlatformOpenId(Integer id) throws IOException;\n\n int countByExample(MemberExample example);\n\n void insertSelective(Member record);\n\n List<Member> selectByExample(MemberExample example);\n\n Member selectByPrimaryKey(Integer id);\n\n void updateByExampleSelective(Member record, MemberExample example);\n\n void updateByPrimaryKeySelective(Member record);\n\n /**\n * 通过手机号查询用户信息\n *\n * @author 暹罗\n */\n Member selectByMobile(String mobile);\n\n /**\n * 微信一键登录\n *\n * @author 暹罗\n */\n Page getListByPage(MemberParam param);\n\n /**\n * 条件查询集合\n *\n * @author 暹罗\n */\n Page getList(int pageNo, int pageSize, MemberParam member);\n\n /**\n *\n *\n * @author 暹罗\n */\n Page<Member> purchasedList(MemberParam param);\n\n /**\n *\n *\n * @author 暹罗\n */\n Page<Member> unPurchasedList(MemberParam param);\n\n /**\n * 登录-账号密码\n *\n * @author 暹罗\n */\n MemberResult login(MemberParam param);\n\n /**\n * 验证码登录\n * 1) 现在验证码登录接口关联了openid属性,目的是为了在下单时直接获取openid\n * 2) 其实不应该这样做,应该是在下单时获取当前运行小程序的微信号的openid,\n * 3) 由于每次切换微信账号时小程序必定是会重新修改openid的,所以也不会造成bug,暂时先这样写就不改动了\n *\n * @author 暹罗\n */\n MemberResult verificationLogin(MemberParam param);\n\n /**\n * 微信登录\n *\n * @author 暹罗\n */\n MemberResult wxLogin(MemberParam param);\n\n /**\n * 获取登录用户信息\n *\n * @author 暹罗\n */\n MemberResult getLoginMemberInfo(MemberParam param);\n\n /**\n * 解除账号绑定的微信\n *\n * @author 暹罗\n */\n void removeBindingWx(MemberParam param);\n\n /**\n * 上传头像\n *\n * @author 暹罗\n */\n void uploadHeadImg(MemberParam param);\n\n /**\n * 修改登录密码\n *\n * @author 暹罗\n */\n void updatePassword(MemberParam param);\n\n /**\n * 登出\n *\n * @author 暹罗\n */\n void logout(MemberParam param);\n\n /**\n * 修改个人资料(邮箱地址、性别、真实姓名)\n *\n * @author 暹罗\n */\n void update(MemberParam param);\n\n /**\n * 修改是否需要弹出新人引导提示为否\n *\n * @author 暹罗\n */\n void updateIsRemindNewPeople(MemberParam param);\n\n /**\n * 修改用户的是否需要请求授权服务通知状态为否/告知已发起过请求授权服务通知\n *\n * @author 暹罗\n */\n void updateIsRequestWxNotify(MemberParam param);\n\n /**\n * 上报使用/进入小程序的定位地址\n *\n * @author 暹罗\n */\n void updateLastUseAddress(MemberParam param);\n\n /**\n * 设置/找回支付密码第一步\n *\n * @author 暹罗\n */\n void forgetPaymentPasswordStep1(MemberParam param);\n\n /**\n * 设置/找回支付密码第二步\n *\n * @author 暹罗\n */\n void forgetPaymentPasswordStep2(MemberParam param);\n\n /**\n * 验证支付密码是否正确(场景:支付、提现)\n *\n * @author 暹罗\n */\n void verifyPaymentPassword(MemberParam param);\n}"
}
] | import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.siam.package_common.constant.BasicResultCode;
import com.siam.package_common.constant.Quantity;
import com.siam.package_common.entity.BasicData;
import com.siam.package_common.entity.BasicResult;
import com.siam.system.modular.package_goods.entity.internal.VipRechargeRecord;
import com.siam.system.modular.package_goods.service.internal.VipRechargeRecordService;
import com.siam.system.modular.package_user.entity.Member;
import com.siam.system.modular.package_user.service.MemberService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map; | 5,838 | package com.siam.system.modular.package_goods.controller.admin.internal;
@Slf4j
@RestController
@RequestMapping(value = "/rest/admin/vipRechargeRecord")
@Transactional(rollbackFor = Exception.class)
@Api(tags = "后台会员充值记录模块相关接口", description = "AdminVipRechargeRecordController")
public class AdminVipRechargeRecordController {
@Autowired
private VipRechargeRecordService vipRechargeRecordService;
@Autowired
private MemberService memberService;
@ApiOperation(value = "会员充值记录列表")
@PostMapping(value = "/list")
public BasicResult list(@RequestBody @Validated(value = {}) VipRechargeRecord vipRechargeRecord){
BasicData basicResult = new BasicData();
vipRechargeRecord.setStatus(Quantity.INT_2);
Page<VipRechargeRecord> page = vipRechargeRecordService.getListByPageJoinMember(vipRechargeRecord.getPageNo(), vipRechargeRecord.getPageSize(), vipRechargeRecord);
return BasicResult.success(page);
}
@ApiOperation(value = "会员充值记录-统计金额")
@PostMapping(value = "/statisticalAmount")
public BasicResult statisticalAmount(@RequestBody @Validated(value = {}) VipRechargeRecord vipRechargeRecord, HttpServletRequest request){
BasicData basicResult = new BasicData();
Map<String, Object> map = vipRechargeRecordService.statisticalAmount(vipRechargeRecord);
basicResult.setData(map);
basicResult.setSuccess(true); | package com.siam.system.modular.package_goods.controller.admin.internal;
@Slf4j
@RestController
@RequestMapping(value = "/rest/admin/vipRechargeRecord")
@Transactional(rollbackFor = Exception.class)
@Api(tags = "后台会员充值记录模块相关接口", description = "AdminVipRechargeRecordController")
public class AdminVipRechargeRecordController {
@Autowired
private VipRechargeRecordService vipRechargeRecordService;
@Autowired
private MemberService memberService;
@ApiOperation(value = "会员充值记录列表")
@PostMapping(value = "/list")
public BasicResult list(@RequestBody @Validated(value = {}) VipRechargeRecord vipRechargeRecord){
BasicData basicResult = new BasicData();
vipRechargeRecord.setStatus(Quantity.INT_2);
Page<VipRechargeRecord> page = vipRechargeRecordService.getListByPageJoinMember(vipRechargeRecord.getPageNo(), vipRechargeRecord.getPageSize(), vipRechargeRecord);
return BasicResult.success(page);
}
@ApiOperation(value = "会员充值记录-统计金额")
@PostMapping(value = "/statisticalAmount")
public BasicResult statisticalAmount(@RequestBody @Validated(value = {}) VipRechargeRecord vipRechargeRecord, HttpServletRequest request){
BasicData basicResult = new BasicData();
Map<String, Object> map = vipRechargeRecordService.statisticalAmount(vipRechargeRecord);
basicResult.setData(map);
basicResult.setSuccess(true); | basicResult.setCode(BasicResultCode.SUCCESS); | 0 | 2023-11-26 12:41:06+00:00 | 8k |
junyharang-coding-study/GraphQL-Study | 자프링-GraphQL-실습/src/main/java/com/junyss/graphqltest/api/people/service/PeopleServiceImpl.java | [
{
"identifier": "DefaultResponse",
"path": "자프링-GraphQL-실습/src/main/java/com/junyss/graphqltest/common/constant/DefaultResponse.java",
"snippet": "@Data\n@AllArgsConstructor\n@Builder\npublic class DefaultResponse<T> {\n\tprivate Integer statusCode;\n\tprivate String message;\n\tprivate Pagination pagination;\n\tprivate T data;\n\n\t/**\n\t * <b>상태 코드 + 부가 설명 반환</b>\n\t *\n\t * @param statusCode Http Status Code Number\n\t * @param message Response Body에 응답할 Message\n\t * @return <T> DefaultResponse<T> Response Body 응답값\n\t */\n\n\tpublic static <T> DefaultResponse<T> response(\n\t\tfinal Integer statusCode,\n\t\tfinal String message) {\n\t\treturn (DefaultResponse<T>)DefaultResponse.builder()\n\t\t\t.statusCode(statusCode)\n\t\t\t.message(message)\n\t\t\t.build();\n\t}\n\n\t/**\n\t * <b>상태 코드 + 부가 설명 + Paging 정보 + 응답 데이터 반환</b>\n\t *\n\t * @param statusCode Http Status Code Number\n\t * @param message Response Body에 응답할 Message\n\t * @param data 연산 뒤 처리 결과값 객체\n\t * @return <T> DefaultResponse<T> Response Body 응답값\n\t */\n\n\tpublic static <T> DefaultResponse<T> response(\n\t\tfinal Integer statusCode,\n\t\tfinal String message,\n\t\tfinal T data) {\n\t\treturn (DefaultResponse<T>)DefaultResponse.builder()\n\t\t\t.statusCode(statusCode)\n\t\t\t.message(message)\n\t\t\t.data(data)\n\t\t\t.build();\n\t}\n\n\t/**\n\t * <b>상태 코드 + 부가 설명 + Paging 정보 + 응답 데이터 반환</b>\n\t *\n\t * @param statusCode Http Status Code Number\n\t * @param message Response Body에 응답할 Message\n\t * @param data 연산 뒤 처리 결과값 객체\n\t * @param pagination Paging 정보\n\t * @return <T> DefaultResponse<T> Response Body 응답값\n\t */\n\n\tpublic static <T> DefaultResponse<T> response(\n\t\tfinal Integer statusCode,\n\t\tfinal String message,\n\t\tfinal T data,\n\t\tfinal Pagination pagination) {\n\t\treturn (DefaultResponse<T>)DefaultResponse.builder()\n\t\t\t.statusCode(statusCode)\n\t\t\t.message(message)\n\t\t\t.data(data)\n\t\t\t.pagination(pagination)\n\t\t\t.build();\n\t}\n}"
},
{
"identifier": "Pagination",
"path": "자프링-GraphQL-실습/src/main/java/com/junyss/graphqltest/common/constant/Pagination.java",
"snippet": "@Data\n@NoArgsConstructor\n@AllArgsConstructor\n@Builder\npublic class Pagination {\n\t// 전체 페이지 수\n\tprivate Integer totalPages;\n\n\t// 전체 데이터 개수\n\tprivate Long totalElements;\n\n\t// 현재 페이지\n\tprivate Integer page;\n\n\t// 현재 페이지 데이터 개수\n\tprivate Integer currentElements;\n\n\tpublic Pagination(Page<?> page) {\n\t\tthis.totalPages = page.getTotalPages();\n\t\tthis.totalElements = page.getTotalElements();\n\t\tthis.page = page.getNumber();\n\t\tthis.currentElements = page.getNumberOfElements();\n\t}\n}"
},
{
"identifier": "BloodType",
"path": "자프링-GraphQL-실습/src/main/java/com/junyss/graphqltest/common/enumtype/BloodType.java",
"snippet": "@Getter\n@NoArgsConstructor\n@AllArgsConstructor\npublic enum BloodType {\n\tA(\"A\"),\n\tB(\"B\"),\n\tO(\"O\"),\n\tAB(\"AB\");\n\n\tprivate String bloodType;\n}"
},
{
"identifier": "Role",
"path": "자프링-GraphQL-실습/src/main/java/com/junyss/graphqltest/common/enumtype/Role.java",
"snippet": "@Getter\n@NoArgsConstructor\n@AllArgsConstructor\npublic enum Role {\n\tdeveloper(\"developer\"),\n\tdesigner(\"designer\"),\n\tplanner(\"planner\");\n\n\tprivate String role;\n}"
},
{
"identifier": "Sex",
"path": "자프링-GraphQL-실습/src/main/java/com/junyss/graphqltest/common/enumtype/Sex.java",
"snippet": "@Getter\n@NoArgsConstructor\n@AllArgsConstructor\npublic enum Sex {\n\n\tmale(\"male\"),\n\tfemale(\"female\");\n\n\tprivate String sex;\n}"
},
{
"identifier": "GraphQLSupportUtil",
"path": "자프링-GraphQL-실습/src/main/java/com/junyss/graphqltest/common/util/GraphQLSupportUtil.java",
"snippet": "@Data\n@NoArgsConstructor(access = AccessLevel.PRIVATE)\n@Component\npublic class GraphQLSupportUtil {\n\n\tpublic static <T> List<T> pageToList(Page<T> pageTypeDto) {\n\t\tif (pageTypeDto.getTotalElements() == 0 && !pageTypeDto.hasContent()) {\n\t\t\treturn Collections.emptyList();\n\t\t}\n\n\t\treturn pageTypeDto.getContent();\n\t}\n}"
},
{
"identifier": "ObjectUtil",
"path": "자프링-GraphQL-실습/src/main/java/com/junyss/graphqltest/common/util/ObjectUtil.java",
"snippet": "@Data\n@NoArgsConstructor(access = AccessLevel.PRIVATE)\n@Component\npublic class ObjectUtil {\n\n\tpublic static <T> Boolean checkObjectExistence(Page<T> targetPageObject) {\n\t\treturn targetPageObject.getTotalElements() == 0 && !targetPageObject.hasContent();\n\t}\n}"
},
{
"identifier": "PagingProcessUtil",
"path": "자프링-GraphQL-실습/src/main/java/com/junyss/graphqltest/common/util/PagingProcessUtil.java",
"snippet": "@Data\n@NoArgsConstructor(access = AccessLevel.PRIVATE)\n@Component\npublic class PagingProcessUtil {\n\n\tpublic static Pageable processPaging(int page, int size) {\n\t\tif (page <= 0 && size <= 0) {\n\t\t\tpage = 1;\n\t\t\tsize = 10;\n\t\t}\n\t\treturn PageRequest.of(page, size);\n\t}\n\n\tpublic static <T> List<T> queryDslPagingProcessing(JPAQuery<T> query, Pageable pageable) {\n\t\tList<T> result = new ArrayList<>();\n\n\t\tif (query.stream().count() >= 2) {\n\t\t\tresult = query.offset(pageable.getOffset())\n\t\t\t\t\t\t .limit(pageable.getPageSize())\n\t\t\t\t\t\t .fetch();\n\t\t} else {\n\t\t\tresult.add(query.fetchOne());\n\t\t}\n\n\t\treturn result;\n\t}\n}"
},
{
"identifier": "PeopleRequestDto",
"path": "자프링-GraphQL-실습/src/main/java/com/junyss/graphqltest/api/people/model/dto/request/PeopleRequestDto.java",
"snippet": "@Data\npublic class PeopleRequestDto {\n\t@NotBlank private Long teamId;\n\t@NotBlank private String lastName;\n\t@NotBlank private String firstName;\n\t@NotBlank private Sex sex;\n\t@NotBlank private BloodType bloodType;\n\t@NotNull @Min(0) private Integer serveYears;\n\t@NotBlank private Role role;\n\t@NotBlank private String hometown;\n}"
},
{
"identifier": "PeopleSearchRequestDto",
"path": "자프링-GraphQL-실습/src/main/java/com/junyss/graphqltest/api/people/model/dto/request/PeopleSearchRequestDto.java",
"snippet": "@Data\n@NoArgsConstructor\n@AllArgsConstructor\npublic class PeopleSearchRequestDto {\n\tprivate Long peopleId;\n\tprivate Long teamId;\n\tprivate String lastName;\n\tprivate String firstName;\n\tprivate Sex sex;\n\tprivate BloodType bloodType;\n\tprivate Integer serveYears;\n\tprivate Role role;\n\tprivate String hometown;\n}"
},
{
"identifier": "PeopleUpdateRequestDto",
"path": "자프링-GraphQL-실습/src/main/java/com/junyss/graphqltest/api/people/model/dto/request/PeopleUpdateRequestDto.java",
"snippet": "@Data\npublic class PeopleUpdateRequestDto {\n\tprivate Long peopleId;\n\tprivate Long teamId;\n\tprivate String lastName;\n\tprivate String firstName;\n\tprivate Sex sex;\n\tprivate BloodType bloodType;\n\tprivate Integer serveYears;\n private Role role;\n\tprivate String hometown;\n}"
},
{
"identifier": "PeopleResponseDto",
"path": "자프링-GraphQL-실습/src/main/java/com/junyss/graphqltest/api/people/model/dto/response/PeopleResponseDto.java",
"snippet": "@Builder\n@Data\n@NoArgsConstructor\n@AllArgsConstructor\npublic class PeopleResponseDto {\n\tprivate Long peopleId;\n\tprivate Long teamId;\n\tprivate String lastName;\n\tprivate String firstName;\n\tprivate Sex sex;\n\tprivate BloodType bloodType;\n\tprivate Integer serveYears;\n\tprivate Role role;\n\tprivate String hometown;\n}"
},
{
"identifier": "People",
"path": "자프링-GraphQL-실습/src/main/java/com/junyss/graphqltest/api/people/model/entity/People.java",
"snippet": "@Getter\n@NoArgsConstructor(access = AccessLevel.PROTECTED)\n@AllArgsConstructor(access = AccessLevel.PRIVATE)\n@Entity\npublic class People {\n\n\t@Id @GeneratedValue(strategy = GenerationType.IDENTITY)\n\tprivate Long peopleId;\n\n\t@ManyToOne(fetch = FetchType.LAZY, targetEntity = Team.class)\n\t@JoinColumn(name = \"team_id\")\n\tprivate Team team;\n\tprivate String lastName;\n\tprivate String firstName;\n\t@Enumerated(EnumType.STRING) private Sex sex;\n\t@Enumerated(EnumType.STRING) private BloodType bloodType;\n\tprivate Integer serveYears;\n\t@Enumerated(EnumType.STRING) private Role role;\n\tprivate String hometown;\n\n\t@Builder\n\tpublic static People toEntity (\n\t\tTeam team,\n\t\tString lastName,\n\t\tString firstName,\n\t\tSex sex,\n\t\tBloodType bloodType,\n\t\tInteger serveYears,\n\t\tRole role,\n\t\tString hometown\n\t) {\n\t\treturn new People (\n\t\t\tnull,\n\t\t\tteam,\n\t\t\tlastName,\n\t\t\tfirstName,\n\t\t\tsex,\n\t\t\tbloodType,\n\t\t\tserveYears,\n\t\t\trole,\n\t\t\thometown);\n\t}\n\n\tpublic void updatePeopleId(Long peopleId) {\n\t\tthis.peopleId = peopleId;\n\t}\n\n\tpublic void updateTeam(Team team) {\n\t\tthis.team = team;\n\t}\n\n\tpublic void updateLastName(String lastName) {\n\t\tthis.lastName = lastName;\n\t}\n\n\tpublic void updateFirstName(String firstName) {\n\t\tthis.firstName = firstName;\n\t}\n\n\tpublic void updateSex(Sex sex) {\n\t\tthis.sex = sex;\n\t}\n\n\tpublic void updateBloodType(BloodType bloodType) {\n\t\tthis.bloodType = bloodType;\n\t}\n\n\tpublic void updateServeYears(Integer serveYears) {\n\t\tthis.serveYears = serveYears;\n\t}\n\n\tpublic void updateRole(Role role) {\n\t\tthis.role = role;\n\t}\n\n\tpublic void updateHomeTown(String hometown) {\n\t\tthis.hometown = hometown;\n\t}\n}"
},
{
"identifier": "PeopleQueryDslRepository",
"path": "자프링-GraphQL-실습/src/main/java/com/junyss/graphqltest/api/people/repository/PeopleQueryDslRepository.java",
"snippet": "@RequiredArgsConstructor\n@Repository\npublic class PeopleQueryDslRepository {\n\n\tprivate final JPAQueryFactory jpaQueryFactory;\n\n\tpublic Page<PeopleResponseDto> findBySearchAndPaging(PeopleSearchRequestDto peopleSearchRequestDto,\n\t\tPageable pageable) {\n\t\tJPAQuery<PeopleResponseDto> query = jpaQueryFactory.select(Projections.constructor(\n\t\t\t\tPeopleResponseDto.class,\n\t\t\t\tpeople.peopleId,\n\t\t\t\tpeople.team.teamId,\n\t\t\t\tpeople.lastName,\n\t\t\t\tpeople.firstName,\n\t\t\t\tpeople.sex,\n\t\t\t\tpeople.bloodType,\n\t\t\t\tpeople.serveYears,\n\t\t\t\tpeople.role,\n\t\t\t\tpeople.hometown))\n\t\t\t.from(people)\n\t\t\t.where(\n\t\t\t\teqPeopleId(peopleSearchRequestDto.getPeopleId()),\n\t\t\t\teqTeam(peopleSearchRequestDto.getTeamId()),\n\t\t\t\teqLastName(peopleSearchRequestDto.getLastName()),\n\t\t\t\teqFirstName(peopleSearchRequestDto.getFirstName()),\n\t\t\t\teqSex(peopleSearchRequestDto.getSex()),\n\t\t\t\teqBloodType(peopleSearchRequestDto.getBloodType()),\n\t\t\t\teqServeYears(peopleSearchRequestDto.getServeYears()),\n\t\t\t\teqRole(peopleSearchRequestDto.getRole()),\n\t\t\t\teqHometown(peopleSearchRequestDto.getHometown()))\n\t\t\t.orderBy(people.peopleId.desc());\n\n\t\treturn new PageImpl<>(\n\t\t\tPagingProcessUtil.queryDslPagingProcessing(query, pageable),\n\t\t\tpageable,\n\t\t\tquery.stream().count());\n\t}\n\n\tpublic Page<PeopleResponseDto> findByPeopleAsTeamId(Long teamId, Pageable pageable) {\n\t\tJPAQuery<PeopleResponseDto> query = jpaQueryFactory.select(\n\t\t\t\tProjections.constructor(\n\t\t\t\t\tPeopleResponseDto.class,\n\t\t\t\t\tpeople.peopleId,\n\t\t\t\t\tpeople.team.teamId,\n\t\t\t\t\tpeople.lastName,\n\t\t\t\t\tpeople.firstName,\n\t\t\t\t\tpeople.sex,\n\t\t\t\t\tpeople.bloodType,\n\t\t\t\t\tpeople.serveYears,\n\t\t\t\t\tpeople.role,\n\t\t\t\t\tpeople.hometown))\n\t\t\t.from(people)\n\t\t\t.innerJoin(team)\n\t\t\t.on(team.teamId.eq(people.team.teamId))\n\t\t\t.where(people.team.teamId.eq(teamId))\n\t\t\t.orderBy(people.peopleId.desc());\n\n\t\treturn new PageImpl<>(\n\t\t\tPagingProcessUtil.queryDslPagingProcessing(query, pageable),\n\t\t\tpageable,\n\t\t\tquery.stream().count());\n\t}\n\n\tprivate BooleanExpression eqPeopleId(Long peopleId) {\n\t\tif (peopleId == null) {\n\t\t\treturn null;\n\t\t}\n\t\treturn people.peopleId.eq(peopleId);\n\t}\n\n\tprivate BooleanExpression eqTeam(Long teamId) {\n\t\tif (teamId == null) {\n\t\t\treturn null;\n\t\t}\n\t\treturn people.team.teamId.eq(teamId);\n\t}\n\n\tprivate BooleanExpression eqLastName(String lastName) {\n\t\tif (!StringUtils.hasText(lastName)) {\n\t\t\treturn null;\n\t\t}\n\t\treturn people.lastName.eq(lastName);\n\t}\n\n\tprivate BooleanExpression eqFirstName(String firstName) {\n\t\tif (!StringUtils.hasText(firstName)) {\n\t\t\treturn null;\n\t\t}\n\t\treturn people.firstName.eq(firstName);\n\t}\n\n\tprivate BooleanExpression eqHometown(String hometown) {\n\t\tif (!StringUtils.hasText(hometown)) {\n\t\t\treturn null;\n\t\t}\n\t\treturn people.hometown.eq(hometown);\n\t}\n\n\tprivate BooleanExpression eqRole(Role role) {\n\t\tif (role == null) {\n\t\t\treturn null;\n\t\t}\n\t\treturn people.role.eq(role);\n\t}\n\n\tprivate BooleanExpression eqServeYears(Integer serveYears) {\n\t\tif (serveYears == null) {\n\t\t\treturn null;\n\t\t}\n\t\treturn people.serveYears.eq(serveYears);\n\t}\n\n\tprivate BooleanExpression eqBloodType(BloodType bloodType) {\n\n\t\tif (bloodType == null) {\n\t\t\treturn null;\n\t\t}\n\t\treturn people.bloodType.eq(bloodType);\n\t}\n\n\tprivate BooleanExpression eqSex(Sex sex) {\n\t\tif (sex == null) {\n\t\t\treturn null;\n\t\t}\n\t\treturn people.sex.eq(sex);\n\t}\n}"
},
{
"identifier": "PeopleRepository",
"path": "자프링-GraphQL-실습/src/main/java/com/junyss/graphqltest/api/people/repository/PeopleRepository.java",
"snippet": "public interface PeopleRepository extends JpaRepository<People, Long> {\n\t@Query(value = \"SELECT people FROM People people where people.team.teamId = :teamId\")\n\tList<People> findAllByTeamId(@Param(\"teamId\") Long teamId);\n}"
},
{
"identifier": "Team",
"path": "자프링-GraphQL-실습/src/main/java/com/junyss/graphqltest/api/team/model/entity/Team.java",
"snippet": "@Getter\n@NoArgsConstructor(access = AccessLevel.PROTECTED)\n@AllArgsConstructor(access = AccessLevel.PRIVATE)\n@Entity\npublic class Team {\n\n\t@Id\n\t@GeneratedValue(strategy = GenerationType.IDENTITY)\n\tprivate Long teamId;\n\tprivate String manager;\n\tprivate String office;\n\tprivate String extensionNumber;\n\tprivate String mascot;\n\tprivate String cleaningDuty;\n\tprivate String project;\n\n\t@Builder\n\tpublic static Team toEntity(\n\t\tString manager,\n\t\tString office,\n\t\tString extensionNumber,\n\t\tString mascot,\n\t\tString cleaningDuty,\n\t\tString project\n\t) {\n\t\treturn new Team(\n\t\t\tnull,\n\t\t\tmanager,\n\t\t\toffice,\n\t\t\textensionNumber,\n\t\t\tmascot,\n\t\t\tcleaningDuty,\n\t\t\tproject);\n\t}\n\n\tpublic void updateManager(String manager) {\n\t\tthis.manager = manager;\n\t}\n\n\tpublic void updateOffice(String office) {\n\t\tthis.office = office;\n\t}\n\n\tpublic void updateExtensionNumber(String extensionNumber) {\n\t\tthis.extensionNumber = extensionNumber;\n\t}\n\n\tpublic void updateMascot(String mascot) {\n\t\tthis.mascot = mascot;\n\t}\n\n\tpublic void updateCleaningDuty(String cleaningDuty) {\n\t\tthis.cleaningDuty = cleaningDuty;\n\t}\n\n\tpublic void updateProject(String project) {\n\t\tthis.project = project;\n\t}\n}"
},
{
"identifier": "TeamRepository",
"path": "자프링-GraphQL-실습/src/main/java/com/junyss/graphqltest/api/team/repository/TeamRepository.java",
"snippet": "public interface TeamRepository extends JpaRepository<Team, Long> {}"
}
] | import java.util.List;
import java.util.Optional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.junyss.graphqltest.common.constant.DefaultResponse;
import com.junyss.graphqltest.common.constant.Pagination;
import com.junyss.graphqltest.common.enumtype.BloodType;
import com.junyss.graphqltest.common.enumtype.Role;
import com.junyss.graphqltest.common.enumtype.Sex;
import com.junyss.graphqltest.common.util.GraphQLSupportUtil;
import com.junyss.graphqltest.common.util.ObjectUtil;
import com.junyss.graphqltest.common.util.PagingProcessUtil;
import com.junyss.graphqltest.api.people.model.dto.request.PeopleRequestDto;
import com.junyss.graphqltest.api.people.model.dto.request.PeopleSearchRequestDto;
import com.junyss.graphqltest.api.people.model.dto.request.PeopleUpdateRequestDto;
import com.junyss.graphqltest.api.people.model.dto.response.PeopleResponseDto;
import com.junyss.graphqltest.api.people.model.entity.People;
import com.junyss.graphqltest.api.people.repository.PeopleQueryDslRepository;
import com.junyss.graphqltest.api.people.repository.PeopleRepository;
import com.junyss.graphqltest.api.team.model.entity.Team;
import com.junyss.graphqltest.api.team.repository.TeamRepository;
import lombok.RequiredArgsConstructor; | 4,466 | package com.junyss.graphqltest.api.people.service;
@RequiredArgsConstructor
@Service
public class PeopleServiceImpl implements PeopleService {
private final PeopleRepository peopleRepository;
private final PeopleQueryDslRepository peopleQueryDslRepository;
private final TeamRepository teamRepository;
@Transactional
@Override | package com.junyss.graphqltest.api.people.service;
@RequiredArgsConstructor
@Service
public class PeopleServiceImpl implements PeopleService {
private final PeopleRepository peopleRepository;
private final PeopleQueryDslRepository peopleQueryDslRepository;
private final TeamRepository teamRepository;
@Transactional
@Override | public DefaultResponse<Long> saveForPeople(PeopleRequestDto peopleRequestDtoDto) { | 0 | 2023-11-22 12:26:00+00:00 | 8k |
windsbell/shardingkey-autofill | src/main/java/com/windsbell/shardingkey/autofill/handler/ShardingKeyCooker.java | [
{
"identifier": "CourseExplain",
"path": "src/main/java/com/windsbell/shardingkey/autofill/jsqlparser/CourseExplain.java",
"snippet": "@Data\npublic class CourseExplain {\n\n private Long cost; // 消耗时间\n\n private String initialSQL; // 初始的SQL\n\n private Statement finalSQL; // 填充分片键的SQL\n\n private Boolean hasFilled; // 是否有进行填充\n\n private List<String> targetTables; // 目标SQL中出现的表集合\n\n private Map<String, Map<String, String>> targetShardingKeyValueMap; // 目标SQL中,需要用到的分片键 【表名 分片键,分片键值 】\n\n private Map<String, Map<String, String>> finalFilledShardingKeyMap; // 目标SQL中,最终填充了的分片键 【表名 分片键,分片键值 】\n\n @Override\n public String toString() {\n return \"auto fill sharding key course explain:\"\n + \"\\ninitialSQL:\\n \" + initialSQL\n + \"\\nfinalSQL:\\n \" + finalSQL\n + \"\\ntargetTables: \" + targetTables\n + \"\\nhasFilled: \" + hasFilled\n + \"\\ntargetShardingKeyValueMap: \" + targetShardingKeyValueMap\n + \"\\nfinalFilledShardingKeyMap: \" + finalFilledShardingKeyMap\n + \"\\ncost: \" + cost + \"ms\";\n }\n\n\n}"
},
{
"identifier": "ShardingKeyFillerAgent",
"path": "src/main/java/com/windsbell/shardingkey/autofill/jsqlparser/ShardingKeyFillerAgent.java",
"snippet": "public class ShardingKeyFillerAgent {\n\n private final CourseExplain courseExplain; // 分片键填充过程说明\n\n private final ShardingKeyFiller shardingKeyFiller; // 分片键填充\n\n public ShardingKeyFillerAgent(Statement statement, Map<String, Map<String, String>> shardingKeyValueMap, Map<String, Map<String, Boolean>> firstShardingKeyHitFlagMap) {\n this.courseExplain = new CourseExplain();\n courseExplain.setHasFilled(false);\n courseExplain.setFinalFilledShardingKeyMap(new LinkedHashMap<>());\n courseExplain.setInitialSQL(statement.toString());\n this.shardingKeyFiller = new ShardingKeyFiller(statement, shardingKeyValueMap, firstShardingKeyHitFlagMap);\n }\n\n public CourseExplain doFill(long start) {\n shardingKeyFiller.doFill();\n combineExplain(start);\n return courseExplain;\n }\n\n private void combineExplain(long start) {\n courseExplain.setFinalSQL(shardingKeyFiller.getStatement());\n courseExplain.setTargetTables(new ArrayList<>(shardingKeyFiller.getTablesAliasMap().keySet()));\n Map<String, Map<String, String>> shardingKeyValueMap = shardingKeyFiller.getShardingKeyValueMap();\n courseExplain.setTargetShardingKeyValueMap(shardingKeyValueMap);\n Map<String, Map<String, Boolean>> firstShardingKeyHitFlagMap = shardingKeyFiller.getFirstShardingKeyHitFlagMap();\n Map<String, Map<String, Boolean>> shardingKeyHitFlagMap = shardingKeyFiller.getShardingKeyHitFlagMap();\n firstShardingKeyHitFlagMap.forEach((k, v) -> {\n Map<String, Boolean> shardingKeyHitFlagInnerMap = shardingKeyHitFlagMap.get(k);\n Map<String, String> shardingKeyValueInnerMap = shardingKeyValueMap.get(k);\n v.forEach((m, n) -> {\n Boolean isHit = shardingKeyHitFlagInnerMap.get(m);\n if (!n && isHit) { // 分片键字段未出现在SQL,并最终填充成功的\n courseExplain.setHasFilled(true);\n Map<String, Map<String, String>> finalFilledShardingKeyMap = courseExplain.getFinalFilledShardingKeyMap();\n Map<String, String> finalFilledShardingKeyInnerMap = finalFilledShardingKeyMap.computeIfAbsent(k, o -> new LinkedHashMap<>());\n finalFilledShardingKeyInnerMap.put(m, shardingKeyValueInnerMap.get(m));\n }\n });\n });\n courseExplain.setCost(System.currentTimeMillis() - start);\n }\n\n}"
},
{
"identifier": "ShardingKeyHitFinder",
"path": "src/main/java/com/windsbell/shardingkey/autofill/jsqlparser/ShardingKeyHitFinder.java",
"snippet": "@Getter\npublic class ShardingKeyHitFinder extends StatementParser {\n\n private Map<String, String> aliasTablesMap; // 【别名 表名】\n\n private Map<String, Map<String, String>> shardingKeyValueMap; // 【表名 分片键字段, 分片键内容】\n\n private Map<String, Map<String, Boolean>> shardingKeyHitFlagMap; // 【表名 分片键,是否设置 】\n\n public ShardingKeyHitFinder(Statement statement, Map<String, Map<String, String>> shardingKeyValueMap) {\n super(statement);\n init(shardingKeyValueMap);\n }\n\n private void init(Map<String, Map<String, String>> shardingKeyValueMap) {\n this.aliasTablesMap = new LinkedHashMap<>();\n this.shardingKeyValueMap = shardingKeyValueMap;\n this.shardingKeyHitFlagMap = initFillShardingKeyFlagMap(shardingKeyValueMap);\n }\n\n public Map<String, Map<String, Boolean>> doFind() {\n statement.accept(this);\n return shardingKeyHitFlagMap;\n }\n\n // 初始化是否命中分片键Map 默认都为未命中\n private Map<String, Map<String, Boolean>> initFillShardingKeyFlagMap(Map<String, Map<String, String>> fillShardingKeyMap) {\n Map<String, Map<String, Boolean>> fillShardingKeyFlagMap = new LinkedHashMap<>();\n fillShardingKeyMap.forEach((k, v) -> {\n Map<String, Boolean> innerMap = new LinkedHashMap<>();\n v.forEach((m, n) -> innerMap.put(m, false));\n fillShardingKeyFlagMap.put(k, innerMap);\n });\n return fillShardingKeyFlagMap;\n }\n\n @Override\n public void visit(Table tableName) {\n super.visit(tableName);\n String tableWholeName = extractTableName(tableName);\n if (!aliasTablesMap.containsKey(tableWholeName)) {\n String alias = tableName.getAlias() != null ? tableName.getAlias().getName() : tableWholeName;\n aliasTablesMap.put(alias, tableWholeName);\n }\n }\n\n @Override\n public void visit(InExpression inExpression) {\n // 只有等于、或者IN条件满足匹配到对应分片键\n Expression leftExpression = inExpression.getLeftExpression();\n if (leftExpression instanceof Column) {\n this.parse((Column) leftExpression);\n }\n super.visit(inExpression);\n }\n\n @Override\n public void visitBinaryExpression(BinaryExpression binaryExpression) {\n // 只有等于、或者IN条件满足匹配到对应分片键\n this.parse(binaryExpression);\n binaryExpression.getLeftExpression().accept(this);\n binaryExpression.getRightExpression().accept(this);\n }\n\n // 扫描解析,标记哪些字段命中分片键,哪些没有命中\n private void parse(BinaryExpression binaryExpression) {\n Expression rightExpression = binaryExpression.getRightExpression();\n if (rightExpression instanceof EqualsTo) {\n EqualsTo equalsTo = (EqualsTo) rightExpression;\n Expression leftExpression = equalsTo.getLeftExpression();\n if (leftExpression instanceof Column\n && (equalsTo.getRightExpression() instanceof StringValue || equalsTo.getRightExpression() instanceof JdbcParameter)) {\n this.parse((Column) leftExpression);\n }\n }\n }\n\n // 若字段命中了,标记命中\n private void parse(Column column) {\n Table table = column.getTable();\n if (table != null) {\n String alias = table.getName();\n String tableName = aliasTablesMap.get(alias);\n if (tableName != null) {\n Map<String, String> tableInnerMap = shardingKeyValueMap.get(tableName);\n if (tableInnerMap != null) {\n String columnName = column.getColumnName();\n if (tableInnerMap.containsKey(columnName)) {\n shardingKeyHitFlagMap.get(tableName).put(columnName, true); // 命中分片键字段\n }\n }\n }\n }\n }\n\n}"
},
{
"identifier": "TableAliasSetter",
"path": "src/main/java/com/windsbell/shardingkey/autofill/jsqlparser/TableAliasSetter.java",
"snippet": "public class TableAliasSetter extends StatementParser {\n\n private Integer round = 0; // 解析轮数\n\n private int counter = 0; // 别名计数器\n\n protected List<String> alias; // 解析的表别名集合\n\n public TableAliasSetter(Statement statement) {\n super(statement);\n init();\n }\n\n private void init() {\n alias = new ArrayList<>();\n statement.accept(this);\n round++;\n }\n\n public void doSet() {\n statement.accept(this);\n }\n\n /**\n * 补充表别名, 以t1,t2形式递增\n */\n protected String getNextAlias() {\n if (counter < 1000) {\n counter++;\n String nextAlias = \"t\" + counter;\n if (alias.contains(nextAlias)) {\n return getNextAlias();\n }\n return nextAlias;\n }\n throw new RuntimeException(\"can`t set table alias more than 1000 tables!\");\n }\n\n @Override\n public void visit(Table tableName) {\n if (round == 0) { // 第一轮收集SQL现有的别名集合\n super.visit(tableName);\n if (tableName.getAlias() != null && !alias.contains(tableName.getAlias().getName())) {\n alias.add(tableName.getAlias().getName());\n }\n }\n }\n\n @Override\n public void visit(PlainSelect item) {\n super.visit(item);\n if (round > 0) {\n // 第一轮之后,补充SQL中为出现别名的条件\n this.matchBody(item);\n }\n }\n\n private void matchBody(PlainSelect plainSelect) {\n FromItem fromItem = plainSelect.getFromItem();\n if (fromItem != null && plainSelect.getJoins() == null) {\n Alias alias = fromItem.getAlias();\n if (alias == null) {\n alias = new Alias(getNextAlias());\n fromItem.setAlias(alias);\n }\n Table table = new Table(alias.getName());\n this.machSelect(plainSelect.getSelectItems(), table);\n this.matchWhere(plainSelect.getWhere(), table);\n this.matchOrderBy(plainSelect.getOrderByElements(), table);\n this.matchGroupBy(plainSelect.getGroupBy(), table);\n this.matchHaving(plainSelect.getHaving(), table);\n }\n }\n\n private void machSelect(List<SelectItem> selectItems, Table table) {\n if (selectItems != null) {\n for (SelectItem selectItem : selectItems) {\n if (selectItem instanceof SelectExpressionItem) {\n SelectExpressionItem selectExpressionItem = (SelectExpressionItem) selectItem;\n Expression expression = selectExpressionItem.getExpression();\n if (expression instanceof Column) {\n this.setTableAlias((Column) expression, table);\n }\n }\n }\n }\n }\n\n private void matchWhere(Expression expression, Table table) {\n if (expression instanceof BinaryExpression) {\n BinaryExpression binaryExpression = (BinaryExpression) expression;\n Expression leftExpression = binaryExpression.getLeftExpression();\n Expression rightExpression = binaryExpression.getRightExpression();\n this.matchWhere(leftExpression, rightExpression, table);\n } else if (expression instanceof InExpression) {\n InExpression inExpression = (InExpression) expression;\n Expression leftExpression = inExpression.getLeftExpression();\n Expression rightExpression = inExpression.getRightExpression();\n this.matchWhere(leftExpression, rightExpression, table);\n }\n }\n\n private void matchWhere(Expression leftExpression, Expression rightExpression, Table table) {\n if (leftExpression instanceof Column) {\n this.setTableAlias((Column) leftExpression, table);\n } else {\n this.matchWhere(leftExpression, table);\n }\n this.matchWhere(rightExpression, table);\n }\n\n private void matchOrderBy(List<OrderByElement> orderByElements, Table table) {\n if (orderByElements != null) {\n for (OrderByElement orderByElement : orderByElements) {\n Expression expression = orderByElement.getExpression();\n if (expression instanceof Column) {\n this.setTableAlias((Column) expression, table);\n }\n }\n }\n }\n\n private void matchGroupBy(GroupByElement groupBy, Table table) {\n if (groupBy != null) {\n for (Expression expression : groupBy.getGroupByExpressionList().getExpressions()) {\n if (expression instanceof Column) {\n this.setTableAlias((Column) expression, table);\n }\n }\n }\n }\n\n private void matchHaving(Expression expression, Table table) {\n if (expression != null) {\n this.matchWhere(expression, table);\n }\n }\n\n private void setTableAlias(Column column, Table table) {\n if (column.getTable() == null) {\n column.setTable(table); // 添加列别名\n }\n }\n\n\n}"
}
] | import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.windsbell.shardingkey.autofill.jsqlparser.CourseExplain;
import com.windsbell.shardingkey.autofill.jsqlparser.ShardingKeyFillerAgent;
import com.windsbell.shardingkey.autofill.jsqlparser.ShardingKeyHitFinder;
import com.windsbell.shardingkey.autofill.jsqlparser.TableAliasSetter;
import com.windsbell.shardingkey.autofill.strategy.*;
import net.sf.jsqlparser.statement.Statement;
import org.springframework.util.Assert;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.BiFunction;
import java.util.stream.Collectors; | 3,869 | package com.windsbell.shardingkey.autofill.handler;
/**
* SQL分片键锅炉房(核心调用链)
*
* @author windbell
*/
public class ShardingKeyCooker {
private final Long start; // 开始时间
private final Statement statement; // sql
private final List<?> parameterList; // 占位符内容值列表
private final List<TableShardingKeyStrategy> tableShardingKeyStrategyList; // 表分片键映射策略列表
private final Map<String, Map<String, String>> fillShardingKeyMap; // 【表名 分片键,分片键值】目标要填充的片键值对内容
private List<BusinessKeyStrategy> businessKeyStrategyList; // 业务分片键字段映射策略列表
private Map<String, TableShardingKeyStrategy> shardingKeyStrategyMap; // 【表名 ,表分片键映射策略】 业务分片键字段映射策略列表
private Map<String, Map<String, Boolean>> firstShardingKeyHitFlagMap; // 【表名 分片键,是否设置 】原始检测收集的结果
private CourseExplain courseExplain; // 分片键填充过程说明
public static ShardingKeyCooker builder(Statement statement, List<TableShardingKeyStrategy> tableShardingKeyStrategyList, List<?> parameterList) {
return new ShardingKeyCooker(statement, tableShardingKeyStrategyList, parameterList);
}
private ShardingKeyCooker(Statement statement, List<TableShardingKeyStrategy> tableShardingKeyStrategyList, List<?> parameterList) {
this.start = System.currentTimeMillis();
this.statement = statement;
this.tableShardingKeyStrategyList = tableShardingKeyStrategyList;
this.parameterList = parameterList;
this.fillShardingKeyMap = new LinkedHashMap<>();
}
// 设置表字段别名
public ShardingKeyCooker setTableAlias() { | package com.windsbell.shardingkey.autofill.handler;
/**
* SQL分片键锅炉房(核心调用链)
*
* @author windbell
*/
public class ShardingKeyCooker {
private final Long start; // 开始时间
private final Statement statement; // sql
private final List<?> parameterList; // 占位符内容值列表
private final List<TableShardingKeyStrategy> tableShardingKeyStrategyList; // 表分片键映射策略列表
private final Map<String, Map<String, String>> fillShardingKeyMap; // 【表名 分片键,分片键值】目标要填充的片键值对内容
private List<BusinessKeyStrategy> businessKeyStrategyList; // 业务分片键字段映射策略列表
private Map<String, TableShardingKeyStrategy> shardingKeyStrategyMap; // 【表名 ,表分片键映射策略】 业务分片键字段映射策略列表
private Map<String, Map<String, Boolean>> firstShardingKeyHitFlagMap; // 【表名 分片键,是否设置 】原始检测收集的结果
private CourseExplain courseExplain; // 分片键填充过程说明
public static ShardingKeyCooker builder(Statement statement, List<TableShardingKeyStrategy> tableShardingKeyStrategyList, List<?> parameterList) {
return new ShardingKeyCooker(statement, tableShardingKeyStrategyList, parameterList);
}
private ShardingKeyCooker(Statement statement, List<TableShardingKeyStrategy> tableShardingKeyStrategyList, List<?> parameterList) {
this.start = System.currentTimeMillis();
this.statement = statement;
this.tableShardingKeyStrategyList = tableShardingKeyStrategyList;
this.parameterList = parameterList;
this.fillShardingKeyMap = new LinkedHashMap<>();
}
// 设置表字段别名
public ShardingKeyCooker setTableAlias() { | TableAliasSetter tableAliasSetter = new TableAliasSetter(statement); | 3 | 2023-11-23 09:05:56+00:00 | 8k |
oxcened/opendialer | feature/settings/src/main/java/dev/alenajam/opendialer/feature/settings/SettingsActivity.java | [
{
"identifier": "KEY_SETTING_BLOCKED_NUMBERS",
"path": "core/common/src/main/java/dev/alenajam/opendialer/core/common/SharedPreferenceHelper.java",
"snippet": "public static final String KEY_SETTING_BLOCKED_NUMBERS = \"blockedNumbers\";"
},
{
"identifier": "KEY_SETTING_DEFAULT",
"path": "core/common/src/main/java/dev/alenajam/opendialer/core/common/SharedPreferenceHelper.java",
"snippet": "public static final String KEY_SETTING_DEFAULT = \"default\";"
},
{
"identifier": "KEY_SETTING_NOTIFICATION_SETTINGS",
"path": "core/common/src/main/java/dev/alenajam/opendialer/core/common/SharedPreferenceHelper.java",
"snippet": "public static final String KEY_SETTING_NOTIFICATION_SETTINGS = \"notificationSettings\";"
},
{
"identifier": "KEY_SETTING_QUICK_RESPONSES",
"path": "core/common/src/main/java/dev/alenajam/opendialer/core/common/SharedPreferenceHelper.java",
"snippet": "public static final String KEY_SETTING_QUICK_RESPONSES = \"quick_responses\";"
},
{
"identifier": "KEY_SETTING_SOUND_VIBRATION",
"path": "core/common/src/main/java/dev/alenajam/opendialer/core/common/SharedPreferenceHelper.java",
"snippet": "public static final String KEY_SETTING_SOUND_VIBRATION = \"sound\";"
},
{
"identifier": "KEY_SETTING_THEME",
"path": "core/common/src/main/java/dev/alenajam/opendialer/core/common/SharedPreferenceHelper.java",
"snippet": "public static final String KEY_SETTING_THEME = \"theme\";"
},
{
"identifier": "CommonUtils",
"path": "core/common/src/main/java/dev/alenajam/opendialer/core/common/CommonUtils.java",
"snippet": "public abstract class CommonUtils {\n\n @SuppressLint(\"DefaultLocale\")\n public static String getDurationTimeString(long durationMilliseconds) {\n\n return String.format(\"%02d:%02d:%02d\",\n TimeUnit.MILLISECONDS.toHours(durationMilliseconds),\n TimeUnit.MILLISECONDS.toMinutes(durationMilliseconds) -\n TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(durationMilliseconds)),\n TimeUnit.MILLISECONDS.toSeconds(durationMilliseconds) -\n TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(durationMilliseconds))\n );\n }\n\n @SuppressLint(\"DefaultLocale\")\n public static String getDurationTimeStringMinimal(long durationMilliseconds) {\n long hours = TimeUnit.MILLISECONDS.toHours(durationMilliseconds);\n long minutes = TimeUnit.MILLISECONDS.toMinutes(durationMilliseconds) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(durationMilliseconds));\n long seconds = TimeUnit.MILLISECONDS.toSeconds(durationMilliseconds) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(durationMilliseconds));\n\n String timeString = \"\";\n if (hours > 0) timeString = timeString.concat(hours + \"h \");\n if (minutes > 0) timeString = timeString.concat(minutes + \"m \");\n if (seconds > 0) timeString = timeString.concat(seconds + \"s\");\n\n return timeString.isEmpty() ? \"0s\" : timeString;\n }\n\n public static Bitmap textToBitmap(Context context, String messageText, float textSize, int textColor) {\n Paint paint = new Paint();\n int pixelTextSize = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,\n textSize, context.getResources().getDisplayMetrics());\n paint.setTextSize(pixelTextSize);\n paint.setColor(textColor);\n paint.setTextAlign(Paint.Align.LEFT);\n\n float baseline = -paint.ascent() + 10; // ascent() is negative\n int width = (int) (paint.measureText(messageText) + 0.5f); // round\n int height = (int) (baseline + paint.descent() + 0.5f);\n\n Bitmap image = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);\n\n Canvas canvas = new Canvas(image);\n canvas.drawText(messageText, 0, baseline, paint);\n\n return image;\n }\n\n public static String getEditTextSelectedText(EditText editText) {\n if (!editText.hasSelection()) return null;\n\n final int start = editText.getSelectionStart();\n final int end = editText.getSelectionEnd();\n\n return String.valueOf(\n start > end ? editText.getText().subSequence(end, start) : editText.getText().subSequence(start, end));\n }\n\n @Deprecated\n public static void startInCallUI(Context context) throws ClassNotFoundException {\n Intent intent = new Intent(context, Class.forName(\"dev.alenajam.opendialer.features.inCall.ui.InCallActivity\"));\n intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);\n context.startActivity(intent);\n }\n\n @SuppressLint(\"MissingPermission\")\n public static void makeCall(Context context, String number) {\n if (PermissionUtils.hasMakeCallPermission(context)) {\n Intent intent = new Intent(Intent.ACTION_CALL, Uri.fromParts(\"tel\", number, null));\n\n TelecomManager telecomManager = (TelecomManager) context.getSystemService(TELECOM_SERVICE);\n if (telecomManager == null) return;\n PhoneAccountHandle defaultPhoneAccount = telecomManager.getDefaultOutgoingPhoneAccount(\"tel\");\n if (defaultPhoneAccount == null) {\n List<PhoneAccountHandle> phoneAccounts = telecomManager.getCallCapablePhoneAccounts();\n if (phoneAccounts.size() < 2) return;\n else {\n // Dual SIM\n SubscriptionManager subscriptionManager = (SubscriptionManager) context.getSystemService(TELEPHONY_SUBSCRIPTION_SERVICE);\n if (subscriptionManager == null) return;\n\n MyDialog dialog = new MyDialog(context);\n dialog.setTitle(context.getString(R.string.choose_sim_card));\n LinearLayout linearLayout = new LinearLayout(context);\n linearLayout.setOrientation(LinearLayout.VERTICAL);\n for (int i = 0; i < phoneAccounts.size(); i++) {\n SubscriptionInfo subscriptionInfo = subscriptionManager.getActiveSubscriptionInfoForSimSlotIndex(i);\n if (subscriptionInfo == null) continue;\n\n View item = LayoutInflater.from(context).inflate(R.layout.item_sim, null);\n TextView carrier = item.findViewById(R.id.carrier);\n carrier.setText(subscriptionInfo.getCarrierName());\n TextView numberTv = item.findViewById(R.id.number);\n numberTv.setText(subscriptionInfo.getNumber());\n subscriptionInfo.getIconTint();\n ImageView icon = item.findViewById(R.id.icon);\n icon.setColorFilter(subscriptionInfo.getIconTint());\n int finalI = i;\n item.setOnClickListener(v -> {\n dialog.hide();\n intent.putExtra(TelecomManager.EXTRA_PHONE_ACCOUNT_HANDLE, phoneAccounts.get(finalI));\n context.startActivity(intent);\n });\n linearLayout.addView(item);\n }\n dialog.setContent(linearLayout);\n dialog.show();\n return;\n }\n }\n context.startActivity(intent);\n }\n }\n\n public static void makeSms(Context context, String number) {\n context.startActivity(new Intent(Intent.ACTION_SENDTO, Uri.fromParts(\"smsto\", number, null)));\n }\n\n public static void copyToClipobard(Context context, String text) {\n ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);\n ClipData clip = ClipData.newPlainText(null, text);\n if (clipboard != null) {\n clipboard.setPrimaryClip(clip);\n Toast.makeText(context, context.getString(R.string.text_copied), Toast.LENGTH_SHORT).show();\n }\n }\n\n public static void showContactDetail(Context context, int contactId) {\n Intent intent = new Intent(Intent.ACTION_VIEW);\n Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_URI, String.valueOf(contactId));\n intent.setData(uri);\n context.startActivity(intent);\n }\n\n public static void setTheme(int mode) {\n AppCompatDelegate.setDefaultNightMode(mode);\n }\n\n public static void hideKeyboard(Activity activity) {\n InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);\n //Find the currently focused view, so we can grab the correct window token from it.\n View view = activity.getCurrentFocus();\n //If no view currently has focus, create a new one, just so we can grab a window token from it\n if (view == null) {\n view = new View(activity);\n }\n if (imm != null) {\n imm.hideSoftInputFromWindow(view.getWindowToken(), 0);\n }\n }\n\n public static float convertDpToPixels(float dp, Context context) {\n return dp * ((float) context.getResources().getDisplayMetrics().densityDpi / DisplayMetrics.DENSITY_DEFAULT);\n }\n\n public static void addContactAsExisting(Context context, String number) {\n Intent addExistingIntent = new Intent(Intent.ACTION_INSERT_OR_EDIT);\n addExistingIntent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);\n addExistingIntent.putExtra(ContactsContract.Intents.Insert.PHONE, number);\n context.startActivity(addExistingIntent);\n }\n\n public static void createContact(Context context, String number) {\n Intent createContactIntent = new Intent(Intent.ACTION_INSERT);\n createContactIntent.setType(ContactsContract.Contacts.CONTENT_TYPE);\n createContactIntent.putExtra(ContactsContract.Intents.Insert.PHONE, number);\n context.startActivity(createContactIntent);\n }\n\n public static boolean isDmtfSettingEnabled(Context context) {\n return Settings.System.getInt(context.getContentResolver(), Settings.System.DTMF_TONE_WHEN_DIALING, 1) == 1;\n }\n\n public static boolean isSoundEffectsEnabled(Context context) {\n return Settings.System.getInt(context.getContentResolver(), Settings.System.SOUND_EFFECTS_ENABLED, 1) == 1;\n }\n\n public static boolean isRingerModeSilentOrVibrate(Context context) {\n AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);\n if (audioManager == null) return false;\n int ringerMode = audioManager.getRingerMode();\n return ringerMode == AudioManager.RINGER_MODE_SILENT || ringerMode == AudioManager.RINGER_MODE_VIBRATE;\n }\n\n public static int getColorFromAttr(Context context, int attrInt) {\n TypedValue typedValue = new TypedValue();\n context.getTheme().resolveAttribute(attrInt, typedValue, true);\n return ContextCompat.getColor(context, typedValue.resourceId);\n }\n\n public static long getCurrentTime() {\n return SystemClock.elapsedRealtime();\n }\n}"
},
{
"identifier": "DefaultPhoneUtils",
"path": "core/common/src/main/java/dev/alenajam/opendialer/core/common/DefaultPhoneUtils.java",
"snippet": "public abstract class DefaultPhoneUtils {\n\n public static boolean hasDefault(Context context) {\n if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {\n @SuppressLint(\"WrongConstant\") RoleManager roleManager = (RoleManager) context.getSystemService(ROLE_SERVICE);\n if (roleManager != null && roleManager.isRoleAvailable(RoleManager.ROLE_DIALER))\n return roleManager.isRoleHeld(RoleManager.ROLE_DIALER);\n } else {\n TelecomManager telecomManager = (TelecomManager) context.getSystemService(TELECOM_SERVICE);\n String defaultDialer = telecomManager.getDefaultDialerPackage();\n if (telecomManager != null && defaultDialer != null)\n return defaultDialer.equals(context.getPackageName());\n }\n return false;\n }\n\n public static void requestDefault(Activity activity, int requestId) {\n if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {\n @SuppressLint(\"WrongConstant\") RoleManager roleManager = (RoleManager) activity.getSystemService(ROLE_SERVICE);\n if (roleManager != null && roleManager.isRoleAvailable(RoleManager.ROLE_DIALER) && !roleManager.isRoleHeld(RoleManager.ROLE_DIALER)) {\n Intent intent = roleManager.createRequestRoleIntent(RoleManager.ROLE_DIALER);\n activity.startActivityForResult(intent, requestId);\n }\n } else {\n TelecomManager telecomManager = (TelecomManager) activity.getSystemService(TELECOM_SERVICE);\n if (telecomManager != null && !telecomManager.getDefaultDialerPackage().equals(activity.getPackageName())) {\n Intent intent = new Intent(TelecomManager.ACTION_CHANGE_DEFAULT_DIALER).putExtra(TelecomManager.EXTRA_CHANGE_DEFAULT_DIALER_PACKAGE_NAME, activity.getPackageName());\n activity.startActivityForResult(intent, requestId);\n }\n }\n }\n\n public static void requestDefault(Fragment fragment, int requestId) {\n if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {\n @SuppressLint(\"WrongConstant\") RoleManager roleManager = (RoleManager) fragment.getContext().getSystemService(ROLE_SERVICE);\n if (roleManager != null && roleManager.isRoleAvailable(RoleManager.ROLE_DIALER) && !roleManager.isRoleHeld(RoleManager.ROLE_DIALER)) {\n Intent intent = roleManager.createRequestRoleIntent(RoleManager.ROLE_DIALER);\n fragment.startActivityForResult(intent, requestId);\n }\n } else {\n TelecomManager telecomManager = (TelecomManager) fragment.getContext().getSystemService(TELECOM_SERVICE);\n if (telecomManager != null && !telecomManager.getDefaultDialerPackage().equals(fragment.getContext().getPackageName())) {\n Intent intent = new Intent(TelecomManager.ACTION_CHANGE_DEFAULT_DIALER).putExtra(TelecomManager.EXTRA_CHANGE_DEFAULT_DIALER_PACKAGE_NAME, fragment.getContext().getPackageName());\n fragment.startActivityForResult(intent, requestId);\n }\n }\n }\n}"
}
] | import static dev.alenajam.opendialer.core.common.SharedPreferenceHelper.KEY_SETTING_BLOCKED_NUMBERS;
import static dev.alenajam.opendialer.core.common.SharedPreferenceHelper.KEY_SETTING_DEFAULT;
import static dev.alenajam.opendialer.core.common.SharedPreferenceHelper.KEY_SETTING_NOTIFICATION_SETTINGS;
import static dev.alenajam.opendialer.core.common.SharedPreferenceHelper.KEY_SETTING_QUICK_RESPONSES;
import static dev.alenajam.opendialer.core.common.SharedPreferenceHelper.KEY_SETTING_SOUND_VIBRATION;
import static dev.alenajam.opendialer.core.common.SharedPreferenceHelper.KEY_SETTING_THEME;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.provider.BlockedNumberContract;
import android.provider.Settings;
import android.telecom.TelecomManager;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.preference.ListPreference;
import androidx.preference.Preference;
import androidx.preference.PreferenceFragmentCompat;
import dev.alenajam.opendialer.core.common.CommonUtils;
import dev.alenajam.opendialer.core.common.DefaultPhoneUtils; | 3,783 | package dev.alenajam.opendialer.feature.settings;
public class SettingsActivity extends AppCompatActivity {
private static final int REQUEST_ID_DEFAULT = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.settings, new SettingsFragment())
.commit();
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeAsUpIndicator(R.drawable.ic_arrow_back);
}
}
public static class SettingsFragment extends PreferenceFragmentCompat implements Preference.OnPreferenceChangeListener, Preference.OnPreferenceClickListener {
Preference defaultPreference;
private TelecomManager telecomManager;
@Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
if (getContext() != null) {
telecomManager = (TelecomManager) getContext().getSystemService(TELECOM_SERVICE);
}
setPreferencesFromResource(R.xml.root_preferences, rootKey);
ListPreference themePreference = getPreferenceManager().findPreference(KEY_SETTING_THEME);
if (themePreference != null) themePreference.setOnPreferenceChangeListener(this);
defaultPreference = getPreferenceManager().findPreference(KEY_SETTING_DEFAULT);
if (defaultPreference != null) defaultPreference.setOnPreferenceClickListener(this);
Preference soundPreference = getPreferenceManager().findPreference(KEY_SETTING_SOUND_VIBRATION);
if (soundPreference != null) soundPreference.setOnPreferenceClickListener(this);
Preference quickResponsesPreference = getPreferenceManager().findPreference(KEY_SETTING_QUICK_RESPONSES);
if (quickResponsesPreference != null)
quickResponsesPreference.setOnPreferenceClickListener(this);
Preference blockedNumbers = getPreferenceManager().findPreference(KEY_SETTING_BLOCKED_NUMBERS);
if (blockedNumbers != null) {
blockedNumbers.setVisible(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && BlockedNumberContract.canCurrentUserBlockNumbers(getContext()));
blockedNumbers.setOnPreferenceClickListener(this);
}
Preference notificationSettings = getPreferenceManager().findPreference(KEY_SETTING_NOTIFICATION_SETTINGS);
if (notificationSettings != null) {
notificationSettings.setVisible(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O);
notificationSettings.setOnPreferenceClickListener(this);
}
}
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
switch (preference.getKey()) {
case KEY_SETTING_THEME:
CommonUtils.setTheme(Integer.parseInt(newValue.toString()));
break;
}
return true;
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_ID_DEFAULT) {
for (int g : grantResults) {
if (g != PackageManager.PERMISSION_GRANTED) return;
}
if (defaultPreference != null) defaultPreference.setEnabled(false);
}
}
@Override
public void onResume() {
super.onResume();
if (defaultPreference != null) { | package dev.alenajam.opendialer.feature.settings;
public class SettingsActivity extends AppCompatActivity {
private static final int REQUEST_ID_DEFAULT = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.settings, new SettingsFragment())
.commit();
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeAsUpIndicator(R.drawable.ic_arrow_back);
}
}
public static class SettingsFragment extends PreferenceFragmentCompat implements Preference.OnPreferenceChangeListener, Preference.OnPreferenceClickListener {
Preference defaultPreference;
private TelecomManager telecomManager;
@Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
if (getContext() != null) {
telecomManager = (TelecomManager) getContext().getSystemService(TELECOM_SERVICE);
}
setPreferencesFromResource(R.xml.root_preferences, rootKey);
ListPreference themePreference = getPreferenceManager().findPreference(KEY_SETTING_THEME);
if (themePreference != null) themePreference.setOnPreferenceChangeListener(this);
defaultPreference = getPreferenceManager().findPreference(KEY_SETTING_DEFAULT);
if (defaultPreference != null) defaultPreference.setOnPreferenceClickListener(this);
Preference soundPreference = getPreferenceManager().findPreference(KEY_SETTING_SOUND_VIBRATION);
if (soundPreference != null) soundPreference.setOnPreferenceClickListener(this);
Preference quickResponsesPreference = getPreferenceManager().findPreference(KEY_SETTING_QUICK_RESPONSES);
if (quickResponsesPreference != null)
quickResponsesPreference.setOnPreferenceClickListener(this);
Preference blockedNumbers = getPreferenceManager().findPreference(KEY_SETTING_BLOCKED_NUMBERS);
if (blockedNumbers != null) {
blockedNumbers.setVisible(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && BlockedNumberContract.canCurrentUserBlockNumbers(getContext()));
blockedNumbers.setOnPreferenceClickListener(this);
}
Preference notificationSettings = getPreferenceManager().findPreference(KEY_SETTING_NOTIFICATION_SETTINGS);
if (notificationSettings != null) {
notificationSettings.setVisible(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O);
notificationSettings.setOnPreferenceClickListener(this);
}
}
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
switch (preference.getKey()) {
case KEY_SETTING_THEME:
CommonUtils.setTheme(Integer.parseInt(newValue.toString()));
break;
}
return true;
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_ID_DEFAULT) {
for (int g : grantResults) {
if (g != PackageManager.PERMISSION_GRANTED) return;
}
if (defaultPreference != null) defaultPreference.setEnabled(false);
}
}
@Override
public void onResume() {
super.onResume();
if (defaultPreference != null) { | boolean hasDefault = DefaultPhoneUtils.hasDefault(getContext()); | 7 | 2023-11-21 21:24:39+00:00 | 8k |
pewaru-333/HomeMedkit-App | app/src/main/java/ru/application/homemedkit/activities/MedicineActivity.java | [
{
"identifier": "ADD",
"path": "app/src/main/java/ru/application/homemedkit/helpers/ConstantsHelper.java",
"snippet": "public static final String ADD = \"add\";"
},
{
"identifier": "ADDING",
"path": "app/src/main/java/ru/application/homemedkit/helpers/ConstantsHelper.java",
"snippet": "public static final String ADDING = \"adding\";"
},
{
"identifier": "BLANK",
"path": "app/src/main/java/ru/application/homemedkit/helpers/ConstantsHelper.java",
"snippet": "public static final String BLANK = \"\";"
},
{
"identifier": "CIS",
"path": "app/src/main/java/ru/application/homemedkit/helpers/ConstantsHelper.java",
"snippet": "public static final String CIS = \"cis\";"
},
{
"identifier": "DUPLICATE",
"path": "app/src/main/java/ru/application/homemedkit/helpers/ConstantsHelper.java",
"snippet": "public static final String DUPLICATE = \"duplicate\";"
},
{
"identifier": "ID",
"path": "app/src/main/java/ru/application/homemedkit/helpers/ConstantsHelper.java",
"snippet": "public static final String ID = \"id\";"
},
{
"identifier": "MEDICINE_ID",
"path": "app/src/main/java/ru/application/homemedkit/helpers/ConstantsHelper.java",
"snippet": "public static final String MEDICINE_ID = \"medicine_id\";"
},
{
"identifier": "NEW_MEDICINE",
"path": "app/src/main/java/ru/application/homemedkit/helpers/ConstantsHelper.java",
"snippet": "public static final String NEW_MEDICINE = \"newMedicine\";"
},
{
"identifier": "toExpDate",
"path": "app/src/main/java/ru/application/homemedkit/helpers/DateHelper.java",
"snippet": "public static String toExpDate(long milli) {\n return milli > 0 ? getDateTime(milli).format(FORMAT_L) : BLANK;\n}"
},
{
"identifier": "getIconType",
"path": "app/src/main/java/ru/application/homemedkit/helpers/ImageHelper.java",
"snippet": "public static Drawable getIconType(Context context, String form) {\n TypedArray icons = context.getResources().obtainTypedArray(R.array.medicine_types_icons);\n String[] types = context.getResources().getStringArray(R.array.medicine_types);\n String type = StringHelper.formName(form).toUpperCase();\n Drawable icon = AppCompatResources.getDrawable(context, R.drawable.vector_type_unknown);\n\n int index = Arrays.asList(types).indexOf(type);\n if (index != -1) icon = icons.getDrawable(index);\n\n return icon;\n}"
},
{
"identifier": "decimalFormat",
"path": "app/src/main/java/ru/application/homemedkit/helpers/StringHelper.java",
"snippet": "public static String decimalFormat(double amount) {\n DecimalFormat decimal = new DecimalFormat(\"0.###\");\n return decimal.format(amount);\n}"
},
{
"identifier": "fromHTML",
"path": "app/src/main/java/ru/application/homemedkit/helpers/StringHelper.java",
"snippet": "public static String fromHTML(String text) {\n return HtmlCompat.fromHtml(text, HtmlCompat.FROM_HTML_SEPARATOR_LINE_BREAK_PARAGRAPH).toString();\n}"
},
{
"identifier": "parseAmount",
"path": "app/src/main/java/ru/application/homemedkit/helpers/StringHelper.java",
"snippet": "public static double parseAmount(String input) {\n NumberFormat format = NumberFormat.getInstance(Locale.getDefault());\n try {\n return Objects.requireNonNull(format.parse(input)).doubleValue();\n } catch (ParseException | NullPointerException e) {\n return 0;\n }\n}"
},
{
"identifier": "RequestAPI",
"path": "app/src/main/java/ru/application/homemedkit/connectionController/RequestAPI.java",
"snippet": "public class RequestAPI implements DecodeCallback {\n private final Activity activity;\n\n public RequestAPI(Activity activity) {\n this.activity = activity;\n }\n\n @Override\n public void onDecoded(@NonNull Result result) {\n if (result.getBarcodeFormat() == BarcodeFormat.DATA_MATRIX) {\n String cis = result.getText().substring(1);\n NetworkCall controller = NetworkClient.getInstance().create(NetworkCall.class);\n Call<MainModel> request = controller.requestInfo(cis);\n\n LoadingDialog loading = new LoadingDialog(activity);\n\n activity.runOnUiThread(loading::showDialog);\n request.enqueue(new RequestNew(activity, cis, loading));\n } else new Snackbars(activity).error();\n }\n\n public void onDecoded(long id, String result) {\n if (result.length() == 85) {\n NetworkCall controller = NetworkClient.getInstance().create(NetworkCall.class);\n Call<MainModel> request = controller.requestInfo(result);\n\n LoadingDialog loading = new LoadingDialog(activity);\n\n activity.runOnUiThread(loading::showDialog);\n request.enqueue(new RequestUpdate(activity, loading, id));\n } else new Snackbars(activity).error();\n }\n}"
},
{
"identifier": "Medicine",
"path": "app/src/main/java/ru/application/homemedkit/databaseController/Medicine.java",
"snippet": "@Entity(tableName = \"medicines\")\npublic class Medicine {\n @PrimaryKey(autoGenerate = true)\n public long id;\n public String cis;\n public String productName;\n public long expDate;\n public String prodFormNormName;\n public String prodDNormName;\n public double prodAmount;\n public String phKinetics;\n public String comment;\n @Embedded\n public Technical technical;\n\n public Medicine() {\n }\n\n @Ignore\n public Medicine(long id) {\n this.id = id;\n }\n\n @Ignore\n public Medicine(String cis,\n String productName,\n long expDate,\n String prodFormNormName,\n String prodDNormName,\n double prodAmount,\n String phKinetics,\n String comment,\n Technical technical) {\n this.cis = cis;\n this.productName = productName;\n this.expDate = expDate;\n this.prodFormNormName = prodFormNormName;\n this.prodDNormName = prodDNormName;\n this.prodAmount = prodAmount;\n this.phKinetics = phKinetics;\n this.comment = comment;\n this.technical = technical;\n }\n\n\n @Ignore\n public Medicine(String productName, long expDate) {\n this.productName = productName;\n this.expDate = expDate;\n }\n\n public Medicine(String cis,\n String productName,\n long expDate,\n String prodFormNormName,\n String prodDNormName,\n String phKinetics,\n Technical technical) {\n this.cis = cis;\n this.productName = productName;\n this.expDate = expDate;\n this.prodFormNormName = prodFormNormName;\n this.prodDNormName = prodDNormName;\n this.phKinetics = phKinetics;\n this.technical = technical;\n }\n\n @Ignore\n public Medicine(long id,\n String cis,\n String productName,\n long expDate,\n String prodFormNormName,\n String prodDNormName,\n double prodAmount,\n String phKinetics,\n String comment,\n Technical technical) {\n this.id = id;\n this.cis = cis;\n this.productName = productName;\n this.expDate = expDate;\n this.prodFormNormName = prodFormNormName;\n this.prodDNormName = prodDNormName;\n this.prodAmount = prodAmount;\n this.phKinetics = phKinetics;\n this.comment = comment;\n this.technical = technical;\n }\n}"
},
{
"identifier": "MedicineDatabase",
"path": "app/src/main/java/ru/application/homemedkit/databaseController/MedicineDatabase.java",
"snippet": "@Database(entities = {Medicine.class, Intake.class, Alarm.class}, version = 1)\npublic abstract class MedicineDatabase extends RoomDatabase {\n\n private static final String DATABASE_NAME = \"medicines\";\n private static MedicineDatabase instance;\n\n public static synchronized MedicineDatabase getInstance(Context context) {\n if (instance == null) {\n instance = Room.databaseBuilder(context, MedicineDatabase.class, DATABASE_NAME)\n .allowMainThreadQueries()\n .build();\n }\n return instance;\n }\n\n public abstract MedicineDAO medicineDAO();\n\n public abstract IntakeDAO intakeDAO();\n\n public abstract AlarmDAO alarmDAO();\n}"
},
{
"identifier": "Technical",
"path": "app/src/main/java/ru/application/homemedkit/databaseController/Technical.java",
"snippet": "public class Technical {\n public boolean scanned;\n public boolean verified;\n\n public Technical(boolean scanned, boolean verified) {\n this.scanned = scanned;\n this.verified = verified;\n }\n}"
},
{
"identifier": "ExpDateDialog",
"path": "app/src/main/java/ru/application/homemedkit/dialogs/ExpDateDialog.java",
"snippet": "public class ExpDateDialog extends MaterialAlertDialogBuilder {\n\n private final Activity activity;\n\n public ExpDateDialog(Context context) {\n super(context);\n\n activity = (Activity) context;\n\n View view = activity.getLayoutInflater().inflate(R.layout.dialog_exp_date, null);\n TextInputEditText expDate = activity.findViewById(R.id.medicine_scanned_exp_date);\n NumberPicker month = view.findViewById(R.id.dialog_exp_date_spinner_month);\n NumberPicker year = view.findViewById(R.id.dialog_exp_date_picker_year);\n\n setMonth(month);\n setYear(year);\n\n setView(view)\n .setTitle(R.string.text_enter_exp_date)\n .setPositiveButton(R.string.text_save, (dialog, which) -> setDate(month, year, expDate));\n\n create().show();\n }\n\n private void setMonth(NumberPicker month) {\n String[] months = activity.getResources().getStringArray(R.array.months_name);\n\n month.setDisplayedValues(months);\n month.setWrapSelectorWheel(false);\n month.setMinValue(0);\n month.setMaxValue(11);\n\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {\n month.setTextSize(52);\n }\n }\n\n private void setYear(NumberPicker year) {\n year.setWrapSelectorWheel(false);\n year.setMinValue(2000);\n year.setMaxValue(2099);\n year.setValue(Calendar.getInstance().get(Calendar.YEAR));\n\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {\n year.setTextSize(52);\n }\n }\n\n private void setDate(NumberPicker month, NumberPicker year, TextInputEditText expDate) {\n String until = activity.getString(R.string.exp_date_until);\n int intMonth = month.getValue() + 1;\n int intYear = year.getValue();\n\n MedicineActivity.timestamp = toTimestamp(intMonth, intYear);\n expDate.setText(String.format(until, toExpDate(intMonth, intYear)));\n }\n}"
},
{
"identifier": "ExpandAnimation",
"path": "app/src/main/java/ru/application/homemedkit/graphics/ExpandAnimation.java",
"snippet": "public class ExpandAnimation implements View.OnClickListener {\n private final MedicineActivity activity;\n private final TextInputLayout layout;\n\n public ExpandAnimation(MedicineActivity activity, TextInputLayout layout) {\n this.activity = activity;\n this.layout = layout;\n }\n\n @Override\n public void onClick(View v) {\n TransitionManager.beginDelayedTransition(layout, new Slide());\n DisplayMetrics metrics = activity.getResources().getDisplayMetrics();\n int height = layout.getLayoutParams().height;\n int wrapContent = ViewGroup.LayoutParams.WRAP_CONTENT;\n int dip = TypedValue.COMPLEX_UNIT_DIP;\n int value = 100;\n\n if (height == wrapContent) {\n layout.getLayoutParams().height = (int) TypedValue.applyDimension(dip, value, metrics);\n layout.setEndIconDrawable(R.drawable.vector_arrow_down);\n } else {\n layout.getLayoutParams().height = wrapContent;\n layout.setEndIconDrawable(R.drawable.vector_arrow_up);\n }\n\n layout.requestLayout();\n }\n}"
},
{
"identifier": "Snackbars",
"path": "app/src/main/java/ru/application/homemedkit/graphics/Snackbars.java",
"snippet": "public class Snackbars {\n\n private static final int ONE = 1000;\n private static final int TWO = 2000;\n private final Activity activity;\n private final int ERROR_COLOR;\n\n public Snackbars(Activity activity) {\n this.activity = activity;\n\n ERROR_COLOR = com.google.android.material.R.color.design_default_color_error;\n }\n\n public void wrongCode() {\n int id = activity.getClass().equals(ScannerActivity.class) ?\n R.id.scanner_view : R.id.scanned_medicine_top_app_bar_toolbar;\n\n Snackbar snackbar = Snackbar.make(activity.findViewById(id), R.string.text_wrong_code, ONE);\n snackbar.setBackgroundTint(ContextCompat.getColor(activity, ERROR_COLOR));\n snackbar.addCallback(new Recreate());\n snackbar.show();\n }\n\n public void codeNotFound() {\n int id = activity.getClass().equals(ScannerActivity.class) ?\n R.id.scanner_view : R.id.scanned_medicine_top_app_bar_toolbar;\n\n Snackbar snackbar = Snackbar.make(activity.findViewById(id), R.string.text_code_not_found, ONE);\n snackbar.setBackgroundTint(ContextCompat.getColor(activity, ERROR_COLOR));\n snackbar.addCallback(new Recreate());\n snackbar.show();\n }\n\n public void wrongCodeCategory() {\n int id = activity.getClass().equals(ScannerActivity.class) ?\n R.id.scanner_view : R.id.scanned_medicine_top_app_bar_toolbar;\n\n Snackbar snackbar = Snackbar.make(activity.findViewById(id), R.string.text_is_not_medicine_code, ONE);\n snackbar.setBackgroundTint(ContextCompat.getColor(activity, ERROR_COLOR));\n snackbar.addCallback(new Recreate());\n snackbar.show();\n }\n\n public void error() {\n int id = activity.getClass().equals(ScannerActivity.class) ?\n R.id.scanner_view : R.id.scanned_medicine_top_app_bar_toolbar;\n\n Snackbar snackbar = Snackbar.make(activity.findViewById(id), R.string.text_unknown_error, ONE);\n snackbar.setBackgroundTint(ContextCompat.getColor(activity, ERROR_COLOR));\n snackbar.show();\n }\n\n public void noNetwork() {\n int id = R.id.button_fetch_data;\n\n Snackbar snackbar = Snackbar.make(activity.findViewById(id),\n R.string.text_connection_error, TWO);\n snackbar.setBackgroundTint(ContextCompat.getColor(activity, ERROR_COLOR));\n snackbar.show();\n }\n\n public void fetchError() {\n int id = R.id.button_fetch_data;\n\n Snackbar snackbar = Snackbar.make(activity.findViewById(id),\n R.string.text_unknown_error, TWO);\n snackbar.setBackgroundTint(ContextCompat.getColor(activity, ERROR_COLOR));\n snackbar.show();\n }\n\n public void duplicateMedicine() {\n int id = R.id.medicine_scanned_layout_ph_kinetics;\n\n Snackbar snackbar = Snackbar.make(activity.findViewById(id),\n R.string.text_medicine_duplicate, ONE);\n snackbar.setBackgroundTint(ContextCompat.getColor(activity, ERROR_COLOR));\n snackbar.show();\n }\n\n private class Recreate extends BaseTransientBottomBar.BaseCallback<Snackbar> {\n @Override\n public void onDismissed(Snackbar transientBottomBar, int event) {\n super.onDismissed(transientBottomBar, event);\n if (activity.getClass().equals(ScannerActivity.class))\n activity.recreate();\n }\n }\n}"
}
] | import static android.view.View.GONE;
import static android.view.View.OnClickListener;
import static android.view.View.VISIBLE;
import static java.lang.String.valueOf;
import static ru.application.homemedkit.helpers.ConstantsHelper.ADD;
import static ru.application.homemedkit.helpers.ConstantsHelper.ADDING;
import static ru.application.homemedkit.helpers.ConstantsHelper.BLANK;
import static ru.application.homemedkit.helpers.ConstantsHelper.CIS;
import static ru.application.homemedkit.helpers.ConstantsHelper.DUPLICATE;
import static ru.application.homemedkit.helpers.ConstantsHelper.ID;
import static ru.application.homemedkit.helpers.ConstantsHelper.MEDICINE_ID;
import static ru.application.homemedkit.helpers.ConstantsHelper.NEW_MEDICINE;
import static ru.application.homemedkit.helpers.DateHelper.toExpDate;
import static ru.application.homemedkit.helpers.ImageHelper.getIconType;
import static ru.application.homemedkit.helpers.StringHelper.decimalFormat;
import static ru.application.homemedkit.helpers.StringHelper.fromHTML;
import static ru.application.homemedkit.helpers.StringHelper.parseAmount;
import android.animation.LayoutTransition;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toolbar.OnMenuItemClickListener;
import androidx.activity.OnBackPressedCallback;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.PopupMenu;
import com.google.android.material.appbar.MaterialToolbar;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.textfield.TextInputEditText;
import com.google.android.material.textfield.TextInputLayout;
import java.util.Arrays;
import ru.application.homemedkit.R;
import ru.application.homemedkit.connectionController.RequestAPI;
import ru.application.homemedkit.databaseController.Medicine;
import ru.application.homemedkit.databaseController.MedicineDatabase;
import ru.application.homemedkit.databaseController.Technical;
import ru.application.homemedkit.dialogs.ExpDateDialog;
import ru.application.homemedkit.graphics.ExpandAnimation;
import ru.application.homemedkit.graphics.Snackbars; | 5,598 | private void setFieldsClickable(boolean flag) {
Arrays.asList(productName, prodFormNormName, prodDNormName, phKinetics)
.forEach(item -> {
if (flag) {
item.addTextChangedListener(this);
item.setRawInputType(InputType.TYPE_CLASS_TEXT);
} else {
item.addTextChangedListener(null);
item.setRawInputType(InputType.TYPE_NULL);
}
item.setFocusableInTouchMode(flag);
item.setFocusable(flag);
item.setCursorVisible(flag);
});
Arrays.asList(prodNormAmount, comment).forEach(item -> {
item.addTextChangedListener(this);
if (item != prodNormAmount)
item.setRawInputType(InputType.TYPE_CLASS_TEXT);
item.setFocusableInTouchMode(true);
item.setFocusable(true);
item.setCursorVisible(true);
});
expDate.addTextChangedListener(flag ? this : null);
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
buttonSave.setVisibility(VISIBLE);
}
@Override
public void afterTextChanged(Editable s) {
}
@Override
public boolean onMenuItemClick(MenuItem item) {
PopupMenu popupMenu = new PopupMenu(this, toolbar.findViewById(R.id.top_app_bar_more));
popupMenu.inflate(R.menu.menu_top_app_bar_more);
popupMenu.setOnMenuItemClickListener(menuItem -> {
database.medicineDAO().delete(new Medicine(primaryKey));
backClick();
return true;
});
popupMenu.show();
return true;
}
private class BackButtonPressed extends OnBackPressedCallback {
public BackButtonPressed() {
super(true);
}
@Override
public void handleOnBackPressed() {
backClick();
}
}
private class SaveChanges implements OnClickListener {
@Override
public void onClick(View v) {
String cis = medicine.cis;
String name = valueOf(productName.getText());
long date = timestamp;
String formNormName = valueOf(prodFormNormName.getText());
String normName = valueOf(prodDNormName.getText());
double prodAmount = parseAmount(valueOf(prodNormAmount.getText()));
String kinetics = valueOf(phKinetics.getText());
String textComment = valueOf(comment.getText());
database.medicineDAO().update(
new Medicine(primaryKey, cis, name, date, formNormName, normName, prodAmount, kinetics, textComment,
new Technical(scanned, verified)));
buttonSave.setVisibility(GONE);
finish();
startActivity(new Intent(getIntent()));
}
}
private class AddMedicine implements OnClickListener {
@Override
public void onClick(View v) {
String name = valueOf(productName.getText());
long date = timestamp;
String formNormName = valueOf(prodFormNormName.getText());
String normName = valueOf(prodDNormName.getText());
double prodAmount = parseAmount(valueOf(prodNormAmount.getText()));
String kinetics = valueOf(phKinetics.getText());
String textComment = valueOf(comment.getText());
boolean scanned = cis != null;
boolean verified = false;
long id = database.medicineDAO().add(
new Medicine(cis, name, date, formNormName, normName, prodAmount, kinetics, textComment,
new Technical(scanned, verified)));
buttonSave.setVisibility(GONE);
finish();
Intent intent = new Intent(getIntent());
intent.putExtra(ID, id);
startActivity(intent);
}
}
private class AddIntake implements OnClickListener {
@Override
public void onClick(View v) {
Intent intent = new Intent(MedicineActivity.this, IntakeActivity.class);
intent.putExtra(MEDICINE_ID, primaryKey); | package ru.application.homemedkit.activities;
public class MedicineActivity extends AppCompatActivity implements TextWatcher, OnMenuItemClickListener {
public static long timestamp = -1;
private MedicineDatabase database;
private Medicine medicine;
private MaterialToolbar toolbar;
private ImageView image;
private TextInputEditText productName, expDate, prodFormNormName, prodDNormName, prodNormAmount, phKinetics, comment;
private FloatingActionButton buttonFetch, buttonAddIntake;
private MaterialButton buttonSave;
private String cis;
private long primaryKey;
private boolean duplicate, scanned, verified;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_medicine);
toolbar = findViewById(R.id.scanned_medicine_top_app_bar_toolbar);
image = findViewById(R.id.image_medicine_scanned_type);
productName = findViewById(R.id.medicine_scanned_product_name);
expDate = findViewById(R.id.medicine_scanned_exp_date);
prodFormNormName = findViewById(R.id.medicine_scanned_prod_form_norm_name);
prodDNormName = findViewById(R.id.medicine_scanned_prod_d_norm_name);
prodNormAmount = findViewById(R.id.medicine_scanned_amount);
phKinetics = findViewById(R.id.medicine_scanned_ph_kinetics);
comment = findViewById(R.id.medicine_scanned_comment);
buttonSave = findViewById(R.id.medicine_card_save_changes);
buttonFetch = findViewById(R.id.button_fetch_data);
buttonAddIntake = findViewById(R.id.button_add_intake);
database = MedicineDatabase.getInstance(this);
primaryKey = getIntent().getLongExtra(ID, 0);
duplicate = getIntent().getBooleanExtra(DUPLICATE, false);
cis = getIntent().getStringExtra(CIS);
if (primaryKey == 0) {
setAddingLayout();
} else {
medicine = database.medicineDAO().getByPK(primaryKey);
scanned = medicine.technical.scanned;
verified = medicine.technical.verified;
if (scanned && verified) setScannedLayout();
else setAddedLayout();
}
toolbar.setOnMenuItemClickListener(this::onMenuItemClick);
toolbar.setNavigationOnClickListener(v -> backClick());
buttonAddIntake.setOnClickListener(new AddIntake());
getOnBackPressedDispatcher().addCallback(new BackButtonPressed());
}
private void setAddingLayout() {
setFieldsClickable(true);
findViewById(R.id.top_app_bar_more).setVisibility(GONE);
buttonAddIntake.setVisibility(View.INVISIBLE);
expDate.setOnClickListener(v -> new ExpDateDialog(this));
buttonSave.setOnClickListener(new AddMedicine());
}
private void setScannedLayout() {
String form = medicine.prodFormNormName;
timestamp = medicine.expDate;
image.setImageDrawable(getIconType(this, form));
productName.setText(medicine.productName);
expDate.setText(getString(R.string.exp_date_until, toExpDate(timestamp)));
prodFormNormName.setText(form);
prodDNormName.setText(medicine.prodDNormName);
prodNormAmount.setText(decimalFormat(medicine.prodAmount));
phKinetics.setText(fromHTML(medicine.phKinetics));
comment.setText(medicine.comment);
setFieldsClickable(false);
buttonSave.setOnClickListener(new SaveChanges());
TextInputLayout layout = findViewById(R.id.medicine_scanned_layout_ph_kinetics);
layout.setClickable(true);
layout.getLayoutTransition().enableTransitionType(LayoutTransition.CHANGING);
layout.setEndIconOnClickListener(new ExpandAnimation(this, layout));
duplicateCheck();
}
private void setAddedLayout() {
String form = medicine.prodFormNormName;
image.setImageDrawable(getIconType(this, form));
productName.setText(medicine.productName);
expDate.setText(medicine.expDate != -1 ? getString(R.string.exp_date_until, toExpDate(medicine.expDate)) : BLANK);
prodFormNormName.setText(form);
prodDNormName.setText(medicine.prodDNormName);
prodNormAmount.setText(decimalFormat(medicine.prodAmount));
phKinetics.setText(medicine.phKinetics);
comment.setText(medicine.comment);
setFieldsClickable(true);
expDate.setOnClickListener(v -> new ExpDateDialog(this));
buttonFetch.setVisibility(medicine.cis != null ? VISIBLE : View.INVISIBLE);
buttonFetch.setOnClickListener(v -> new RequestAPI(this)
.onDecoded(primaryKey, medicine.cis));
buttonSave.setOnClickListener(new SaveChanges());
duplicateCheck();
}
private void backClick() {
Intent intent = new Intent(this, MainActivity.class);
if (!getIntent().getBooleanExtra(ADDING, false))
intent.putExtra(NEW_MEDICINE, true);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
private void duplicateCheck() {
if (duplicate) new Snackbars(this).duplicateMedicine();
}
private void setFieldsClickable(boolean flag) {
Arrays.asList(productName, prodFormNormName, prodDNormName, phKinetics)
.forEach(item -> {
if (flag) {
item.addTextChangedListener(this);
item.setRawInputType(InputType.TYPE_CLASS_TEXT);
} else {
item.addTextChangedListener(null);
item.setRawInputType(InputType.TYPE_NULL);
}
item.setFocusableInTouchMode(flag);
item.setFocusable(flag);
item.setCursorVisible(flag);
});
Arrays.asList(prodNormAmount, comment).forEach(item -> {
item.addTextChangedListener(this);
if (item != prodNormAmount)
item.setRawInputType(InputType.TYPE_CLASS_TEXT);
item.setFocusableInTouchMode(true);
item.setFocusable(true);
item.setCursorVisible(true);
});
expDate.addTextChangedListener(flag ? this : null);
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
buttonSave.setVisibility(VISIBLE);
}
@Override
public void afterTextChanged(Editable s) {
}
@Override
public boolean onMenuItemClick(MenuItem item) {
PopupMenu popupMenu = new PopupMenu(this, toolbar.findViewById(R.id.top_app_bar_more));
popupMenu.inflate(R.menu.menu_top_app_bar_more);
popupMenu.setOnMenuItemClickListener(menuItem -> {
database.medicineDAO().delete(new Medicine(primaryKey));
backClick();
return true;
});
popupMenu.show();
return true;
}
private class BackButtonPressed extends OnBackPressedCallback {
public BackButtonPressed() {
super(true);
}
@Override
public void handleOnBackPressed() {
backClick();
}
}
private class SaveChanges implements OnClickListener {
@Override
public void onClick(View v) {
String cis = medicine.cis;
String name = valueOf(productName.getText());
long date = timestamp;
String formNormName = valueOf(prodFormNormName.getText());
String normName = valueOf(prodDNormName.getText());
double prodAmount = parseAmount(valueOf(prodNormAmount.getText()));
String kinetics = valueOf(phKinetics.getText());
String textComment = valueOf(comment.getText());
database.medicineDAO().update(
new Medicine(primaryKey, cis, name, date, formNormName, normName, prodAmount, kinetics, textComment,
new Technical(scanned, verified)));
buttonSave.setVisibility(GONE);
finish();
startActivity(new Intent(getIntent()));
}
}
private class AddMedicine implements OnClickListener {
@Override
public void onClick(View v) {
String name = valueOf(productName.getText());
long date = timestamp;
String formNormName = valueOf(prodFormNormName.getText());
String normName = valueOf(prodDNormName.getText());
double prodAmount = parseAmount(valueOf(prodNormAmount.getText()));
String kinetics = valueOf(phKinetics.getText());
String textComment = valueOf(comment.getText());
boolean scanned = cis != null;
boolean verified = false;
long id = database.medicineDAO().add(
new Medicine(cis, name, date, formNormName, normName, prodAmount, kinetics, textComment,
new Technical(scanned, verified)));
buttonSave.setVisibility(GONE);
finish();
Intent intent = new Intent(getIntent());
intent.putExtra(ID, id);
startActivity(intent);
}
}
private class AddIntake implements OnClickListener {
@Override
public void onClick(View v) {
Intent intent = new Intent(MedicineActivity.this, IntakeActivity.class);
intent.putExtra(MEDICINE_ID, primaryKey); | intent.putExtra(ADD, true); | 0 | 2023-11-19 10:26:15+00:00 | 8k |
3dcitydb/citydb-tool | citydb-operation/src/main/java/org/citydb/operation/exporter/feature/FeatureExporter.java | [
{
"identifier": "FeatureType",
"path": "citydb-database/src/main/java/org/citydb/database/schema/FeatureType.java",
"snippet": "public class FeatureType {\n public static final FeatureType UNDEFINED = new FeatureType(1, Name.of(\"Undefined\", Namespaces.CORE),\n Table.FEATURE, false, null, null, null, null);\n\n private final int id;\n private final Name name;\n private final Table table;\n private final boolean topLevel;\n private final Integer superTypeId;\n private final Map<Name, Property> properties;\n private final Join join;\n private final JoinTable joinTable;\n private FeatureType superType;\n\n FeatureType(int id, Name name, Table table, boolean topLevel, Integer superTypeId,\n Map<Name, Property> properties, Join join, JoinTable joinTable) {\n this.id = id;\n this.name = name;\n this.table = table;\n this.topLevel = topLevel;\n this.superTypeId = superTypeId;\n this.properties = properties;\n this.join = join;\n this.joinTable = joinTable;\n }\n\n static FeatureType of(int id, Name name, boolean topLevel, Integer superTypeId, JSONObject object) throws SchemaException {\n String tableName = object.getString(\"table\");\n JSONArray propertiesArray = object.getJSONArray(\"properties\");\n JSONObject joinObject = object.getJSONObject(\"join\");\n JSONObject joinTableObject = object.getJSONObject(\"joinTable\");\n\n if (tableName == null) {\n throw new SchemaException(\"No table defined for feature type (ID \" + id + \").\");\n } else if (joinObject != null && joinTableObject != null) {\n throw new SchemaException(\"The feature type (ID \" + id + \") defines both a join and a join table.\");\n }\n\n Table table = Table.of(tableName);\n if (table == null) {\n throw new SchemaException(\"The table \" + tableName + \" of feature type (ID: \" + id + \") is not supported.\");\n }\n\n try {\n Map<Name, Property> properties = null;\n if (propertiesArray != null && !propertiesArray.isEmpty()) {\n properties = new LinkedHashMap<>();\n for (Object item : propertiesArray) {\n if (item instanceof JSONObject propertyObject) {\n Property property = Property.of(propertyObject);\n properties.put(property.getName(), property);\n }\n }\n\n if (properties.size() != propertiesArray.size()) {\n throw new SchemaException(\"The properties array contains invalid properties.\");\n }\n }\n\n return new FeatureType(id, name, table, topLevel, superTypeId, properties,\n joinObject != null ? Join.of(joinObject) : null,\n joinTableObject != null ? JoinTable.of(joinTableObject) : null);\n } catch (SchemaException e) {\n throw new SchemaException(\"Failed to build feature type (ID: \" + id + \").\", e);\n }\n }\n\n public int getId() {\n return id;\n }\n\n public Name getName() {\n return name;\n }\n\n public Table getTable() {\n return table;\n }\n\n public boolean isTopLevel() {\n return topLevel;\n }\n\n public Optional<FeatureType> getSuperType() {\n return Optional.ofNullable(superType);\n }\n\n public Map<Name, Property> getProperties() {\n return properties != null ? properties : Collections.emptyMap();\n }\n\n public Optional<Join> getJoin() {\n return Optional.ofNullable(join);\n }\n\n public Optional<JoinTable> getJoinTable() {\n return Optional.ofNullable(joinTable);\n }\n\n void postprocess(SchemaMapping schemaMapping) throws SchemaException {\n if (superTypeId != null) {\n superType = schemaMapping.getFeatureType(superTypeId);\n if (superType == FeatureType.UNDEFINED) {\n throw new SchemaException(\"The feature type (ID \" + id + \") references an undefined \" +\n \"supertype (ID \" + superTypeId + \").\");\n }\n }\n\n try {\n if (properties != null) {\n for (Property property : properties.values()) {\n property.postprocess(properties, schemaMapping);\n if (property.getJoin().isEmpty() && property.getJoinTable().isEmpty()) {\n Table table = property.getType().map(DataType::getTable).orElse(null);\n if (table == Table.PROPERTY) {\n property.setJoin(new Join(Table.PROPERTY, \"id\", \"feature_id\"));\n }\n }\n }\n\n properties.values().removeIf(property -> property.getParentIndex() != null);\n }\n } catch (SchemaException e) {\n throw new SchemaException(\"Failed to build feature type (ID \" + id + \").\", e);\n }\n }\n}"
},
{
"identifier": "Feature",
"path": "citydb-model/src/main/java/org/citydb/model/feature/Feature.java",
"snippet": "public class Feature extends ModelObject<Feature> implements Describable<FeatureDescriptor> {\n private final Name featureType;\n private Envelope envelope;\n private OffsetDateTime lastModificationDate;\n private String updatingPerson;\n private String reasonForUpdate;\n private String lineage;\n private PropertyMap<Attribute> attributes;\n private PropertyMap<GeometryProperty> geometries;\n private PropertyMap<ImplicitGeometryProperty> implicitGeometries;\n private PropertyMap<FeatureProperty> features;\n private PropertyMap<AppearanceProperty> appearances;\n private PropertyMap<AddressProperty> addresses;\n private FeatureDescriptor descriptor;\n\n protected Feature(Name featureType) {\n this.featureType = Objects.requireNonNull(featureType, \"The feature type must not be null.\");\n }\n\n protected Feature(FeatureTypeProvider provider) {\n this(provider.getName());\n }\n\n public static Feature of(FeatureTypeProvider provider) {\n Objects.requireNonNull(provider, \"The feature type provider must not be null.\");\n return new Feature(provider);\n }\n\n public static Feature of(Name featureType) {\n return new Feature(featureType);\n }\n\n public Name getFeatureType() {\n return featureType;\n }\n\n public Optional<Envelope> getEnvelope() {\n return Optional.ofNullable(envelope);\n }\n\n public Feature setEnvelope(Envelope envelope) {\n this.envelope = asChild(envelope);\n return this;\n }\n\n public Optional<OffsetDateTime> getLastModificationDate() {\n return Optional.ofNullable(lastModificationDate);\n }\n\n public Feature setLastModificationDate(OffsetDateTime lastModificationDate) {\n this.lastModificationDate = lastModificationDate;\n return this;\n }\n\n public Optional<String> getUpdatingPerson() {\n return Optional.ofNullable(updatingPerson);\n }\n\n public Feature setUpdatingPerson(String updatingPerson) {\n this.updatingPerson = updatingPerson;\n return this;\n }\n\n public Optional<String> getReasonForUpdate() {\n return Optional.ofNullable(reasonForUpdate);\n }\n\n public Feature setReasonForUpdate(String reasonForUpdate) {\n this.reasonForUpdate = reasonForUpdate;\n return this;\n }\n\n public Optional<String> getLineage() {\n return Optional.ofNullable(lineage);\n }\n\n public Feature setLineage(String lineage) {\n this.lineage = lineage;\n return this;\n }\n\n public boolean hasAttributes() {\n return attributes != null && !attributes.isEmpty();\n }\n\n public PropertyMap<Attribute> getAttributes() {\n if (attributes == null) {\n attributes = new PropertyMap<>(this);\n }\n\n return attributes;\n }\n\n public Feature setAttributes(Collection<Attribute> attributes) {\n this.attributes = new PropertyMap<>(this, attributes);\n return this;\n }\n\n public Feature addAttribute(Attribute attribute) {\n if (attribute != null) {\n getAttributes().put(attribute);\n }\n\n return this;\n }\n\n public boolean hasGeometries() {\n return geometries != null && !geometries.isEmpty();\n }\n\n public PropertyMap<GeometryProperty> getGeometries() {\n if (geometries == null) {\n geometries = new PropertyMap<>(this);\n }\n\n return geometries;\n }\n\n public Feature setGeometries(Collection<GeometryProperty> geometries) {\n this.geometries = new PropertyMap<>(this, geometries);\n return this;\n }\n\n public Feature addGeometry(GeometryProperty geometry) {\n if (geometry != null) {\n getGeometries().put(geometry);\n }\n\n return this;\n }\n\n public boolean hasImplicitGeometries() {\n return implicitGeometries != null && !implicitGeometries.isEmpty();\n }\n\n public PropertyMap<ImplicitGeometryProperty> getImplicitGeometries() {\n if (implicitGeometries == null) {\n implicitGeometries = new PropertyMap<>(this);\n }\n\n return implicitGeometries;\n }\n\n public Feature setImplicitGeometries(Collection<ImplicitGeometryProperty> implicitGeometries) {\n this.implicitGeometries = new PropertyMap<>(this, implicitGeometries);\n return this;\n }\n\n public Feature addImplicitGeometry(ImplicitGeometryProperty implicitGeometry) {\n if (implicitGeometry != null) {\n getImplicitGeometries().put(implicitGeometry);\n }\n\n return this;\n }\n\n public boolean hasFeatures() {\n return features != null && !features.isEmpty();\n }\n\n public PropertyMap<FeatureProperty> getFeatures() {\n if (features == null) {\n features = new PropertyMap<>(this);\n }\n\n return features;\n }\n\n public Feature setFeatures(Collection<FeatureProperty> features) {\n this.features = new PropertyMap<>(this, features);\n return this;\n }\n\n public Feature addFeature(FeatureProperty feature) {\n if (feature != null) {\n getFeatures().put(feature);\n }\n\n return this;\n }\n\n public boolean hasAppearances() {\n return appearances != null && !appearances.isEmpty();\n }\n\n public PropertyMap<AppearanceProperty> getAppearances() {\n if (appearances == null) {\n appearances = new PropertyMap<>(this);\n }\n\n return appearances;\n }\n\n public Feature setAppearances(Collection<AppearanceProperty> appearances) {\n this.appearances = new PropertyMap<>(this, appearances);\n return this;\n }\n\n public Feature addAppearance(AppearanceProperty appearance) {\n if (appearance != null) {\n getAppearances().put(appearance);\n }\n\n return this;\n }\n\n public boolean hasAddresses() {\n return addresses != null && !addresses.isEmpty();\n }\n\n public PropertyMap<AddressProperty> getAddresses() {\n if (addresses == null) {\n addresses = new PropertyMap<>(this);\n }\n\n return addresses;\n }\n\n public Feature setAddresses(Collection<AddressProperty> addresses) {\n this.addresses = new PropertyMap<>(this, addresses);\n return this;\n }\n\n public Feature addAddress(AddressProperty address) {\n if (address != null) {\n getAddresses().put(address);\n }\n\n return this;\n }\n\n public boolean hasProperties() {\n return hasAttributes()\n || hasGeometries()\n || hasImplicitGeometries()\n || hasFeatures()\n || hasAppearances()\n || hasAddresses();\n }\n\n public List<Property<?>> getProperties() {\n return Stream.of(attributes, geometries, implicitGeometries, features, appearances, addresses)\n .filter(Objects::nonNull)\n .map(PropertyMap::getAll)\n .flatMap(Collection::stream)\n .collect(Collectors.toList());\n }\n\n public List<Property<?>> getPropertiesIf(Predicate<Property<?>> predicate) {\n return getProperties().stream()\n .filter(predicate)\n .collect(Collectors.toList());\n }\n\n public void addProperty(Property<?> property) {\n if (property instanceof FeatureProperty featureProperty) {\n addFeature(featureProperty);\n } else if (property instanceof GeometryProperty geometryProperty) {\n addGeometry(geometryProperty);\n } else if (property instanceof ImplicitGeometryProperty implicitGeometryProperty) {\n addImplicitGeometry(implicitGeometryProperty);\n } else if (property instanceof AppearanceProperty appearanceProperty) {\n addAppearance(appearanceProperty);\n } else if (property instanceof AddressProperty addressProperty) {\n addAddress(addressProperty);\n } else if (property instanceof Attribute attribute) {\n addAttribute(attribute);\n }\n }\n\n @Override\n public Optional<FeatureDescriptor> getDescriptor() {\n return Optional.ofNullable(descriptor);\n }\n\n @Override\n public Feature setDescriptor(FeatureDescriptor descriptor) {\n this.descriptor = descriptor;\n return this;\n }\n\n @Override\n public void accept(Visitor visitor) {\n visitor.visit(this);\n }\n\n @Override\n protected Feature self() {\n return this;\n }\n}"
},
{
"identifier": "FeatureDescriptor",
"path": "citydb-model/src/main/java/org/citydb/model/feature/FeatureDescriptor.java",
"snippet": "public class FeatureDescriptor extends DatabaseDescriptor {\n private final int objectClassId;\n\n private FeatureDescriptor(long id, int objectClassId) {\n super(id);\n this.objectClassId = objectClassId;\n }\n\n public static FeatureDescriptor of(long id, int objectClassId) {\n return new FeatureDescriptor(id, objectClassId);\n }\n\n public int getObjectClassId() {\n return objectClassId;\n }\n}"
},
{
"identifier": "ExportException",
"path": "citydb-operation/src/main/java/org/citydb/operation/exporter/ExportException.java",
"snippet": "public class ExportException extends Exception {\n\n public ExportException() {\n super();\n }\n\n public ExportException(String message) {\n super(message);\n }\n\n public ExportException(Throwable cause) {\n super(cause);\n }\n\n public ExportException(String message, Throwable cause) {\n super(message, cause);\n }\n}"
},
{
"identifier": "ExportHelper",
"path": "citydb-operation/src/main/java/org/citydb/operation/exporter/ExportHelper.java",
"snippet": "public class ExportHelper {\n private final DatabaseAdapter adapter;\n private final ExportOptions options;\n private final Connection connection;\n private final Postprocessor postprocessor;\n private final SchemaMapping schemaMapping;\n private final TableHelper tableHelper;\n private final int srid;\n private final String srsName;\n private final Set<String> featureIdCache = new HashSet<>();\n private final Set<String> surfaceDataIdCache = new HashSet<>();\n private final Set<String> implicitGeometryIdCache = new HashSet<>();\n private final Set<String> addressIdCache = new HashSet<>();\n private final Set<String> externalFileIdCache = new HashSet<>();\n\n ExportHelper(DatabaseAdapter adapter, ExportOptions options) throws SQLException {\n this.adapter = adapter;\n this.options = options;\n\n connection = adapter.getPool().getConnection();\n postprocessor = new Postprocessor();\n schemaMapping = adapter.getSchemaAdapter().getSchemaMapping();\n tableHelper = new TableHelper(this);\n srid = adapter.getDatabaseMetadata().getSpatialReference().getSRID();\n srsName = adapter.getDatabaseMetadata().getSpatialReference().getURI();\n }\n\n public DatabaseAdapter getAdapter() {\n return adapter;\n }\n\n public ExportOptions getOptions() {\n return options;\n }\n\n public SchemaMapping getSchemaMapping() {\n return schemaMapping;\n }\n\n public Connection getConnection() {\n return connection;\n }\n\n public SurfaceDataMapper getSurfaceDataMapper() {\n return postprocessor.getSurfaceDataMapper();\n }\n\n public TableHelper getTableHelper() {\n return tableHelper;\n }\n\n public int getSRID() {\n return srid;\n }\n\n public String getSrsName() {\n return srsName;\n }\n\n public String createId() {\n return \"ID_\" + UUID.randomUUID();\n }\n\n public String getOrCreateId(Referencable object) {\n if (object.getObjectId().isPresent()) {\n return object.getObjectId().get();\n } else {\n String objectId = createId();\n object.setObjectId(objectId);\n return objectId;\n }\n }\n\n public boolean lookupAndPut(Feature feature) {\n String objectId = feature.getObjectId().orElse(null);\n return objectId != null && !featureIdCache.add(objectId);\n }\n\n public boolean lookupAndPut(SurfaceData<?> surfaceData) {\n String objectId = surfaceData.getObjectId().orElse(null);\n return objectId != null && !surfaceDataIdCache.add(objectId);\n }\n\n public boolean lookupAndPut(ImplicitGeometry geometry) {\n String objectId = geometry.getObjectId().orElse(null);\n return objectId != null && !implicitGeometryIdCache.add(objectId);\n }\n\n public boolean lookupAndPut(Address address) {\n String objectId = address.getObjectId().orElse(null);\n return objectId != null && !addressIdCache.add(objectId);\n }\n\n public boolean lookupAndPut(ExternalFile externalFile) {\n String objectId = externalFile.getObjectId().orElse(null);\n return objectId != null && !externalFileIdCache.add(objectId);\n }\n\n Feature exportFeature(long id) throws ExportException {\n try {\n Feature feature = tableHelper.getOrCreateExporter(FeatureExporter.class).doExport(id);\n postprocessor.process(feature);\n return feature;\n } catch (Exception e) {\n throw new ExportException(\"Failed to export feature (ID: \" + id + \").\", e);\n } finally {\n clear();\n }\n }\n\n ImplicitGeometry exportImplicitGeometry(long id) throws ExportException {\n try {\n ImplicitGeometry implicitGeometry = tableHelper.getOrCreateExporter(ImplicitGeometryExporter.class)\n .doExport(id);\n postprocessor.process(implicitGeometry);\n return implicitGeometry;\n } catch (Exception e) {\n throw new ExportException(\"Failed to export implicit geometry (ID: \" + id + \").\", e);\n } finally {\n clear();\n }\n }\n\n private void clear() {\n featureIdCache.clear();\n surfaceDataIdCache.clear();\n implicitGeometryIdCache.clear();\n addressIdCache.clear();\n externalFileIdCache.clear();\n }\n\n protected void close() throws ExportException, SQLException {\n tableHelper.close();\n connection.close();\n }\n}"
},
{
"identifier": "DatabaseExporter",
"path": "citydb-operation/src/main/java/org/citydb/operation/exporter/common/DatabaseExporter.java",
"snippet": "public abstract class DatabaseExporter {\n protected final ExportHelper helper;\n protected final DatabaseAdapter adapter;\n protected final SchemaMapping schemaMapping;\n protected final TableHelper tableHelper;\n\n protected PreparedStatement stmt;\n\n public DatabaseExporter(ExportHelper helper) {\n this.helper = helper;\n this.adapter = helper.getAdapter();\n this.schemaMapping = helper.getSchemaMapping();\n this.tableHelper = helper.getTableHelper();\n }\n\n protected Long getLong(String column, ResultSet rs) throws SQLException {\n long value = rs.getLong(column);\n return !rs.wasNull() ? value : null;\n }\n\n protected Double getDouble(String column, ResultSet rs) throws SQLException {\n double value = rs.getDouble(column);\n return !rs.wasNull() ? value : null;\n }\n\n protected Boolean getBoolean(String column, ResultSet rs) throws SQLException {\n int value = rs.getInt(column);\n return !rs.wasNull() ? value == 1 : null;\n }\n\n protected JSONObject getJSONObject(String content) {\n return JSON.parseObject(content, JSONReader.Feature.UseBigDecimalForDoubles);\n }\n\n protected JSONArray getJSONArray(String content) {\n return JSON.parseArray(content, JSONReader.Feature.UseBigDecimalForDoubles);\n }\n\n protected Name getName(String nameColumn, String namespaceIdColumn, ResultSet rs) throws SQLException {\n String localName = rs.getString(nameColumn);\n if (!rs.wasNull()) {\n int namespaceId = rs.getInt(namespaceIdColumn);\n return !rs.wasNull() ?\n Name.of(localName, schemaMapping.getNamespace(namespaceId).getURI()) :\n Name.of(localName);\n }\n\n return null;\n }\n\n protected DataType getDataType(String column, ResultSet rs) throws SQLException {\n int dataTypeId = rs.getInt(column);\n return !rs.wasNull() ?\n DataType.of(schemaMapping.getDataType(dataTypeId).getName()) :\n null;\n }\n\n protected ArrayValue getArrayValue(String content) {\n if (content != null) {\n JSONArray json = getJSONArray(content);\n if (json != null) {\n return ArrayValue.ofList(json);\n }\n }\n\n return null;\n }\n\n protected Color getColor(String rgba) {\n try {\n return Color.ofHexString(rgba);\n } catch (Exception e) {\n return null;\n }\n }\n\n protected Geometry<?> getGeometry(Object geometryObject) throws ExportException {\n try {\n return geometryObject != null ?\n adapter.getGeometryAdapter().getGeometry(geometryObject)\n .setSRID(helper.getSRID())\n .setSrsName(helper.getSrsName()) :\n null;\n } catch (GeometryException e) {\n throw new ExportException(\"Failed to convert database geometry.\", e);\n }\n }\n\n protected <T extends Geometry<?>> T getGeometry(Object geometryObject, Class<T> type) throws ExportException {\n Geometry<?> geometry = getGeometry(geometryObject);\n return type.isInstance(geometry) ? type.cast(geometry) : null;\n }\n\n protected Envelope getEnvelope(Object geometryObject) throws ExportException {\n Geometry<?> geometry = getGeometry(geometryObject);\n return geometry != null ? geometry.getEnvelope() : null;\n }\n\n public void close() throws ExportException, SQLException {\n if (stmt != null) {\n stmt.close();\n }\n }\n}"
},
{
"identifier": "HierarchyBuilder",
"path": "citydb-operation/src/main/java/org/citydb/operation/exporter/hierarchy/HierarchyBuilder.java",
"snippet": "public class HierarchyBuilder {\n private final long rootId;\n private final ExportHelper helper;\n private final TableHelper tableHelper;\n private final PropertyBuilder propertyBuilder;\n private final Hierarchy hierarchy = new Hierarchy();\n private final List<PropertyStub> propertyStubs = new ArrayList<>();\n\n private HierarchyBuilder(long rootId, ExportHelper helper) {\n this.rootId = rootId;\n this.helper = helper;\n tableHelper = helper.getTableHelper();\n propertyBuilder = new PropertyBuilder(helper);\n }\n\n public static HierarchyBuilder newInstance(long rootId, ExportHelper helper) {\n return new HierarchyBuilder(rootId, helper);\n }\n\n public HierarchyBuilder initialize(ResultSet rs) throws ExportException, SQLException {\n Set<Long> appearanceIds = new HashSet<>();\n Set<Long> implicitGeometryIds = new HashSet<>();\n\n while (rs.next()) {\n long nestedFeatureId = rs.getLong(\"val_feature_id\");\n if (!rs.wasNull() && hierarchy.getFeature(nestedFeatureId) == null) {\n hierarchy.addFeature(nestedFeatureId, tableHelper.getOrCreateExporter(FeatureExporter.class)\n .doExport(nestedFeatureId, rs));\n }\n\n long geometryId = rs.getLong(\"val_geometry_id\");\n if (!rs.wasNull() && hierarchy.getGeometry(geometryId) == null) {\n hierarchy.addGeometry(geometryId, tableHelper.getOrCreateExporter(GeometryExporter.class)\n .doExport(geometryId, false, rs));\n }\n\n long appearanceId = rs.getLong(\"val_appearance_id\");\n if (!rs.wasNull()) {\n appearanceIds.add(appearanceId);\n }\n\n long addressId = rs.getLong(\"val_address_id\");\n if (!rs.wasNull() && hierarchy.getAddress(addressId) == null) {\n hierarchy.addAddress(addressId, tableHelper.getOrCreateExporter(AddressExporter.class)\n .doExport(addressId, rs));\n }\n\n long implicitGeometryId = rs.getLong(\"val_implicitgeom_id\");\n if (!rs.wasNull()) {\n implicitGeometryIds.add(implicitGeometryId);\n }\n\n long featureId = rs.getLong(\"feature_id\");\n if (!rs.wasNull()) {\n PropertyStub propertyStub = tableHelper.getOrCreateExporter(PropertyExporter.class)\n .doExport(featureId, rs);\n if (propertyStub != null) {\n propertyStubs.add(propertyStub);\n }\n }\n }\n\n tableHelper.getOrCreateExporter(AppearanceExporter.class)\n .doExport(appearanceIds, implicitGeometryIds)\n .forEach(hierarchy::addAppearance);\n\n tableHelper.getOrCreateExporter(ImplicitGeometryExporter.class)\n .doExport(implicitGeometryIds, hierarchy.getAppearances().values())\n .forEach(hierarchy::addImplicitGeometry);\n\n return this;\n }\n\n public Hierarchy build() {\n helper.lookupAndPut(hierarchy.getFeature(rootId));\n\n Iterator<PropertyStub> iterator = propertyStubs.iterator();\n while (iterator.hasNext()) {\n PropertyStub propertyStub = iterator.next();\n hierarchy.addProperty(propertyStub.getDescriptor().getId(),\n propertyBuilder.build(propertyStub, hierarchy));\n iterator.remove();\n }\n\n for (Property<?> property : hierarchy.getProperties().values()) {\n long parentId = property.getDescriptor().map(PropertyDescriptor::getParentId).orElse(0L);\n if (parentId != 0) {\n Attribute attribute = hierarchy.getProperty(parentId, Attribute.class);\n if (attribute != null) {\n attribute.addProperty(property);\n }\n } else {\n long featureId = property.getDescriptor().map(PropertyDescriptor::getFeatureId).orElse(0L);\n Feature feature = hierarchy.getFeature(featureId);\n if (feature != null) {\n feature.addProperty(property);\n }\n }\n }\n\n return hierarchy;\n }\n}"
}
] | import java.sql.SQLException;
import java.time.OffsetDateTime;
import org.citydb.database.schema.FeatureType;
import org.citydb.model.feature.Feature;
import org.citydb.model.feature.FeatureDescriptor;
import org.citydb.operation.exporter.ExportException;
import org.citydb.operation.exporter.ExportHelper;
import org.citydb.operation.exporter.common.DatabaseExporter;
import org.citydb.operation.exporter.hierarchy.HierarchyBuilder;
import java.sql.ResultSet; | 6,592 | /*
* citydb-tool - Command-line tool for the 3D City Database
* https://www.3dcitydb.org/
*
* Copyright 2022-2023
* virtualcitysystems GmbH, Germany
* https://vc.systems/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.citydb.operation.exporter.feature;
public class FeatureExporter extends DatabaseExporter {
public FeatureExporter(ExportHelper helper) throws SQLException {
super(helper);
stmt = helper.getConnection().prepareStatement(adapter.getSchemaAdapter().getFeatureHierarchyQuery());
}
public Feature doExport(long id) throws ExportException, SQLException {
stmt.setLong(1, id);
try (ResultSet rs = stmt.executeQuery()) {
return HierarchyBuilder.newInstance(id, helper)
.initialize(rs)
.build()
.getFeature(id);
}
}
public Feature doExport(long id, ResultSet rs) throws ExportException, SQLException { | /*
* citydb-tool - Command-line tool for the 3D City Database
* https://www.3dcitydb.org/
*
* Copyright 2022-2023
* virtualcitysystems GmbH, Germany
* https://vc.systems/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.citydb.operation.exporter.feature;
public class FeatureExporter extends DatabaseExporter {
public FeatureExporter(ExportHelper helper) throws SQLException {
super(helper);
stmt = helper.getConnection().prepareStatement(adapter.getSchemaAdapter().getFeatureHierarchyQuery());
}
public Feature doExport(long id) throws ExportException, SQLException {
stmt.setLong(1, id);
try (ResultSet rs = stmt.executeQuery()) {
return HierarchyBuilder.newInstance(id, helper)
.initialize(rs)
.build()
.getFeature(id);
}
}
public Feature doExport(long id, ResultSet rs) throws ExportException, SQLException { | FeatureType featureType = schemaMapping.getFeatureType(rs.getInt("objectclass_id")); | 0 | 2023-11-19 12:29:54+00:00 | 8k |
magmamaintained/Magma-1.12.2 | src/main/java/org/magmafoundation/magma/configuration/MagmaConfig.java | [
{
"identifier": "YamlConfiguration",
"path": "src/main/java/org/bukkit/configuration/file/YamlConfiguration.java",
"snippet": "public class YamlConfiguration extends FileConfiguration {\n protected static final String COMMENT_PREFIX = \"# \";\n protected static final String BLANK_CONFIG = \"{}\\n\";\n private final DumperOptions yamlOptions = new DumperOptions();\n private final Representer yamlRepresenter = new YamlRepresenter();\n private final Yaml yaml = new Yaml(new YamlConstructor(), yamlRepresenter, yamlOptions);\n\n @Override\n public String saveToString() {\n yamlOptions.setIndent(options().indent());\n yamlOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);\n yamlRepresenter.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);\n\n String header = buildHeader();\n String dump = yaml.dump(getValues(false));\n\n if (dump.equals(BLANK_CONFIG)) {\n dump = \"\";\n }\n\n return header + dump;\n }\n\n @Override\n public void loadFromString(String contents) throws InvalidConfigurationException {\n Validate.notNull(contents, \"Contents cannot be null\");\n\n Map<?, ?> input;\n try {\n input = (Map<?, ?>) yaml.load(contents);\n } catch (YAMLException e) {\n throw new InvalidConfigurationException(e);\n } catch (ClassCastException e) {\n throw new InvalidConfigurationException(\"Top level is not a Map.\");\n }\n\n String header = parseHeader(contents);\n if (header.length() > 0) {\n options().header(header);\n }\n\n if (input != null) {\n convertMapsToSections(input, this);\n }\n }\n\n protected void convertMapsToSections(Map<?, ?> input, ConfigurationSection section) {\n for (Map.Entry<?, ?> entry : input.entrySet()) {\n String key = entry.getKey().toString();\n Object value = entry.getValue();\n\n if (value instanceof Map) {\n convertMapsToSections((Map<?, ?>) value, section.createSection(key));\n } else {\n section.set(key, value);\n }\n }\n }\n\n protected String parseHeader(String input) {\n String[] lines = input.split(\"\\r?\\n\", -1);\n StringBuilder result = new StringBuilder();\n boolean readingHeader = true;\n boolean foundHeader = false;\n\n for (int i = 0; (i < lines.length) && (readingHeader); i++) {\n String line = lines[i];\n\n if (line.startsWith(COMMENT_PREFIX)) {\n if (i > 0) {\n result.append(\"\\n\");\n }\n\n if (line.length() > COMMENT_PREFIX.length()) {\n result.append(line.substring(COMMENT_PREFIX.length()));\n }\n\n foundHeader = true;\n } else if ((foundHeader) && (line.length() == 0)) {\n result.append(\"\\n\");\n } else if (foundHeader) {\n readingHeader = false;\n }\n }\n\n return result.toString();\n }\n\n @Override\n protected String buildHeader() {\n String header = options().header();\n\n if (options().copyHeader()) {\n Configuration def = getDefaults();\n\n if ((def != null) && (def instanceof FileConfiguration)) {\n FileConfiguration filedefaults = (FileConfiguration) def;\n String defaultsHeader = filedefaults.buildHeader();\n\n if ((defaultsHeader != null) && (defaultsHeader.length() > 0)) {\n return defaultsHeader;\n }\n }\n }\n\n if (header == null) {\n return \"\";\n }\n\n StringBuilder builder = new StringBuilder();\n String[] lines = header.split(\"\\r?\\n\", -1);\n boolean startedHeader = false;\n\n for (int i = lines.length - 1; i >= 0; i--) {\n builder.insert(0, \"\\n\");\n\n if ((startedHeader) || (lines[i].length() != 0)) {\n builder.insert(0, lines[i]);\n builder.insert(0, COMMENT_PREFIX);\n startedHeader = true;\n }\n }\n\n return builder.toString();\n }\n\n @Override\n public YamlConfigurationOptions options() {\n if (options == null) {\n options = new YamlConfigurationOptions(this);\n }\n\n return (YamlConfigurationOptions) options;\n }\n\n /**\n * Creates a new {@link YamlConfiguration}, loading from the given file.\n * <p>\n * Any errors loading the Configuration will be logged and then ignored.\n * If the specified input is not a valid config, a blank config will be\n * returned.\n * <p>\n * The encoding used may follow the system dependent default.\n *\n * @param file Input file\n * @return Resulting configuration\n * @throws IllegalArgumentException Thrown if file is null\n */\n public static YamlConfiguration loadConfiguration(File file) {\n Validate.notNull(file, \"File cannot be null\");\n\n YamlConfiguration config = new YamlConfiguration();\n\n try {\n config.load(file);\n } catch (FileNotFoundException ex) {\n } catch (IOException ex) {\n Bukkit.getLogger().log(Level.SEVERE, \"Cannot load \" + file, ex);\n } catch (InvalidConfigurationException ex) {\n Bukkit.getLogger().log(Level.SEVERE, \"Cannot load \" + file, ex);\n }\n\n return config;\n }\n\n /**\n * Creates a new {@link YamlConfiguration}, loading from the given reader.\n * <p>\n * Any errors loading the Configuration will be logged and then ignored.\n * If the specified input is not a valid config, a blank config will be\n * returned.\n *\n * @param reader input\n * @return resulting configuration\n * @throws IllegalArgumentException Thrown if stream is null\n */\n public static YamlConfiguration loadConfiguration(Reader reader) {\n Validate.notNull(reader, \"Stream cannot be null\");\n\n YamlConfiguration config = new YamlConfiguration();\n\n try {\n config.load(reader);\n } catch (IOException ex) {\n Bukkit.getLogger().log(Level.SEVERE, \"Cannot load configuration from stream\", ex);\n } catch (InvalidConfigurationException ex) {\n Bukkit.getLogger().log(Level.SEVERE, \"Cannot load configuration from stream\", ex);\n }\n\n return config;\n }\n}"
},
{
"identifier": "MagmaCommand",
"path": "src/main/java/org/magmafoundation/magma/commands/MagmaCommand.java",
"snippet": "public class MagmaCommand extends Command {\n\n public MagmaCommand(String name) {\n super(name);\n\n this.description = \"Magma commands\";\n this.usageMessage = \"/magma [mods|playermods|dump]\";\n this.setPermission(\"magma.commands.magma\");\n }\n\n @Override\n public List<String> tabComplete(CommandSender sender, String alias, String[] args, Location location) throws IllegalArgumentException {\n if (args.length <= 1) {\n return CommandBase.getListOfStringsMatchingLastWord(args, \"mods\", \"playermods\", \"dump\");\n }\n return Collections.emptyList();\n }\n\n @Override\n public boolean execute(CommandSender sender, String commandLabel, String[] args) {\n\n if (!sender.hasPermission(\"magma.commands.magma\")) {\n sender.sendMessage(ChatColor.RED + \"You don't got the permission to execute this command!\");\n return false;\n }\n\n if (args.length == 0) {\n sender.sendMessage(ChatColor.RED + \"Usage: \" + usageMessage);\n return false;\n }\n\n switch (args[0].toLowerCase()) {\n case \"mods\":\n sender.sendMessage(ChatColor.WHITE + \"Mods (\" + ServerAPI.getModSize() + \"): \"+ ChatColor.GREEN + ServerAPI.getModList().substring(1, ServerAPI.getModList().length() - 1));\n break;\n case \"playermods\":\n if (args.length == 1) {\n sender.sendMessage(ChatColor.RED + \"Usage: \" + usageMessage);\n return false;\n }\n\n Player player = Bukkit.getPlayer(args[1].toString());\n if (player != null) {\n sender.sendMessage(ChatColor.WHITE + \"Mods (\" + PlayerAPI.getModSize(player) + \"): \"+ ChatColor.GREEN + PlayerAPI.getModlist(player).substring(1, PlayerAPI.getModlist(player).length() - 1));\n } else {\n sender.sendMessage(ChatColor.RED + \"The player [\" + args[1] + \"] is not online.\");\n }\n break;\n case \"dump\":\n createMagmaDump(\"worlds.mdump\");\n createMagmaDump(\"permissions.mdump\");\n createMagmaDump(\"materials.mdump\");\n createMagmaDump(\"biomes.mdump\");\n sender.sendMessage(ChatColor.RED + \"Dump saved!\");\n break;\n default:\n sender.sendMessage(ChatColor.RED + \"Usage: \" + usageMessage);\n return false;\n }\n\n return true;\n }\n\n private void createMagmaDump(String fileName) {\n try {\n\n\n File dumpFolder = new File(\"dump\");\n dumpFolder.mkdirs();\n File dumpFile = new File(dumpFolder, fileName);\n OutputStream os = new FileOutputStream(dumpFile);\n Writer writer = new OutputStreamWriter(os);\n\n switch (fileName.split(\"\\\\.\")[0]) {\n case \"worlds\":\n for (WorldServer world : DimensionManager.getWorlds()) {\n writer.write(String.format(\"Stats for %s [%s] with id %d\\n\", world, world.provider.getDimensionType().name(), world.dimension));\n writer.write(\"Current Tick: \" + world.worldInfo.getWorldTotalTime() + \"\\n\");\n writer.write(\"\\nEntities: \");\n writer.write(\"count - \" + world.loadedEntityList.size() + \"\\n\");\n for (Entity entity : world.loadedEntityList) {\n writer.write(String.format(\" %s at (%.4f,%.4f,%.4f)\\n\", entity.getClass().getName(), entity.posX, entity.posY, entity.posZ));\n }\n writer.write(\"\\nTileEntities: \");\n writer.write(\"count - \" + world.loadedTileEntityList.size() + \"\\n\");\n for (TileEntity entity : world.loadedTileEntityList) {\n writer.write(String.format(\" %s at (%d,%d,%d)\\n\", entity.getClass().getName(), entity.getPos().getX(), entity.getPos().getY(), entity.getPos().getZ()));\n }\n writer.write(\"\\nLoaded Chunks: \");\n writer.write(\"count - \" + world.getChunkProvider().getLoadedChunkCount() + \"\\n\");\n writer.write(\"------------------------------------\\n\");\n }\n writer.close();\n case \"permissions\":\n\n for (Command command : MinecraftServer.getServerInstance().server.getCommandMap().getCommands()) {\n if (command.getPermission() == null) {\n continue;\n }\n writer.write(command.getName() + \": \" + command.getPermission() + \"\\n\");\n }\n\n writer.close();\n case \"materials\":\n\n for (Material material : Material.values()) {\n writer.write(material.name() + \"\\n\");\n }\n\n writer.close();\n case \"biomes\":\n\n for (Biome biome : ForgeRegistries.BIOMES.getValuesCollection()) {\n writer.write(biome.getRegistryName() + \"\\n\");\n }\n\n writer.close();\n }\n } catch (Exception e) {\n\n }\n\n\n }\n}"
},
{
"identifier": "TPSCommand",
"path": "src/main/java/org/magmafoundation/magma/commands/TPSCommand.java",
"snippet": "public class TPSCommand extends Command {\n\n public TPSCommand(String name) {\n super(name);\n this.description = \"Gets the current ticks per second for the server\";\n this.usageMessage = \"/tps\";\n this.setPermission(\"spigot.command.tps\");\n }\n\n public static String format(double tps) // Paper - Made static\n {\n return ((tps > 18.0) ? ChatColor.GREEN : (tps > 16.0) ? ChatColor.YELLOW : ChatColor.RED).toString()\n + ((tps > 20.0) ? \"*\" : \"\") + Math.min(Math.round(tps * 100.0) / 100.0, 20.0);\n }\n\n private static final long mean(long[] array) {\n if(array == null) return -1;\n long r = 0;\n for (long i : array) {\n r += i;\n }\n return r / array.length;\n }\n\n @Override\n public boolean execute(CommandSender sender, String commandLabel, String[] args) {\n if (!this.testPermission(sender)) {\n return true;\n }\n\n World currentWorld = null;\n if (sender instanceof CraftPlayer) {\n currentWorld = ((CraftPlayer) sender).getWorld();\n }\n sender.sendMessage(String\n .format(\"%s%s%s-----------%s%s%s<%s%s Worlds %s%s%s>%s%s%s-----------\", ChatColor.GRAY, ChatColor.BOLD, ChatColor.STRIKETHROUGH, ChatColor.DARK_GRAY, ChatColor.BOLD,\n ChatColor.STRIKETHROUGH, ChatColor.GREEN, ChatColor.ITALIC, ChatColor.DARK_GRAY, ChatColor.BOLD, ChatColor.STRIKETHROUGH, ChatColor.GRAY, ChatColor.BOLD, ChatColor.STRIKETHROUGH));\n final MinecraftServer server = MinecraftServer.getServerInst();\n ChatColor colourTPS;\n for (World world : server.server.getWorlds()) {\n if (world instanceof CraftWorld) {\n boolean current = currentWorld != null && currentWorld == world;\n net.minecraft.world.WorldServer mcWorld = ((CraftWorld) world).getHandle();\n String bukkitName = world.getName();\n int dimensionId = mcWorld.provider.getDimension();\n String name = mcWorld.provider.getDimensionType().getName();\n String displayName = name.equals(bukkitName) ? name : String.format(\"%s | %s\", name, bukkitName);\n\n double worldTickTime = mean(server.worldTickTimes.get(dimensionId)) * 1.0E-6D;\n double worldTPS = Math.min(1000.0 / worldTickTime, 20);\n\n if (worldTPS >= 18.0) {\n colourTPS = ChatColor.GREEN;\n } else if (worldTPS >= 15.0) {\n colourTPS = ChatColor.YELLOW;\n } else {\n colourTPS = ChatColor.RED;\n }\n\n sender.sendMessage(String.format(\"%s[%d] %s%s %s- %s%.2fms / %s%.2ftps\", ChatColor.GOLD, dimensionId,\n current ? ChatColor.GREEN : ChatColor.YELLOW, displayName, ChatColor.RESET,\n ChatColor.YELLOW, worldTickTime, colourTPS, worldTPS));\n }\n }\n\n double meanTickTime = mean(server.tickTimeArray) * 1.0E-6D;\n double meanTPS = Math.min(1000.0 / meanTickTime, 20);\n if (meanTPS >= 18.0) {\n colourTPS = ChatColor.GREEN;\n } else if (meanTPS >= 15.0) {\n colourTPS = ChatColor.YELLOW;\n } else {\n colourTPS = ChatColor.RED;\n }\n sender.sendMessage(String.format(\"%s%sOverall: %s%s%.2fms / %s%.2ftps\", ChatColor.WHITE, ChatColor.BOLD, ChatColor.RESET,\n ChatColor.YELLOW, meanTickTime, colourTPS, meanTPS));\n // Paper start - Further improve tick handling\n double[] tps = org.bukkit.Bukkit.getTPS();\n String[] tpsAvg = Arrays.stream(tps).mapToObj(TPSCommand::format).toArray(String[]::new);\n\n sender.sendMessage(String\n .format(\"%s%s%s-----------%s%s%s<%s%s TPS Graph (48 Seconds) %s%s%s>%s%s%s-----------\", ChatColor.GRAY, ChatColor.BOLD, ChatColor.STRIKETHROUGH, ChatColor.DARK_GRAY, ChatColor.BOLD,\n ChatColor.STRIKETHROUGH, ChatColor.GREEN, ChatColor.ITALIC, ChatColor.DARK_GRAY, ChatColor.BOLD, ChatColor.STRIKETHROUGH, ChatColor.GRAY, ChatColor.BOLD, ChatColor.STRIKETHROUGH));\n if (!TPSTracker.lines.isEmpty()) {\n TPSTracker.lines.forEach(sender::sendMessage);\n }\n String status = ChatColor.GRAY + \"Unknown\";\n try {\n final double currentTPS = (double) Double.valueOf(DedicatedServer.TPS);\n if (currentTPS >= 17.0) {\n status = ChatColor.GREEN + \"STABLE\";\n } else if (currentTPS >= 15.0) {\n status = ChatColor.YELLOW + \"SOME STABILITY ISSUES\";\n } else if (currentTPS >= 10.0) {\n status = ChatColor.RED + \"LAGGING. CHECK TIMINGS.\";\n } else if (currentTPS < 10.0) {\n status = ChatColor.DARK_RED + \"UNSTABLE\";\n } else if (currentTPS < 3.0) {\n status = ChatColor.RED + \"SEND HELP!!!!!\";\n }\n } catch (Exception ex) {\n ex.printStackTrace();\n }\n sender.sendMessage(String.format(\"%s%sServer Status: %s\", ChatColor.WHITE, ChatColor.BOLD, status));\n return true;\n }\n\n\n}"
},
{
"identifier": "VersionCommand",
"path": "src/main/java/org/magmafoundation/magma/commands/VersionCommand.java",
"snippet": "public class VersionCommand extends Command {\n\n public VersionCommand(String name) {\n super(name);\n\n this.description = \"Gets the version of the server including any plugins in use\";\n this.usageMessage = \"/version [plugin name]\";\n this.setAliases(Arrays.asList(\"ver\", \"about\"));\n this.setPermission(\"bukkit.command.version\");\n }\n\n @Override\n public boolean execute(CommandSender sender, String commandLabel, String[] args) {\n if (!this.testPermission(sender)) {\n return true;\n }\n\n if(args.length == 0){\n sender.sendMessage(\"This server is running \" + Bukkit.getName() + \" version \" + Magma.getVersion() + \" (Implementing API version \" + Bukkit.getBukkitVersion() + \", Forge Version \" + ForgeVersion.getVersion() + \")\");\n }else {\n StringBuilder name = new StringBuilder();\n\n for (String arg : args) {\n if (name.length() > 0) {\n name.append(' ');\n }\n\n name.append(arg);\n }\n\n String pluginName = name.toString();\n Plugin exactPlugin = Bukkit.getPluginManager().getPlugin(pluginName);\n if (exactPlugin != null) {\n describeToSender(exactPlugin, sender);\n return true;\n }\n\n boolean found = false;\n pluginName = pluginName.toLowerCase(java.util.Locale.ENGLISH);\n for (Plugin plugin : Bukkit.getPluginManager().getPlugins()) {\n if (plugin.getName().toLowerCase(java.util.Locale.ENGLISH).contains(pluginName)) {\n describeToSender(plugin, sender);\n found = true;\n }\n }\n\n if (!found) {\n sender.sendMessage(\"This server is not running any plugin by that name.\");\n sender.sendMessage(\"Use /plugins to get a list of plugins.\");\n }\n }\n return true;\n }\n\n private void describeToSender(Plugin plugin, CommandSender sender) {\n PluginDescriptionFile desc = plugin.getDescription();\n sender.sendMessage(ChatColor.GREEN + desc.getName() + ChatColor.WHITE + \" version \" + ChatColor.GREEN + desc.getVersion());\n\n if (desc.getDescription() != null) {\n sender.sendMessage(desc.getDescription());\n }\n\n if (desc.getWebsite() != null) {\n sender.sendMessage(\"Website: \" + ChatColor.GREEN + desc.getWebsite());\n }\n\n if (!desc.getAuthors().isEmpty()) {\n if (desc.getAuthors().size() == 1) {\n sender.sendMessage(\"Author: \" + getAuthors(desc));\n } else {\n sender.sendMessage(\"Authors: \" + getAuthors(desc));\n }\n }\n }\n\n private String getAuthors(final PluginDescriptionFile desc) {\n StringBuilder result = new StringBuilder();\n List<String> authors = desc.getAuthors();\n\n for (int i = 0; i < authors.size(); i++) {\n if (result.length() > 0) {\n result.append(ChatColor.WHITE);\n\n if (i < authors.size() - 1) {\n result.append(\", \");\n } else {\n result.append(\" and \");\n }\n }\n\n result.append(ChatColor.GREEN);\n result.append(authors.get(i));\n }\n\n return result.toString();\n }\n\n @Override\n public List<String> tabComplete(CommandSender sender, String alias, String[] args) {\n Validate.notNull(sender, \"Sender cannot be null\");\n Validate.notNull(args, \"Arguments cannot be null\");\n Validate.notNull(alias, \"Alias cannot be null\");\n\n if (args.length == 1) {\n List<String> completions = new ArrayList<String>();\n String toComplete = args[0].toLowerCase(java.util.Locale.ENGLISH);\n for (Plugin plugin : Bukkit.getPluginManager().getPlugins()) {\n if (StringUtil.startsWithIgnoreCase(plugin.getName(), toComplete)) {\n completions.add(plugin.getName());\n }\n }\n return completions;\n }\n return ImmutableList.of();\n }\n\n}"
},
{
"identifier": "Value",
"path": "src/main/java/org/magmafoundation/magma/configuration/value/Value.java",
"snippet": "public abstract class Value<T> {\n\n public final String path;\n public final T key;\n public final String description;\n\n public Value(String path, T key, String description) {\n this.path = path;\n this.key = key;\n this.description = description;\n }\n\n public abstract T getValues();\n\n public abstract void setValues(String values);\n}"
},
{
"identifier": "BooleanValue",
"path": "src/main/java/org/magmafoundation/magma/configuration/value/values/BooleanValue.java",
"snippet": "public class BooleanValue extends Value<Boolean> {\n\n private Boolean value;\n private ConfigBase configBase;\n\n public BooleanValue(ConfigBase configBase, String path, Boolean key, String description) {\n super(path, key, description);\n this.value = key;\n this.configBase = configBase;\n }\n\n @Override\n public Boolean getValues() {\n return value;\n }\n\n @Override\n public void setValues(String values) {\n this.value = BooleanUtils.toBooleanObject(values);\n this.value = this.value == null ? key : this.value;\n configBase.set(path, this.value);\n }\n}"
},
{
"identifier": "IntValue",
"path": "src/main/java/org/magmafoundation/magma/configuration/value/values/IntValue.java",
"snippet": "public class IntValue extends Value<Integer> {\n\n private Integer value;\n private ConfigBase configBase;\n\n public IntValue(ConfigBase configBase, String path, Integer key, String description) {\n super(path, key, description);\n this.value = key;\n this.configBase = configBase;\n }\n\n @Override\n public Integer getValues() {\n return this.value;\n }\n\n @Override\n public void setValues(String values) {\n this.value = NumberUtils.toInt(values, key);\n configBase.set(path, this.value);\n }\n}"
},
{
"identifier": "StringArrayValue",
"path": "src/main/java/org/magmafoundation/magma/configuration/value/values/StringArrayValue.java",
"snippet": "public class StringArrayValue extends ArrayValue<String> {\n\n public StringArrayValue(ConfigBase config, String path, String key, String description) {\n super(config, path, key, description);\n }\n\n @Override\n public void initArray(String array) {\n array = array.replaceAll(\"\\\\[(.*)\\\\]\", \"$1\");\n String[] vals = array.split(\",\");\n\n this.valueArray = new ArrayList<String>(vals.length);\n this.valueSet = new HashSet<String>(vals.length);\n\n Arrays.stream(vals).filter(val -> val.length() != 0).map(String::trim).forEach(val -> this.valueArray.add(val));\n this.valueSet.addAll(this.valueArray);\n }\n}"
},
{
"identifier": "StringValue",
"path": "src/main/java/org/magmafoundation/magma/configuration/value/values/StringValue.java",
"snippet": "public class StringValue extends Value<String> {\n\n private String value;\n private ConfigBase config;\n\n public StringValue(ConfigBase config, String path, String key, String description) {\n super(path, key, description);\n this.value = key;\n this.config = config;\n }\n\n @Override\n public String getValues() {\n return this.value;\n }\n\n @Override\n public void setValues(String values) {\n config.set(path, this.value = values);\n }\n}"
}
] | import org.magmafoundation.magma.commands.MagmaCommand;
import org.magmafoundation.magma.commands.TPSCommand;
import org.magmafoundation.magma.commands.VersionCommand;
import org.magmafoundation.magma.configuration.value.Value;
import org.magmafoundation.magma.configuration.value.values.BooleanValue;
import org.magmafoundation.magma.configuration.value.values.IntValue;
import org.magmafoundation.magma.configuration.value.values.StringArrayValue;
import org.magmafoundation.magma.configuration.value.values.StringValue;
import com.google.common.collect.Lists;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.List;
import java.util.logging.Level;
import net.minecraft.server.MinecraftServer;
import org.apache.commons.io.FileUtils;
import org.bukkit.configuration.file.YamlConfiguration; | 6,980 | /*
* Magma Server
* Copyright (C) 2019-2022.
*
* 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 org.magmafoundation.magma.configuration;
/**
* MagmaConfig
*
* @author Hexeption [email protected]
* @since 19/08/2019 - 05:14 am
*/
public class MagmaConfig extends ConfigBase {
public static MagmaConfig instance = new MagmaConfig();
//============================Debug======================================
public final BooleanValue debugPrintBukkitMatterials = new BooleanValue(this, "debug.debugPrintBukkitMatterials", false, "Prints the Forge Bukkit Materials");
public final BooleanValue debugPrintBukkitBannerPatterns = new BooleanValue(this, "debug.debugPrintBukkitBannerPatterns", false, "Prints the Forge Bukkit Banner Patterns");
public final BooleanValue debugPrintCommandNode = new BooleanValue(this, "debug.debugPrintCommandNode", false, "Prints out all Command Nodes for permissions");
public final BooleanValue debugPrintBiomes = new BooleanValue(this, "debug.debugPrintBiomes", false, "Prints out all registered biomes");
public final BooleanValue debugPrintSounds = new BooleanValue(this, "debug.debugPrintSounds", false, "Prints out all registered sounds");
//============================Console======================================
public final StringValue highlightLevelError = new StringValue(this, "console.colour.level.error", "c", "The colour for the error level");
public final StringValue highlightLevelWarning = new StringValue(this, "console.colour.level.warning", "e", "The colour for the warning level");
public final StringValue highlightLevelInfo = new StringValue(this, "console.colour.level.info", "2", "The colour for the info level");
public final StringValue highlightLevelFatal = new StringValue(this, "console.colour.level.fatal", "e", "The colour for the fatal level");
public final StringValue highlightLevelTrace = new StringValue(this, "console.colour.level.trace", "e", "The colour for the trace level");
public final StringValue highlightMessageError = new StringValue(this, "console.colour.message.error", "c", "The colour for the error message");
public final StringValue highlightMessageWarning = new StringValue(this, "console.colour.message.warning", "e", "The colour for the warning message");
public final StringValue highlightMessageInfo = new StringValue(this, "console.colour.message.info", "2", "The colour for the info message");
public final StringValue highlightMessageFatal = new StringValue(this, "console.colour.message.fatal", "e", "The colour for the fatal message");
public final StringValue highlightMessageTrace = new StringValue(this, "console.colour.message.trace", "e", "The colour for the trace message");
public final StringValue highlightTimeError = new StringValue(this, "console.colour.time.error", "c", "The colour for the error time");
public final StringValue highlightTimeWarning = new StringValue(this, "console.colour.time.warning", "e", "The colour for the warning time");
public final StringValue highlightTimeInfo = new StringValue(this, "console.colour.time.info", "2", "The colour for the info time");
public final StringValue highlightTimeFatal = new StringValue(this, "console.colour.time.fatal", "e", "The colour for the fatal time");
public final StringValue highlightTimeTrace = new StringValue(this, "console.colour.time.trace", "e", "The colour for the trace time");
//============================Black List Mods=============================
public final BooleanValue blacklistedModsEnable = new BooleanValue(this, "forge.blacklistedmods.enabled", false, "Enable blacklisting of mods");
public final StringArrayValue blacklistedMods = new StringArrayValue(this, "forge.blacklistedmods.list", "", "A list of mods to blacklist");
public final StringValue blacklistedModsKickMessage = new StringValue(this, "forge.blacklistedmods.kickmessage", "Please Remove Blacklisted Mods", "Mod Blacklist kick message");
//=============================WORLD SETTINGS============================= | /*
* Magma Server
* Copyright (C) 2019-2022.
*
* 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 org.magmafoundation.magma.configuration;
/**
* MagmaConfig
*
* @author Hexeption [email protected]
* @since 19/08/2019 - 05:14 am
*/
public class MagmaConfig extends ConfigBase {
public static MagmaConfig instance = new MagmaConfig();
//============================Debug======================================
public final BooleanValue debugPrintBukkitMatterials = new BooleanValue(this, "debug.debugPrintBukkitMatterials", false, "Prints the Forge Bukkit Materials");
public final BooleanValue debugPrintBukkitBannerPatterns = new BooleanValue(this, "debug.debugPrintBukkitBannerPatterns", false, "Prints the Forge Bukkit Banner Patterns");
public final BooleanValue debugPrintCommandNode = new BooleanValue(this, "debug.debugPrintCommandNode", false, "Prints out all Command Nodes for permissions");
public final BooleanValue debugPrintBiomes = new BooleanValue(this, "debug.debugPrintBiomes", false, "Prints out all registered biomes");
public final BooleanValue debugPrintSounds = new BooleanValue(this, "debug.debugPrintSounds", false, "Prints out all registered sounds");
//============================Console======================================
public final StringValue highlightLevelError = new StringValue(this, "console.colour.level.error", "c", "The colour for the error level");
public final StringValue highlightLevelWarning = new StringValue(this, "console.colour.level.warning", "e", "The colour for the warning level");
public final StringValue highlightLevelInfo = new StringValue(this, "console.colour.level.info", "2", "The colour for the info level");
public final StringValue highlightLevelFatal = new StringValue(this, "console.colour.level.fatal", "e", "The colour for the fatal level");
public final StringValue highlightLevelTrace = new StringValue(this, "console.colour.level.trace", "e", "The colour for the trace level");
public final StringValue highlightMessageError = new StringValue(this, "console.colour.message.error", "c", "The colour for the error message");
public final StringValue highlightMessageWarning = new StringValue(this, "console.colour.message.warning", "e", "The colour for the warning message");
public final StringValue highlightMessageInfo = new StringValue(this, "console.colour.message.info", "2", "The colour for the info message");
public final StringValue highlightMessageFatal = new StringValue(this, "console.colour.message.fatal", "e", "The colour for the fatal message");
public final StringValue highlightMessageTrace = new StringValue(this, "console.colour.message.trace", "e", "The colour for the trace message");
public final StringValue highlightTimeError = new StringValue(this, "console.colour.time.error", "c", "The colour for the error time");
public final StringValue highlightTimeWarning = new StringValue(this, "console.colour.time.warning", "e", "The colour for the warning time");
public final StringValue highlightTimeInfo = new StringValue(this, "console.colour.time.info", "2", "The colour for the info time");
public final StringValue highlightTimeFatal = new StringValue(this, "console.colour.time.fatal", "e", "The colour for the fatal time");
public final StringValue highlightTimeTrace = new StringValue(this, "console.colour.time.trace", "e", "The colour for the trace time");
//============================Black List Mods=============================
public final BooleanValue blacklistedModsEnable = new BooleanValue(this, "forge.blacklistedmods.enabled", false, "Enable blacklisting of mods");
public final StringArrayValue blacklistedMods = new StringArrayValue(this, "forge.blacklistedmods.list", "", "A list of mods to blacklist");
public final StringValue blacklistedModsKickMessage = new StringValue(this, "forge.blacklistedmods.kickmessage", "Please Remove Blacklisted Mods", "Mod Blacklist kick message");
//=============================WORLD SETTINGS============================= | public final IntValue expMergeMaxValue = new IntValue(this, "experience-merge-max-value", -1, | 6 | 2023-11-22 11:25:51+00:00 | 8k |
Barsanti5BI/flight-simulator | src/Aereoporto/ZonaPartenze/ZonaPartenze.java | [
{
"identifier": "ImpiegatoControlliStiva",
"path": "src/Persona/ImpiegatoControlliStiva.java",
"snippet": "public class ImpiegatoControlliStiva extends Thread{\n private Scanner s;\n private ArrayList<String> oggettiProibiti;\n private ArrayList<Turista> turistiPericolosi;\n private ArrayList<Aereo> listaDiAerei;\n\n\n public ImpiegatoControlliStiva(Scanner s, ArrayList<String> oggettiProibiti, ArrayList<Aereo> listaDiAerei, int id){\n this.s = s;\n this.oggettiProibiti = oggettiProibiti;\n this.listaDiAerei = listaDiAerei;\n setName(id+\"\");\n }\n\n public void run(){\n while(true)\n {\n if (s != null)\n {\n // controllore dei bagagli da stiva sospetti\n if (!s.getCodaBagagliControllati().isEmpty() && !s.getCodaBagagliControllati().isEmpty()) {\n Bagaglio bPericoloso = s.getCodaBagagliPericolosi().pop();\n String controllo = ControlloApprofondito(bPericoloso.getOggettiContenuti());\n Turista proprietario = bPericoloso.getProprietario();\n\n if (controllo == \"\") {\n System.out.println(\"Il bagaglio \" + bPericoloso.getEtichetta().getIdRiconoscimentoBagaglio() + \" è sicuro, non contiene nessun oggetto proibito\");\n s.getCodaBagagliControllati().push(bPericoloso);\n System.out.println(\"Il proprietario \" + bPericoloso.getProprietario().getDoc().getNome() + \" del bagaglio \" + bPericoloso.getEtichetta().getIdRiconoscimentoBagaglio() + \" non nescessita di ulteriori controlli\");\n } else {\n System.out.println(\"Il bagaglio \" + bPericoloso.getEtichetta().getIdRiconoscimentoBagaglio() + \" è bloccato poichè contiene: \" + controllo);\n System.out.println(\"Il proprietario \" + bPericoloso.getProprietario().getDoc().getNome() + \" verrà bloccato al gate\");\n turistiPericolosi.add(proprietario);\n }\n\n Bagaglio bSicuro = s.getCodaBagagliControllati().pop();\n Aereo aGiusto = null;\n\n for (Aereo a : listaDiAerei) {\n if (bSicuro.getEtichetta().getCodiceVeivolo() == a.Get_ID()) {\n aGiusto = a;\n break;\n }\n }\n\n aGiusto.Get_Stiva().Aggiungi_Bagaglio_Stiva(bSicuro);\n }\n else\n {\n System.out.println(\"Impiegato controlli stiva: \\\"Sto aspettando\\\"\");\n try {\n Thread.sleep(5);\n } catch (InterruptedException e) {\n throw new RuntimeException(e);\n }\n }\n }\n }\n }\n\n public String ControlloApprofondito(List<Oggetto> ogg)\n {\n String oggettiTrovati = \"\";\n\n for(Oggetto o : ogg)\n {\n for(String o1 : oggettiProibiti)\n {\n if (o.getNome() == o1)\n {\n oggettiTrovati += \" \" + o.getNome();\n }\n }\n }\n\n return oggettiTrovati;\n }\n\n public ArrayList<Turista> getTuristiPericolosi()\n {\n return turistiPericolosi;\n }\n}"
},
{
"identifier": "Turista",
"path": "src/Persona/Turista.java",
"snippet": "public class Turista extends Thread{\n\n // Determinazione turista\n public boolean inPartenza;\n public boolean inArrivo;\n\n //ZONA CHECKIN\n public ZonaCheckIn zonaCheckIn;\n public int indiceSettore;\n public boolean deveFareCheckIn;\n private CartaImbarco cartaImbarco;\n\n //ZONA CONTROLLI\n public ZonaControlli zonaControlli;\n public int IndiceSettore;\n public boolean deveFareControlli;\n public boolean devePoggiareBagagliAiControlli;\n public boolean deveFareControlliAlMetalDetector;\n public boolean deveRitirareBagagliAiControlli;\n public boolean controlliFattiConSuccesso;\n public boolean bagaglioSospetto;\n public boolean controlloMetalDetectorSospetto;\n public boolean perquisizioneTerminata;\n\n //ZONA NEGOZI\n public ZonaNegozi zonaNegozi;\n public int indiceNegozio;\n public boolean vuoleFareAcquisto;\n public List<Prodotto> oggettiDaComprare;\n private @Nullable Bagaglio bagaglio;\n private boolean pagato;\n\n // ZONA GATE\n public ZonaPartenze zonaPartenze;\n public boolean prontoPerImbarcarsi;\n public boolean passatoControlliGate;\n public boolean esitoControlloGate;\n public boolean gateGiusto;\n\n // ZONA ARRIVI\n\n public ZonaArrivi zonaArrivi;\n public boolean arrivatoAreaArrivi;\n public boolean haPassatoControlliArr;\n public boolean esitoControlli;\n public boolean haRitiratoBagagliArr;\n public boolean haFinitoArr;\n\n // elementi utili\n private List<Oggetto> oggetti;\n private Documento doc;\n private Random r;\n private int codAereo;\n\n public Turista(Documento doc, Bagaglio bag, CartaImbarco cartaImbarco, List<Oggetto> oggetti, int codAereo,ZonaCheckIn zonaCheckIn, ZonaControlli zonaControlli, ZonaNegozi zonaNegozi, ZonaPartenze zonaPartenze){\n this.bagaglio = bag;\n this.cartaImbarco = cartaImbarco;\n this.oggetti = oggetti;\n this.doc = doc;\n setName(doc.getCognome() + \" \" + doc.getNome());\n r = new Random();\n vuoleFareAcquisto = r.nextBoolean();\n this.codAereo = codAereo;\n this.inPartenza = inPartenza;\n\n deveFareCheckIn = true;\n deveFareControlli = false;\n devePoggiareBagagliAiControlli = true;\n deveFareControlliAlMetalDetector = true;\n deveRitirareBagagliAiControlli = true;\n controlliFattiConSuccesso = false;\n bagaglioSospetto = false;\n controlloMetalDetectorSospetto = false;\n perquisizioneTerminata = false;\n prontoPerImbarcarsi = false;\n passatoControlliGate = false;\n esitoControlloGate = false;\n gateGiusto = false;\n arrivatoAreaArrivi = false;\n haPassatoControlliArr = false;\n esitoControlli = false;\n haRitiratoBagagliArr = false;\n haFinitoArr = false;\n inPartenza = true;\n this.zonaCheckIn = zonaCheckIn;\n this.zonaControlli = zonaControlli;\n this.zonaNegozi = zonaNegozi;\n this.zonaPartenze = zonaPartenze;\n }\n\n public void run(){\n System.out.println(\"Il turista \" + getName() + \" è stato generato\");\n while (true){\n try{\n // IL TURISTA DEVE PARTIRE\n if (inPartenza)\n {\n System.out.println(\"Il turista\" + getName() + \" si prepara ad affrontare il suo viaggio!\");\n\n // ZONA CHECK-IN\n if(deveFareCheckIn) {\n System.out.println(\"Il turista \" + getName() + \" si mette in attesa al banco del check-in per prendere la sua carta d'imbarco\");\n zonaCheckIn.getBanco().getCodaTuristi().push(this);\n\n synchronized (zonaCheckIn.getBanco().getImpiegatoCheckIn()) {\n while(deveFareCheckIn) {\n zonaCheckIn.getBanco().getImpiegatoCheckIn().wait();\n }\n }\n System.out.println(\"Il turista \" + getName() + \" ha la sua carta d'imbarco e va ai controlli\");\n deveFareControlli = true;\n }\n\n // ZONA CONTROLLI\n if (deveFareControlli) {\n System.out.println(\"Il turista \" + getName() + \" è arrivato ai controlli\");\n\n Settore settore = zonaControlli.getSettore(0);\n MetalDetector metalDetector = settore.getMetalDetector();\n Scanner scanner = settore.getScannerBagagali();\n\n if (devePoggiareBagagliAiControlli) {\n if (bagaglio != null) {\n scanner.getCodaBagagli().push(bagaglio);\n System.out.println(\"Il turista \" + getName() + \" ha poggiato i bagagli sul rullo\");\n devePoggiareBagagliAiControlli = false;\n bagaglio = null;\n deveRitirareBagagliAiControlli = true;\n }\n else\n {\n devePoggiareBagagliAiControlli = false;\n deveRitirareBagagliAiControlli = false;\n }\n }\n\n if (deveFareControlliAlMetalDetector) {\n System.out.println(\"Il turista \" + getName() + \" si sta mettendo in coda per il metal detector\");\n metalDetector.getCodaTuristiAttesa().push(this);\n\n synchronized (metalDetector) {\n while (deveFareControlliAlMetalDetector) {\n metalDetector.wait();\n }\n }\n\n if (!controlloMetalDetectorSospetto) {\n if (deveRitirareBagagliAiControlli) {\n if (bagaglioSospetto) {\n System.out.println(\"Turista arrestato!\");\n break;\n } else {\n // il turista continua a cercare il bagaglio finchè non lo\n System.out.println(\"Il turista \" + getName() + \" sta cercando il suo bagaglio...\");\n cercaBagaglio(scanner.getCodaBagagliControllati());\n }\n }\n } else {\n System.out.println(\"Scansione di potenziali oggetti metallicie effettuata\");\n synchronized (metalDetector.getImpiegatoControlli()) {\n while (!perquisizioneTerminata) {\n metalDetector.getImpiegatoControlli().wait();\n }\n }\n break;\n }\n\n deveFareControlli = false;\n controlliFattiConSuccesso = true;\n prontoPerImbarcarsi = true;\n }\n\n // ZONA NEGOZI\n if (vuoleFareAcquisto) {\n\n indiceNegozio = r.nextInt(0, zonaNegozi.getListaNegozi().size());\n\n Negozio n = zonaNegozi.getListaNegozi().get(indiceNegozio);\n\n Thread.sleep(1000);\n\n System.out.println(\"Il turista \" + getName() + \" è entrato nel negozio \" + n.getNome());\n decidiCosaComprare(n);\n n.getCodaCassa().push(this);\n\n synchronized (n.getImpiegatoNegozi())\n {\n while(!pagato)\n {\n n.getImpiegatoNegozi().wait();\n }\n }\n vuoleFareAcquisto = false;\n prontoPerImbarcarsi = true;\n }\n\n if(prontoPerImbarcarsi)\n {\n List<Gate> gates = zonaPartenze.getListaGate();\n Gate mioGate = null;\n\n for(Gate g : gates)\n {\n if (g.getId() == cartaImbarco.getGate())\n {\n mioGate = g;\n break;\n }\n }\n\n synchronized (mioGate)\n {\n while (!passatoControlliGate)\n {\n gates.wait();\n }\n }\n\n if(gateGiusto)\n {\n System.out.println(\"Il turista è entrato nel gate giusto\");\n if(esitoControlloGate)\n {\n System.out.println(\"Turista imbarcato\");\n break;\n }\n else\n {\n System.out.println(\"Turista arrestato\");\n break;\n }\n }\n else\n {\n System.out.println(\"Gate sbagliatp\");\n break;\n }\n }\n }\n } else if (inArrivo) // IL TURISTA E' ARRIVATO\n {\n while(!arrivatoAreaArrivi)\n {\n if(arrivatoAreaArrivi)\n {\n System.out.println(\"Il turista \" + getName() + \" è arrivato all'aeroporto\");\n break;\n }\n else\n {\n Thread.sleep(5);\n }\n }\n\n if(!haPassatoControlliArr)\n {\n Dogana dogana = zonaArrivi.getDogana();\n System.out.println(\"Il bagaglio di \" + getName() + \" è stato ritirato\");\n RitiroBagagli ritiroBagagli = zonaArrivi.getRitiroBagagli();\n\n synchronized (dogana.getControllore())\n {\n System.out.println(\"In attesa dei controlli alla dogana...\");\n while(!haPassatoControlliArr)\n {\n dogana.getControllore().wait();\n }\n }\n\n if(esitoControlli)\n {\n if (bagaglio == null)\n {\n System.out.println(\"Il turista \" + getName() + \" sta cercando il suo bagaglio\");\n // c'è un while che va avanti finchè non trova il bagaglio\n cercaBagaglio(ritiroBagagli.getCodaBagagli());\n }\n\n haRitiratoBagagliArr = true;\n haFinitoArr = true;\n break;\n }\n else\n {\n System.out.println(\"Il turista \" + getName() + \" sta cercando il suo bagaglio\");\n break;\n }\n }\n }\n\n Thread.sleep(2);\n }\n catch (InterruptedException ex){\n System.out.println(ex);\n }\n\n }\n\n }\n\n public int getCodAereo(){\n return codAereo;\n }\n\n public Bagaglio getBagaglio() {\n return bagaglio;\n }\n public void setBagaglio(@Nullable Bagaglio bagaglio) {\n this.bagaglio = bagaglio;\n }\n\n public List<Oggetto> GetListaOggetti()\n {\n return oggetti;\n }\n public Documento getDoc(){\n return doc;\n }\n public CartaImbarco GetCartaImbarco(){return cartaImbarco;}\n public void setCartaImbarco(CartaImbarco c) { cartaImbarco = c; }\n\n public void cercaBagaglio(Coda<Bagaglio> codaBag)\n {\n while(true)\n {\n Bagaglio b = codaBag.pop();\n\n if (b.getEtichetta().getIdRiconoscimentoBagaglio() == cartaImbarco.getIdRiconoscimentoBagaglio())\n {\n bagaglio = b;\n break;\n }\n else\n {\n codaBag.push(b);\n }\n }\n }\n\n public void decidiCosaComprare(Negozio n)\n {\n List<Prodotto> coseDisponibili = n.getOggettiInVendita();\n\n for(int i = 0; i <= r.nextInt(0, 11); i++)\n {\n int indiceElemento = r.nextInt(0, coseDisponibili.size());\n oggettiDaComprare.add(coseDisponibili.get(indiceElemento));\n }\n }\n\n public void inserisciTuristaGate(Gate gate)\n {\n gate.getCodaGenerale().push(this);\n prontoPerImbarcarsi = false;\n }\n\n public void setGateGiusto(boolean var)\n {\n gateGiusto = var;\n }\n\n public void setEsitoControlloGate(boolean var)\n {\n esitoControlloGate = var;\n }\n\n public void setPassatoControlliGate(Boolean var)\n {\n esitoControlloGate = var;\n }\n\n public void setArrivatoAreaArrivi(Boolean var)\n {\n arrivatoAreaArrivi = var;\n }\n}"
},
{
"identifier": "Gate",
"path": "src/Aereo/Gate.java",
"snippet": "public class Gate extends Thread{\n Timer timer;\n TimerTask timerTask;\n int nomeGate;\n String destinazione;\n Coda<Turista> codaPrioritaria;\n Coda<Turista> codaNormale;\n Boolean TerminatiIControlli;\n Coda<Turista> codaTurista;\n Boolean GateAperto;\n Coda<Turista> codaGenerale;\n ImpiegatoControlliStiva impiegatoControlliStiva;\n public Gate(int nomeGate, Coda<Turista> codaGenerale, String destinazione, ImpiegatoControlliStiva impiegatoControlliStiva){\n timer = new Timer();\n timerTask = new TimerTask() {\n @Override\n public void run() {\n TerminatiIControlli = true;\n System.out.println(\"Il gate \" + nomeGate + \" si è chiuso\");\n }\n };\n codaPrioritaria = new Coda<>();\n codaNormale = new Coda<>();\n codaTurista = new Coda<>();\n\n this.codaGenerale = codaGenerale;\n TerminatiIControlli = false;\n this.destinazione = destinazione;\n this.nomeGate = nomeGate;\n this.impiegatoControlliStiva = impiegatoControlliStiva;\n }\n public void run(){\n try {\n timer.schedule(timerTask, 60000); //Programma il TimerTask per eseguirlo dopo un ritardo specificato\n\n while(!codaGenerale.isEmpty()){ //creo la coda prioritaria e la coda normale\n Turista t = codaGenerale.pop();\n if(t.GetCartaImbarco().getPrioritario() || isPasseggeroInPrioritaria()){\n codaPrioritaria.push(t);\n sleep(100);\n System.out.println(\"Il turista \"+ t.GetCartaImbarco().getCognomePasseggero() + \" \" + t.GetCartaImbarco().getNomePasseggero() + \" è entrato nella coda prioritaria nel gate \" + nomeGate);\n }\n else{\n codaNormale.push(t);\n sleep(100);\n System.out.println(\"Il turista \" + t.GetCartaImbarco().getCognomePasseggero() + \" \" + t.GetCartaImbarco().getNomePasseggero() + \" è entrato nella coda normale nel gate \" + nomeGate);\n }\n }\n while (!codaPrioritaria.isEmpty()) { //prima la coda prioritaria\n Turista t = codaPrioritaria.pop();\n EffettuaControllo(t);\n\n }\n while (!codaNormale.isEmpty()) { //dopo la coda normale\n Turista t = codaNormale.pop();\n EffettuaControllo(t);\n }\n // TerminatiIControlli verrà impostato su true dal TimerTask\n }catch(InterruptedException ex){\n System.out.println(ex.getMessage());\n }\n\n }\n public Boolean getTerminatiIControlli(){\n return TerminatiIControlli;\n }\n\n //Metodo che controllo se la destinazione del gate corrisponde alla destinazione segnata\n //nella carta d'imbarco dei turisti, e effettua controllo su turisti pericolosi\n public void EffettuaControllo(Turista t){\n try{\n if(destinazione.equals(t.GetCartaImbarco().getViaggio())){\n sleep(100);\n System.out.println(\" Il turista \" + t.GetCartaImbarco().getCognomePasseggero() + \" \" + t.GetCartaImbarco().getNomePasseggero() + \" ha effettuato il controllo effettuato nel gate \" + nomeGate);\n t.setGateGiusto(true);\n }\n else{\n sleep(100);\n t.setGateGiusto(false);\n System.out.println(\" Il turista \" + t.GetCartaImbarco().getCognomePasseggero() + \" \" + t.GetCartaImbarco().getNomePasseggero() + \" ha sbagliato gate\");\n }\n\n boolean controlloTPericoloso = false;\n\n for(Turista tPericoloso : impiegatoControlliStiva.getTuristiPericolosi())\n {\n if (tPericoloso == t) {\n controlloTPericoloso = true;\n break;\n }\n }\n\n if (!controlloTPericoloso)\n {\n t.setEsitoControlloGate(true);\n codaTurista.push(t);\n }\n else\n {\n t.setEsitoControlloGate(false);\n }\n\n t.setPassatoControlliGate(true);\n t.notify();\n }catch (InterruptedException ex){\n System.out.println(ex.getMessage());\n }\n }\n\n public Coda<Turista> getCodaTurista() {\n return codaTurista;\n }\n\n //Metodo che apre il gate\n public void openGate(){ //mi fa partire il gate\n GateAperto = true;\n this.start();\n }\n\n //Feature Marco Perin\n private boolean isPasseggeroInPrioritaria() {\n int minRange = 0;\n int maxRange = 500;\n\n // Utilizzo una probabilità del 2% per spostare un passeggero nella coda prioritaria\n double probabilita = 0.02;\n\n int randomValue = new Random().nextInt(maxRange - minRange + 1) + minRange;\n\n // Restituisci true se il numero casuale è inferiore alla probabilità desiderata moltiplicata per il range massimo\n return randomValue < probabilita * maxRange;\n }\n public String getDestinazione(){return destinazione;}\n public boolean getGateAperto(){ return GateAperto;}\n\n public int Get_Nome_Gate(){return nomeGate;}\n\n public Coda<Turista> getCodaGenerale()\n {\n return codaGenerale;\n }\n}"
},
{
"identifier": "ZonaAeroporto",
"path": "src/Aereoporto/Common/ZonaAeroporto.java",
"snippet": "public class ZonaAeroporto {\n public @Nullable ZonaAeroporto zonaSuccessiva;\n public @Nullable ZonaAeroporto zonaPrecedente;\n public void impostaZonaSuccessiva(ZonaAeroporto zonaSuccessiva) {\n this.zonaSuccessiva = zonaSuccessiva;\n }\n public void impostaZonaPrecedente(ZonaAeroporto zonaPrecedente) {\n this.zonaPrecedente = zonaPrecedente;\n }\n}"
},
{
"identifier": "Viaggio",
"path": "src/TorreDiControllo/Viaggio.java",
"snippet": "public class Viaggio\n{\n Boolean finito;\n public Pilota p;\n public Aereo a;\n private String destinazione;\n //partenza o arrivo, true = partenza, false = arrivo\n private Boolean pa;\n private int numGate;\n public Viaggio(String d, Aereo aereo,Pilota pilota, boolean partenzaArrivo, int nG)\n {\n p = pilota;\n a = aereo;\n destinazione = d;\n finito = false;\n pa = partenzaArrivo;\n numGate = nG;\n }\n\n public String DammiDestinzazione()\n {\n return destinazione;\n }\n\n public int GetNumGate()\n {\n return numGate;\n }\n public Boolean DimmiSeFinito()\n {\n return finito;\n }\n public Aereo getAereo()\n {\n return a;\n }\n}"
},
{
"identifier": "Coda",
"path": "src/Utils/Coda.java",
"snippet": "public class Coda<T> {\n private LinkedList<T> list;\n\n public int size(){\n return list.size();\n }\n\n public Coda(){\n list = new LinkedList<T>();\n }\n\n public T pop(){\n try{\n while(list.isEmpty())\n Thread.sleep(10);\n } catch(InterruptedException ex) {}\n return this.estrai();\n }\n\n private synchronized T estrai() {\n return list.removeFirst(); }\n\n public boolean isEmpty() {\n return list.isEmpty();\n }\n\n public synchronized void push(T element){\n list.addLast(element);\n }\n}"
}
] | import Persona.ImpiegatoControlliStiva;
import Persona.Turista;
import Aereo.Gate;
import Aereoporto.Common.ZonaAeroporto;
import TorreDiControllo.Viaggio;
import Utils.Coda;
import java.util.ArrayList;
import java.util.List; | 6,349 | package Aereoporto.ZonaPartenze;
public class ZonaPartenze extends ZonaAeroporto {
ArrayList<Gate> listaGate;
| package Aereoporto.ZonaPartenze;
public class ZonaPartenze extends ZonaAeroporto {
ArrayList<Gate> listaGate;
| public ZonaPartenze(ArrayList<Viaggio> viaggi, ImpiegatoControlliStiva impiegatoControlliStiva) | 0 | 2023-11-18 07:13:43+00:00 | 8k |
Youkehai/openai_assistants_java | assistants-front/src/main/java/com/kh/assistants/front/controller/AssistantsApiController.java | [
{
"identifier": "CommonPathReq",
"path": "assistants-framework/openai-spring-boot-starter-assistant/src/main/java/io/github/youkehai/assistant/core/req/CommonPathReq.java",
"snippet": "@Data\n@Accessors(chain = true)\n@AllArgsConstructor\n@NoArgsConstructor\npublic class CommonPathReq {\n private final static CommonPathReq emptyObj = new CommonPathReq();\n\n /**\n * 单独用一个这个方法,是因为该方法很常用\n * 创建一个带线程 ID 的路径参数对象\n *\n * @param threadId 线程ID\n * @return 路径参数对象\n */\n public static CommonPathReq newByThreadId(String threadId) {\n return new CommonPathReq().setThreadId(threadId);\n }\n\n /**\n * 线程 ID\n */\n private String threadId;\n\n /**\n * 助理 ID\n */\n private String assistantsId;\n\n /**\n * 运行任务 ID\n */\n private String runId;\n\n /**\n * 文件 ID\n */\n private String fileId;\n\n /**\n * 步骤 ID\n */\n private String stepId;\n\n /**\n * 消息 ID\n */\n private String messageId;\n\n /**\n * 获取路径参数,只获取不为空的\n *\n * @return\n */\n public Map<String, Object> getPathParams() {\n return BeanUtil.beanToMap(this);\n }\n\n public static CommonPathReq empty() {\n return emptyObj;\n }\n}"
},
{
"identifier": "PageReq",
"path": "assistants-framework/openai-spring-boot-starter-assistant/src/main/java/io/github/youkehai/assistant/core/req/PageReq.java",
"snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\n@EqualsAndHashCode(callSuper = true)\npublic class PageReq extends BaseReq {\n\n /**\n * 查询条数\n */\n private Integer limit = 50;\n\n /**\n * 排序\n * 不传默认 desc\n * 按 createAt排序\n */\n private String order = \"desc\";\n\n /**\n * 分页使用,表示只查询 after 指定的 ID 之后的数据\n */\n private String after;\n\n /**\n * 分页使用,表示只查询 before 指定的 ID 之前的数据\n */\n private String before;\n}"
},
{
"identifier": "CreateAssistantFileReq",
"path": "assistants-framework/openai-spring-boot-starter-assistant/src/main/java/io/github/youkehai/assistant/core/req/assistants/CreateAssistantFileReq.java",
"snippet": "@Data\n@EqualsAndHashCode(callSuper = true)\n@Accessors(chain = true)\npublic class CreateAssistantFileReq extends BaseReq {\n\n /**\n * 文件ID,已有 file 中选一个绑定具体的 assistant\n */\n @JsonProperty(\"file_id\")\n private String fileId;\n\n /**\n * 上传新的文件,并绑定 assistant\n */\n private MultipartFile file;\n\n /**\n * 助理ID\n */\n private String assistantId;\n}"
},
{
"identifier": "CreateAndRunReq",
"path": "assistants-framework/openai-spring-boot-starter-assistant/src/main/java/io/github/youkehai/assistant/core/req/message/CreateAndRunReq.java",
"snippet": "@Data\npublic class CreateAndRunReq {\n\n /**\n * 助理 ID\n */\n private String assistant_id;\n\n /**\n * 消息内容\n */\n private String content;\n}"
},
{
"identifier": "CreateMessageReq",
"path": "assistants-framework/openai-spring-boot-starter-assistant/src/main/java/io/github/youkehai/assistant/core/req/message/CreateMessageReq.java",
"snippet": "@Data\n@EqualsAndHashCode(callSuper = true)\n@Accessors(chain = true)\npublic class CreateMessageReq extends BaseReq {\n\n /**\n * 角色 发送消息只支持 user\n */\n private String role = \"user\";\n\n /**\n * 消息内容\n */\n private String content;\n\n private String[] file_ids;\n}"
},
{
"identifier": "CreateRunReq",
"path": "assistants-framework/openai-spring-boot-starter-assistant/src/main/java/io/github/youkehai/assistant/core/req/run/CreateRunReq.java",
"snippet": "@Data\n@Accessors(chain = true)\n@EqualsAndHashCode(callSuper = true)\npublic class CreateRunReq extends BaseReq {\n\n /**\n * 助理 ID\n */\n private String assistant_id;\n\n /**\n * 运行的模型\n */\n private String model;\n\n /**\n * 本次运行,使用该 instructions 重写并覆盖掉原始设定的 instructions\n */\n private String instructions;\n\n /**\n * 本次运行,想执行的工具\n */\n private List<Tool> tools;\n\n /**\n * 当需要使用 创建一个新线程,发完消息之后,立即 run 时使用\n * 相当于将 创建线程-发送消息-开启运行 变为一个动作\n */\n private ThreadReq thread;\n}"
},
{
"identifier": "BasePageResp",
"path": "assistants-framework/openai-spring-boot-starter-assistant/src/main/java/io/github/youkehai/assistant/core/resp/BasePageResp.java",
"snippet": "@Data\npublic class BasePageResp<T> {\n\n /**\n * 类型,基本就是 list\n */\n private String object;\n\n /**\n * 分页数据\n */\n private List<T> data;\n\n /**\n * 当前页第一个ID\n */\n @JsonProperty(\"first_id\")\n private String firstId;\n\n /**\n * 当前页最后一个ID\n */\n @JsonProperty(\"last_id\")\n private String lastId;\n\n /**\n * 是否还有更多数据\n */\n @JsonProperty(\"has_more\")\n private boolean hasMore;\n}"
},
{
"identifier": "AssistantFile",
"path": "assistants-framework/openai-spring-boot-starter-assistant/src/main/java/io/github/youkehai/assistant/core/resp/assistants/AssistantFile.java",
"snippet": "@Data\n@EqualsAndHashCode(callSuper = true)\n@Accessors(chain = true)\npublic class AssistantFile extends BaseResp {\n\n /**\n * 助理 ID\n */\n @JsonProperty(\"assistant_id\")\n private String assistantId;\n}"
},
{
"identifier": "Assistants",
"path": "assistants-framework/openai-spring-boot-starter-assistant/src/main/java/io/github/youkehai/assistant/core/resp/assistants/Assistants.java",
"snippet": "@Data\n@EqualsAndHashCode(callSuper = true)\npublic class Assistants extends BaseResp {\n\n /**\n * 助手的名称,最大长度为 256 个字符\n */\n private String name;\n\n /**\n * 助手的描述,最大长度为 512 个字符\n */\n private String description;\n\n /**\n * 使用的模型 ID。可以使用 List models API 查看所有可用模型\n */\n // model 字段:\n private String model;\n\n /**\n * 助手使用的系统指令,最大长度为 32768 个字符\n */\n private String instructions;\n\n /**\n * 助手启用的工具列表。每个助手最多可以有 128 个工具。工具类型可以是 code_interpreter、retrieval 或 function\n */\n private List<Tool> tools;\n\n /**\n * 附加到此助手的文件 ID 列表。助手最多可以附加 20 个文件。文件按创建日期升序排列\n */\n @JsonProperty(\"file_ids\")\n private List<String> fileIds;\n\n}"
},
{
"identifier": "File",
"path": "assistants-framework/openai-spring-boot-starter-assistant/src/main/java/io/github/youkehai/assistant/core/resp/file/File.java",
"snippet": "@Data\n@EqualsAndHashCode(callSuper = true)\npublic class File extends BaseResp {\n\n private String purpose;\n\n private String filename;\n\n private Long bytes;\n\n private String status;\n\n @JsonProperty(\"status_details\")\n private String statusDetails;\n\n /**\n * 对文件名进行 url 解码\n *\n * @return 解码后的文件名\n */\n public String getFileName() {\n return URLDecoder.decode(this.filename, StandardCharsets.UTF_8);\n }\n}"
},
{
"identifier": "Message",
"path": "assistants-framework/openai-spring-boot-starter-assistant/src/main/java/io/github/youkehai/assistant/core/resp/message/Message.java",
"snippet": "@Data\n@EqualsAndHashCode(callSuper = true)\npublic class Message extends BaseResp {\n\n /**\n * 线程ID\n */\n @JsonProperty(\"thread_id\")\n private String threadId;\n\n /**\n * 角色\n * One of user or assistant.\n */\n private String role;\n\n /**\n * 消息内容\n */\n private List<Content> content;\n\n /**\n * 助理ID\n */\n @JsonProperty(\"assistant_id\")\n private String assistantId;\n\n @JsonProperty(\"run_id\")\n private String runId;\n\n @JsonProperty(\"file_ids\")\n private String[] fileIds;\n\n}"
},
{
"identifier": "Run",
"path": "assistants-framework/openai-spring-boot-starter-assistant/src/main/java/io/github/youkehai/assistant/core/resp/run/Run.java",
"snippet": "@Data\n@EqualsAndHashCode(callSuper = true)\npublic class Run extends RunBaseResp {\n\n /**\n * 当前 run 必须完成的动作,可能为空或一个对象\n */\n @JsonProperty(\"required_action\")\n private RequiredAction requiredAction;\n\n @JsonIgnore\n private Long started_at;\n\n /**\n * 开始运行的时间\n */\n private String startedAt;\n\n public String getStartedAt() {\n return DateUtil.formatDateByTimeStamp(started_at);\n }\n\n /**\n * 当前任务用的模型\n */\n private String model;\n /**\n * 用到的 assistants 中编写的 instructions 内容\n */\n private String instructions;\n /**\n * 本次 run 的任务中,用到的所有 tool\n */\n private List<Tool> tools;\n\n @JsonProperty(\"file_ids\")\n private List<String> fileIds;\n}"
},
{
"identifier": "RunStep",
"path": "assistants-framework/openai-spring-boot-starter-assistant/src/main/java/io/github/youkehai/assistant/core/resp/run/RunStep.java",
"snippet": "@Data\n@EqualsAndHashCode(callSuper = true)\n@Accessors(chain = true)\npublic class RunStep extends RunBaseResp {\n\n @JsonProperty(\"run_id\")\n private String runId;\n\n /**\n * 运行步骤的类型,可以是\n * message_creation (模型自己生成)\n * 或\n * tool_calls(通过 assistant 配置的具体 tool 得到的结果)\n */\n private String type;\n\n /**\n * run step 的详情信息\n * 如果调用了 function ,会记录具体调用了哪个 function,使用了什么参数,并且 function 给出的返回值\n * 如果调用了 code_interpreter ,也会记录具体调用的返回值明细\n */\n @JsonProperty(\"step_details\")\n private RunStepDetail stepDetails;\n\n}"
},
{
"identifier": "Thread",
"path": "assistants-framework/openai-spring-boot-starter-assistant/src/main/java/io/github/youkehai/assistant/core/resp/thread/Thread.java",
"snippet": "@Data\n@EqualsAndHashCode(callSuper = true)\npublic class Thread extends BaseResp {\n}"
},
{
"identifier": "AssistantsMessageApiService",
"path": "assistants-framework/openai-spring-boot-starter-assistant/src/main/java/io/github/youkehai/assistant/core/service/AssistantsMessageApiService.java",
"snippet": "public class AssistantsMessageApiService extends BaseService {\n\n\n /**\n * 获取线程消息列表\n *\n * @param threadId 线程 ID\n * @param pageReq 分页参数\n * @return 消息列表\n */\n public BasePageResp<Message> getMessageList(String threadId, PageReq pageReq) {\n return super.parsePageData(super.requestByPage(RequestUrlEnum.LIST_MESSAGE, pageReq, CommonPathReq.newByThreadId(threadId)),\n Message.class);\n }\n\n /**\n * 发送消息\n *\n * @param threadId 线程ID\n * @param createMessageReq 消息,文件 id 内容\n * @return 发送完之后的消息\n */\n public Message createMessage(String threadId, CreateMessageReq createMessageReq) {\n return parse(super.request(RequestUrlEnum.CREATE_MESSAGE, createMessageReq, CommonPathReq.newByThreadId(threadId)),\n Message.class);\n }\n\n /**\n * 修改线程消息\n *\n * @param threadId 线程 ID\n * @param messageId 消息 ID\n * @param metadata 源数据\n * @return 修改后的消息\n */\n public Message modifyMessage(String threadId, String messageId, Map<String, String> metadata) {\n return parse(super.request(RequestUrlEnum.MODIFY_MESSAGE, new BaseReq(metadata), CommonPathReq.newByThreadId(threadId).setMessageId(messageId)),\n Message.class);\n }\n\n\n /**\n * 检索线程中,某一个消息的指定文件信息\n *\n * @param threadId 线程 ID\n * @param messageId 消息 ID\n * @param fileId 文件 ID\n * @return 文件信息\n */\n public MessageFile retrieveMessageFile(String threadId, String messageId, String fileId) {\n return parse(super.request(RequestUrlEnum.RETRIEVE_MESSAGE_FILE, CommonPathReq.newByThreadId(threadId)\n .setMessageId(messageId).setFileId(fileId)),\n MessageFile.class);\n }\n\n /**\n * 获取指定消息用到的文件\n *\n * @param threadId 聊天线程 ID\n * @param messageId 消息 ID\n * @param pageReq 分页参数\n * @return 文件 list\n */\n public BasePageResp<MessageFile> messageFileList(String threadId, String messageId, PageReq pageReq) {\n CommonPathReq commonPathReq = new CommonPathReq().setMessageId(messageId)\n .setThreadId(threadId);\n return super.parsePageData(super.requestByPage(RequestUrlEnum.LIST_MESSAGE_FILE, pageReq, commonPathReq),\n MessageFile.class);\n }\n}"
},
{
"identifier": "AssistantsRunApiService",
"path": "assistants-framework/openai-spring-boot-starter-assistant/src/main/java/io/github/youkehai/assistant/core/service/AssistantsRunApiService.java",
"snippet": "public class AssistantsRunApiService extends BaseService {\n\n /**\n * 获取线程所有的 run 任务列表分页\n *\n * @param threadId 线程 ID\n * @param pageReq 分页参数\n * @return run 任务列表分页\n */\n public BasePageResp<Run> getRunList(String threadId, PageReq pageReq) {\n return super.parsePageData(super.requestByPage(RequestUrlEnum.LIST_RUN, pageReq, CommonPathReq.newByThreadId(threadId)),\n Run.class);\n }\n\n /**\n * 创建运行任务\n *\n * @param threadId 线程ID\n * @param createRunReq 创建运行任务参数\n * @return 创建完成后的 run 任务信息\n */\n public Run createRun(String threadId, CreateRunReq createRunReq) {\n return super.parse(super.request(RequestUrlEnum.CREATE_RUN, createRunReq, CommonPathReq.newByThreadId(threadId)),\n Run.class);\n }\n\n /**\n * 检索 run 的具体信息\n *\n * @param threadId 线程 ID\n * @param runId run 任务 ID\n * @return run 的详情信息\n */\n public Run retireveRun(String threadId, String runId) {\n return super.parse(super.request(RequestUrlEnum.RETRIEVE_RUN, CommonPathReq.newByThreadId(threadId)\n .setRunId(runId)),\n Run.class);\n }\n\n /**\n * 取消正在 run 的任务\n *\n * @param threadId 线程 ID\n * @param runId run 任务 ID\n * @return run 的详情信息\n */\n public Run cancelRun(String threadId, String runId) {\n return super.parse(super.request(RequestUrlEnum.CANCEL_RUN, CommonPathReq.newByThreadId(threadId)\n .setRunId(runId)),\n Run.class);\n }\n\n /**\n * 修改线程消息\n *\n * @param threadId 线程 ID\n * @param runId run 任务 ID\n * @param metadata 源数据\n * @return 修改后的 run 对象\n */\n public Run modifyRun(String threadId, String runId, Map<String, String> metadata) {\n return parse(super.request(RequestUrlEnum.MODIFY_RUN, new BaseReq(metadata), CommonPathReq.newByThreadId(threadId)\n .setRunId(runId)),\n Run.class);\n }\n\n\n /**\n * 提交运行中任务的返回值\n *\n * @param threadId 线程 ID\n * @param runId 运行任务的 ID\n * @param submitOutputs 提交的数据\n * @return run 对象\n */\n public Run submitToolOutputsToRun(String threadId, String runId, List<SubmitOutputReq.Item> submitOutputs) {\n SubmitOutputReq reqVo = new SubmitOutputReq();\n reqVo.setTool_outputs(submitOutputs);\n return super.parse(super.request(RequestUrlEnum.SUBMIT_TOOL_OUTPUTS_TO_RUN, reqVo,\n CommonPathReq.newByThreadId(threadId).setRunId(runId)),\n Run.class);\n }\n\n /**\n * 创建线程-发送消息-运行任务\n *\n * @param createRunReq 对应参数\n * @return 任务的信息\n */\n public Run createAndRun(CreateRunReq createRunReq) {\n return super.parse(super.request(RequestUrlEnum.CREATE_THREAD_AND_RUN, createRunReq),\n Run.class);\n }\n\n /**\n * 获取 run 具体的运行情况,并获取某一个步骤的具体运行情况\n *\n * @param threadId 线程 ID\n * @param runId 运行任务 ID\n * @param stepId 步骤 ID\n * @return 具体步骤的详细运行情况\n */\n public RunStep retrieveRunStep(String threadId, String runId, String stepId) {\n return super.parse(super.request(RequestUrlEnum.RETRIEVE_RUN_STEP, CommonPathReq.newByThreadId(threadId)\n .setRunId(runId).setStepId(stepId)),\n RunStep.class);\n }\n\n /**\n * 获取 run 所有的运行步骤列表\n *\n * @param threadId 线程 ID\n * @param runId 运行任务 ID\n * @return 具体步骤的详细运行情况\n */\n public BasePageResp<RunStep> listRunSteps(String threadId, String runId, PageReq pageReq) {\n return super.parsePageData(super.requestByPage(RequestUrlEnum.LIST_RUN_STEPS, pageReq,\n CommonPathReq.newByThreadId(threadId).setRunId(runId)),\n RunStep.class);\n }\n}"
},
{
"identifier": "AssistantsService",
"path": "assistants-framework/openai-spring-boot-starter-assistant/src/main/java/io/github/youkehai/assistant/core/service/AssistantsService.java",
"snippet": "@Slf4j\npublic class AssistantsService extends BaseService {\n\n /**\n * 创建一个AI助理\n *\n * @param assistantReq 创建参数\n * @return 创建成功的对象\n */\n public Assistants createAssistant(AssistantReq assistantReq) {\n return super.parse(super.request(RequestUrlEnum.CREATE_ASSISTANTS, assistantReq),\n Assistants.class);\n }\n\n /**\n * 编辑指定的 assistant\n *\n * @param assistantId 本次修改的 assistantId\n * @param assistantReq 修改参数\n * @return 修改后的对象\n */\n public Assistants modifyAssistant(String assistantId, AssistantReq assistantReq) {\n return super.parse(super.request(RequestUrlEnum.MODIFY_ASSISTANT, assistantReq, new CommonPathReq().setAssistantsId(assistantId)),\n Assistants.class);\n }\n\n /**\n * 删除指定的 assistant\n *\n * @param assistantId 被删除的 assistantId\n * @return 被删除的 assistantId\n */\n public String deleteAssistant(String assistantId) {\n super.request(RequestUrlEnum.DELETE_ASSISTANT, new CommonPathReq().setAssistantsId(assistantId));\n return assistantId;\n }\n\n /**\n * 获取所有 assistants 集合,分页\n *\n * @param pageReq 分页参数\n * @return assistants 列表\n */\n public BasePageResp<Assistants> getAssistantList(PageReq pageReq) {\n return super.parsePageData(super.requestByPage(RequestUrlEnum.LIST_ASSISTANTS, pageReq, CommonPathReq.empty()),\n Assistants.class);\n }\n\n\n /**\n * 上传文件到 openai 中的 assistant 中,并关联具体的 assistant\n * 如果未传递 file,则必须传递 fileId\n *\n * @param req 上传请求参数,其中 file 和 fileId 只能二选一传递,其中 file 的优先级 大于 fileId\n * 如果传了 file,则不会用 fileId 再去继续绑定\n * @return 文件对象,包含文件ID,名称等\n */\n public AssistantFile uploadFile(CreateAssistantFileReq req) {\n log.debug(\"上传文件并绑定具体的assistant[assistant-create_assistant_file],请求参数:{}\", req);\n //1.传了文件,则先上传文件\n BindFileReq bindFileReq = new BindFileReq().setFileId(req.getFileId());\n if (req.getFile() != null) {\n File file = upload(req.getFile());\n //1.1 获取到新上传的文件 ID\n bindFileReq.setFileId(file.getId());\n }\n //2. 将具体的 file 绑定至 assistant中\n String request = super.request(RequestUrlEnum.CREATE_ASSISTANT_FILE, bindFileReq, new CommonPathReq().setAssistantsId(req.getAssistantId()));\n log.debug(\"上传文件[assistant-create_assistant_file],openai返回值:{}\", request);\n return parse(request, AssistantFile.class);\n }\n\n /**\n * 获取助理信息\n *\n * @param assistantId 助理 Assistant ID\n * @return 助理信息\n */\n public Assistants retrieveAssistants(String assistantId) {\n return super.parse(super.request(RequestUrlEnum.RETRIEVE_ASSISTANT, new CommonPathReq().setAssistantsId(assistantId)),\n Assistants.class);\n }\n\n /**\n * 查询指定 assistant 的文件列表\n *\n * @param assistantsId 助理ID\n * @param pageReq 分页参数\n * @return A list of assistant file objects.\n */\n public BasePageResp<AssistantFile> assistantsFileList(String assistantsId, PageReq pageReq) {\n CommonPathReq commonPathReq = new CommonPathReq().setAssistantsId(assistantsId);\n return super.parsePageData(super.requestByPage(RequestUrlEnum.LIST_ASSISTANT_FILE, pageReq, commonPathReq),\n AssistantFile.class);\n }\n\n /**\n * 删除助理的指定文件\n *\n * @param assistantsId 助理 ID\n * @param fileId 文件 ID\n * @return 文件 ID\n */\n public String deleteAssistantFile(String assistantsId, String fileId) {\n CommonPathReq commonPathReq = new CommonPathReq().setAssistantsId(assistantsId).setFileId(fileId);\n super.request(RequestUrlEnum.DELETE_ASSISTANT_FILE, commonPathReq);\n return fileId;\n }\n\n /**\n * \"获取 assistants file 详情\n *\n * @param assistantsId 助理 ID\n * @param fileId 文件 ID\n * @return 文件信息\n */\n public AssistantFile retrieveAssistantFile(String assistantsId, String fileId) {\n CommonPathReq commonPathReq = new CommonPathReq().setAssistantsId(assistantsId).setFileId(fileId);\n return parse(super.request(RequestUrlEnum.RETRIEVE_ASSISTANT_FILE, commonPathReq),\n AssistantFile.class);\n }\n}"
},
{
"identifier": "AssistantsThreadApiService",
"path": "assistants-framework/openai-spring-boot-starter-assistant/src/main/java/io/github/youkehai/assistant/core/service/AssistantsThreadApiService.java",
"snippet": "public class AssistantsThreadApiService extends BaseService {\n\n /**\n * 获取线程信息\n *\n * @param threadId 线程ID\n * @return 线程信息\n */\n public Thread retrieveThread(String threadId) {\n return super.parse(super.request(RequestUrlEnum.RETRIEVE_THREAD, CommonPathReq.newByThreadId(threadId)),\n Thread.class);\n }\n\n /**\n * 创建线程,并发送消息\n *\n * @param message 消息内容,可以传一个空对象\n * @return 线程信息\n */\n public Thread createThread(CreateMessageReq message) {\n return parse(super.request(RequestUrlEnum.CREATE_THREAD, message),\n Thread.class);\n }\n\n /**\n * 删除线程\n *\n * @param threadId 线程ID\n * @return 被删除的线程 ID\n */\n public String deleteThreadId(String threadId) {\n super.request(RequestUrlEnum.DELETE_THREAD, CommonPathReq.newByThreadId(threadId));\n return threadId;\n }\n\n /**\n * 修改线程的 metadata 信息\n *\n * @param threadId 线程 ID\n * @param metadata metadata\n * @return 修改后的 thread 对象\n */\n public Thread modifyThread(String threadId, Map<String, String> metadata) {\n return super.parse(super.request(RequestUrlEnum.MODIFY_THREAD,\n new UpdateThreadReq().setMetadata(metadata),\n CommonPathReq.newByThreadId(threadId)), Thread.class);\n }\n}"
}
] | import io.github.youkehai.assistant.core.req.CommonPathReq;
import io.github.youkehai.assistant.core.req.PageReq;
import io.github.youkehai.assistant.core.req.assistants.CreateAssistantFileReq;
import io.github.youkehai.assistant.core.req.message.CreateAndRunReq;
import io.github.youkehai.assistant.core.req.message.CreateMessageReq;
import io.github.youkehai.assistant.core.req.run.CreateRunReq;
import io.github.youkehai.assistant.core.resp.BasePageResp;
import io.github.youkehai.assistant.core.resp.assistants.AssistantFile;
import io.github.youkehai.assistant.core.resp.assistants.Assistants;
import io.github.youkehai.assistant.core.resp.file.File;
import io.github.youkehai.assistant.core.resp.message.Message;
import io.github.youkehai.assistant.core.resp.run.Run;
import io.github.youkehai.assistant.core.resp.run.RunStep;
import io.github.youkehai.assistant.core.resp.thread.Thread;
import io.github.youkehai.assistant.core.service.AssistantsMessageApiService;
import io.github.youkehai.assistant.core.service.AssistantsRunApiService;
import io.github.youkehai.assistant.core.service.AssistantsService;
import io.github.youkehai.assistant.core.service.AssistantsThreadApiService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile; | 6,961 | package com.kh.assistants.front.controller;
/**
* assistants api
*/
@AllArgsConstructor
@Tag(name = "assistantsAPI")
@RestController
@RequestMapping("/assistant")
@Slf4j
public class AssistantsApiController {
private final AssistantsMessageApiService assistantsMessageApiService;
private final AssistantsRunApiService assistantsRunApiService;
private final AssistantsService assistantsService;
private final AssistantsThreadApiService assistantsThreadApiService;
@Operation(summary = "获取消息列表")
@GetMapping("/message/{threadId}") | package com.kh.assistants.front.controller;
/**
* assistants api
*/
@AllArgsConstructor
@Tag(name = "assistantsAPI")
@RestController
@RequestMapping("/assistant")
@Slf4j
public class AssistantsApiController {
private final AssistantsMessageApiService assistantsMessageApiService;
private final AssistantsRunApiService assistantsRunApiService;
private final AssistantsService assistantsService;
private final AssistantsThreadApiService assistantsThreadApiService;
@Operation(summary = "获取消息列表")
@GetMapping("/message/{threadId}") | public BasePageResp<Message> messageList(@PathVariable("threadId") String threadId, PageReq pageReqVO) { | 10 | 2023-11-25 13:19:47+00:00 | 8k |
confluentinc/flink-cookbook | pattern-matching-cep/src/test/java/io/confluent/developer/cookbook/flink/PatternMatchingCEPTest.java | [
{
"identifier": "TOPIC",
"path": "pattern-matching-cep/src/main/java/io/confluent/developer/cookbook/flink/PatternMatchingCEP.java",
"snippet": "static final String TOPIC = \"input\";"
},
{
"identifier": "HOT",
"path": "pattern-matching-cep/src/main/java/io/confluent/developer/cookbook/flink/records/SensorReading.java",
"snippet": "public static long HOT = 50L;"
},
{
"identifier": "MiniClusterExtensionFactory",
"path": "change-data-capture/src/test/java/io/confluent/developer/cookbook/flink/extensions/MiniClusterExtensionFactory.java",
"snippet": "public final class MiniClusterExtensionFactory {\n\n private static final int PARALLELISM = 2;\n\n public static MiniClusterExtension withDefaultConfiguration() {\n return new MiniClusterExtension(defaultBuilder().build());\n }\n\n public static MiniClusterExtension withCustomConfiguration(Configuration configuration) {\n return new MiniClusterExtension(defaultBuilder().setConfiguration(configuration).build());\n }\n\n private MiniClusterExtensionFactory() {}\n\n private static Builder defaultBuilder() {\n return new MiniClusterResourceConfiguration.Builder()\n .setNumberSlotsPerTaskManager(PARALLELISM)\n .setNumberTaskManagers(1);\n }\n}"
},
{
"identifier": "MatcherV1",
"path": "pattern-matching-cep/src/main/java/io/confluent/developer/cookbook/flink/patterns/MatcherV1.java",
"snippet": "public class MatcherV1 implements PatternMatcher<SensorReading, SensorReading> {\n\n public Pattern<SensorReading, ?> pattern(Duration limitOfHeatTolerance) {\n AfterMatchSkipStrategy skipStrategy = AfterMatchSkipStrategy.skipPastLastEvent();\n\n return Pattern.<SensorReading>begin(\"first-hot-reading\", skipStrategy)\n .where(\n new SimpleCondition<>() {\n @Override\n public boolean filter(SensorReading reading) {\n return reading.sensorIsHot();\n }\n })\n .followedBy(\"still-hot-later\")\n .where(new StillHotLater(\"first-hot-reading\", limitOfHeatTolerance));\n }\n\n public PatternProcessFunction<SensorReading, SensorReading> process() {\n\n return new PatternProcessFunction<>() {\n @Override\n public void processMatch(\n Map<String, List<SensorReading>> map,\n Context context,\n Collector<SensorReading> out) {\n\n SensorReading event = map.get(\"still-hot-later\").get(0);\n out.collect(event);\n }\n };\n }\n}"
},
{
"identifier": "MatcherV2",
"path": "pattern-matching-cep/src/main/java/io/confluent/developer/cookbook/flink/patterns/MatcherV2.java",
"snippet": "public class MatcherV2 implements PatternMatcher<SensorReading, SensorReading> {\n\n public Pattern<SensorReading, ?> pattern(Duration limitOfHeatTolerance) {\n AfterMatchSkipStrategy skipStrategy = AfterMatchSkipStrategy.skipPastLastEvent();\n\n return Pattern.<SensorReading>begin(\"first-hot-reading\", skipStrategy)\n .where(\n new SimpleCondition<>() {\n @Override\n public boolean filter(SensorReading reading) {\n return reading.sensorIsHot();\n }\n })\n .notFollowedBy(\"cool-in-between\")\n .where(\n new SimpleCondition<>() {\n @Override\n public boolean filter(SensorReading reading) {\n return reading.sensorIsCool();\n }\n })\n .followedBy(\"still-hot-later\")\n .where(new StillHotLater(\"first-hot-reading\", limitOfHeatTolerance));\n }\n\n public PatternProcessFunction<SensorReading, SensorReading> process() {\n\n return new PatternProcessFunction<>() {\n @Override\n public void processMatch(\n Map<String, List<SensorReading>> map,\n Context context,\n Collector<SensorReading> out) {\n\n SensorReading event = map.get(\"still-hot-later\").get(0);\n out.collect(event);\n }\n };\n }\n}"
},
{
"identifier": "MatcherV3",
"path": "pattern-matching-cep/src/main/java/io/confluent/developer/cookbook/flink/patterns/MatcherV3.java",
"snippet": "public class MatcherV3 implements PatternMatcher<SensorReading, SensorReading> {\n\n public Pattern<SensorReading, ?> pattern(Duration limitOfHeatTolerance) {\n AfterMatchSkipStrategy skipStrategy = AfterMatchSkipStrategy.skipPastLastEvent();\n\n return Pattern.<SensorReading>begin(\"starts-cool\", skipStrategy)\n .where(\n new SimpleCondition<>() {\n @Override\n public boolean filter(SensorReading reading) {\n return reading.sensorIsCool();\n }\n })\n .next(\"gets-hot\")\n .where(\n new SimpleCondition<>() {\n @Override\n public boolean filter(SensorReading reading) {\n return reading.sensorIsHot();\n }\n })\n .oneOrMore()\n .consecutive()\n .next(\"stays-hot-long-enough\")\n .where(new StillHotLater(\"gets-hot\", limitOfHeatTolerance));\n }\n\n public PatternProcessFunction<SensorReading, SensorReading> process() {\n\n return new PatternProcessFunction<>() {\n @Override\n public void processMatch(\n Map<String, List<SensorReading>> map,\n Context context,\n Collector<SensorReading> out) {\n SensorReading event = map.get(\"stays-hot-long-enough\").get(0);\n out.collect(event);\n }\n };\n }\n}"
},
{
"identifier": "PatternMatcher",
"path": "pattern-matching-cep/src/main/java/io/confluent/developer/cookbook/flink/patterns/PatternMatcher.java",
"snippet": "public interface PatternMatcher<IN, OUT> {\n\n Pattern<IN, ?> pattern(Duration limitOfHeatTolerance);\n\n PatternProcessFunction<IN, OUT> process();\n}"
},
{
"identifier": "OscillatingSensorReadingSupplier",
"path": "pattern-matching-cep/src/test/java/io/confluent/developer/cookbook/flink/records/OscillatingSensorReadingSupplier.java",
"snippet": "public class OscillatingSensorReadingSupplier implements Supplier<SensorReading> {\n private final long secondsOfHeat;\n\n /**\n * @param secondsOfHeat The sensors run HOT for secondsOfHeat seconds and then are cool for\n * secondsOfHeat seconds. Ideally, secondsOfHeat should be a divisor of 60.\n */\n public OscillatingSensorReadingSupplier(long secondsOfHeat) {\n this.secondsOfHeat = secondsOfHeat;\n }\n\n @Override\n public SensorReading get() {\n final long deviceId = 0;\n final Instant now = Instant.now();\n final long secondsInTheCurrentMinute = now.getEpochSecond() % 60;\n final long temp =\n ((secondsInTheCurrentMinute % (2 * secondsOfHeat)) < secondsOfHeat)\n ? HOT + 10L\n : HOT - 10L;\n\n return new SensorReading(deviceId, temp, now);\n }\n}"
},
{
"identifier": "RisingSensorReadingSupplier",
"path": "pattern-matching-cep/src/test/java/io/confluent/developer/cookbook/flink/records/RisingSensorReadingSupplier.java",
"snippet": "public class RisingSensorReadingSupplier implements Supplier<SensorReading> {\n private long temp;\n\n public RisingSensorReadingSupplier(long initialTemp) {\n this.temp = initialTemp;\n }\n\n @Override\n public SensorReading get() {\n final long deviceId = 0;\n final Instant now = Instant.now();\n\n return new SensorReading(deviceId, temp++, now);\n }\n}"
},
{
"identifier": "SensorReading",
"path": "pattern-matching-cep/src/main/java/io/confluent/developer/cookbook/flink/records/SensorReading.java",
"snippet": "public class SensorReading {\n\n public static long HOT = 50L;\n\n // A Flink POJO must have public fields, or getters and setters\n public long deviceId;\n public long temperature;\n\n // Serialize the timestamps in ISO-8601 format for greater compatibility\n @JsonFormat(\n shape = JsonFormat.Shape.STRING,\n pattern = \"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'\",\n timezone = \"UTC\")\n public Instant timestamp;\n\n // A Flink POJO must have a no-args default constructor\n public SensorReading() {}\n\n public SensorReading(final long deviceId, final long temperature, final Instant timestamp) {\n this.deviceId = deviceId;\n this.temperature = temperature;\n this.timestamp = timestamp;\n }\n\n public boolean sensorIsHot() {\n return temperature >= HOT;\n }\n\n public boolean sensorIsCool() {\n return temperature < HOT;\n }\n\n // Used for printing during development\n @Override\n public String toString() {\n return \"Event{\"\n + \"deviceId=\"\n + deviceId\n + \", temperature='\"\n + temperature\n + '\\''\n + \", timestamp=\"\n + timestamp\n + '}';\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) {\n return true;\n }\n\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n\n SensorReading sensorReading = (SensorReading) o;\n\n return (deviceId == sensorReading.deviceId)\n && (temperature == sensorReading.temperature)\n && timestamp.equals(sensorReading.timestamp);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(deviceId, temperature, timestamp);\n }\n}"
},
{
"identifier": "SensorReadingDeserializationSchema",
"path": "pattern-matching-cep/src/main/java/io/confluent/developer/cookbook/flink/records/SensorReadingDeserializationSchema.java",
"snippet": "public class SensorReadingDeserializationSchema\n extends AbstractDeserializationSchema<SensorReading> {\n\n private static final long serialVersionUID = 1L;\n\n private transient ObjectMapper objectMapper;\n\n /**\n * For performance reasons it's better to create on ObjectMapper in this open method rather than\n * creating a new ObjectMapper for every record.\n */\n @Override\n public void open(InitializationContext context) {\n // JavaTimeModule is needed for Java 8 data time (Instant) support\n objectMapper = JsonMapper.builder().build().registerModule(new JavaTimeModule());\n }\n\n @Override\n public SensorReading deserialize(byte[] message) throws IOException {\n return objectMapper.readValue(message, SensorReading.class);\n }\n}"
},
{
"identifier": "CookbookKafkaCluster",
"path": "compiled-plan/src/test/java/io/confluent/developer/cookbook/flink/utils/CookbookKafkaCluster.java",
"snippet": "public class CookbookKafkaCluster extends EmbeddedKafkaCluster {\n\n private static final ObjectMapper OBJECT_MAPPER =\n JsonMapper.builder().build().registerModule(new JavaTimeModule());\n\n public CookbookKafkaCluster() {\n super(EmbeddedKafkaClusterConfig.defaultClusterConfig());\n\n this.start();\n }\n\n /**\n * Creates a topic with the given name and synchronously writes all data from the given stream\n * to that topic.\n *\n * @param topic topic to create\n * @param topicData data to write\n * @param <EVENT> event type\n */\n public <EVENT> void createTopic(String topic, Stream<EVENT> topicData) {\n createTopic(TopicConfig.withName(topic));\n topicData.forEach(record -> sendEventAsJSON(topic, record));\n }\n\n /**\n * Creates a topic with the given name and asynchronously writes all data from the given stream\n * to that topic.\n *\n * @param topic topic to create\n * @param topicData data to write\n * @param <EVENT> event type\n */\n public <EVENT> void createTopicAsync(String topic, Stream<EVENT> topicData) {\n createTopic(TopicConfig.withName(topic));\n new Thread(() -> topicData.forEach(record -> sendEventAsJSON(topic, record)), \"Generator\")\n .start();\n }\n\n /**\n * Sends one JSON-encoded event to the topic and sleeps for 100ms.\n *\n * @param event An event to send to the topic.\n */\n private <EVENT> void sendEventAsJSON(String topic, EVENT event) {\n try {\n final SendValues<String> sendRequest =\n SendValues.to(topic, OBJECT_MAPPER.writeValueAsString(event)).build();\n this.send(sendRequest);\n Thread.sleep(100);\n } catch (InterruptedException | JsonProcessingException e) {\n throw new RuntimeException(e);\n }\n }\n}"
}
] | import static io.confluent.developer.cookbook.flink.PatternMatchingCEP.TOPIC;
import static io.confluent.developer.cookbook.flink.records.SensorReading.HOT;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertThrows;
import io.confluent.developer.cookbook.flink.extensions.MiniClusterExtensionFactory;
import io.confluent.developer.cookbook.flink.patterns.MatcherV1;
import io.confluent.developer.cookbook.flink.patterns.MatcherV2;
import io.confluent.developer.cookbook.flink.patterns.MatcherV3;
import io.confluent.developer.cookbook.flink.patterns.PatternMatcher;
import io.confluent.developer.cookbook.flink.records.OscillatingSensorReadingSupplier;
import io.confluent.developer.cookbook.flink.records.RisingSensorReadingSupplier;
import io.confluent.developer.cookbook.flink.records.SensorReading;
import io.confluent.developer.cookbook.flink.records.SensorReadingDeserializationSchema;
import io.confluent.developer.cookbook.flink.utils.CookbookKafkaCluster;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
import org.apache.flink.connector.kafka.source.KafkaSource;
import org.apache.flink.connector.kafka.source.enumerator.initializer.OffsetsInitializer;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.test.junit5.MiniClusterExtension;
import org.apache.flink.types.PojoTestUtils;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension; | 4,277 | package io.confluent.developer.cookbook.flink;
class PatternMatchingCEPTest {
@RegisterExtension
static final MiniClusterExtension FLINK =
MiniClusterExtensionFactory.withDefaultConfiguration();
private static final int EVENTS_PER_SECOND = 10;
/**
* Verify that Flink recognizes the SensorReading type as a POJO that it can serialize
* efficiently.
*/
@Test
void sensorReadingsAreAPOJOs() {
PojoTestUtils.assertSerializedAsPojo(SensorReading.class);
}
@Test
void matcherV2FindsMoreThanOneRisingHotStreak() throws Exception {
Duration limitOfHeatTolerance = Duration.ofSeconds(1);
long secondsOfData = 3;
PatternMatcher<SensorReading, SensorReading> matcherV2 = new MatcherV2();
assertThat(risingHotStreaks(HOT - 1, secondsOfData, matcherV2, limitOfHeatTolerance))
.hasSizeGreaterThan(1);
}
@Test
void matcherV3FindsOneRisingHotStreak() throws Exception {
Duration limitOfHeatTolerance = Duration.ofSeconds(1);
long secondsOfData = 3;
PatternMatcher<SensorReading, SensorReading> matcherV3 = new MatcherV3();
assertThat(risingHotStreaks(HOT - 1, secondsOfData, matcherV3, limitOfHeatTolerance))
.hasSize(1);
}
@Test
void matcherV2FindsAnOscillatingHotStreak() throws Exception {
long secondsOfHeat = 3;
Duration limitOfHeatTolerance = Duration.ofSeconds(2);
PatternMatcher<SensorReading, SensorReading> matcherV2 = new MatcherV2();
assertThat(oscillatingHotStreaks(secondsOfHeat, matcherV2, limitOfHeatTolerance))
.isNotEmpty();
}
@Test
void matcherV3FindsAnOscillatingHotStreak() throws Exception {
long secondsOfHeat = 3;
Duration limitOfHeatTolerance = Duration.ofSeconds(2);
PatternMatcher<SensorReading, SensorReading> matcherV3 = new MatcherV3();
assertThat(oscillatingHotStreaks(secondsOfHeat, matcherV3, limitOfHeatTolerance))
.isNotEmpty();
}
@Test
void matcherV1ErroneouslyFindsOscillatingHotStreaks() {
long secondsOfHeat = 1;
Duration limitOfHeatTolerance = Duration.ofSeconds(2);
PatternMatcher<SensorReading, SensorReading> matcherV1 = new MatcherV1();
assertThrows(
AssertionError.class,
() ->
assertThat(
oscillatingHotStreaks(
secondsOfHeat, matcherV1, limitOfHeatTolerance))
.isEmpty());
}
@Test
void matcherV2FindsNoOscillatingHotStreaks() throws Exception {
long secondsOfHeat = 1;
Duration limitOfHeatTolerance = Duration.ofSeconds(2);
PatternMatcher<SensorReading, SensorReading> matcherV2 = new MatcherV2();
assertThat(oscillatingHotStreaks(secondsOfHeat, matcherV2, limitOfHeatTolerance)).isEmpty();
}
@Test
void matcherV3FindsNoOscillatingHotStreaks() throws Exception {
long secondsOfHeat = 1;
Duration limitOfHeatTolerance = Duration.ofSeconds(2);
PatternMatcher<SensorReading, SensorReading> matcherV3 = new MatcherV3();
assertThat(oscillatingHotStreaks(secondsOfHeat, matcherV3, limitOfHeatTolerance)).isEmpty();
}
private List<SensorReading> risingHotStreaks(
long initialTemp,
long secondsOfData,
PatternMatcher<SensorReading, SensorReading> matcher,
Duration limitOfHeatTolerance)
throws Exception {
Stream<SensorReading> readings =
Stream.generate(new RisingSensorReadingSupplier(initialTemp))
.limit(secondsOfData * EVENTS_PER_SECOND);
return runTestJob(readings, matcher, limitOfHeatTolerance);
}
private List<SensorReading> oscillatingHotStreaks(
long secondsOfHeat,
PatternMatcher<SensorReading, SensorReading> matcher,
Duration limitOfHeatTolerance)
throws Exception {
Stream<SensorReading> readings =
Stream.generate(new OscillatingSensorReadingSupplier(secondsOfHeat))
.limit(3 * secondsOfHeat * EVENTS_PER_SECOND);
return runTestJob(readings, matcher, limitOfHeatTolerance);
}
private List<SensorReading> runTestJob(
Stream<SensorReading> stream,
PatternMatcher<SensorReading, SensorReading> patternMatcher,
Duration limitOfHeatTolerance)
throws Exception {
| package io.confluent.developer.cookbook.flink;
class PatternMatchingCEPTest {
@RegisterExtension
static final MiniClusterExtension FLINK =
MiniClusterExtensionFactory.withDefaultConfiguration();
private static final int EVENTS_PER_SECOND = 10;
/**
* Verify that Flink recognizes the SensorReading type as a POJO that it can serialize
* efficiently.
*/
@Test
void sensorReadingsAreAPOJOs() {
PojoTestUtils.assertSerializedAsPojo(SensorReading.class);
}
@Test
void matcherV2FindsMoreThanOneRisingHotStreak() throws Exception {
Duration limitOfHeatTolerance = Duration.ofSeconds(1);
long secondsOfData = 3;
PatternMatcher<SensorReading, SensorReading> matcherV2 = new MatcherV2();
assertThat(risingHotStreaks(HOT - 1, secondsOfData, matcherV2, limitOfHeatTolerance))
.hasSizeGreaterThan(1);
}
@Test
void matcherV3FindsOneRisingHotStreak() throws Exception {
Duration limitOfHeatTolerance = Duration.ofSeconds(1);
long secondsOfData = 3;
PatternMatcher<SensorReading, SensorReading> matcherV3 = new MatcherV3();
assertThat(risingHotStreaks(HOT - 1, secondsOfData, matcherV3, limitOfHeatTolerance))
.hasSize(1);
}
@Test
void matcherV2FindsAnOscillatingHotStreak() throws Exception {
long secondsOfHeat = 3;
Duration limitOfHeatTolerance = Duration.ofSeconds(2);
PatternMatcher<SensorReading, SensorReading> matcherV2 = new MatcherV2();
assertThat(oscillatingHotStreaks(secondsOfHeat, matcherV2, limitOfHeatTolerance))
.isNotEmpty();
}
@Test
void matcherV3FindsAnOscillatingHotStreak() throws Exception {
long secondsOfHeat = 3;
Duration limitOfHeatTolerance = Duration.ofSeconds(2);
PatternMatcher<SensorReading, SensorReading> matcherV3 = new MatcherV3();
assertThat(oscillatingHotStreaks(secondsOfHeat, matcherV3, limitOfHeatTolerance))
.isNotEmpty();
}
@Test
void matcherV1ErroneouslyFindsOscillatingHotStreaks() {
long secondsOfHeat = 1;
Duration limitOfHeatTolerance = Duration.ofSeconds(2);
PatternMatcher<SensorReading, SensorReading> matcherV1 = new MatcherV1();
assertThrows(
AssertionError.class,
() ->
assertThat(
oscillatingHotStreaks(
secondsOfHeat, matcherV1, limitOfHeatTolerance))
.isEmpty());
}
@Test
void matcherV2FindsNoOscillatingHotStreaks() throws Exception {
long secondsOfHeat = 1;
Duration limitOfHeatTolerance = Duration.ofSeconds(2);
PatternMatcher<SensorReading, SensorReading> matcherV2 = new MatcherV2();
assertThat(oscillatingHotStreaks(secondsOfHeat, matcherV2, limitOfHeatTolerance)).isEmpty();
}
@Test
void matcherV3FindsNoOscillatingHotStreaks() throws Exception {
long secondsOfHeat = 1;
Duration limitOfHeatTolerance = Duration.ofSeconds(2);
PatternMatcher<SensorReading, SensorReading> matcherV3 = new MatcherV3();
assertThat(oscillatingHotStreaks(secondsOfHeat, matcherV3, limitOfHeatTolerance)).isEmpty();
}
private List<SensorReading> risingHotStreaks(
long initialTemp,
long secondsOfData,
PatternMatcher<SensorReading, SensorReading> matcher,
Duration limitOfHeatTolerance)
throws Exception {
Stream<SensorReading> readings =
Stream.generate(new RisingSensorReadingSupplier(initialTemp))
.limit(secondsOfData * EVENTS_PER_SECOND);
return runTestJob(readings, matcher, limitOfHeatTolerance);
}
private List<SensorReading> oscillatingHotStreaks(
long secondsOfHeat,
PatternMatcher<SensorReading, SensorReading> matcher,
Duration limitOfHeatTolerance)
throws Exception {
Stream<SensorReading> readings =
Stream.generate(new OscillatingSensorReadingSupplier(secondsOfHeat))
.limit(3 * secondsOfHeat * EVENTS_PER_SECOND);
return runTestJob(readings, matcher, limitOfHeatTolerance);
}
private List<SensorReading> runTestJob(
Stream<SensorReading> stream,
PatternMatcher<SensorReading, SensorReading> patternMatcher,
Duration limitOfHeatTolerance)
throws Exception {
| try (final CookbookKafkaCluster kafka = new CookbookKafkaCluster(EVENTS_PER_SECOND)) { | 11 | 2023-11-20 16:31:54+00:00 | 8k |
objectionary/opeo-maven-plugin | src/main/java/org/eolang/opeo/jeo/JeoDecompiler.java | [
{
"identifier": "DecompilerMachine",
"path": "src/main/java/org/eolang/opeo/decompilation/DecompilerMachine.java",
"snippet": "public final class DecompilerMachine {\n\n /**\n * Output Stack.\n */\n private final Deque<AstNode> stack;\n\n /**\n * Local variables.\n */\n private final LocalVariables locals;\n\n /**\n * Instruction handlers.\n */\n private final Map<Integer, InstructionHandler> handlers;\n\n /**\n * Arguments provided to decompiler.\n */\n private final Map<String, String> arguments;\n\n /**\n * Constructor.\n */\n public DecompilerMachine() {\n this(new HashMap<>());\n }\n\n /**\n * Constructor.\n * @param args Arguments provided to decompiler.\n */\n public DecompilerMachine(final Map<String, String> args) {\n this(new LocalVariables(), args);\n }\n\n /**\n * Constructor.\n * @param locals Local variables.\n * @param arguments Arguments provided to decompiler.\n */\n public DecompilerMachine(final LocalVariables locals, final Map<String, String> arguments) {\n this.stack = new LinkedList<>();\n this.locals = locals;\n this.arguments = arguments;\n this.handlers = new MapOf<>(\n new MapEntry<>(Opcodes.ICONST_1, new IconstHandler()),\n new MapEntry<>(Opcodes.ICONST_2, new IconstHandler()),\n new MapEntry<>(Opcodes.ICONST_3, new IconstHandler()),\n new MapEntry<>(Opcodes.ICONST_4, new IconstHandler()),\n new MapEntry<>(Opcodes.ICONST_5, new IconstHandler()),\n new MapEntry<>(Opcodes.IADD, new AddHandler()),\n new MapEntry<>(Opcodes.IMUL, new MulHandler()),\n new MapEntry<>(Opcodes.ILOAD, new LoadHandler(Type.INT_TYPE)),\n new MapEntry<>(Opcodes.LLOAD, new LoadHandler(Type.LONG_TYPE)),\n new MapEntry<>(Opcodes.FLOAD, new LoadHandler(Type.FLOAT_TYPE)),\n new MapEntry<>(Opcodes.DLOAD, new LoadHandler(Type.DOUBLE_TYPE)),\n new MapEntry<>(Opcodes.ALOAD, new LoadHandler(Type.getType(Object.class))),\n new MapEntry<>(Opcodes.ISTORE, new StoreHandler(Type.INT_TYPE)),\n new MapEntry<>(Opcodes.LSTORE, new StoreHandler(Type.LONG_TYPE)),\n new MapEntry<>(Opcodes.FSTORE, new StoreHandler(Type.FLOAT_TYPE)),\n new MapEntry<>(Opcodes.DSTORE, new StoreHandler(Type.DOUBLE_TYPE)),\n new MapEntry<>(Opcodes.ASTORE, new StoreHandler(Type.getType(Object.class))),\n new MapEntry<>(Opcodes.NEW, new NewHandler()),\n new MapEntry<>(Opcodes.DUP, new DupHandler()),\n new MapEntry<>(Opcodes.BIPUSH, new BipushHandler()),\n new MapEntry<>(Opcodes.INVOKESPECIAL, new InvokespecialHandler()),\n new MapEntry<>(Opcodes.INVOKEVIRTUAL, new InvokevirtualHandler()),\n new MapEntry<>(Opcodes.GETFIELD, new GetFieldHandler()),\n new MapEntry<>(Opcodes.PUTFIELD, new PutFieldHnadler()),\n new MapEntry<>(Opcodes.LDC, new LdcHandler()),\n new MapEntry<>(Opcodes.POP, new PopHandler()),\n new MapEntry<>(Opcodes.RETURN, new ReturnHandler()),\n new MapEntry<>(JeoLabel.LABEL_OPCODE, new LabelHandler())\n );\n }\n\n /**\n * Decompile instructions into directives.\n * @param instructions Instructions to decompile.\n * @return Decompiled instructions.\n */\n public Iterable<Directive> decompileToXmir(final Instruction... instructions) {\n Arrays.stream(instructions)\n .forEach(inst -> this.handler(inst.opcode()).handle(inst));\n return new Root(new ListOf<>(this.stack.descendingIterator())).toXmir();\n }\n\n /**\n * Decompile instructions.\n * @param instructions Instructions to decompile.\n * @return Decompiled code.\n */\n public String decompile(final Instruction... instructions) {\n Arrays.stream(instructions)\n .forEach(inst -> this.handler(inst.opcode()).handle(inst));\n return new Root(new ListOf<>(this.stack.descendingIterator())).print();\n }\n\n /**\n * Do we add number to opcode name or not?\n * if true then we add number to opcode name:\n * RETURN -> RETURN-1\n * if false then we do not add number to opcode name:\n * RETURN -> RETURN\n * @return Opcodes counting.\n */\n private boolean counting() {\n return this.arguments.getOrDefault(\"counting\", \"true\").equals(\"true\");\n }\n\n /**\n * Get instruction handler.\n * @param opcode Instruction opcode.\n * @return Instruction handler.\n */\n private InstructionHandler handler(final int opcode) {\n return this.handlers.getOrDefault(opcode, new UnimplementedHandler());\n }\n\n /**\n * Pops n arguments from the stack.\n * @param number Number of arguments to pop.\n * @return List of arguments.\n */\n private List<AstNode> popArguments(final int number) {\n final List<AstNode> args = new LinkedList<>();\n for (int index = 0; index < number; ++index) {\n args.add(this.stack.pop());\n }\n return args;\n }\n\n /**\n * Instruction handler.\n * @since 0.1\n */\n private interface InstructionHandler {\n\n /**\n * Handle instruction.\n * @param instruction Instruction to handle.\n */\n void handle(Instruction instruction);\n\n }\n\n /**\n * Aload instruction handler.\n * @since 0.1\n */\n private final class LoadHandler implements InstructionHandler {\n\n /**\n * Type of the variable.\n */\n private final Type type;\n\n /**\n * Constructor.\n * @param type Type of the variable.\n */\n private LoadHandler(final Type type) {\n this.type = type;\n }\n\n @Override\n public void handle(final Instruction instruction) {\n DecompilerMachine.this.stack.push(\n DecompilerMachine.this.locals.variable(\n (Integer) instruction.operands().get(0),\n this.type,\n true\n )\n );\n }\n\n }\n\n /**\n * Store instruction handler.\n * @since 0.1\n */\n private final class StoreHandler implements InstructionHandler {\n\n /**\n * Type of the variable.\n */\n private final Type type;\n\n /**\n * Constructor.\n * @param type Type of the variable.\n */\n private StoreHandler(final Type type) {\n this.type = type;\n }\n\n @Override\n public void handle(final Instruction instruction) {\n DecompilerMachine.this.stack.push(\n new StoreLocal(\n DecompilerMachine.this.locals.variable(\n (Integer) instruction.operands().get(0),\n this.type,\n false\n ),\n DecompilerMachine.this.stack.pop()\n )\n );\n }\n }\n\n /**\n * New instruction handler.\n * @since 0.1\n */\n private class NewHandler implements InstructionHandler {\n @Override\n public void handle(final Instruction instruction) {\n DecompilerMachine.this.stack.push(new Reference());\n }\n\n }\n\n /**\n * Getfield instruction handler.\n * @since 0.1\n */\n private class GetFieldHandler implements InstructionHandler {\n\n @Override\n public void handle(final Instruction instruction) {\n final String owner = (String) instruction.operand(0);\n final String name = (String) instruction.operand(1);\n final String descriptor = (String) instruction.operand(2);\n DecompilerMachine.this.stack.push(\n new InstanceField(\n DecompilerMachine.this.stack.pop(),\n new Attributes()\n .name(name)\n .descriptor(descriptor)\n .owner(owner)\n .type(\"field\")\n )\n );\n }\n }\n\n /**\n * Putfield instruction handler.\n * @since 0.1\n */\n private class PutFieldHnadler implements InstructionHandler {\n\n @Override\n public void handle(final Instruction instruction) {\n final AstNode value = DecompilerMachine.this.stack.pop();\n final AstNode target = DecompilerMachine.this.stack.pop();\n final Attributes attributes = new Attributes()\n .type(\"field\")\n .owner((String) instruction.operand(0))\n .name((String) instruction.operand(1))\n .descriptor((String) instruction.operand(2));\n DecompilerMachine.this.stack.push(\n new WriteField(target, value, attributes)\n );\n }\n }\n\n /**\n * Dup instruction handler.\n * @since 0.1\n */\n private class DupHandler implements InstructionHandler {\n @Override\n public void handle(final Instruction instruction) {\n DecompilerMachine.this.stack.push(DecompilerMachine.this.stack.peek());\n }\n\n }\n\n /**\n * Bipush instruction handler.\n * @since 0.1\n */\n private class BipushHandler implements InstructionHandler {\n @Override\n public void handle(final Instruction instruction) {\n DecompilerMachine.this.stack.push(new Literal(instruction.operand(0)));\n }\n\n }\n\n /**\n * Pop instruction handler.\n * @since 0.1\n */\n private class PopHandler implements InstructionHandler {\n @Override\n public void handle(final Instruction ignore) {\n // We ignore this instruction intentionally.\n }\n\n }\n\n /**\n * Return instruction handler.\n * @since 0.1\n */\n private class ReturnHandler implements InstructionHandler {\n @Override\n public void handle(final Instruction instruction) {\n DecompilerMachine.this.stack.push(\n new Opcode(\n instruction.opcode(),\n instruction.operands(),\n DecompilerMachine.this.counting()\n )\n );\n }\n\n }\n\n /**\n * Invokespecial instruction handler.\n * @since 0.1\n */\n private class InvokespecialHandler implements InstructionHandler {\n @Override\n public void handle(final Instruction instruction) {\n if (!instruction.operand(1).equals(\"<init>\")) {\n throw new UnsupportedOperationException(\n String.format(\"Instruction %s is not supported yet\", instruction)\n );\n }\n final String descriptor = (String) instruction.operand(2);\n final List<AstNode> args = DecompilerMachine.this.popArguments(\n Type.getArgumentCount(descriptor)\n );\n final String target = (String) instruction.operand(0);\n //@checkstyle MethodBodyCommentsCheck (10 lines)\n // @todo #76:90min Target might not be an Object.\n // Here we just compare with object, but if the current class has a parent, the\n // target might not be an Object. We should compare with the current class name\n // instead. Moreover, we have to pass the 'target' as an argument to the\n // constructor of the 'Super' class somehow.\n if (\"java/lang/Object\".equals(target)) {\n DecompilerMachine.this.stack.push(\n new Super(DecompilerMachine.this.stack.pop(), args, descriptor)\n );\n } else {\n ((Reference) DecompilerMachine.this.stack.pop())\n .link(new Constructor(target, args));\n }\n }\n }\n\n /**\n * Invokevirtual instruction handler.\n * @since 0.1\n */\n private class InvokevirtualHandler implements InstructionHandler {\n @Override\n public void handle(final Instruction instruction) {\n final String owner = (String) instruction.operand(0);\n final String method = (String) instruction.operand(1);\n final String descriptor = (String) instruction.operand(2);\n final List<AstNode> args = DecompilerMachine.this.popArguments(\n Type.getArgumentCount(descriptor)\n );\n final AstNode source = DecompilerMachine.this.stack.pop();\n DecompilerMachine.this.stack.push(\n new Invocation(\n source, new Attributes().name(method).descriptor(descriptor).owner(owner), args\n )\n );\n }\n\n }\n\n /**\n * Ldc instruction handler.\n * @since 0.1\n */\n private class LdcHandler implements InstructionHandler {\n @Override\n public void handle(final Instruction instruction) {\n DecompilerMachine.this.stack.push(new Literal(instruction.operand(0)));\n }\n\n }\n\n /**\n * Unimplemented instruction handler.\n * @since 0.1\n */\n private class UnimplementedHandler implements InstructionHandler {\n @Override\n public void handle(final Instruction instruction) {\n DecompilerMachine.this.stack.push(\n new Opcode(\n instruction.opcode(),\n instruction.operands(),\n DecompilerMachine.this.counting()\n )\n );\n }\n\n }\n\n /**\n * Add instruction handler.\n * @since 0.1\n */\n private class AddHandler implements InstructionHandler {\n @Override\n public void handle(final Instruction instruction) {\n if (instruction.opcode() == Opcodes.IADD) {\n final AstNode right = DecompilerMachine.this.stack.pop();\n final AstNode left = DecompilerMachine.this.stack.pop();\n DecompilerMachine.this.stack.push(new Add(left, right));\n } else {\n DecompilerMachine.this.stack.push(\n new Opcode(\n instruction.opcode(),\n instruction.operands(),\n DecompilerMachine.this.counting()\n )\n );\n }\n }\n }\n\n /**\n * Mul instruction handler.\n * @since 0.1\n */\n private class MulHandler implements InstructionHandler {\n @Override\n public void handle(final Instruction instruction) {\n if (instruction.opcode() == Opcodes.IMUL) {\n final AstNode right = DecompilerMachine.this.stack.pop();\n final AstNode left = DecompilerMachine.this.stack.pop();\n DecompilerMachine.this.stack.push(new Mul(left, right));\n } else {\n DecompilerMachine.this.stack.push(\n new Opcode(\n instruction.opcode(),\n instruction.operands(),\n DecompilerMachine.this.counting()\n )\n );\n }\n }\n }\n\n /**\n * Iconst instruction handler.\n * @since 0.1\n */\n private class IconstHandler implements InstructionHandler {\n\n @Override\n public void handle(final Instruction instruction) {\n switch (instruction.opcode()) {\n case Opcodes.ICONST_1:\n DecompilerMachine.this.stack.push(new Literal(1));\n break;\n case Opcodes.ICONST_2:\n DecompilerMachine.this.stack.push(new Literal(2));\n break;\n case Opcodes.ICONST_3:\n DecompilerMachine.this.stack.push(new Literal(3));\n break;\n case Opcodes.ICONST_4:\n DecompilerMachine.this.stack.push(new Literal(4));\n break;\n case Opcodes.ICONST_5:\n DecompilerMachine.this.stack.push(new Literal(5));\n break;\n default:\n throw new UnsupportedOperationException(\n String.format(\"Instruction %s is not supported yet\", instruction)\n );\n }\n }\n }\n\n /**\n * Label instruction handler.\n * @since 0.1\n */\n private class LabelHandler implements InstructionHandler {\n\n @Override\n public void handle(final Instruction instruction) {\n DecompilerMachine.this.stack.push(\n new Label(new Literal(instruction.operand(0)))\n );\n }\n }\n}"
},
{
"identifier": "LocalVariables",
"path": "src/main/java/org/eolang/opeo/decompilation/LocalVariables.java",
"snippet": "public final class LocalVariables {\n\n /**\n * Method access modifiers.\n */\n private final int modifiers;\n\n /**\n * Constructor.\n */\n public LocalVariables() {\n this(Opcodes.ACC_PUBLIC);\n }\n\n /**\n * Constructor.\n * @param modifiers Method access modifiers.\n */\n public LocalVariables(final int modifiers) {\n this.modifiers = modifiers;\n }\n\n /**\n * Get variable by index.\n * @param index Index.\n * @param type Type.\n * @param load Load or store.\n * @return Variable.\n */\n public AstNode variable(final int index, final Type type, final boolean load) {\n final AstNode result;\n if (index == 0 && (this.modifiers & Opcodes.ACC_STATIC) == 0) {\n result = new This();\n } else if (load) {\n result = new Variable(type, Variable.Operation.LOAD, index);\n } else {\n result = new Variable(type, Variable.Operation.STORE, index);\n }\n return result;\n }\n}"
}
] | import org.eolang.opeo.decompilation.DecompilerMachine;
import org.eolang.opeo.decompilation.LocalVariables;
import org.w3c.dom.Node;
import org.xembly.Transformers;
import org.xembly.Xembler;
import com.jcabi.xml.XML;
import com.jcabi.xml.XMLDocument;
import java.util.Map;
import java.util.stream.Collectors;
import org.eolang.jeo.representation.xmir.XmlMethod;
import org.eolang.jeo.representation.xmir.XmlNode;
import org.eolang.jeo.representation.xmir.XmlProgram; | 4,671 | /*
* The MIT License (MIT)
*
* Copyright (c) 2016-2023 Objectionary.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. 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 org.eolang.opeo.jeo;
/**
* Decompiler that gets jeo instructions and decompiles them into high-level EO constructs.
* @since 0.1
*/
public final class JeoDecompiler {
/**
* Program in XMIR format received from jeo maven plugin.
*/
private final XML prog;
/**
* Constructor.
* @param prog Program in XMIR format received from jeo maven plugin.
*/
public JeoDecompiler(final XML prog) {
this.prog = prog;
}
/**
* Decompile program.
* @return EO program.
*/
public XML decompile() {
final Node node = this.prog.node();
new XmlProgram(node).top()
.methods()
.forEach(JeoDecompiler::decompile);
return new XMLDocument(node);
}
/**
* Decompile method.
* @param method Method.
*/
private static void decompile(final XmlMethod method) {
if (!method.instructions().isEmpty()) {
method.replaceInstructions(
new XmlNode(
new Xembler(
new DecompilerMachine( | /*
* The MIT License (MIT)
*
* Copyright (c) 2016-2023 Objectionary.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. 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 org.eolang.opeo.jeo;
/**
* Decompiler that gets jeo instructions and decompiles them into high-level EO constructs.
* @since 0.1
*/
public final class JeoDecompiler {
/**
* Program in XMIR format received from jeo maven plugin.
*/
private final XML prog;
/**
* Constructor.
* @param prog Program in XMIR format received from jeo maven plugin.
*/
public JeoDecompiler(final XML prog) {
this.prog = prog;
}
/**
* Decompile program.
* @return EO program.
*/
public XML decompile() {
final Node node = this.prog.node();
new XmlProgram(node).top()
.methods()
.forEach(JeoDecompiler::decompile);
return new XMLDocument(node);
}
/**
* Decompile method.
* @param method Method.
*/
private static void decompile(final XmlMethod method) {
if (!method.instructions().isEmpty()) {
method.replaceInstructions(
new XmlNode(
new Xembler(
new DecompilerMachine( | new LocalVariables(method.access()), | 1 | 2023-11-20 13:01:13+00:00 | 8k |
GregTech-Chinese-Community/EPCore | src/main/java/cn/gtcommunity/epimorphism/api/capability/impl/OreProcessingLogic.java | [
{
"identifier": "EPUniverUtil",
"path": "src/main/java/cn/gtcommunity/epimorphism/api/utils/EPUniverUtil.java",
"snippet": "public class EPUniverUtil {\n\n // Utils\n public static int getOrDefault(NBTTagCompound tag, String key, int defaultValue){\n if(tag.hasKey(key)){\n return tag.getInteger(key);\n }\n return defaultValue;\n }\n\n public static <T> T getOrDefault(BooleanSupplier canGet, Supplier<T> getter, T defaultValue){\n return canGet.getAsBoolean() ? getter.get() : defaultValue;\n }\n\n // List Utils\n public static <T> int maxLength(List<List<T>> lists) {\n return lists.stream().mapToInt(List::size).max().orElse(0);\n }\n\n public static <T> List<T> consistentList(List<T> list, int length) {\n if (list.size() >= length) {\n return list;\n }\n List<T> finalList = new ArrayList<>(list);\n T last = list.get(list.size() - 1);\n for (int i = 0; i < length - list.size(); i++) {\n finalList.add(last);\n }\n return finalList;\n }\n\n // Set Utils\n public static int intValueOfBitSet(BitSet set){\n int result = 0;\n for(int i = 0; i<set.length();i++){\n result = result | (set.get(i)?1:0) << i;\n }\n return result;\n }\n\n public static BitSet forIntToBitSet(int i,int length){\n return forIntToBitSet(i,length,new BitSet(length));\n }\n\n public static BitSet forIntToBitSet(int i,int length,BitSet result){\n for(int j = 0;j<length;j++){\n if(((i & ( 0b1 << j)) / ( 0b1 << j)) == 1){\n result.set(j);\n }\n else {\n result.clear(j);\n }\n }\n return result;\n }\n\n // Face Utils\n public static EnumFacing getFacingFromNeighbor(BlockPos pos, BlockPos neighbor){\n BlockPos rel = neighbor.subtract(pos);\n if(rel.getX() == 1){\n return EAST;\n }\n if(rel.getX() == -1){\n return WEST;\n }\n if(rel.getY() == 1){\n return UP;\n }\n if(rel.getY() == -1){\n return DOWN;\n }\n if(rel.getZ() == 1){\n return SOUTH;\n }\n return NORTH;\n }\n\n public static EnumFacing getCounterClockWise(EnumFacing self) {\n\n return switch (self) {\n case NORTH -> WEST;\n case SOUTH -> EAST;\n case WEST -> SOUTH;\n case EAST -> NORTH;\n default -> throw new IllegalStateException(\"Unable to get CCW facing of \" + self);\n };\n }\n\n public static EnumFacing getClockWise(EnumFacing self) {\n\n return switch (self) {\n case NORTH -> EAST;\n case SOUTH -> WEST;\n case WEST -> NORTH;\n case EAST -> SOUTH;\n default -> throw new IllegalStateException(\"Unable to get Y-rotated facing of \" + self);\n };\n }\n\n // Item Utils\n public static int stackToInt(ItemStack stack) {\n if (isStackInvalid(stack)) return 0;\n return itemToInt(stack.getItem(), stack.getMetadata());\n }\n\n public static int itemToInt(Item item, int meta) {\n return Item.getIdFromItem(item) | (meta << 16);\n }\n\n public static boolean isStackInvalid(Object stack) {\n return !(stack instanceof ItemStack) || ((ItemStack) stack).getCount() < 0;\n }\n\n public static boolean isStackValid(Object aStack) {\n return (aStack instanceof ItemStack) && ((ItemStack) aStack).getCount() >= 0;\n }\n\n public static ItemStack intToStack(int aStack) {\n int tID = aStack & (~0 >>> 16), tMeta = aStack >>> 16;\n Item tItem = Item.getItemById(tID);\n if (tItem != null) return new ItemStack(tItem, 1, tMeta);\n return null;\n }\n\n public static ItemStack copyAmountUnsafe(long aAmount, Object... aStacks) {\n ItemStack rStack = copy(aStacks);\n if (isStackInvalid(rStack)) return null;\n if (aAmount > Integer.MAX_VALUE) aAmount = Integer.MAX_VALUE;\n else if (aAmount < 0) aAmount = 0;\n rStack.setCount((int) aAmount);\n return rStack;\n }\n\n public static ItemStack copy(Object... aStacks) {\n for (Object tStack : aStacks) if (isStackValid(tStack)) return ((ItemStack) tStack).copy();\n return null;\n }\n\n // MetaTileEntity Utils\n public static <T> MetaTileEntity[] getGTTierHatches(MultiblockAbility<T> ability, int tier) {\n return MultiblockAbility.REGISTRY.get(ability).stream()\n .filter(mte -> {\n if (mte != null && mte instanceof MetaTileEntityMultiblockPart) {\n return ((MetaTileEntityMultiblockPart) mte).getTier() <= tier;\n }\n return false;\n }).toArray(MetaTileEntity[]::new);\n }\n\n public static MetaTileEntityHolder getTileEntity(MetaTileEntity tile) {\n MetaTileEntityHolder holder = new MetaTileEntityHolder();\n holder.setMetaTileEntity(tile);\n holder.getMetaTileEntity().onPlacement();\n holder.getMetaTileEntity().setFrontFacing(EnumFacing.SOUTH);\n return holder;\n }\n\n // Tier Utils\n public static int getOpticalGlassTier(int glassTier) {\n return (int) (Math.floor((double) glassTier / 2) + glassTier % 2 - 2);\n }\n}"
},
{
"identifier": "EPMetaTileEntityIntegratedOreFactory",
"path": "src/main/java/cn/gtcommunity/epimorphism/common/metatileentities/multiblock/EPMetaTileEntityIntegratedOreFactory.java",
"snippet": "public class EPMetaTileEntityIntegratedOreFactory extends MultiblockWithDisplayBase implements IDataInfoProvider {\n protected OreProcessingLogic logic;\n protected IEnergyContainer energyContainer;\n protected IMultipleTankHandler inputFluidInventory;\n protected IItemHandlerModifiable inputItemInventory;\n protected IItemHandlerModifiable outputItemInventory;\n\n public EPMetaTileEntityIntegratedOreFactory(ResourceLocation metaTileEntityId) {\n super(metaTileEntityId);\n this.logic = new OreProcessingLogic(this);\n }\n\n @Override\n public MetaTileEntity createMetaTileEntity(IGregTechTileEntity iGregTechTileEntity) {\n return new EPMetaTileEntityIntegratedOreFactory(metaTileEntityId);\n }\n\n @Override\n protected void updateFormedValid() {\n this.logic.update();\n }\n\n public IEnergyContainer getEnergyContainer() {\n return energyContainer;\n }\n\n public IItemHandlerModifiable getInputInventory() {\n return inputItemInventory;\n }\n\n public IItemHandlerModifiable getOutputInventory() {\n return outputItemInventory;\n }\n\n public IMultipleTankHandler getInputFluidInventory() {\n return inputFluidInventory;\n }\n\n\n protected void initializeAbilities() {\n this.inputFluidInventory = new FluidTankList(true, getAbilities(MultiblockAbility.IMPORT_FLUIDS));\n this.inputItemInventory = new ItemHandlerList(getAbilities(MultiblockAbility.IMPORT_ITEMS));\n this.outputItemInventory = new ItemHandlerList(getAbilities(MultiblockAbility.EXPORT_ITEMS));\n this.energyContainer = new EnergyContainerList(getAbilities(MultiblockAbility.INPUT_ENERGY));\n }\n\n private void resetTileAbilities() {\n this.inputFluidInventory = new FluidTankList(true);\n this.inputItemInventory = new ItemHandlerList(Collections.emptyList());\n this.outputItemInventory = new ItemHandlerList(Collections.emptyList());\n this.energyContainer = new EnergyContainerList(Lists.newArrayList());\n }\n\n @Override\n protected void formStructure(PatternMatchContext context) {\n super.formStructure(context);\n initializeAbilities();\n }\n\n @Override\n public void invalidateStructure() {\n super.invalidateStructure();\n resetTileAbilities();\n this.logic.invalidate();\n }\n\n @Nonnull\n @Override\n protected BlockPattern createStructurePattern() {\n return FactoryBlockPattern.start()\n .aisle(\n \"EEEEEE \",\n \"IGGGGI \",\n \"IGGGGI \",\n \"IGGGGI \",\n \"IGGGGI \",\n \"IIIIII \",\n \" \",\n \" \",\n \" \",\n \" \",\n \" \",\n \" \"\n )\n .aisle(\n \"EEEEEEEEEEE\",\n \"GT T ICCCI\",\n \"GT T ICCCI\",\n \"GT T ICCCI\",\n \"GT T ICCCI\",\n \"IOOOOIICCCI\",\n \" CCC \",\n \" CCC \",\n \" CCC \",\n \" CCC \",\n \" CCC \",\n \" \"\n )\n .aisle(\n \"EEEEEEEEEEE\",\n \"G XX C D\",\n \"G XX CPPPD\",\n \"G XX C C\",\n \"G XX CPPPC\",\n \"IOOOOIC C\",\n \" CPPPC\",\n \" C C\",\n \" CPPPC\",\n \" C C\",\n \" CPPPC\",\n \" WWW \"\n )\n .aisle(\n \"EEEEEEEEEEE\",\n \"G XX C D\",\n \"G XX CPPPD\",\n \"G XX C C\",\n \"G XX CPPPC\",\n \"IOOOOIC C\",\n \" CPPPC\",\n \" C C\",\n \" CPPPC\",\n \" C C\",\n \" CPPPC\",\n \" WWW \"\n )\n .aisle(\n \"EEEEEEEEEEE\",\n \"GT T ICCCI\",\n \"GT T ICSCI\",\n \"GT T ICCCI\",\n \"GT T ICCCI\",\n \"IOOOOIICCCI\",\n \" CCC \",\n \" CCC \",\n \" CCC \",\n \" CCC \",\n \" CCC \",\n \" \"\n )\n .aisle(\n \"EEEEEE \",\n \"IGGGGI \",\n \"IGGGGI \",\n \"IGGGGI \",\n \"IGGGGI \",\n \"IIIIII \",\n \" \",\n \" \",\n \" \",\n \" \",\n \" \",\n \" \"\n )\n .where('S', selfPredicate())\n .where('I', states(getCasingAState()))\n .where('C', states(getCasingBState()))\n .where('P', states(getBoilerState()))\n .where('G', states(getGlassState()))\n .where('T', states(getFrameState()))\n .where('X', states(getGearBoxState()))\n .where('E', states(getCasingAState()).or(abilities(MultiblockAbility.INPUT_ENERGY).setMinGlobalLimited(1)).or(abilities(MultiblockAbility.MAINTENANCE_HATCH).setMinGlobalLimited(1)))\n .where('O', states(getCasingAState()).or(abilities(MultiblockAbility.IMPORT_ITEMS)))\n .where('W', states(getCasingBState()).or(abilities(MultiblockAbility.MUFFLER_HATCH).setExactLimit(1)).or(abilities(MultiblockAbility.IMPORT_FLUIDS)))\n .where('D', states(getCasingBState()).or(abilities(MultiblockAbility.EXPORT_ITEMS)))\n .where(' ', any())\n .build();\n }\n\n private static IBlockState getCasingAState() {\n return EPMetablocks.EP_MULTIBLOCK_CASING.getState(EPBlockMultiblockCasing.CasingType.IRIDIUM_CASING);\n }\n private static IBlockState getCasingBState() {\n return MetaBlocks.METAL_CASING.getState(BlockMetalCasing.MetalCasingType.STAINLESS_CLEAN);\n }\n private static IBlockState getBoilerState() {\n return MetaBlocks.BOILER_CASING.getState(BlockBoilerCasing.BoilerCasingType.TUNGSTENSTEEL_PIPE);\n }\n private static IBlockState getGlassState() {\n return MetaBlocks.TRANSPARENT_CASING.getState(BlockGlassCasing.CasingType.LAMINATED_GLASS);\n }\n private static IBlockState getFrameState() {\n return MetaBlocks.FRAMES.get(TungstenSteel).getBlock(TungstenSteel);\n }\n private static IBlockState getGearBoxState() {\n return MetaBlocks.TURBINE_CASING.getState(BlockTurbineCasing.TurbineCasingType.STEEL_GEARBOX);\n }\n\n @SideOnly(Side.CLIENT)\n @Override\n public ICubeRenderer getBaseTexture(IMultiblockPart iMultiblockPart) {\n if ((iMultiblockPart instanceof MetaTileEntityItemBus && ((MetaTileEntityItemBus)iMultiblockPart).getExportItems().getSlots() == 0)\n || iMultiblockPart instanceof MetaTileEntityMEInputBus\n || iMultiblockPart instanceof MetaTileEntityEnergyHatch\n || iMultiblockPart instanceof IMaintenanceHatch\n ) {\n return EPTextures.IRIDIUM_CASING;\n } else {\n return Textures.CLEAN_STAINLESS_STEEL_CASING;\n }\n }\n\n @SideOnly(Side.CLIENT)\n @Nonnull\n @Override\n protected ICubeRenderer getFrontOverlay() {\n return EPTextures.CVD_UNIT_OVERLAY;\n }\n\n @SideOnly(Side.CLIENT)\n @Override\n public void renderMetaTileEntity(CCRenderState renderState, Matrix4 translation, IVertexOperation[] pipeline) {\n super.renderMetaTileEntity(renderState, translation, pipeline);\n this.getFrontOverlay().renderOrientedState(renderState, translation, pipeline, getFrontFacing(), this.logic.isActive(), this.logic.isWorkingEnabled());\n }\n\n\n @Override\n protected void addDisplayText(List<ITextComponent> textList) {\n super.addDisplayText(textList);\n if (isStructureFormed()) {\n if (this.energyContainer != null && energyContainer.getEnergyCapacity() > 0) {\n long maxVoltage = Math.max(energyContainer.getInputVoltage(), energyContainer.getOutputVoltage());\n String voltageName = GTValues.VNF[GTUtility.getFloorTierByVoltage(maxVoltage)];\n textList.add(new TextComponentTranslation(\"gregtech.multiblock.max_energy_per_tick\", TextFormattingUtil.formatNumbers(maxVoltage), voltageName));\n }\n EPLog.logger.info(logic.isActive());\n if (!logic.isWorkingEnabled()) {\n textList.add(new TextComponentTranslation(\"gregtech.multiblock.work_paused\"));\n\n } else if (logic.isActive()) {\n textList.add(new TextComponentTranslation(\"gregtech.multiblock.running\"));\n int currentProgress = (int) (logic.getProgressPercent() * 100);\n if (logic.getParallelLimit() != 1) {\n textList.add(new TextComponentTranslation(\"gregtech.multiblock.parallel\", logic.getParallelLimit()));\n }\n textList.add(new TextComponentTranslation(\"gregtech.multiblock.progress\", currentProgress));\n } else {\n textList.add(new TextComponentTranslation(\"gregtech.multiblock.idling\"));\n }\n switch (logic.getMode()) {\n case 0 -> textList.add(new TextComponentTranslation(\"epimorphism.machine.integrated_ore_factory.mode.0\"));\n\n case 1 -> textList.add(new TextComponentTranslation(\"epimorphism.machine.integrated_ore_factory.mode.1\"));\n\n case 2 -> textList.add(new TextComponentTranslation(\"epimorphism.machine.integrated_ore_factory.mode.2\"));\n\n case 3 -> textList.add(new TextComponentTranslation(\"epimorphism.machine.integrated_ore_factory.mode.3\"));\n\n case 4 -> textList.add(new TextComponentTranslation(\"epimorphism.machine.integrated_ore_factory.mode.4\"));\n\n default -> textList.add(new TextComponentTranslation(\"epimorphism.machine.integrated_ore_factory.mode.error\"));\n }\n if (!drainEnergy(true)) {\n textList.add(new TextComponentTranslation(\"gregtech.multiblock.not_enough_energy\").setStyle(new Style().setColor(TextFormatting.RED)));\n }\n }\n }\n\n @Override\n public void addInformation(ItemStack stack, @Nullable World world, @Nonnull List<String> tooltip, boolean advanced) {\n super.addInformation(stack, world, tooltip, advanced);\n tooltip.add(I18n.format(\"epimorphism.machine.integrated_ore_factory.tooltip.1\"));\n if (Keyboard.isKeyDown(Keyboard.KEY_LSHIFT)) {\n tooltip.add(I18n.format(\"epimorphism.machine.integrated_ore_factory.tooltip_shift.1\"));\n tooltip.add(I18n.format(\"epimorphism.machine.integrated_ore_factory.tooltip_shift.2\"));\n }else {\n tooltip.add(I18n.format(\"gregtech.tooltip.hold_shift\"));\n }\n }\n\n @Override\n public final boolean onScrewdriverClick(EntityPlayer playerIn, EnumHand hand, EnumFacing facing, CuboidRayTraceResult hitResult) {\n if (playerIn.isSneaking()) {\n logic.setVoidStone(!logic.isVoidStone());\n if (playerIn.getEntityWorld().isRemote) {\n playerIn.sendMessage( new TextComponentTranslation(\"epimorphism.machine.integrated_ore_factory.void.\" + logic.isVoidStone()));\n }\n }else {\n logic.setMode((logic.getMode() + 1) % 5);\n }\n return true;\n }\n\n public int getEnergyTier() {\n if (energyContainer == null) return GTValues.IV;\n return Math.max(GTValues.IV, GTUtility.getFloorTierByVoltage(energyContainer.getInputVoltage()));\n }\n\n @Override\n public boolean isActive() {\n return (isStructureFormed() && this.logic.isActive() && this.logic.isWorkingEnabled());\n }\n\n public IMultipleTankHandler getImportFluid() {\n return this.inputFluidInventory;\n }\n\n public long getEnergyInputPerSecond() {\n return energyContainer.getInputPerSec();\n }\n\n\n public boolean drainEnergy(boolean simulate) {\n long energyToDrain = GTValues.VA[getEnergyTier()];\n long resultEnergy = energyContainer.getEnergyStored() - energyToDrain;\n if (resultEnergy >= 0L && resultEnergy <= energyContainer.getEnergyCapacity()) {\n if (!simulate)\n energyContainer.changeEnergy(-energyToDrain);\n return true;\n }\n return false;\n }\n\n @Override\n public NBTTagCompound writeToNBT(@Nonnull NBTTagCompound data) {\n super.writeToNBT(data);\n return this.logic.serializeNBT(data);\n }\n\n @Override\n public void readFromNBT(NBTTagCompound data) {\n super.readFromNBT(data);\n this.logic.deserializeNBT(data);\n }\n\n @Override\n public void writeInitialSyncData(PacketBuffer buf) {\n super.writeInitialSyncData(buf);\n this.logic.writeInitialData(buf);\n }\n\n @Override\n public void receiveInitialSyncData(PacketBuffer buf) {\n super.receiveInitialSyncData(buf);\n this.logic.receiveInitialData(buf);\n }\n\n @Override\n public void writeCustomData(int discriminator, Consumer<PacketBuffer> dataWriter) {\n super.writeCustomData(discriminator, dataWriter);\n }\n\n @Override\n public void receiveCustomData(int dataId, PacketBuffer buf) {\n super.receiveCustomData(dataId, buf);\n this.logic.receiveCustomData(dataId, buf);\n }\n\n @Override\n public <T> T getCapability(Capability<T> capability, EnumFacing side) {\n if (capability == GregtechTileCapabilities.CAPABILITY_WORKABLE)\n return GregtechTileCapabilities.CAPABILITY_WORKABLE.cast(this.logic);\n if (capability == GregtechTileCapabilities.CAPABILITY_CONTROLLABLE)\n return GregtechTileCapabilities.CAPABILITY_CONTROLLABLE.cast(this.logic);\n return super.getCapability(capability, side);\n }\n\n @Nonnull\n @Override\n public List<ITextComponent> getDataInfo() {\n List<ITextComponent> list = new ArrayList<>();\n if (logic.getMaxProgress() > 0) {\n list.add(new TextComponentTranslation(\"behavior.tricorder.workable_progress\",\n new TextComponentTranslation(TextFormattingUtil.formatNumbers(logic.getProgress() / 20)).setStyle(new Style().setColor(TextFormatting.GREEN)),\n new TextComponentTranslation(TextFormattingUtil.formatNumbers(logic.getMaxProgress() / 20)).setStyle(new Style().setColor(TextFormatting.YELLOW))\n ));\n }\n\n list.add(new TextComponentTranslation(\"behavior.tricorder.energy_container_storage\",\n new TextComponentTranslation(TextFormattingUtil.formatNumbers(energyContainer.getEnergyStored())).setStyle(new Style().setColor(TextFormatting.GREEN)),\n new TextComponentTranslation(TextFormattingUtil.formatNumbers(energyContainer.getEnergyCapacity())).setStyle(new Style().setColor(TextFormatting.YELLOW))\n ));\n\n if (logic.getRecipeEUt() > 0) {\n list.add(new TextComponentTranslation(\"behavior.tricorder.workable_consumption\",\n new TextComponentTranslation(TextFormattingUtil.formatNumbers(logic.getRecipeEUt())).setStyle(new Style().setColor(TextFormatting.RED)),\n new TextComponentTranslation(TextFormattingUtil.formatNumbers(logic.getRecipeEUt() == 0 ? 0 : 1)).setStyle(new Style().setColor(TextFormatting.RED))\n ));\n }\n\n list.add(new TextComponentTranslation(\"behavior.tricorder.multiblock_energy_input\",\n new TextComponentTranslation(TextFormattingUtil.formatNumbers(energyContainer.getInputVoltage())).setStyle(new Style().setColor(TextFormatting.YELLOW)),\n new TextComponentTranslation(GTValues.VN[GTUtility.getTierByVoltage(energyContainer.getInputVoltage())]).setStyle(new Style().setColor(TextFormatting.YELLOW))\n ));\n\n if (ConfigHolder.machines.enableMaintenance && hasMaintenanceMechanics()) {\n list.add(new TextComponentTranslation(\"behavior.tricorder.multiblock_maintenance\",\n new TextComponentTranslation(TextFormattingUtil.formatNumbers(getNumMaintenanceProblems())).setStyle(new Style().setColor(TextFormatting.RED))\n ));\n }\n\n if (logic.getParallelLimit() > 1) {\n list.add(new TextComponentTranslation(\"behavior.tricorder.multiblock_parallel\",\n new TextComponentTranslation(TextFormattingUtil.formatNumbers(logic.getParallelLimit())).setStyle(new Style().setColor(TextFormatting.GREEN))\n ));\n }\n if (logic.getMode() < 5 && logic.getMode() >= 0) {\n list.add(new TextComponentTranslation(\"epimorphism.machine.integrated_ore_factory.mode.\" + logic.getMode()));\n }\n return list;\n }\n}"
}
] | import cn.gtcommunity.epimorphism.api.utils.EPUniverUtil;
import cn.gtcommunity.epimorphism.common.metatileentities.multiblock.EPMetaTileEntityIntegratedOreFactory;
import gregtech.api.GTValues;
import gregtech.api.capability.*;
import gregtech.api.capability.impl.EnergyContainerList;
import gregtech.api.metatileentity.MetaTileEntity;
import gregtech.api.recipes.Recipe;
import gregtech.api.recipes.RecipeMaps;
import gregtech.api.unification.OreDictUnifier;
import gregtech.api.unification.material.Materials;
import gregtech.api.unification.ore.OrePrefix;
import gregtech.api.util.GTTransferUtils;
import gregtech.api.util.GTUtility;
import gregtech.common.ConfigHolder;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.network.PacketBuffer;
import net.minecraft.util.NonNullList;
import net.minecraft.world.World;
import net.minecraftforge.common.util.Constants;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.items.IItemHandlerModifiable;
import net.minecraftforge.oredict.OreDictionary;
import javax.annotation.Nonnull;
import java.util.*;
import java.util.stream.Collectors; | 6,116 | package cn.gtcommunity.epimorphism.api.capability.impl;
/*
* Referenced some code from GT5 Unofficial
*
* https://github.com/GTNewHorizons/GT5-Unofficial/
* */
//TODO 重写配方逻辑以添加满箱检测和更好的配方检测
public class OreProcessingLogic implements IWorkable{
private static final int MAX_PARA = 1024;
private static final HashSet<Integer> isCrushedOre = new HashSet<>();
private static final HashSet<Integer> isCrushedPureOre = new HashSet<>();
private static final HashSet<Integer> isPureDust = new HashSet<>();
private static final HashSet<Integer> isImpureDust = new HashSet<>();
private static final HashSet<Integer> isThermal = new HashSet<>();
private static final HashSet<Integer> isOre = new HashSet<>();
private ItemStack[] midProduct;
protected int[] overclockResults;
private int progressTime = 0;
protected int maxProgressTime;
private boolean isActive;
protected boolean canRecipeProgress = true;
protected int recipeEUt;
protected List<FluidStack> fluidOutputs;
protected NonNullList<ItemStack> itemOutputs;
protected boolean workingEnabled = true;
protected boolean hasNotEnoughEnergy;
protected boolean wasActiveAndNeedsUpdate;
protected boolean isOutputsFull;
private int mode = 0;
private static boolean init = false;
private boolean isVoidStone = false; | package cn.gtcommunity.epimorphism.api.capability.impl;
/*
* Referenced some code from GT5 Unofficial
*
* https://github.com/GTNewHorizons/GT5-Unofficial/
* */
//TODO 重写配方逻辑以添加满箱检测和更好的配方检测
public class OreProcessingLogic implements IWorkable{
private static final int MAX_PARA = 1024;
private static final HashSet<Integer> isCrushedOre = new HashSet<>();
private static final HashSet<Integer> isCrushedPureOre = new HashSet<>();
private static final HashSet<Integer> isPureDust = new HashSet<>();
private static final HashSet<Integer> isImpureDust = new HashSet<>();
private static final HashSet<Integer> isThermal = new HashSet<>();
private static final HashSet<Integer> isOre = new HashSet<>();
private ItemStack[] midProduct;
protected int[] overclockResults;
private int progressTime = 0;
protected int maxProgressTime;
private boolean isActive;
protected boolean canRecipeProgress = true;
protected int recipeEUt;
protected List<FluidStack> fluidOutputs;
protected NonNullList<ItemStack> itemOutputs;
protected boolean workingEnabled = true;
protected boolean hasNotEnoughEnergy;
protected boolean wasActiveAndNeedsUpdate;
protected boolean isOutputsFull;
private int mode = 0;
private static boolean init = false;
private boolean isVoidStone = false; | private final EPMetaTileEntityIntegratedOreFactory metaTileEntity; | 1 | 2023-11-26 01:56:35+00:00 | 8k |
LaughingMuffin/laughing-logger | app/src/main/java/org/laughing/logger/util/ThemeWrapper.java | [
{
"identifier": "App",
"path": "app/src/main/java/org/laughing/logger/App.java",
"snippet": "public class App extends Application {\n public static final String MUFFIN_ADS = \"MUFFIN-ADS\";\n private static App instance;\n private SharedPreferences preferences;\n\n public App() {\n instance = this;\n }\n\n @Override\n public void onCreate() {\n super.onCreate();\n\n CrashlyticsWrapper.initCrashlytics(this);\n\n // Log the Mobile Ads SDK version.\n Log.d(MUFFIN_ADS, \"Google Mobile Ads SDK Version: \" + MobileAds.getVersion());\n\n MobileAds.initialize(this, new OnInitializationCompleteListener() {\n @Override\n public void onInitializationComplete(InitializationStatus initializationStatus) {\n Log.i(MUFFIN_ADS, \"onInitializationComplete: Init Done!\");\n }\n });\n }\n\n public static App get() {\n if (instance == null) {\n instance = new App();\n }\n return instance;\n }\n\n public SharedPreferences getPreferences() {\n if (preferences == null) {\n preferences = PreferenceManager.getDefaultSharedPreferences(this);\n }\n return preferences;\n }\n\n @ColorInt\n public static int getColorFromAttr(Context context, @AttrRes int attr) {\n TypedValue typedValue = new TypedValue();\n if (context != null && context.getTheme().resolveAttribute(attr, typedValue, true))\n return typedValue.data;\n else\n return Color.RED;\n }\n}"
},
{
"identifier": "ColorScheme",
"path": "app/src/main/java/org/laughing/logger/data/ColorScheme.java",
"snippet": "public enum ColorScheme {\n Amoled(R.string.pref_theme_choice_amoled_value, R.color.main_background_amoled,\n R.color.light_primary, R.array.dark_theme_colors, R.color.spinner_droptown_dark,\n R.color.main_bubble_background_dark_2, false, R.color.accent),\n Dark(R.string.pref_theme_choice_dark_value, R.color.main_background_dark,\n R.color.light_primary, R.array.dark_theme_colors, R.color.spinner_droptown_dark,\n R.color.main_bubble_background_dark_2, false, R.color.accent),\n Light(R.string.pref_theme_choice_light_value, R.color.main_background_light,\n R.color.main_foreground_light, R.array.light_theme_colors, R.color.spinner_droptown_light,\n R.color.main_bubble_background_light_2, true, R.color.main_bubble_background_light_2),\n Android(R.string.pref_theme_choice_android_value, R.color.main_background_android,\n R.color.main_foreground_android, R.array.android_theme_colors, R.color.spinner_droptown_android,\n R.color.main_bubble_background_light, true, R.color.yellow1),\n Verizon(R.string.pref_theme_choice_verizon_value, R.color.main_background_verizon,\n R.color.main_foreground_verizon, R.array.dark_theme_colors, R.color.spinner_droptown_verizon,\n R.color.main_bubble_background_verizon, false, R.color.yellow1),\n Att(R.string.pref_theme_choice_att_value, R.color.main_background_att,\n R.color.main_foreground_att, R.array.light_theme_colors, R.color.spinner_droptown_att,\n R.color.main_bubble_background_light, true, R.color.main_bubble_background_light_2),\n Sprint(R.string.pref_theme_choice_sprint_value, R.color.main_background_sprint,\n R.color.main_foreground_sprint, R.array.dark_theme_colors, R.color.spinner_droptown_sprint,\n R.color.main_bubble_background_dark, false, R.color.yellow1),\n Tmobile(R.string.pref_theme_choice_tmobile_value, R.color.main_background_tmobile,\n R.color.main_foreground_tmobile, R.array.light_theme_colors, R.color.spinner_droptown_tmobile,\n R.color.main_bubble_background_tmobile, true, R.color.main_bubble_background_light_2),\n ;\n\n private static Map<String, ColorScheme> preferenceNameToColorScheme = new HashMap<>();\n private int nameResource;\n private int backgroundColorResource;\n private int foregroundColorResource;\n private int spinnerColorResource;\n private int bubbleBackgroundColorResource;\n private int tagColorsResource;\n private boolean useLightProgressBar;\n private int selectedColorResource;\n private int backgroundColor = -1;\n private int foregroundColor = -1;\n private int spinnerColor = -1;\n private int bubbleBackgroundColor = -1;\n private int selectedColor = -1;\n private int[] tagColors;\n\n ColorScheme(int nameResource, int backgroundColorResource, int foregroundColorResource,\n int tagColorsResource, int spinnerColorResource, int bubbleBackgroundColorResource,\n boolean useLightProgressBar, int selectedColorResource) {\n this.nameResource = nameResource;\n this.backgroundColorResource = backgroundColorResource;\n this.foregroundColorResource = foregroundColorResource;\n this.tagColorsResource = tagColorsResource;\n this.spinnerColorResource = spinnerColorResource;\n this.bubbleBackgroundColorResource = bubbleBackgroundColorResource;\n this.useLightProgressBar = useLightProgressBar;\n this.selectedColorResource = selectedColorResource;\n }\n\n public static ColorScheme findByPreferenceName(String name, Context context) {\n if (preferenceNameToColorScheme.isEmpty()) {\n // initialize map\n for (ColorScheme colorScheme : values()) {\n preferenceNameToColorScheme.put(context.getText(colorScheme.getNameResource()).toString(), colorScheme);\n }\n }\n return preferenceNameToColorScheme.get(name);\n }\n\n public String getDisplayableName(Context context) {\n\n CharSequence[] themeChoiceValues = context.getResources().getStringArray(R.array.pref_theme_choices_values);\n int idx = ArrayUtil.indexOf(themeChoiceValues, context.getString(nameResource));\n return context.getResources().getStringArray(R.array.pref_theme_choices_names)[idx];\n\n }\n\n public int getNameResource() {\n return nameResource;\n }\n\n public int getSelectedColor(Context context) {\n if (selectedColor == -1) {\n selectedColor = ContextCompat.getColor(context, selectedColorResource);\n }\n return selectedColor;\n }\n\n public int getBackgroundColor(Context context) {\n if (backgroundColor == -1) {\n backgroundColor = ContextCompat.getColor(context, backgroundColorResource);\n }\n return backgroundColor;\n }\n\n public int getForegroundColor(Context context) {\n if (foregroundColor == -1) {\n foregroundColor = ContextCompat.getColor(context, foregroundColorResource);\n }\n return foregroundColor;\n }\n\n public int[] getTagColors(Context context) {\n if (tagColors == null) {\n tagColors = context.getResources().getIntArray(tagColorsResource);\n }\n return tagColors;\n }\n\n public int getSpinnerColor(Context context) {\n if (spinnerColor == -1) {\n spinnerColor = ContextCompat.getColor(context, spinnerColorResource);\n }\n return spinnerColor;\n }\n\n public int getBubbleBackgroundColor(Context context) {\n if (bubbleBackgroundColor == -1) {\n bubbleBackgroundColor = ContextCompat.getColor(context, bubbleBackgroundColorResource);\n }\n return bubbleBackgroundColor;\n }\n\n public boolean isUseLightProgressBar() {\n return useLightProgressBar;\n }\n}"
},
{
"identifier": "PreferenceHelper",
"path": "app/src/main/java/org/laughing/logger/helper/PreferenceHelper.java",
"snippet": "public class PreferenceHelper {\n\n private static final String WIDGET_EXISTS_PREFIX = \"widget_\";\n private static float textSize = -1;\n private static Character defaultLogLevel = null;\n private static Boolean showTimestampAndPid = null;\n private static ColorScheme colorScheme = null;\n private static int displayLimit = -1;\n private static String filterPattern = null;\n private static UtilLogger log = new UtilLogger(PreferenceHelper.class);\n\n public static void clearCache() {\n defaultLogLevel = null;\n filterPattern = null;\n textSize = -1;\n showTimestampAndPid = null;\n colorScheme = null;\n displayLimit = -1;\n }\n\n /**\n * Record that we managed to get root in JellyBean.\n *\n * @param context\n * @return\n */\n public static void setJellybeanRootRan(Context context) {\n SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);\n Editor editor = sharedPrefs.edit();\n editor.putBoolean(context.getString(R.string.pref_ran_jellybean_su_update), true);\n editor.commit();\n }\n\n /**\n * Return true if we have root in jelly bean.\n *\n * @param context\n * @return\n */\n public static boolean getJellybeanRootRan(Context context) {\n SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);\n return sharedPrefs.getBoolean(context.getString(R.string.pref_ran_jellybean_su_update), false);\n }\n\n public static boolean getWidgetExistsPreference(Context context, int appWidgetId) {\n\n SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);\n String widgetExists = WIDGET_EXISTS_PREFIX.concat(Integer.toString(appWidgetId));\n\n return sharedPrefs.getBoolean(widgetExists, false);\n }\n\n public static void setWidgetExistsPreference(Context context, int[] appWidgetIds) {\n\n SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);\n\n Editor editor = sharedPrefs.edit();\n\n for (int appWidgetId : appWidgetIds) {\n String widgetExists = WIDGET_EXISTS_PREFIX.concat(Integer.toString(appWidgetId));\n editor.putBoolean(widgetExists, true);\n }\n\n editor.apply();\n\n }\n\n public static int getDisplayLimitPreference(Context context) {\n\n if (displayLimit == -1) {\n\n SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);\n\n String defaultValue = context.getText(R.string.pref_display_limit_default).toString();\n\n String intAsString = sharedPrefs.getString(context.getText(R.string.pref_display_limit).toString(), defaultValue);\n\n try {\n displayLimit = Integer.parseInt(intAsString);\n } catch (NumberFormatException e) {\n displayLimit = Integer.parseInt(defaultValue);\n }\n }\n\n return displayLimit;\n }\n\n public static String getFilterPatternPreference(Context context) {\n\n if (filterPattern == null) {\n\n SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);\n\n String defaultValue = context.getText(R.string.pref_filter_pattern_default).toString();\n\n filterPattern = sharedPrefs.getString(context.getText(R.string.pref_filter_pattern).toString(), defaultValue);\n\n }\n\n return filterPattern;\n }\n\n public static void setFilterPatternPreference(Context context, String value) {\n SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);\n Editor editor = sharedPrefs.edit();\n\n editor.putString(context.getText(R.string.pref_filter_pattern).toString(), value);\n\n editor.apply();\n }\n\n public static int getLogLinePeriodPreference(Context context) {\n SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);\n\n String defaultValue = context.getText(R.string.pref_log_line_period_default).toString();\n\n String intAsString = sharedPrefs.getString(context.getText(R.string.pref_log_line_period).toString(), defaultValue);\n\n try {\n return Integer.parseInt(intAsString);\n } catch (NumberFormatException e) {\n return Integer.parseInt(defaultValue);\n }\n }\n\n public static void setDisplayLimitPreference(Context context, int value) {\n SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);\n Editor editor = sharedPrefs.edit();\n\n editor.putString(context.getText(R.string.pref_display_limit).toString(), Integer.toString(value));\n\n editor.apply();\n }\n\n public static void setLogLinePeriodPreference(Context context, int value) {\n SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);\n Editor editor = sharedPrefs.edit();\n\n editor.putString(context.getText(R.string.pref_log_line_period).toString(), Integer.toString(value));\n\n editor.apply();\n }\n\n public static char getDefaultLogLevelPreference(Context context) {\n\n if (defaultLogLevel == null) {\n SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);\n\n String logLevelPref = sharedPrefs.getString(\n context.getText(R.string.pref_default_log_level).toString(),\n context.getText(R.string.log_level_value_verbose).toString());\n\n defaultLogLevel = logLevelPref.charAt(0);\n }\n\n return defaultLogLevel;\n\n\n }\n\n public static float getTextSizePreference(Context context) {\n\n if (textSize == -1) {\n\n SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);\n\n String textSizePref = sharedPrefs.getString(\n context.getText(R.string.pref_text_size).toString(),\n context.getText(R.string.text_size_medium_value).toString());\n\n if (textSizePref.contentEquals(context.getText(R.string.text_size_xsmall_value))) {\n cacheTextsize(context, R.dimen.text_size_xsmall);\n } else if (textSizePref.contentEquals(context.getText(R.string.text_size_small_value))) {\n cacheTextsize(context, R.dimen.text_size_small);\n } else if (textSizePref.contentEquals(context.getText(R.string.text_size_medium_value))) {\n cacheTextsize(context, R.dimen.text_size_medium);\n } else if (textSizePref.contentEquals(context.getText(R.string.text_size_large_value))) {\n cacheTextsize(context, R.dimen.text_size_large);\n } else { // xlarge\n cacheTextsize(context, R.dimen.text_size_xlarge);\n }\n }\n\n return textSize;\n\n }\n\n private static void cacheTextsize(Context context, int dimenId) {\n\n float unscaledSize = context.getResources().getDimension(dimenId);\n\n log.d(\"unscaledSize is %g\", unscaledSize);\n\n textSize = unscaledSize;\n }\n\n public static boolean getShowTimestampAndPidPreference(Context context) {\n\n if (showTimestampAndPid == null) {\n SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);\n\n showTimestampAndPid = sharedPrefs.getBoolean(context.getText(R.string.pref_show_timestamp).toString(), true);\n }\n\n return showTimestampAndPid;\n\n }\n\n public static boolean getHidePartialSelectHelpPreference(Context context) {\n\n SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);\n\n return sharedPrefs.getBoolean(\n context.getText(R.string.pref_hide_partial_select_help).toString(), false);\n }\n\n public static void setHidePartialSelectHelpPreference(Context context, boolean bool) {\n\n SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);\n Editor editor = sharedPrefs.edit();\n\n editor.putBoolean(context.getString(R.string.pref_hide_partial_select_help), bool);\n\n editor.apply();\n\n }\n\n public static boolean getExpandedByDefaultPreference(Context context) {\n\n SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);\n\n return sharedPrefs.getBoolean(\n context.getText(R.string.pref_expanded_by_default).toString(), false);\n }\n\n public static ColorScheme getColorScheme(Context context) {\n\n if (colorScheme == null) {\n\n SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);\n String colorSchemeName = sharedPrefs.getString(\n context.getText(R.string.pref_theme).toString(), context.getText(ColorScheme.Light.getNameResource()).toString());\n\n colorScheme = ColorScheme.findByPreferenceName(colorSchemeName, context);\n }\n\n return colorScheme;\n\n }\n\n public static void setColorScheme(Context context, ColorScheme colorScheme) {\n\n SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);\n Editor editor = sharedPrefs.edit();\n\n editor.putString(context.getString(R.string.pref_theme), context.getText(colorScheme.getNameResource()).toString());\n\n editor.apply();\n\n }\n\n public static List<String> getBuffers(Context context) {\n SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);\n\n String defaultValue = context.getString(R.string.pref_buffer_choice_main_value);\n String key = context.getString(R.string.pref_buffer);\n\n String value = sharedPrefs.getString(key, defaultValue);\n\n return Arrays.asList(StringUtil.split(value, MultipleChoicePreference.DELIMITER));\n }\n\n public static List<String> getBufferNames(Context context) {\n List<String> buffers = getBuffers(context);\n\n List<String> bufferNames = new ArrayList<>();\n\n // TODO: this is inefficient - O(n^2)\n for (String buffer : buffers) {\n int idx = Arrays.asList(context.getResources().getStringArray(\n R.array.pref_buffer_choice_values)).indexOf(buffer);\n bufferNames.add(context.getResources().getStringArray(R.array.pref_buffer_choices)[idx]);\n }\n return bufferNames;\n }\n\n public static void setBuffer(Context context, int stringResId) {\n SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);\n\n String key = context.getString(R.string.pref_buffer);\n String value = context.getString(stringResId);\n\n Editor editor = sharedPrefs.edit();\n\n editor.putString(key, value);\n\n editor.apply();\n }\n\n public static boolean getIncludeDeviceInfoPreference(Context context) {\n SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);\n\n return sharedPrefs.getBoolean(context.getString(R.string.pref_include_device_info), true);\n }\n\n public static void setIncludeDeviceInfoPreference(Context context, boolean value) {\n SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);\n\n Editor editor = sharedPrefs.edit();\n editor.putBoolean(context.getString(R.string.pref_include_device_info), value);\n editor.apply();\n }\n\n public static boolean isScrubberEnabled(Context context) {\n SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);\n return sharedPrefs.getBoolean(\"scrubber\", false);\n }\n\n public static boolean getIncludeDmesgPreference(Context context) {\n SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);\n\n return sharedPrefs.getBoolean(context.getString(R.string.pref_include_dmesg), true);\n }\n\n public static void setIncludeDmesgPreference(Context context, boolean value) {\n SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context);\n\n Editor editor = sharedPrefs.edit();\n editor.putBoolean(context.getString(R.string.pref_include_dmesg), value);\n editor.apply();\n }\n}"
}
] | import android.app.Activity;
import android.content.Context;
import android.os.Build;
import androidx.annotation.StyleRes;
import org.laughing.logger.App;
import org.laughing.logger.R;
import org.laughing.logger.data.ColorScheme;
import org.laughing.logger.helper.PreferenceHelper; | 5,066 | package org.laughing.logger.util;
/**
* Created by Snow Volf on 16.07.2019, 20:40
*/
public abstract class ThemeWrapper {
/**
* Apply theme to an Activity
*/
public static void applyTheme(Activity ctx) {
int theme;
switch (Theme.values()[getThemeIndex()]) {
case LIGHT:
theme = R.style.Theme_LaughingLogger_Light;
if (isDarkScheme(ctx)){
PreferenceHelper.setColorScheme(ctx, ColorScheme.Light);
}
break;
case DARK:
theme = R.style.Theme_LaughingLogger;
if (isLightScheme(ctx)) {
PreferenceHelper.setColorScheme(ctx, ColorScheme.Dark);
}
break;
case AMOLED:
theme = R.style.Theme_LaughingLogger_Amoled;
if (isLightScheme(ctx)) {
PreferenceHelper.setColorScheme(ctx, ColorScheme.Amoled);
}
break;
default:
// Force use the light theme
theme = R.style.Theme_LaughingLogger_Light;
break;
}
ctx.setTheme(theme);
applyAccent(ctx);
}
private static void applyAccent(Context ctx){
int accent;
switch (Accent.values()[getAccentIndex()]){
case RED:
accent = R.style.AccentRed;
break;
case PINK:
accent = R.style.AccentPink;
break;
case PURPLE:
accent = R.style.AccentPurple;
break;
case INDIGO:
accent = R.style.AccentIndigo;
break;
case BLUE:
accent = R.style.AccentBlue;
break;
case LBLUE:
accent = R.style.AccentLBlue;
break;
case CYAN:
accent = R.style.AccentCyan;
break;
case TEAL:
accent = R.style.AccentTeal;
break;
case GREEN:
accent = R.style.AccentGreen;
break;
case LGREEN:
accent = R.style.AccentLGreen;
break;
case LIME:
accent = R.style.AccentLime;
break;
case YELLOW:
accent = R.style.AccentYellow;
break;
case AMBER:
accent = R.style.AccentAmber;
break;
case ORANGE:
accent = R.style.AccentOrange;
break;
case DORANGE:
accent = R.style.AccentDOrange;
break;
case BROWN:
accent = R.style.AccentBrown;
break;
case GREY:
accent = R.style.AccentGrey;
break;
case BGREY:
accent = R.style.AccentBGrey;
break;
default:
accent = R.style.AccentBlue;
break;
}
ctx.getTheme().applyStyle(accent, true);
}
@StyleRes
public static int getDialogTheme(){
int theme;
switch (Theme.values()[getThemeIndex()]){
case LIGHT:
theme = R.style.Theme_MaterialComponents_Light_Dialog_Alert;
break;
case DARK:
theme = R.style.DarkAppTheme_Dialog;
break;
case AMOLED:
theme = R.style.AmoledAppTheme_Dialog;
break;
default:
theme = R.style.Theme_MaterialComponents_Light_Dialog_Alert;
}
return theme;
}
/**
* Get a saved theme number
*/
private static int getThemeIndex() { | package org.laughing.logger.util;
/**
* Created by Snow Volf on 16.07.2019, 20:40
*/
public abstract class ThemeWrapper {
/**
* Apply theme to an Activity
*/
public static void applyTheme(Activity ctx) {
int theme;
switch (Theme.values()[getThemeIndex()]) {
case LIGHT:
theme = R.style.Theme_LaughingLogger_Light;
if (isDarkScheme(ctx)){
PreferenceHelper.setColorScheme(ctx, ColorScheme.Light);
}
break;
case DARK:
theme = R.style.Theme_LaughingLogger;
if (isLightScheme(ctx)) {
PreferenceHelper.setColorScheme(ctx, ColorScheme.Dark);
}
break;
case AMOLED:
theme = R.style.Theme_LaughingLogger_Amoled;
if (isLightScheme(ctx)) {
PreferenceHelper.setColorScheme(ctx, ColorScheme.Amoled);
}
break;
default:
// Force use the light theme
theme = R.style.Theme_LaughingLogger_Light;
break;
}
ctx.setTheme(theme);
applyAccent(ctx);
}
private static void applyAccent(Context ctx){
int accent;
switch (Accent.values()[getAccentIndex()]){
case RED:
accent = R.style.AccentRed;
break;
case PINK:
accent = R.style.AccentPink;
break;
case PURPLE:
accent = R.style.AccentPurple;
break;
case INDIGO:
accent = R.style.AccentIndigo;
break;
case BLUE:
accent = R.style.AccentBlue;
break;
case LBLUE:
accent = R.style.AccentLBlue;
break;
case CYAN:
accent = R.style.AccentCyan;
break;
case TEAL:
accent = R.style.AccentTeal;
break;
case GREEN:
accent = R.style.AccentGreen;
break;
case LGREEN:
accent = R.style.AccentLGreen;
break;
case LIME:
accent = R.style.AccentLime;
break;
case YELLOW:
accent = R.style.AccentYellow;
break;
case AMBER:
accent = R.style.AccentAmber;
break;
case ORANGE:
accent = R.style.AccentOrange;
break;
case DORANGE:
accent = R.style.AccentDOrange;
break;
case BROWN:
accent = R.style.AccentBrown;
break;
case GREY:
accent = R.style.AccentGrey;
break;
case BGREY:
accent = R.style.AccentBGrey;
break;
default:
accent = R.style.AccentBlue;
break;
}
ctx.getTheme().applyStyle(accent, true);
}
@StyleRes
public static int getDialogTheme(){
int theme;
switch (Theme.values()[getThemeIndex()]){
case LIGHT:
theme = R.style.Theme_MaterialComponents_Light_Dialog_Alert;
break;
case DARK:
theme = R.style.DarkAppTheme_Dialog;
break;
case AMOLED:
theme = R.style.AmoledAppTheme_Dialog;
break;
default:
theme = R.style.Theme_MaterialComponents_Light_Dialog_Alert;
}
return theme;
}
/**
* Get a saved theme number
*/
private static int getThemeIndex() { | return Integer.parseInt(App.get().getPreferences().getString("ui.theme", String.valueOf(Theme.LIGHT.ordinal()))); | 0 | 2023-11-19 15:31:51+00:00 | 8k |
GT-ARC/opaca-core | opaca-platform/src/test/java/de/gtarc/opaca/platform/tests/ContainerTests.java | [
{
"identifier": "AgentContainerApi",
"path": "opaca-model/src/main/java/de/gtarc/opaca/api/AgentContainerApi.java",
"snippet": "public interface AgentContainerApi extends CommonApi{\n\n String ENV_CONTAINER_ID = \"CONTAINER_ID\";\n\n String ENV_PLATFORM_URL = \"PLATFORM_URL\";\n\n String ENV_TOKEN = \"TOKEN\";\n\n int DEFAULT_PORT = 8082;\n\n /**\n * Get information on the container, to be called by the Runtime Platform after start\n *\n * REST Route: GET /info\n *\n * @return Information on the started container\n */\n AgentContainer getContainerInfo() throws IOException;\n\n}"
},
{
"identifier": "AgentContainer",
"path": "opaca-model/src/main/java/de/gtarc/opaca/model/AgentContainer.java",
"snippet": "@Data @AllArgsConstructor @NoArgsConstructor\npublic class AgentContainer {\n\n /** ID of the container; does not necessarily have to be the Docker Container ID */\n @NonNull\n String containerId;\n\n /** the Image this container was started from */\n @NonNull\n AgentContainerImage image;\n\n /** Map of Arguments given to the AgentContainer for the Parameters of the Image */\n @NonNull\n Map<String, String> arguments = Map.of();\n\n /** list of agents running on this container; this might change during its life-time */\n @NonNull\n List<AgentDescription> agents = List.of();\n\n /** when the container was started */\n @NonNull\n @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = \"yyyy-MM-dd'T'HH:mm:ss.SSSXXX\", timezone = \"Z\")\n ZonedDateTime runningSince;\n\n /** connectivity information; NOTE: this is not set by the AgentContainer itself, but by the RuntimePlatform! */\n Connectivity connectivity;\n\n @Data @AllArgsConstructor @NoArgsConstructor\n public static class Connectivity {\n\n /** this container's public URL (e.g. the URL of the Runtime Platform, Docker Host, or Kubernetes Node */\n @NonNull\n String publicUrl;\n\n /** where the port where the container provides the OPACA API is mapped to */\n int apiPortMapping;\n\n /** where additional ports exposed by the container are mapped to */\n @NonNull\n Map<Integer, AgentContainerImage.PortDescription> extraPortMappings = Map.of();\n\n }\n\n}"
},
{
"identifier": "AgentDescription",
"path": "opaca-model/src/main/java/de/gtarc/opaca/model/AgentDescription.java",
"snippet": "@Data @AllArgsConstructor @NoArgsConstructor\npublic class AgentDescription {\n\n // TODO also list messages this agent understands and would react to\n\n /** ID of the agent, should be globally unique, e.g. a UUID */\n @NonNull\n String agentId;\n\n /** name/type of the agent, e.g. \"VehicleAgent\" or similar */\n String agentType;\n\n /** list of actions provided by this agent, if any */\n @NonNull\n List<Action> actions = List.of();\n\n /** list of endpoints for sending or receiving streaming data */\n @NonNull\n List<Stream> streams = List.of();\n\n}"
},
{
"identifier": "RuntimePlatform",
"path": "opaca-model/src/main/java/de/gtarc/opaca/model/RuntimePlatform.java",
"snippet": "@Data @AllArgsConstructor @NoArgsConstructor\npublic class RuntimePlatform {\n\n /** the external base URL where to reach this platform */\n @NonNull\n String baseUrl;\n\n /** Agent Containers managed by this platform */\n @NonNull\n List<AgentContainer> containers = List.of();\n\n /** List of capabilities this platform provides, e.g. \"gpu-support\"; format to be specified */\n @NonNull\n List<String> provides = List.of();\n\n /** List of base URLs of other platforms this platform is connected with */\n @NonNull\n List<String> connections = List.of();\n\n}"
},
{
"identifier": "Application",
"path": "opaca-platform/src/main/java/de/gtarc/opaca/platform/Application.java",
"snippet": "@SpringBootApplication\npublic class Application {\n\n public static void main(String[] args) {\n SpringApplication.run(Application.class, args);\n }\n\n}"
},
{
"identifier": "RestHelper",
"path": "opaca-model/src/main/java/de/gtarc/opaca/util/RestHelper.java",
"snippet": "@Log\n@AllArgsConstructor\npublic class RestHelper {\n\n public final String baseUrl;\n public final String token;\n\n public static final ObjectMapper mapper = JsonMapper.builder()\n .findAndAddModules().build();\n\n\n public <T> T get(String path, Class<T> type) throws IOException {\n var stream = request(\"GET\", path, null);\n return type == null ? null : mapper.readValue(stream, type);\n }\n\n public <T> T post(String path, Object payload, Class<T> type) throws IOException {\n var stream = request(\"POST\", path, payload);\n return type == null ? null : mapper.readValue(stream, type);\n }\n\n public <T> T delete(String path, Object payload, Class<T> type) throws IOException {\n var stream = request(\"DELETE\", path, payload);\n return type == null ? null : mapper.readValue(stream, type);\n }\n\n public ResponseEntity<StreamingResponseBody> getStream(String path) {\n StreamingResponseBody responseBody = response -> {\n InputStream stream = request(\"GET\", path, null);\n int bytesRead;\n byte[] buffer = new byte[1024];\n try (BufferedInputStream bis = new BufferedInputStream(stream)) {\n while ((bytesRead = bis.read(buffer)) != -1) {\n response.write(buffer, 0, bytesRead);\n }\n } catch (IOException e) {\n throw new UncheckedIOException(e);\n }\n };\n\n return ResponseEntity.ok()\n .contentType(MediaType.APPLICATION_OCTET_STREAM)\n .body(responseBody);\n }\n\n public InputStream request(String method, String path, Object payload) throws IOException {\n log.info(String.format(\"%s %s%s (%s)\", method, baseUrl, path, payload));\n HttpURLConnection connection = (HttpURLConnection) new URL(baseUrl + path).openConnection();\n connection.setRequestMethod(method);\n connection.setRequestProperty(\"Content-Type\", \"application/json; charset=UTF-8\");\n\n if (token != null && ! token.isEmpty()) {\n connection.setRequestProperty(\"Authorization\", \"Bearer \" + token);\n }\n \n if (payload != null) {\n String json = mapper.writeValueAsString(payload);\n byte[] bytes = json.getBytes(StandardCharsets.UTF_8);\n connection.setDoOutput(true);\n connection.setFixedLengthStreamingMode(bytes.length);\n connection.connect();\n try (OutputStream os = connection.getOutputStream()) {\n os.write(bytes);\n }\n } else {\n connection.connect();\n }\n\n if (connection.getResponseCode() < HttpURLConnection.HTTP_BAD_REQUEST) {\n return connection.getInputStream();\n } else {\n throw new IOException(String.format(\"%s: %s\",\n connection.getResponseCode(), readStream(connection.getErrorStream())));\n }\n }\n \n public static JsonNode readJson(String json) throws IOException {\n return mapper.readTree(json);\n }\n\n public static Map<String, JsonNode> readMap(String json) throws IOException {\n TypeReference<Map<String, JsonNode>> prototype = new TypeReference<>() {};\n return mapper.readValue(json, prototype);\n }\n\n public static <T> T readObject(String json, Class<T> type) throws IOException {\n return mapper.readValue(json, type);\n }\n\n public static String writeJson(Object obj) throws IOException {\n return mapper.writeValueAsString(obj);\n }\n\n public String readStream(InputStream stream) {\n return stream == null ? null : new BufferedReader(new InputStreamReader(stream))\n .lines().collect(Collectors.joining(\"\\n\"));\n\n }\n\n}"
},
{
"identifier": "TestUtils",
"path": "opaca-platform/src/test/java/de/gtarc/opaca/platform/tests/TestUtils.java",
"snippet": "public class TestUtils {\n\n /**\n * Agent-container image providing some nonsensical actions useful for unit testing\n * This is the docker image of `examples/sample-container`. When adding a new feature to\n * the sample-container for testing some new function of the Runtime Platform, increment\n * the version number and push the image to the DAI Gitlab Docker Registry\n *\n * > docker build -t test-image examples/sample-container/\n * (change to TEST_IMAGE=\"test-image\" and test locally if it works)\n * > docker tag test-image registry.gitlab.dai-labor.de/pub/unit-tests/opaca-sample-container:vXYZ\n * > docker push registry.gitlab.dai-labor.de/pub/unit-tests/opaca-sample-container:vXYZ\n */\n static final String TEST_IMAGE = \"registry.gitlab.dai-labor.de/pub/unit-tests/opaca-sample-container:v17\";\n\n /*\n * HELPER METHODS\n */\n\n public static PostAgentContainer getSampleContainerImage() {\n var image = new AgentContainerImage();\n image.setImageName(TEST_IMAGE);\n image.setExtraPorts(Map.of(\n 8888, new AgentContainerImage.PortDescription(\"TCP\", \"TCP Test Port\"),\n 8889, new AgentContainerImage.PortDescription(\"UDP\", \"UDP Test Port\")\n ));\n return new PostAgentContainer(image, Map.of(), null);\n }\n\n public static void addImageParameters(PostAgentContainer sampleRequest) {\n // parameters should match those defined in the sample-agent-container-image's own container.json!\n sampleRequest.getImage().setParameters(List.of(\n new ImageParameter(\"database\", \"string\", false, false, \"mongodb\"),\n new ImageParameter(\"username\", \"string\", true, false, null),\n new ImageParameter(\"password\", \"string\", true, true, null)\n ));\n }\n\n public static String buildQuery(Map<String, Object> params) {\n if (params != null) {\n var query = new StringBuilder();\n for (String key : params.keySet()) {\n query.append(String.format(\"&%s=%s\", key, params.get(key)));\n }\n return query.toString().replaceFirst(\"&\", \"?\");\n } else {\n return \"\";\n }\n }\n\n public static HttpURLConnection request(String host, String method, String path, Object payload) throws IOException {\n return requestWithToken(host, method, path, payload, null);\n }\n\n // this is NOT using RestHelper since we are also interested in the exact HTTP Return Code\n public static HttpURLConnection requestWithToken(String host, String method, String path, Object payload, String token) throws IOException {\n HttpURLConnection connection = (HttpURLConnection) new URL(host + path).openConnection();\n connection.setRequestMethod(method);\n\n if (token != null) {\n connection.setRequestProperty(\"Authorization\", \"Bearer \" + token);\n }\n\n if (payload != null) {\n String json = RestHelper.mapper.writeValueAsString(payload);\n byte[] bytes = json.getBytes(StandardCharsets.UTF_8);\n connection.setDoOutput(true);\n connection.setFixedLengthStreamingMode(bytes.length);\n connection.setRequestProperty(\"Content-Type\", \"application/json; charset=UTF-8\");\n connection.connect();\n try (OutputStream os = connection.getOutputStream()) {\n os.write(bytes);\n }\n } else {\n connection.connect();\n }\n return connection;\n }\n\n public static String result(HttpURLConnection connection) throws IOException {\n return new String(connection.getInputStream().readAllBytes());\n }\n\n public static <T> T result(HttpURLConnection connection, Class<T> type) throws IOException {\n return RestHelper.mapper.readValue(connection.getInputStream(), type);\n }\n\n public static String error(HttpURLConnection connection) throws IOException {\n return new String(connection.getErrorStream().readAllBytes());\n }\n\n public static String getBaseUrl(String localUrl) throws IOException {\n var con = request(localUrl, \"GET\", \"/info\", null);\n return result(con, RuntimePlatform.class).getBaseUrl();\n }\n\n public static String postSampleContainer(String platformUrl) throws IOException {\n var postContainer = getSampleContainerImage();\n var con = request(platformUrl, \"POST\", \"/containers\", postContainer);\n if (con.getResponseCode() != 200) {\n var message = new String(con.getErrorStream().readAllBytes());\n throw new IOException(\"Failed to POST sample container: \" + message);\n }\n return result(con);\n }\n\n public static void connectPlatforms(String platformUrl, String connectedUrl) throws IOException {\n var connectedBaseUrl = getBaseUrl(connectedUrl);\n var loginCon = new LoginConnection(null, null, connectedBaseUrl);\n var con = request(platformUrl, \"POST\", \"/connections\", loginCon);\n if (con.getResponseCode() != 200) {\n var message = new String(con.getErrorStream().readAllBytes());\n throw new IOException(\"Failed to connect platforms: \" + message);\n }\n }\n\n}"
}
] | import de.gtarc.opaca.api.AgentContainerApi;
import de.gtarc.opaca.model.AgentContainer;
import de.gtarc.opaca.model.AgentDescription;
import de.gtarc.opaca.model.RuntimePlatform;
import de.gtarc.opaca.platform.Application;
import de.gtarc.opaca.util.RestHelper;
import org.junit.*;
import org.springframework.boot.SpringApplication;
import org.springframework.context.ConfigurableApplicationContext;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static de.gtarc.opaca.platform.tests.TestUtils.*; | 5,647 | var message = Map.of("payload", "testMessage", "replyTo", "doesnotmatter");
var con = request(PLATFORM_URL, "POST", "/send/unknownagent", message);
Assert.assertEquals(404, con.getResponseCode());
}
/**
* call broadcast, check that it arrived via another invoke
*/
@Test
public void testBroadcast() throws Exception {
var message = Map.of("payload", "testBroadcast", "replyTo", "doesnotmatter");
var con = request(PLATFORM_URL, "POST", "/broadcast/topic", message);
Assert.assertEquals(200, con.getResponseCode());
con = request(PLATFORM_URL, "POST", "/invoke/GetInfo/sample1", Map.of());
Assert.assertEquals(200, con.getResponseCode());
var res = result(con, Map.class);
Assert.assertEquals("testBroadcast", res.get("lastBroadcast"));
}
/**
* test that container's /info route can be accessed via that port
*/
@Test
public void testApiPort() throws Exception {
var con = request(PLATFORM_URL, "GET", "/containers/" + containerId, null);
var res = result(con, AgentContainer.class).getConnectivity();
// access /info route through exposed port
var url = String.format("%s:%s", res.getPublicUrl(), res.getApiPortMapping());
System.out.println(url);
con = request(url, "GET", "/info", null);
Assert.assertEquals(200, con.getResponseCode());
}
/**
* test exposed extra port (has to be provided in sample image)
*/
@Test
public void testExtraPortTCP() throws Exception {
var con = request(PLATFORM_URL, "GET", "/containers/" + containerId, null);
var res = result(con, AgentContainer.class).getConnectivity();
var url = String.format("%s:%s", res.getPublicUrl(), "8888");
con = request(url, "GET", "/", null);
Assert.assertEquals(200, con.getResponseCode());
Assert.assertEquals("It Works!", result(con));
}
@Test
public void testExtraPortUDP() throws Exception {
var addr = InetAddress.getByName("localhost");
DatagramSocket clientSocket = new DatagramSocket();
byte[] sendData = "Test".getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, addr, 8889);
clientSocket.send(sendPacket);
byte[] receiveData = new byte[1024];
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
clientSocket.receive(receivePacket);
String receivedMessage = new String(receivePacket.getData(), 0, receivePacket.getLength());
Assert.assertEquals("TestTest", receivedMessage);
clientSocket.close();
}
/**
* TODO check somehow that notify worked
*/
@Test
public void testContainerNotify() throws Exception {
var con1 = request(PLATFORM_URL, "POST", "/containers/notify", containerId);
Assert.assertEquals(200, con1.getResponseCode());
}
/**
* tries to notify about non-existing container
*/
@Test
public void testInvalidContainerNotify() throws Exception {
var con1 = request(PLATFORM_URL, "POST", "/containers/notify", "container-does-not-exist");
Assert.assertEquals(404, con1.getResponseCode());
}
/**
* test that connectivity info is still there after /notify
*/
@Test
public void testNotifyConnectivity() throws Exception {
request(PLATFORM_URL, "POST", "/containers/notify", containerId);
var con = request(PLATFORM_URL, "GET", "/containers/" + containerId, null);
var res = result(con, AgentContainer.class);
Assert.assertNotNull(res.getConnectivity());
}
/**
* Deploy an additional sample-container on the same platform, so there are two of the same.
* Then /send and /broadcast messages to one particular container, then /invoke the GetInfo
* action of the respective containers to check that the messages were delivered correctly.
*/
@Test
public void testSendWithContainerId() throws Exception {
// deploy a second sample container image on platform A
var image = getSampleContainerImage();
var con = request(PLATFORM_URL, "POST", "/containers", image);
var newContainerId = result(con);
try {
// directed /send and /broadcast to both containers
var msg1 = Map.of("payload", "\"Message to First Container\"", "replyTo", "");
var msg2 = Map.of("payload", "\"Message to Second Container\"", "replyTo", "");
request(PLATFORM_URL, "POST", "/broadcast/topic?containerId=" + containerId, msg1);
request(PLATFORM_URL, "POST", "/send/sample1?containerId=" + newContainerId, msg2);
Thread.sleep(500);
// directed /invoke of GetInfo to check last messages of first container
con = request(PLATFORM_URL, "POST", "/invoke/GetInfo/sample1?containerId=" + containerId, Map.of());
var res1 = result(con, Map.class);
System.out.println(res1); | package de.gtarc.opaca.platform.tests;
/**
* This module is for tests that require the sample agent container to be deployed for e.g. testing invoking actions.
* The tests should not deploy other container, or if so, those should be removed after the test. In general, all the
* tests should be (and remain) independent of each other, able to run individually or in any order.
* At the start, a single runtime platform is started and a sample-agent-container is deployed. That state should be
* maintained after each test.
*/
public class ContainerTests {
private static final int PLATFORM_PORT = 8003;
private static final String PLATFORM_URL = "http://localhost:" + PLATFORM_PORT;
private static ConfigurableApplicationContext platform = null;
private static String containerId = null;
@BeforeClass
public static void setupPlatform() throws IOException {
platform = SpringApplication.run(Application.class,
"--server.port=" + PLATFORM_PORT);
containerId = postSampleContainer(PLATFORM_URL);
}
@AfterClass
public static void stopPlatform() {
platform.close();
}
@After
public void checkInvariant() throws Exception {
var con1 = request(PLATFORM_URL, "GET", "/info", null);
var res1 = result(con1, RuntimePlatform.class);
Assert.assertEquals(1, res1.getContainers().size());
var agents = res1.getContainers().get(0).getAgents();
Assert.assertEquals(2, agents.size());
}
/**
* get container info
*/
@Test
public void testGetContainerInfo() throws Exception {
var con = request(PLATFORM_URL, "GET", "/containers/" + containerId, null);
Assert.assertEquals(200, con.getResponseCode());
var res = result(con, AgentContainer.class);
Assert.assertEquals(containerId, res.getContainerId());
}
@Test
public void testGetAgents() throws Exception {
var con = request(PLATFORM_URL, "GET", "/agents", null);
Assert.assertEquals(200, con.getResponseCode());
var res = result(con, List.class);
Assert.assertEquals(2, res.size());
}
@Test
public void testGetAgent() throws Exception {
var con = request(PLATFORM_URL, "GET", "/agents/sample1", null);
Assert.assertEquals(200, con.getResponseCode());
var res = result(con, AgentDescription.class);
Assert.assertEquals("sample1", res.getAgentId());
}
@Test
public void testGetUnknownAgent() throws Exception {
var con = request(PLATFORM_URL, "GET", "/agents/unknown", null);
Assert.assertEquals(200, con.getResponseCode());
var res = result(con);
Assert.assertTrue(res.isEmpty());
}
/**
* call invoke, check result
*/
@Test
public void testInvokeAction() throws Exception {
var params = Map.of("x", 23, "y", 42);
var con = request(PLATFORM_URL, "POST", "/invoke/Add", params);
Assert.assertEquals(200, con.getResponseCode());
var res = result(con, Integer.class);
Assert.assertEquals(65L, res.longValue());
}
@Test
public void testStream() throws Exception {
var con = request(PLATFORM_URL, "GET", "/stream/GetStream", null);
Assert.assertEquals(200, con.getResponseCode());
var inputStream = con.getInputStream();
var bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
var response = bufferedReader.readLine();
Assert.assertEquals("{\"key\":\"value\"}", response);
}
/**
* call invoke with agent, check result
*/
@Test
public void testInvokeAgentAction() throws Exception {
for (String name : List.of("sample1", "sample2")) {
var con = request(PLATFORM_URL, "POST", "/invoke/GetInfo/" + name, Map.of());
var res = result(con, Map.class);
Assert.assertEquals(name, res.get("name"));
}
}
@Test
public void testInvokeFail() throws Exception {
var con = request(PLATFORM_URL, "POST", "/invoke/Fail", Map.of());
Assert.assertEquals(502, con.getResponseCode());
var msg = error(con);
Assert.assertTrue(msg.contains("Action Failed (as expected)"));
}
/**
* test that action invocation fails if it does not respond within the specified time
* TODO this is not ideal yet... the original error may contain a descriptive message that is lost
*/
@Test
public void testInvokeTimeout() throws Exception {
var params = Map.of("message", "timeout-test", "sleep_seconds", 5);
var con = request(PLATFORM_URL, "POST", "/invoke/DoThis?timeout=2", params);
Assert.assertEquals(502, con.getResponseCode());
}
/**
* invoke action with mismatched/missing parameters
* TODO case of missing parameter could also be handled by platform, resulting in 422 error
*/
@Test
public void testInvokeParamMismatch() throws Exception {
var con = request(PLATFORM_URL, "POST", "/invoke/DoThis",
Map.of("message", "missing 'sleep_seconds' parameter!"));
Assert.assertEquals(502, con.getResponseCode());
}
/**
* try to invoke unknown action
* -> 404 (not found)
*/
@Test
public void testUnknownAction() throws Exception {
var con = request(PLATFORM_URL, "POST", "/invoke/UnknownAction", Map.of());
Assert.assertEquals(404, con.getResponseCode());
con = request(PLATFORM_URL, "POST", "/invoke/Add/unknownagent", Map.of());
Assert.assertEquals(404, con.getResponseCode());
}
/**
* call send, check that it arrived via another invoke
*/
@Test
public void testSend() throws Exception {
var message = Map.of("payload", "testMessage", "replyTo", "doesnotmatter");
var con = request(PLATFORM_URL, "POST", "/send/sample1", message);
Assert.assertEquals(200, con.getResponseCode());
con = request(PLATFORM_URL, "POST", "/invoke/GetInfo/sample1", Map.of());
Assert.assertEquals(200, con.getResponseCode());
var res = result(con, Map.class);
Assert.assertEquals("testMessage", res.get("lastMessage"));
}
/**
* try to send message to unknown agent
* -> 404 (not found)
*/
@Test
public void testUnknownSend() throws Exception {
var message = Map.of("payload", "testMessage", "replyTo", "doesnotmatter");
var con = request(PLATFORM_URL, "POST", "/send/unknownagent", message);
Assert.assertEquals(404, con.getResponseCode());
}
/**
* call broadcast, check that it arrived via another invoke
*/
@Test
public void testBroadcast() throws Exception {
var message = Map.of("payload", "testBroadcast", "replyTo", "doesnotmatter");
var con = request(PLATFORM_URL, "POST", "/broadcast/topic", message);
Assert.assertEquals(200, con.getResponseCode());
con = request(PLATFORM_URL, "POST", "/invoke/GetInfo/sample1", Map.of());
Assert.assertEquals(200, con.getResponseCode());
var res = result(con, Map.class);
Assert.assertEquals("testBroadcast", res.get("lastBroadcast"));
}
/**
* test that container's /info route can be accessed via that port
*/
@Test
public void testApiPort() throws Exception {
var con = request(PLATFORM_URL, "GET", "/containers/" + containerId, null);
var res = result(con, AgentContainer.class).getConnectivity();
// access /info route through exposed port
var url = String.format("%s:%s", res.getPublicUrl(), res.getApiPortMapping());
System.out.println(url);
con = request(url, "GET", "/info", null);
Assert.assertEquals(200, con.getResponseCode());
}
/**
* test exposed extra port (has to be provided in sample image)
*/
@Test
public void testExtraPortTCP() throws Exception {
var con = request(PLATFORM_URL, "GET", "/containers/" + containerId, null);
var res = result(con, AgentContainer.class).getConnectivity();
var url = String.format("%s:%s", res.getPublicUrl(), "8888");
con = request(url, "GET", "/", null);
Assert.assertEquals(200, con.getResponseCode());
Assert.assertEquals("It Works!", result(con));
}
@Test
public void testExtraPortUDP() throws Exception {
var addr = InetAddress.getByName("localhost");
DatagramSocket clientSocket = new DatagramSocket();
byte[] sendData = "Test".getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, addr, 8889);
clientSocket.send(sendPacket);
byte[] receiveData = new byte[1024];
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
clientSocket.receive(receivePacket);
String receivedMessage = new String(receivePacket.getData(), 0, receivePacket.getLength());
Assert.assertEquals("TestTest", receivedMessage);
clientSocket.close();
}
/**
* TODO check somehow that notify worked
*/
@Test
public void testContainerNotify() throws Exception {
var con1 = request(PLATFORM_URL, "POST", "/containers/notify", containerId);
Assert.assertEquals(200, con1.getResponseCode());
}
/**
* tries to notify about non-existing container
*/
@Test
public void testInvalidContainerNotify() throws Exception {
var con1 = request(PLATFORM_URL, "POST", "/containers/notify", "container-does-not-exist");
Assert.assertEquals(404, con1.getResponseCode());
}
/**
* test that connectivity info is still there after /notify
*/
@Test
public void testNotifyConnectivity() throws Exception {
request(PLATFORM_URL, "POST", "/containers/notify", containerId);
var con = request(PLATFORM_URL, "GET", "/containers/" + containerId, null);
var res = result(con, AgentContainer.class);
Assert.assertNotNull(res.getConnectivity());
}
/**
* Deploy an additional sample-container on the same platform, so there are two of the same.
* Then /send and /broadcast messages to one particular container, then /invoke the GetInfo
* action of the respective containers to check that the messages were delivered correctly.
*/
@Test
public void testSendWithContainerId() throws Exception {
// deploy a second sample container image on platform A
var image = getSampleContainerImage();
var con = request(PLATFORM_URL, "POST", "/containers", image);
var newContainerId = result(con);
try {
// directed /send and /broadcast to both containers
var msg1 = Map.of("payload", "\"Message to First Container\"", "replyTo", "");
var msg2 = Map.of("payload", "\"Message to Second Container\"", "replyTo", "");
request(PLATFORM_URL, "POST", "/broadcast/topic?containerId=" + containerId, msg1);
request(PLATFORM_URL, "POST", "/send/sample1?containerId=" + newContainerId, msg2);
Thread.sleep(500);
// directed /invoke of GetInfo to check last messages of first container
con = request(PLATFORM_URL, "POST", "/invoke/GetInfo/sample1?containerId=" + containerId, Map.of());
var res1 = result(con, Map.class);
System.out.println(res1); | Assert.assertEquals(containerId, res1.get(AgentContainerApi.ENV_CONTAINER_ID)); | 0 | 2023-11-23 11:06:10+00:00 | 8k |
lushangkan/AutoStreamingAssistant | src/main/java/cn/cutemc/autostreamingassistant/AutoStreamingAssistant.java | [
{
"identifier": "WorldStatus",
"path": "src/main/java/cn/cutemc/autostreamingassistant/beans/WorldStatus.java",
"snippet": "@Getter\n@Setter\npublic class WorldStatus {\n private boolean loading;\n}"
},
{
"identifier": "Camera",
"path": "src/main/java/cn/cutemc/autostreamingassistant/camera/Camera.java",
"snippet": "public class Camera {\n\n public UUID cameraPlayerUUID = null;\n public MinecraftClient client;\n\n public Camera() {\n client = MinecraftClient.getInstance();\n }\n\n public void bindCamera(PlayerEntity target) {\n clearPlayerInventory(target);\n\n client.setCameraEntity(target);\n\n cameraPlayerUUID = target.getUuid();\n }\n\n public BindResult bindCamera(String targetName) {\n if (client.world == null) return BindResult.WORLD_IS_NULL;\n\n ClientPlayerEntity player = client.player;\n\n if (player == null) return BindResult.PLAYER_IS_NULL;\n\n List<PlayerListEntry> targetList = player.networkHandler.getPlayerList().stream().filter(playerListEntry -> playerListEntry.getProfile().getName().equals(targetName)).toList();\n\n if (targetList.size() != 1) {\n return BindResult.NOT_FOUND_PLAYER;\n }\n\n PlayerEntity target = client.world.getPlayerByUuid(targetList.get(0).getProfile().getId());\n\n if (target == null) {\n return BindResult.NOT_AT_NEAR_BY;\n }\n\n bindCamera(target);\n\n return BindResult.SUCCESS;\n }\n\n public BindResult bindCamera(UUID targetUUID) {\n if (client.world == null) return BindResult.WORLD_IS_NULL;\n\n ClientPlayerEntity player = client.player;\n\n if (player == null) return BindResult.PLAYER_IS_NULL;\n\n List<PlayerListEntry> targetList = player.networkHandler.getPlayerList().stream().filter(playerListEntry -> playerListEntry.getProfile().getId().equals(targetUUID)).toList();\n\n if (targetList.size() != 1) {\n return BindResult.NOT_FOUND_PLAYER;\n }\n\n PlayerEntity target = client.world.getPlayerByUuid(targetList.get(0).getProfile().getId());\n\n if (target == null) {\n return BindResult.NOT_AT_NEAR_BY;\n }\n\n bindCamera(target);\n\n return BindResult.SUCCESS;\n }\n\n public UnbindResult unbindCamera() {\n if (cameraPlayerUUID == null) return UnbindResult.NOT_BOUND_CAMERA;\n\n client.setCameraEntity(client.player);\n\n cameraPlayerUUID = null;\n\n return UnbindResult.SUCCESS;\n }\n\n public void clearPlayerInventory(PlayerEntity player) {\n player.getInventory().clear();\n }\n}"
},
{
"identifier": "ModCommands",
"path": "src/main/java/cn/cutemc/autostreamingassistant/commands/ModCommands.java",
"snippet": "public class ModCommands implements ClientCommandRegistrationCallback {\n\n public ModCommands() {\n ClientCommandRegistrationCallback.EVENT.register(this);\n }\n\n @Override\n public void register(CommandDispatcher<FabricClientCommandSource> dispatcher, CommandRegistryAccess registryAccess) {\n dispatcher.register(\n ClientCommandManager.literal(\"autostreamingassistant\").executes(this::mainCommand)\n .then(ClientCommandManager.literal(\"help\").executes(this::helpCommand))\n .then(ClientCommandManager.literal(\"listmonitor\").executes(this::listMonitorCommand))\n .then(ClientCommandManager.literal(\"camera\").executes(this::cameraCommand)\n .then(ClientCommandManager.literal(\"bind\").then(ClientCommandManager.argument(\"target\", StringArgumentType.string()).suggests((context, builder) -> {\n ClientPlayerEntity clientPlayer = MinecraftClient.getInstance().player;\n if (clientPlayer == null) throw new RuntimeException(\"ClientPlayer is null!\");\n return CommandSource.suggestMatching(clientPlayer.networkHandler.getPlayerList().stream().filter(player -> AutoStreamingAssistant.CAMERA.cameraPlayerUUID == null || !AutoStreamingAssistant.CAMERA.cameraPlayerUUID.equals(player.getProfile().getId())).map(player -> player.getProfile().getName()), builder);\n }).executes(this::bindCameraCommand)))\n .then(ClientCommandManager.literal(\"unbind\").executes(this::unbindCameraCommand))\n )\n );\n }\n\n public int mainCommand(CommandContext<FabricClientCommandSource> context) {\n return helpCommand(context);\n }\n\n public int helpCommand(CommandContext<FabricClientCommandSource> context) {\n FabricClientCommandSource source = context.getSource();\n source.sendFeedback(\n Text.translatable(\"commands.autostreamingassistant.help.title\").append(\": \\n\").styled(style -> style.withColor(TextColor.parse(\"gold\")))\n .append(Text.literal(\"● /autostreamingassistant help\").styled(style -> style.withColor(TextColor.parse(\"dark_aqua\")))).append(Text.literal(\" - \")).append(Text.translatable(\"commands.autostreamingassistant.help.help.description\").append(\"\\n\"))\n .append(Text.literal(\"● /autostreamingassistant listmonitor\").styled(style -> style.withColor(TextColor.parse(\"dark_aqua\")))).append(Text.literal(\" - \")).append(Text.translatable(\"commands.autostreamingassistant.help.listmonitor.description\").append(\"\\n\"))\n .append(Text.literal(\"● /autostreamingassistant camera bind\").styled(style -> style.withColor(TextColor.parse(\"dark_aqua\")))).append(Text.literal(\" - \")).append(Text.translatable(\"commands.autostreamingassistant.help.camera.bind.description\").append(\"\\n\"))\n .append(Text.literal(\"● /autostreamingassistant camera unbind\").styled(style -> style.withColor(TextColor.parse(\"dark_aqua\")))).append(Text.literal(\" - \")).append(Text.translatable(\"commands.autostreamingassistant.help.camera.unbind.description\").append(\"\\n\"))\n );\n return 1;\n }\n\n public int listMonitorCommand(CommandContext<FabricClientCommandSource> context) {\n FabricClientCommandSource source = context.getSource();\n\n PointerBuffer buffer = GLFW.glfwGetMonitors();\n long primaryMonitor = GLFW.glfwGetPrimaryMonitor();\n\n if (buffer == null) {\n source.sendFeedback(Text.translatable(\"commands.autostreamingassistant.listmonitor.notfound\").styled(style -> style.withColor(TextColor.parse(\"red\"))));\n return 1;\n }\n\n MutableText result = Text.translatable(\"commands.autostreamingassistant.listmonitor.title\").append(\":\\n\").styled(style -> style.withColor(TextColor.parse(\"gold\")));\n\n for (int i = 0; i < buffer.capacity(); i++) {\n long monitorHandle = buffer.get(i);\n\n String name = GLFW.glfwGetMonitorName(monitorHandle);\n if (name == null) {\n name = Text.translatable(\"commands.autostreamingassistant.listmonitor.unknown\").getString();\n }\n\n GLFWVidMode videoMode = GLFW.glfwGetVideoMode(monitorHandle);\n\n int height = -1;\n int width = -1;\n\n if (videoMode != null) {\n height = videoMode.height();\n width = videoMode.width();\n }\n\n boolean isPrimary = monitorHandle == primaryMonitor;\n\n result.append(Text.literal(\"\\n\"));\n result.append(Text.translatable(\"commands.autostreamingassistant.listmonitor.monitor\").append(\"#\" + i + \": \" + (isPrimary ? \"(\" + Text.translatable(\"commands.autostreamingassistant.listmonitor.primary\").getString() + \")\" : \"\") + \"\\n\")).styled(style -> style.withColor(TextColor.parse(\"gold\")));\n result.append(Text.translatable(\"commands.autostreamingassistant.listmonitor.name\").append(\": \").styled(style -> style.withColor(TextColor.parse(\"dark_aqua\")))).append(Text.literal(name)).append(Text.literal(\"\\n\"));\n result.append(Text.translatable(\"commands.autostreamingassistant.listmonitor.height\").append(\": \").styled(style -> style.withColor(TextColor.parse(\"dark_aqua\")))).append(Text.literal(height != -1 ? String.valueOf(height) : Text.translatable(\"commands.autostreamingassistant.listmonitor.height.error\").getString())).append(Text.literal(\"\\n\"));\n result.append(Text.translatable(\"commands.autostreamingassistant.listmonitor.width\").append(\": \").styled(style -> style.withColor(TextColor.parse(\"dark_aqua\")))).append(Text.literal(width != -1 ? String.valueOf(width) : Text.translatable(\"commands.autostreamingassistant.listmonitor.width.error\").getString()));\n\n }\n\n source.sendFeedback(result);\n\n return 1;\n }\n\n public int cameraCommand(CommandContext<FabricClientCommandSource> context) {\n return helpCommand(context);\n }\n\n public int bindCameraCommand(CommandContext<FabricClientCommandSource> context) {\n String targetName = StringArgumentType.getString(context, \"target\");\n\n\n switch (AutoStreamingAssistant.CAMERA.bindCamera(targetName)) {\n case NOT_FOUND_PLAYER -> context.getSource().sendFeedback(Text.translatable(\"commands.autostreamingassistant.camera.bind.notfound\", targetName).styled(style -> style.withColor(TextColor.parse(\"red\"))));\n case NOT_AT_NEAR_BY -> context.getSource().sendFeedback(Text.translatable(\"commands.autostreamingassistant.camera.bind.notatnearby\", targetName).styled(style -> style.withColor(TextColor.parse(\"yellow\"))));\n case SUCCESS -> {\n context.getSource().sendFeedback(Text.translatable(\"commands.autostreamingassistant.camera.bind.bound\", targetName).styled(style -> style.withColor(TextColor.parse(\"gold\"))));\n\n ServerManualBindCameraPacket packet = new ServerManualBindCameraPacket();\n packet.setPlayerUuid(AutoStreamingAssistant.CAMERA.cameraPlayerUUID);\n Gson gson = new Gson();\n\n ClientPlayNetworking.send(PacketID.MANUAL_BIND_CAMERA, PacketByteBufs.create().writeBytes(gson.toJson(packet).getBytes(StandardCharsets.UTF_8)));\n }\n }\n\n return 1;\n }\n\n public int unbindCameraCommand(CommandContext<FabricClientCommandSource> context) {\n switch (AutoStreamingAssistant.CAMERA.unbindCamera()) {\n case NOT_BOUND_CAMERA -> context.getSource().sendFeedback(Text.translatable(\"commands.autostreamingassistant.camera.unbind.notbound\").styled(style -> style.withColor(TextColor.parse(\"red\"))));\n case SUCCESS -> context.getSource().sendFeedback(Text.translatable(\"commands.autostreamingassistant.camera.unbind.unbound\").styled(style -> style.withColor(TextColor.parse(\"gold\"))));\n }\n\n return 1;\n }\n}"
},
{
"identifier": "ModConfig",
"path": "src/main/java/cn/cutemc/autostreamingassistant/config/ModConfig.java",
"snippet": "@Log4j2\npublic class ModConfig {\n\n public MainConfig mainConfig;\n public ConfigHolder<MainConfig> configHolder;\n\n public ModConfig() {\n AutoConfig.register(MainConfig.class, GsonConfigSerializer::new);\n\n configHolder = AutoConfig.getConfigHolder(MainConfig.class);\n\n mainConfig = configHolder.getConfig();\n\n log.info(\"Registering Config Listeners...\");\n ConfigListener configListener = new ConfigListener();\n configHolder.registerLoadListener(configListener);\n configHolder.registerSaveListener(configListener);\n }\n\n}"
},
{
"identifier": "ModKeyBinding",
"path": "src/main/java/cn/cutemc/autostreamingassistant/keybindings/ModKeyBinding.java",
"snippet": "public class ModKeyBinding {\n\n public KeyBinding keyBinding;\n\n public ModKeyBinding() {\n keyBinding = KeyBindingHelper.registerKeyBinding(new KeyBinding(\n \"key.autostreamingassistant.togglelockmouse\",\n InputUtil.Type.KEYSYM,\n GLFW.GLFW_KEY_M,\n \"key.autostreamingassistant.category\"\n ));\n }\n}"
},
{
"identifier": "ConfigListener",
"path": "src/main/java/cn/cutemc/autostreamingassistant/listeners/ConfigListener.java",
"snippet": "public class ConfigListener implements ConfigSerializeEvent.Load<MainConfig>, ConfigSerializeEvent.Save<MainConfig> {\n\n @Override\n public ActionResult onLoad(ConfigHolder<MainConfig> configHolder, MainConfig mainConfig) {\n Mouse mouse = MinecraftClient.getInstance().mouse;\n if (!mouse.isCursorLocked() && !mainConfig.disableMouseLock) mouse.lockCursor();\n if (mouse.isCursorLocked() && mainConfig.disableMouseLock) mouse.unlockCursor();\n return ActionResult.SUCCESS;\n }\n\n @Override\n public ActionResult onSave(ConfigHolder<MainConfig> configHolder, MainConfig mainConfig) {\n Mouse mouse = MinecraftClient.getInstance().mouse;\n if (!mouse.isCursorLocked() && !mainConfig.disableMouseLock) mouse.lockCursor();\n if (mouse.isCursorLocked() && mainConfig.disableMouseLock) mouse.unlockCursor();\n return ActionResult.SUCCESS;\n }\n\n}"
},
{
"identifier": "KeyListener",
"path": "src/main/java/cn/cutemc/autostreamingassistant/listeners/KeyListener.java",
"snippet": "public class KeyListener implements ClientTickEvents.EndTick{\n\n public KeyListener() {\n ClientTickEvents.END_CLIENT_TICK.register(this);\n }\n\n @Override\n public void onEndTick(MinecraftClient client) {\n while (AutoStreamingAssistant.KEYBINDING.keyBinding.wasPressed()) {\n MainConfig mainConfig = AutoStreamingAssistant.CONFIG.mainConfig;\n\n mainConfig.disableMouseLock = !mainConfig.disableMouseLock;\n\n AutoStreamingAssistant.CONFIG.configHolder.save();\n }\n }\n}"
},
{
"identifier": "ClientBindCameraHandler",
"path": "src/main/java/cn/cutemc/autostreamingassistant/network/packets/ClientBindCameraHandler.java",
"snippet": "public class ClientBindCameraHandler implements ClientPlayNetworking.PlayChannelHandler {\n\n public ClientBindCameraHandler() {\n ClientPlayNetworking.registerGlobalReceiver(PacketID.BIND_CAMERA, this);\n }\n\n @Override\n public void receive(MinecraftClient client, ClientPlayNetworkHandler handler, PacketByteBuf buf, PacketSender responseSender) {\n if (client.world == null) return;\n\n Gson gson = new Gson();\n String jsonStr = new String(BufferUtils.toBytes(buf), StandardCharsets.UTF_8);\n\n BindCameraMessage message = gson.fromJson(jsonStr, BindCameraMessage.class);\n\n Runnable thread = () -> {\n Runnable bindCamera = () -> client.execute(() -> {\n BindResult result = AutoStreamingAssistant.CAMERA.bindCamera(message.getPlayerUuid());\n\n BindCameraResultMessage resultMessage = new BindCameraResultMessage();\n resultMessage.setSuccess(result == BindResult.SUCCESS);\n resultMessage.setResult(result);\n\n PacketByteBuf resultBuf = PacketByteBufs.create();\n resultBuf.writeBytes(gson.toJson(resultMessage).getBytes(StandardCharsets.UTF_8));\n\n responseSender.sendPacket(PacketID.BIND_CAMERA_RESULT, resultBuf);\n });\n\n if (client.world.getPlayers().stream().filter(player -> player.getUuid().equals(message.getPlayerUuid())).toList().size() != 1) {\n // 找不到玩家\n\n for (int i = 0; i < AutoStreamingAssistant.CONFIG.mainConfig.findPlayerTimeout; i++) {\n try {\n Thread.sleep(1000);\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n\n if (client.world.getPlayers().stream().filter(player -> player.getUuid().equals(message.getPlayerUuid())).toList().size() == 1) {\n bindCamera.run();\n return;\n }\n }\n\n // 超时\n BindCameraResultMessage resultMessage = new BindCameraResultMessage();\n resultMessage.setSuccess(false);\n resultMessage.setResult(BindResult.NOT_FOUND_PLAYER);\n\n PacketByteBuf resultBuf = PacketByteBufs.create();\n resultBuf.writeBytes(gson.toJson(resultMessage).getBytes(StandardCharsets.UTF_8));\n\n responseSender.sendPacket(PacketID.BIND_CAMERA_RESULT, resultBuf);\n\n return;\n }\n\n bindCamera.run();\n };\n\n if (AutoStreamingAssistant.worldStatus.isLoading()) {\n // 加载世界中, 等待结束后再执行\n PropertyChangeSupport changeListener = new PropertyChangeSupport(AutoStreamingAssistant.worldStatus);\n changeListener.addPropertyChangeListener(\"loading\", evt -> {\n if (!AutoStreamingAssistant.worldStatus.isLoading()) {\n new Thread(thread).start();\n }\n });\n\n return;\n }\n\n new Thread(thread).start();\n }\n\n @Getter\n @Setter\n static class BindCameraMessage {\n private UUID playerUuid;\n }\n\n @Getter\n @Setter\n static class BindCameraResultMessage {\n private boolean success;\n private BindResult result;\n }\n\n}"
},
{
"identifier": "ClientRequestBindStatusHandle",
"path": "src/main/java/cn/cutemc/autostreamingassistant/network/packets/ClientRequestBindStatusHandle.java",
"snippet": "public class ClientRequestBindStatusHandle implements ClientPlayNetworking.PlayChannelHandler {\n\n public ClientRequestBindStatusHandle() {\n ClientPlayNetworking.registerGlobalReceiver(PacketID.REQUEST_BIND_STATUS, this);\n }\n\n @Override\n public void receive(MinecraftClient client, ClientPlayNetworkHandler handler, PacketByteBuf buf, PacketSender responseSender) {\n BindStatusMessage bindStatusMessage = new BindStatusMessage();\n bindStatusMessage.setPlayerUuid(AutoStreamingAssistant.CAMERA.cameraPlayerUUID);\n\n responseSender.sendPacket(PacketID.BIND_STATUS, PacketByteBufs.create().writeBytes(new Gson().toJson(bindStatusMessage).getBytes(StandardCharsets.UTF_8)));\n }\n\n @Getter\n @Setter\n static class BindStatusMessage {\n private UUID playerUuid;\n }\n}"
},
{
"identifier": "ClientRequestStatusHandler",
"path": "src/main/java/cn/cutemc/autostreamingassistant/network/packets/ClientRequestStatusHandler.java",
"snippet": "@Log4j2\npublic class ClientRequestStatusHandler implements ClientPlayNetworking.PlayChannelHandler {\n\n public ClientRequestStatusHandler() {\n ClientPlayNetworking.registerGlobalReceiver(PacketID.REQUEST_STATUS, this);\n }\n\n @Override\n public void receive(MinecraftClient client, ClientPlayNetworkHandler handler, PacketByteBuf buf, PacketSender responseSender) {\n String jsonStr = new String(BufferUtils.toBytes(buf), StandardCharsets.UTF_8);\n Gson gson = new Gson();\n RequestStatusMessage requestStatusMessage = gson.fromJson(jsonStr, RequestStatusMessage.class);\n\n ClientStatusMessage clientStatusMessage = new ClientStatusMessage();\n clientStatusMessage.setStatus(AutoStreamingAssistant.CAMERA.cameraPlayerUUID == null ? ClientStatus.READY : ClientStatus.BOUND);\n clientStatusMessage.setVersion(AutoStreamingAssistant.VERSION);\n String resultJson = gson.toJson(clientStatusMessage);\n\n responseSender.sendPacket(PacketID.CLIENT_STATUS, PacketByteBufs.create().writeBytes(resultJson.getBytes(StandardCharsets.UTF_8)));\n }\n\n @Getter\n @Setter\n static class RequestStatusMessage {\n private String version;\n }\n\n @Getter\n @Setter\n static class ClientStatusMessage {\n private ClientStatus status;\n private String version;\n }\n}"
},
{
"identifier": "ClientUnbindCameraHandler",
"path": "src/main/java/cn/cutemc/autostreamingassistant/network/packets/ClientUnbindCameraHandler.java",
"snippet": "public class ClientUnbindCameraHandler implements ClientPlayNetworking.PlayChannelHandler {\n\n public ClientUnbindCameraHandler() {\n ClientPlayNetworking.registerGlobalReceiver(PacketID.UNBIND_CAMERA, this);\n }\n\n @Override\n public void receive(MinecraftClient client, ClientPlayNetworkHandler handler, PacketByteBuf buf, PacketSender responseSender) {\n UnbindResult result = AutoStreamingAssistant.CAMERA.unbindCamera();\n\n Gson gson = new Gson();\n\n UnbindCameraResultMessage message = new UnbindCameraResultMessage();\n message.setSuccess(result == UnbindResult.SUCCESS);\n message.setResult(result);\n\n String jsonStr = gson.toJson(message);\n\n PacketByteBuf packetByteBuf = PacketByteBufs.create();\n packetByteBuf.writeBytes(jsonStr.getBytes(StandardCharsets.UTF_8));\n\n responseSender.sendPacket(PacketID.UNBIND_CAMERA_RESULT, packetByteBuf);\n }\n\n @Getter\n @Setter\n static class UnbindCameraResultMessage {\n private boolean success;\n private UnbindResult result;\n }\n\n}"
},
{
"identifier": "SystemUtils",
"path": "src/main/java/cn/cutemc/autostreamingassistant/utils/SystemUtils.java",
"snippet": "public class SystemUtils {\n\n @SneakyThrows\n public static boolean isLinuxMint() {\n if (!System.getProperty(\"os.name\").equals(\"Linux\")) return false;\n\n DefaultExecutor executor = new DefaultExecutor();\n\n CommandLine cmdLine = CommandLine.parse(\"lsb_release -i\");\n\n ByteArrayOutputStream stream = new ByteArrayOutputStream();\n executor.setStreamHandler(new PumpStreamHandler(stream));\n\n int resultCode = executor.execute(cmdLine);\n\n if (resultCode != 0) return false;\n\n String resultStr = stream.toString(StandardCharsets.UTF_8);\n\n return resultStr.toLowerCase().replaceAll(\" \", \"\").contains(\"linuxmint\");\n }\n\n}"
}
] | import cn.cutemc.autostreamingassistant.beans.WorldStatus;
import cn.cutemc.autostreamingassistant.camera.Camera;
import cn.cutemc.autostreamingassistant.commands.ModCommands;
import cn.cutemc.autostreamingassistant.config.ModConfig;
import cn.cutemc.autostreamingassistant.keybindings.ModKeyBinding;
import cn.cutemc.autostreamingassistant.listeners.ConfigListener;
import cn.cutemc.autostreamingassistant.listeners.KeyListener;
import cn.cutemc.autostreamingassistant.network.packets.ClientBindCameraHandler;
import cn.cutemc.autostreamingassistant.network.packets.ClientRequestBindStatusHandle;
import cn.cutemc.autostreamingassistant.network.packets.ClientRequestStatusHandler;
import cn.cutemc.autostreamingassistant.network.packets.ClientUnbindCameraHandler;
import cn.cutemc.autostreamingassistant.utils.SystemUtils;
import lombok.extern.log4j.Log4j2;
import net.fabricmc.api.ClientModInitializer;
import net.fabricmc.loader.api.FabricLoader; | 5,033 | package cn.cutemc.autostreamingassistant;
@Log4j2
public class AutoStreamingAssistant implements ClientModInitializer {
public static String VERSION;
public static ModConfig CONFIG;
public static ModKeyBinding KEYBINDING;
public static Camera CAMERA;
public static boolean isLinuxMint = false; | package cn.cutemc.autostreamingassistant;
@Log4j2
public class AutoStreamingAssistant implements ClientModInitializer {
public static String VERSION;
public static ModConfig CONFIG;
public static ModKeyBinding KEYBINDING;
public static Camera CAMERA;
public static boolean isLinuxMint = false; | public static WorldStatus worldStatus = new WorldStatus(); | 0 | 2023-11-20 14:02:38+00:00 | 8k |
myzticbean/QSFindItemAddOn | src/main/java/io/myzticbean/finditemaddon/Handlers/GUIHandler/PaginatedMenu.java | [
{
"identifier": "FindItemAddOn",
"path": "src/main/java/io/myzticbean/finditemaddon/FindItemAddOn.java",
"snippet": "public final class FindItemAddOn extends JavaPlugin {\n\n private static Plugin plugin;\n public FindItemAddOn() { plugin = this; }\n public static Plugin getInstance() { return plugin; }\n public static String serverVersion;\n private final static int BS_PLUGIN_METRIC_ID = 12382;\n private final static int SPIGOT_PLUGIN_ID = 95104;\n private final static int REPEATING_TASK_SCHEDULE_MINS = 15*60*20;\n private static ConfigProvider configProvider;\n private static boolean isPluginOutdated = false;\n private static boolean qSReremakeInstalled = false;\n private static boolean qSHikariInstalled = false;\n private static QSApi qsApi;\n\n private static final HashMap<Player, PlayerMenuUtility> playerMenuUtilityMap = new HashMap<>();\n\n @Override\n public void onLoad() {\n LoggerUtils.logInfo(\"A Shop Search AddOn for QuickShop developed by ronsane\");\n\n // Show warning if it's a snapshot build\n if(this.getDescription().getVersion().toLowerCase().contains(\"snapshot\")) {\n LoggerUtils.logWarning(\"This is a SNAPSHOT build! NOT recommended for production servers.\");\n LoggerUtils.logWarning(\"If you find any bugs, please report them here: https://gitlab.com/ronsane/QSFindItemAddOn/-/issues\");\n }\n\n\n }\n @Override\n public void onEnable() {\n\n if(!Bukkit.getPluginManager().isPluginEnabled(\"QuickShop\")\n && !Bukkit.getPluginManager().isPluginEnabled(\"QuickShop-Hikari\")) {\n LoggerUtils.logInfo(\"Delaying QuickShop hook as they are not enabled yet\");\n }\n else if(Bukkit.getPluginManager().isPluginEnabled(\"QuickShop\")) {\n qSReremakeInstalled = true;\n }\n else {\n qSHikariInstalled = true;\n }\n\n // Registering Bukkit event listeners\n initBukkitEventListeners();\n\n // Handle config file\n this.saveDefaultConfig();\n this.getConfig().options().copyDefaults(true);\n ConfigSetup.setupConfig();\n ConfigSetup.get().options().copyDefaults(true);\n ConfigSetup.checkForMissingProperties();\n ConfigSetup.saveConfig();\n initConfigProvider();\n ConfigSetup.copySampleConfig();\n\n initCommands();\n\n // Run plugin startup logic after server is done loading\n Bukkit.getScheduler().scheduleSyncDelayedTask(FindItemAddOn.getInstance(), () -> runPluginStartupTasks());\n }\n\n @Override\n public void onDisable() {\n // Plugin shutdown logic\n if(qsApi != null) {\n ShopSearchActivityStorageUtil.saveShopsToFile();\n }\n else {\n LoggerUtils.logError(\"Uh oh! Looks like either this plugin has crashed or you don't have QuickShop or QuickShop-Hikari installed.\");\n }\n LoggerUtils.logInfo(\"Bye!\");\n }\n\n private void runPluginStartupTasks() {\n// if(!Bukkit.getPluginManager().isPluginEnabled(\"QuickShop\")\n// && !Bukkit.getPluginManager().isPluginEnabled(\"QuickShop-Hikari\")) {\n// LoggerUtils.logError(\"QuickShop is required to use this addon. Please install QuickShop and try again!\");\n// LoggerUtils.logError(\"Both QuickShop-Reremake and QuickShop-Hikari are supported by this addon.\");\n// LoggerUtils.logError(\"Download links:\");\n// LoggerUtils.logError(\"» QuickShop-Reremake: https://www.spigotmc.org/resources/62575\");\n// LoggerUtils.logError(\"» QuickShop-Hikari: https://www.spigotmc.org/resources/100125\");\n// getServer().getPluginManager().disablePlugin(this);\n// return;\n// }\n// else if(Bukkit.getPluginManager().isPluginEnabled(\"QuickShop\")) {\n// qSReremakeInstalled = true;\n// qsApi = new QSReremakeAPIHandler();\n// LoggerUtils.logInfo(\"Found QuickShop-Reremake\");\n// }\n// else if(Bukkit.getPluginManager().isPluginEnabled(\"QuickShop-Hikari\")) {\n// qSHikariInstalled = true;\n// qsApi = new QSHikariAPIHandler();\n// LoggerUtils.logInfo(\"Found QuickShop-Hikari\");\n// }\n\n serverVersion = Bukkit.getServer().getVersion();\n LoggerUtils.logInfo(\"Server version found: \" + serverVersion);\n\n if(!isQSReremakeInstalled() && !isQSHikariInstalled()) {\n LoggerUtils.logError(\"QuickShop is required to use this addon. Please install QuickShop and try again!\");\n LoggerUtils.logError(\"Both QuickShop-Reremake and QuickShop-Hikari are supported by this addon.\");\n LoggerUtils.logError(\"Download links:\");\n LoggerUtils.logError(\"» QuickShop-Reremake: https://www.spigotmc.org/resources/62575\");\n LoggerUtils.logError(\"» QuickShop-Hikari: https://www.spigotmc.org/resources/100125\");\n getServer().getPluginManager().disablePlugin(this);\n return;\n }\n else if(isQSReremakeInstalled()) {\n LoggerUtils.logInfo(\"Found QuickShop-Reremake\");\n qsApi = new QSReremakeAPIHandler();\n qsApi.registerSubCommand();\n } else {\n LoggerUtils.logInfo(\"Found QuickShop-Hikari\");\n qsApi = new QSHikariAPIHandler();\n qsApi.registerSubCommand();\n }\n\n // Load all hidden shops from file\n ShopSearchActivityStorageUtil.loadShopsFromFile();\n\n // v2.0.0 - Migrating hiddenShops.json to shops.json\n ShopSearchActivityStorageUtil.migrateHiddenShopsToShopsJson();\n\n PlayerWarpsPlugin.setup();\n EssentialsXPlugin.setup();\n WGPlugin.setup();\n\n initExternalPluginEventListeners();\n\n // Initiate batch tasks\n LoggerUtils.logInfo(\"Registering tasks\");\n Bukkit.getServer().getScheduler().scheduleSyncRepeatingTask(this, new Task15MinInterval(), 0, REPEATING_TASK_SCHEDULE_MINS);\n\n // init metrics\n LoggerUtils.logInfo(\"Registering anonymous bStats metrics\");\n Metrics metrics = new Metrics(this, BS_PLUGIN_METRIC_ID);\n\n // Check for plugin updates\n new UpdateChecker(SPIGOT_PLUGIN_ID).getLatestVersion(version -> {\n if(this.getDescription().getVersion().equalsIgnoreCase(version)) {\n LoggerUtils.logInfo(\"Oh awesome! Plugin is up to date\");\n } else {\n isPluginOutdated = true;\n if(version.toLowerCase().contains(\"snapshot\")) {\n LoggerUtils.logWarning(\"Plugin has a new snapshot version available! (Version: \" + version + \")\");\n }\n else {\n LoggerUtils.logWarning(\"Plugin has a new update available! (Version: \" + version + \")\");\n }\n LoggerUtils.logWarning(\"Download here: https://www.spigotmc.org/resources/\" + SPIGOT_PLUGIN_ID + \"/\");\n }\n });\n }\n\n private void initCommands() {\n LoggerUtils.logInfo(\"Registering commands\");\n initFindItemCmd();\n initFindItemAdminCmd();\n }\n\n private void initBukkitEventListeners() {\n LoggerUtils.logInfo(\"Registering Bukkit event listeners\");\n this.getServer().getPluginManager().registerEvents(new PluginEnableEventListener(), this);\n this.getServer().getPluginManager().registerEvents(new PlayerCommandSendEventListener(), this);\n this.getServer().getPluginManager().registerEvents(new MenuListener(), this);\n this.getServer().getPluginManager().registerEvents(new PlayerJoinEventListener(), this);\n }\n private void initExternalPluginEventListeners() {\n LoggerUtils.logInfo(\"Registering external plugin event listeners\");\n if(PlayerWarpsPlugin.getIsEnabled()) {\n this.getServer().getPluginManager().registerEvents(new PWPlayerWarpRemoveEventListener(), this);\n this.getServer().getPluginManager().registerEvents(new PWPlayerWarpCreateEventListener(), this);\n }\n }\n \n public static ConfigProvider getConfigProvider() {\n return configProvider;\n }\n\n public static void initConfigProvider() {\n configProvider = new ConfigProvider();\n }\n\n public static PlayerMenuUtility getPlayerMenuUtility(Player p){\n PlayerMenuUtility playerMenuUtility;\n if(playerMenuUtilityMap.containsKey(p)) {\n return playerMenuUtilityMap.get(p);\n }\n else {\n playerMenuUtility = new PlayerMenuUtility(p);\n playerMenuUtilityMap.put(p, playerMenuUtility);\n return playerMenuUtility;\n }\n }\n\n public static boolean getPluginOutdated() {\n return isPluginOutdated;\n }\n\n public static int getPluginID() {\n return SPIGOT_PLUGIN_ID;\n }\n\n private void initFindItemCmd() {\n List<String> alias;\n if(StringUtils.isEmpty(FindItemAddOn.getConfigProvider().FIND_ITEM_TO_SELL_AUTOCOMPLETE)\n || StringUtils.containsIgnoreCase(FindItemAddOn.getConfigProvider().FIND_ITEM_TO_SELL_AUTOCOMPLETE, \" \")) {\n alias = Arrays.asList(\"shopsearch\", \"searchshop\", \"searchitem\");\n }\n else {\n alias = FindItemAddOn.getConfigProvider().FIND_ITEM_COMMAND_ALIAS;\n }\n // Register the subcommands under a core command\n try {\n CommandManager.createCoreCommand(\n this,\n \"finditem\",\n \"Search for items from all shops using an interactive GUI\",\n \"/finditem\",\n (commandSender, subCommandList) -> {\n commandSender.sendMessage(ColorTranslator.translateColorCodes(\"\"));\n commandSender.sendMessage(ColorTranslator.translateColorCodes(\"&7------------------------\"));\n commandSender.sendMessage(ColorTranslator.translateColorCodes(\"&6&lShop Search Commands\"));\n commandSender.sendMessage(ColorTranslator.translateColorCodes(\"&7------------------------\"));\n for (SubCommand subCommand : subCommandList) {\n commandSender.sendMessage(ColorTranslator.translateColorCodes(\"&#ff9933\" + subCommand.getSyntax() + \" &#a3a3c2\" + subCommand.getDescription()));\n }\n commandSender.sendMessage(ColorTranslator.translateColorCodes(\"\"));\n commandSender.sendMessage(ColorTranslator.translateColorCodes(\"&#b3b300Command alias:\"));\n alias.forEach(alias_i -> {\n commandSender.sendMessage(ColorTranslator.translateColorCodes(\"&8&l» db300/\" + alias_i));\n });\n commandSender.sendMessage(ColorTranslator.translateColorCodes(\"\"));\n },\n alias,\n SellSubCmd.class,\n BuySubCmd.class,\n HideShopSubCmd.class,\n RevealShopSubCmd.class);\n LoggerUtils.logInfo(\"Registered /finditem command\");\n } catch (NoSuchFieldException | IllegalAccessException e) {\n LoggerUtils.logError(e.getMessage());\n e.printStackTrace();\n }\n }\n\n private void initFindItemAdminCmd() {\n List<String> alias = List.of(\"fiadmin\");\n try {\n CommandManager.createCoreCommand(\n this,\n \"finditemadmin\",\n \"Admin command for Shop Search addon\",\n \"/finditemadmin\",\n (commandSender, subCommandList) -> {\n if (\n (commandSender.isOp())\n || (!commandSender.isOp() && (commandSender.hasPermission(PlayerPerms.FINDITEM_ADMIN.value())\n || commandSender.hasPermission(PlayerPerms.FINDITEM_RELOAD.value())))\n ) {\n commandSender.sendMessage(ColorTranslator.translateColorCodes(\"\"));\n commandSender.sendMessage(ColorTranslator.translateColorCodes(\"&7-----------------------------\"));\n commandSender.sendMessage(ColorTranslator.translateColorCodes(\"&6&lShop Search Admin Commands\"));\n commandSender.sendMessage(ColorTranslator.translateColorCodes(\"&7-----------------------------\"));\n\n for (SubCommand subCommand : subCommandList) {\n commandSender.sendMessage(ColorTranslator.translateColorCodes(\"&#ff1a1a\" + subCommand.getSyntax() + \" &#a3a3c2\" + subCommand.getDescription()));\n }\n commandSender.sendMessage(ColorTranslator.translateColorCodes(\"\"));\n commandSender.sendMessage(ColorTranslator.translateColorCodes(\"&#b3b300Command alias:\"));\n alias.forEach(alias_i -> {\n commandSender.sendMessage(ColorTranslator.translateColorCodes(\"&8&l» db300/\" + alias_i));\n });\n commandSender.sendMessage(ColorTranslator.translateColorCodes(\"\"));\n }\n },\n alias,\n ReloadSubCmd.class);\n LoggerUtils.logInfo(\"Registered /finditemadmin command\");\n } catch (NoSuchFieldException | IllegalAccessException e) {\n LoggerUtils.logError(e.getMessage());\n e.printStackTrace();\n }\n }\n\n public static boolean isQSReremakeInstalled() {\n return qSReremakeInstalled;\n }\n\n public static boolean isQSHikariInstalled() {\n return qSHikariInstalled;\n }\n\n public static void setQSReremakeInstalled(boolean qSReremakeInstalled) {\n FindItemAddOn.qSReremakeInstalled = qSReremakeInstalled;\n }\n\n public static void setQSHikariInstalled(boolean qSHikariInstalled) {\n FindItemAddOn.qSHikariInstalled = qSHikariInstalled;\n }\n\n public static QSApi getQsApiInstance() {\n return qsApi;\n }\n\n}"
},
{
"identifier": "FoundShopItemModel",
"path": "src/main/java/io/myzticbean/finditemaddon/Models/FoundShopItemModel.java",
"snippet": "@Getter\n@AllArgsConstructor\npublic class FoundShopItemModel {\n private final double shopPrice;\n private final int remainingStockOrSpace;\n private final UUID shopOwner;\n private final Location shopLocation;\n private final ItemStack item;\n}"
},
{
"identifier": "LoggerUtils",
"path": "src/main/java/io/myzticbean/finditemaddon/Utils/LoggerUtils.java",
"snippet": "public class LoggerUtils {\n public static void logDebugInfo(String text) {\n if(FindItemAddOn.getConfigProvider().DEBUG_MODE) {\n Bukkit.getLogger().warning(ColorTranslator.translateColorCodes(\"[QSFindItemAddOn-DebugLog] \" + text));\n }\n }\n public static void logInfo(String text) {\n Bukkit.getLogger().info(ColorTranslator.translateColorCodes(\"[QSFindItemAddOn] \" + text));\n }\n public static void logError(String text) {\n Bukkit.getLogger().severe(ColorTranslator.translateColorCodes(\"[QSFindItemAddOn] \" + text));\n }\n public static void logWarning(String text) {\n// Bukkit.getConsoleSender().sendMessage(ColorTranslator.translateColorCodes(\"[QSFindItemAddOn] &6\" + text));\n Bukkit.getLogger().warning(ColorTranslator.translateColorCodes(\"[QSFindItemAddOn] \" + text));\n }\n}"
}
] | import io.myzticbean.finditemaddon.FindItemAddOn;
import io.myzticbean.finditemaddon.Models.FoundShopItemModel;
import io.myzticbean.finditemaddon.Utils.LoggerUtils;
import me.kodysimpson.simpapi.colors.ColorTranslator;
import org.apache.commons.lang3.StringUtils;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import java.util.List;
import java.util.UUID; | 4,136 | package io.myzticbean.finditemaddon.Handlers.GUIHandler;
public abstract class PaginatedMenu extends Menu {
protected int page = 0;
protected int maxItemsPerPage = 45;
protected int index = 0;
protected ItemStack backButton;
protected ItemStack nextButton;
protected ItemStack closeInvButton;
private final String BACK_BUTTON_SKIN_ID = "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvZjZkYWI3MjcxZjRmZjA0ZDU0NDAyMTkwNjdhMTA5YjVjMGMxZDFlMDFlYzYwMmMwMDIwNDc2ZjdlYjYxMjE4MCJ9fX0=";
private final String NEXT_BUTTON_SKIN_ID = "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvOGFhMTg3ZmVkZTg4ZGUwMDJjYmQ5MzA1NzVlYjdiYTQ4ZDNiMWEwNmQ5NjFiZGM1MzU4MDA3NTBhZjc2NDkyNiJ9fX0=";
public PaginatedMenu(PlayerMenuUtility playerMenuUtility) {
super(playerMenuUtility);
initMaterialsForBottomBar();
}
public PaginatedMenu(PlayerMenuUtility playerMenuUtility, List<FoundShopItemModel> searchResult) {
super(playerMenuUtility);
initMaterialsForBottomBar();
super.playerMenuUtility.setPlayerShopSearchResult(searchResult);
}
private void initMaterialsForBottomBar() {
createGUIBackButton();
createGUINextButton();
createGUICloseInvButton();
}
public void addMenuBottomBar() {
inventory.setItem(45, backButton);
inventory.setItem(53, nextButton);
inventory.setItem(49, closeInvButton);
inventory.setItem(46, super.GUI_FILLER_ITEM);
inventory.setItem(47, super.GUI_FILLER_ITEM);
inventory.setItem(48, super.GUI_FILLER_ITEM);
inventory.setItem(50, super.GUI_FILLER_ITEM);
inventory.setItem(51, super.GUI_FILLER_ITEM);
inventory.setItem(52, super.GUI_FILLER_ITEM);
}
private void createGUIBackButton() { | package io.myzticbean.finditemaddon.Handlers.GUIHandler;
public abstract class PaginatedMenu extends Menu {
protected int page = 0;
protected int maxItemsPerPage = 45;
protected int index = 0;
protected ItemStack backButton;
protected ItemStack nextButton;
protected ItemStack closeInvButton;
private final String BACK_BUTTON_SKIN_ID = "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvZjZkYWI3MjcxZjRmZjA0ZDU0NDAyMTkwNjdhMTA5YjVjMGMxZDFlMDFlYzYwMmMwMDIwNDc2ZjdlYjYxMjE4MCJ9fX0=";
private final String NEXT_BUTTON_SKIN_ID = "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvOGFhMTg3ZmVkZTg4ZGUwMDJjYmQ5MzA1NzVlYjdiYTQ4ZDNiMWEwNmQ5NjFiZGM1MzU4MDA3NTBhZjc2NDkyNiJ9fX0=";
public PaginatedMenu(PlayerMenuUtility playerMenuUtility) {
super(playerMenuUtility);
initMaterialsForBottomBar();
}
public PaginatedMenu(PlayerMenuUtility playerMenuUtility, List<FoundShopItemModel> searchResult) {
super(playerMenuUtility);
initMaterialsForBottomBar();
super.playerMenuUtility.setPlayerShopSearchResult(searchResult);
}
private void initMaterialsForBottomBar() {
createGUIBackButton();
createGUINextButton();
createGUICloseInvButton();
}
public void addMenuBottomBar() {
inventory.setItem(45, backButton);
inventory.setItem(53, nextButton);
inventory.setItem(49, closeInvButton);
inventory.setItem(46, super.GUI_FILLER_ITEM);
inventory.setItem(47, super.GUI_FILLER_ITEM);
inventory.setItem(48, super.GUI_FILLER_ITEM);
inventory.setItem(50, super.GUI_FILLER_ITEM);
inventory.setItem(51, super.GUI_FILLER_ITEM);
inventory.setItem(52, super.GUI_FILLER_ITEM);
}
private void createGUIBackButton() { | Material backButtonMaterial = Material.getMaterial(FindItemAddOn.getConfigProvider().SHOP_GUI_BACK_BUTTON_MATERIAL); | 0 | 2023-11-22 11:36:01+00:00 | 8k |
DIDA-lJ/qiyao-12306 | services/ticket-service/src/main/java/org/opengoofy/index12306/biz/ticketservice/service/handler/ticket/TrainSecondClassPurchaseTicketHandler.java | [
{
"identifier": "VehicleSeatTypeEnum",
"path": "services/ticket-service/src/main/java/org/opengoofy/index12306/biz/ticketservice/common/enums/VehicleSeatTypeEnum.java",
"snippet": "@RequiredArgsConstructor\npublic enum VehicleSeatTypeEnum {\n\n /**\n * 商务座\n */\n BUSINESS_CLASS(0, \"BUSINESS_CLASS\", \"商务座\"),\n\n /**\n * 一等座\n */\n FIRST_CLASS(1, \"FIRST_CLASS\", \"一等座\"),\n\n /**\n * 二等座\n */\n SECOND_CLASS(2, \"SECOND_CLASS\", \"二等座\"),\n\n /**\n * 二等包座\n */\n SECOND_CLASS_CABIN_SEAT(3, \"SECOND_CLASS_CABIN_SEAT\", \"二等包座\"),\n\n /**\n * 一等卧\n */\n FIRST_SLEEPER(4, \"FIRST_SLEEPER\", \"一等卧\"),\n\n /**\n * 二等卧\n */\n SECOND_SLEEPER(5, \"SECOND_SLEEPER\", \"二等卧\"),\n\n /**\n * 软卧\n */\n SOFT_SLEEPER(6, \"SOFT_SLEEPER\", \"软卧\"),\n\n /**\n * 硬卧\n */\n HARD_SLEEPER(7, \"HARD_SLEEPER\", \"硬卧\"),\n\n /**\n * 硬座\n */\n HARD_SEAT(8, \"HARD_SEAT\", \"硬座\"),\n\n /**\n * 高级软卧\n */\n DELUXE_SOFT_SLEEPER(9, \"DELUXE_SOFT_SLEEPER\", \"高级软卧\"),\n\n /**\n * 动卧\n */\n DINING_CAR_SLEEPER(10, \"DINING_CAR_SLEEPER\", \"动卧\"),\n\n /**\n * 软座\n */\n SOFT_SEAT(11, \"SOFT_SEAT\", \"软座\"),\n\n /**\n * 特等座\n */\n FIRST_CLASS_SEAT(12, \"FIRST_CLASS_SEAT\", \"特等座\"),\n\n /**\n * 无座\n */\n NO_SEAT_SLEEPER(13, \"NO_SEAT_SLEEPER\", \"无座\"),\n\n /**\n * 其他\n */\n OTHER(14, \"OTHER\", \"其他\");\n\n @Getter\n private final Integer code;\n\n @Getter\n private final String name;\n\n @Getter\n private final String value;\n\n /**\n * 根据编码查找名称\n */\n public static String findNameByCode(Integer code) {\n return Arrays.stream(VehicleSeatTypeEnum.values())\n .filter(each -> Objects.equals(each.getCode(), code))\n .findFirst()\n .map(VehicleSeatTypeEnum::getName)\n .orElse(null);\n }\n\n /**\n * 根据编码查找值\n */\n public static String findValueByCode(Integer code) {\n return Arrays.stream(VehicleSeatTypeEnum.values())\n .filter(each -> Objects.equals(each.getCode(), code))\n .findFirst()\n .map(VehicleSeatTypeEnum::getValue)\n .orElse(null);\n }\n}"
},
{
"identifier": "VehicleTypeEnum",
"path": "services/ticket-service/src/main/java/org/opengoofy/index12306/biz/ticketservice/common/enums/VehicleTypeEnum.java",
"snippet": "@RequiredArgsConstructor\npublic enum VehicleTypeEnum {\n\n /**\n * 高铁\n */\n HIGH_SPEED_RAIN(0, \"HIGH_SPEED_RAIN\", \"高铁\", ListUtil.of(BUSINESS_CLASS.getCode(), FIRST_CLASS.getCode(), SECOND_CLASS.getCode())),\n\n /**\n * 动车\n */\n BULLET(1, \"BULLET\", \"动车\", ListUtil.of(SECOND_CLASS_CABIN_SEAT.getCode(), FIRST_SLEEPER.getCode(), SECOND_SLEEPER.getCode(), NO_SEAT_SLEEPER.getCode())),\n\n /**\n * 普通车\n */\n REGULAR_TRAIN(2, \"REGULAR_TRAIN\", \"普通车\", ListUtil.of(SOFT_SLEEPER.getCode(), HARD_SLEEPER.getCode(), HARD_SEAT.getCode(), NO_SEAT_SLEEPER.getCode())),\n\n /**\n * 汽车\n */\n CAR(3, \"CAR\", \"汽车\", null),\n\n /**\n * 飞机\n */\n AIRPLANE(4, \"AIRPLANE\", \"飞机\", null);\n\n @Getter\n private final Integer code;\n\n @Getter\n private final String name;\n\n @Getter\n private final String value;\n\n @Getter\n private final List<Integer> seatTypes;\n\n /**\n * 根据编码查找名称\n */\n public static String findNameByCode(Integer code) {\n return Arrays.stream(VehicleTypeEnum.values())\n .filter(each -> Objects.equals(each.getCode(), code))\n .findFirst()\n .map(VehicleTypeEnum::getName)\n .orElse(null);\n }\n\n /**\n * 根据编码查找座位类型集合\n */\n public static List<Integer> findSeatTypesByCode(Integer code) {\n return Arrays.stream(VehicleTypeEnum.values())\n .filter(each -> Objects.equals(each.getCode(), code))\n .findFirst()\n .map(VehicleTypeEnum::getSeatTypes)\n .orElse(null);\n }\n}"
},
{
"identifier": "PurchaseTicketPassengerDetailDTO",
"path": "services/ticket-service/src/main/java/org/opengoofy/index12306/biz/ticketservice/dto/domain/PurchaseTicketPassengerDetailDTO.java",
"snippet": "@Data\npublic class PurchaseTicketPassengerDetailDTO {\n\n /**\n * 乘车人 ID\n */\n private String passengerId;\n\n /**\n * 座位类型\n */\n private Integer seatType;\n}"
},
{
"identifier": "TrainSeatBaseDTO",
"path": "services/ticket-service/src/main/java/org/opengoofy/index12306/biz/ticketservice/dto/domain/TrainSeatBaseDTO.java",
"snippet": "@Builder\n@Data\n@AllArgsConstructor\npublic class TrainSeatBaseDTO {\n\n /**\n * 高铁列车 ID\n */\n private String trainId;\n\n /**\n * 列车起始站点\n */\n private String departure;\n\n /**\n * 列车到达站点\n */\n private String arrival;\n\n /**\n * 乘客信息\n */\n private List<PurchaseTicketPassengerDetailDTO> passengerSeatDetails;\n\n /**\n * 选择座位信息\n */\n private List<String> chooseSeatList;\n}"
},
{
"identifier": "SeatService",
"path": "services/ticket-service/src/main/java/org/opengoofy/index12306/biz/ticketservice/service/SeatService.java",
"snippet": "public interface SeatService extends IService<SeatDO> {\n\n /**\n * 获取列车车厢中可用的座位集合\n *\n * @param trainId 列车 ID\n * @param carriageNumber 车厢号\n * @param seatType 座位类型\n * @param departure 出发站\n * @param arrival 到达站\n * @return 可用座位集合\n */\n List<String> listAvailableSeat(String trainId, String carriageNumber, Integer seatType, String departure, String arrival);\n\n /**\n * 获取列车车厢余票集合\n *\n * @param trainId 列车 ID\n * @param departure 出发站\n * @param arrival 到达站\n * @param trainCarriageList 车厢编号集合\n * @return 车厢余票集合\n */\n List<Integer> listSeatRemainingTicket(String trainId, String departure, String arrival, List<String> trainCarriageList);\n\n /**\n * 查询列车有余票的车厢号集合\n *\n * @param trainId 列车 ID\n * @param carriageType 车厢类型\n * @param departure 出发站\n * @param arrival 到达站\n * @return 车厢号集合\n */\n List<String> listUsableCarriageNumber(String trainId, Integer carriageType, String departure, String arrival);\n\n /**\n * 锁定选中以及沿途车票状态\n *\n * @param trainId 列车 ID\n * @param departure 出发站\n * @param arrival 到达站\n * @param trainPurchaseTicketRespList 乘车人以及座位信息\n */\n void lockSeat(String trainId, String departure, String arrival, List<TrainPurchaseTicketRespDTO> trainPurchaseTicketRespList);\n\n /**\n * 解锁选中以及沿途车票状态\n *\n * @param trainId 列车 ID\n * @param departure 出发站\n * @param arrival 到达站\n * @param trainPurchaseTicketResults 乘车人以及座位信息\n */\n void unlock(String trainId, String departure, String arrival, List<TrainPurchaseTicketRespDTO> trainPurchaseTicketResults);\n}"
},
{
"identifier": "AbstractTrainPurchaseTicketTemplate",
"path": "services/ticket-service/src/main/java/org/opengoofy/index12306/biz/ticketservice/service/handler/ticket/base/AbstractTrainPurchaseTicketTemplate.java",
"snippet": "public abstract class AbstractTrainPurchaseTicketTemplate implements IPurchaseTicket, CommandLineRunner, AbstractExecuteStrategy<SelectSeatDTO, List<TrainPurchaseTicketRespDTO>> {\n\n private DistributedCache distributedCache;\n private String ticketAvailabilityCacheUpdateType;\n private TrainStationService trainStationService;\n\n /**\n * 选择座位\n *\n * @param requestParam 购票请求入参\n * @return 乘车人座位\n */\n protected abstract List<TrainPurchaseTicketRespDTO> selectSeats(SelectSeatDTO requestParam);\n\n protected TrainSeatBaseDTO buildTrainSeatBaseDTO(SelectSeatDTO requestParam) {\n return TrainSeatBaseDTO.builder()\n .trainId(requestParam.getRequestParam().getTrainId())\n .departure(requestParam.getRequestParam().getDeparture())\n .arrival(requestParam.getRequestParam().getArrival())\n .chooseSeatList(requestParam.getRequestParam().getChooseSeats())\n .passengerSeatDetails(requestParam.getPassengerSeatDetails())\n .build();\n }\n\n @Override\n public List<TrainPurchaseTicketRespDTO> executeResp(SelectSeatDTO requestParam) {\n List<TrainPurchaseTicketRespDTO> actualResult = selectSeats(requestParam);\n // 扣减车厢余票缓存,扣减站点余票缓存\n if (CollUtil.isNotEmpty(actualResult) && !StrUtil.equals(ticketAvailabilityCacheUpdateType, \"binlog\")) {\n String trainId = requestParam.getRequestParam().getTrainId();\n String departure = requestParam.getRequestParam().getDeparture();\n String arrival = requestParam.getRequestParam().getArrival();\n StringRedisTemplate stringRedisTemplate = (StringRedisTemplate) distributedCache.getInstance();\n List<RouteDTO> routeDTOList = trainStationService.listTakeoutTrainStationRoute(trainId, departure, arrival);\n routeDTOList.forEach(each -> {\n String keySuffix = StrUtil.join(\"_\", trainId, each.getStartStation(), each.getEndStation());\n stringRedisTemplate.opsForHash().increment(TRAIN_STATION_REMAINING_TICKET + keySuffix, String.valueOf(requestParam.getSeatType()), -actualResult.size());\n });\n }\n return actualResult;\n }\n\n @Override\n public void run(String... args) throws Exception {\n distributedCache = ApplicationContextHolder.getBean(DistributedCache.class);\n trainStationService = ApplicationContextHolder.getBean(TrainStationService.class);\n ConfigurableEnvironment configurableEnvironment = ApplicationContextHolder.getBean(ConfigurableEnvironment.class);\n ticketAvailabilityCacheUpdateType = configurableEnvironment.getProperty(\"ticket.availability.cache-update.type\", \"\");\n }\n}"
},
{
"identifier": "SelectSeatDTO",
"path": "services/ticket-service/src/main/java/org/opengoofy/index12306/biz/ticketservice/service/handler/ticket/dto/SelectSeatDTO.java",
"snippet": "@Data\n@NoArgsConstructor\n@AllArgsConstructor\n@Builder\npublic final class SelectSeatDTO {\n\n /**\n * 座位类型\n */\n private Integer seatType;\n\n /**\n * 座位对应的乘车人集合\n */\n private List<PurchaseTicketPassengerDetailDTO> passengerSeatDetails;\n\n /**\n * 购票原始入参\n */\n private PurchaseTicketReqDTO requestParam;\n}"
},
{
"identifier": "TrainPurchaseTicketRespDTO",
"path": "services/ticket-service/src/main/java/org/opengoofy/index12306/biz/ticketservice/service/handler/ticket/dto/TrainPurchaseTicketRespDTO.java",
"snippet": "@Data\npublic class TrainPurchaseTicketRespDTO {\n\n /**\n * 乘车人 ID\n */\n private String passengerId;\n\n /**\n * 乘车人姓名\n */\n private String realName;\n\n /**\n * 乘车人证件类型\n */\n private Integer idType;\n\n /**\n * 乘车人证件号\n */\n private String idCard;\n\n /**\n * 乘车人手机号\n */\n private String phone;\n\n /**\n * 用户类型 0:成人 1:儿童 2:学生 3:残疾军人\n */\n private Integer userType;\n\n /**\n * 席别类型\n */\n private Integer seatType;\n\n /**\n * 车厢号\n */\n private String carriageNumber;\n\n /**\n * 座位号\n */\n private String seatNumber;\n\n /**\n * 座位金额\n */\n private Integer amount;\n}"
},
{
"identifier": "SeatSelection",
"path": "services/ticket-service/src/main/java/org/opengoofy/index12306/biz/ticketservice/service/handler/ticket/select/SeatSelection.java",
"snippet": "public class SeatSelection {\n\n public static int[][] adjacent(int numSeats, int[][] seatLayout) {\n int numRows = seatLayout.length;\n int numCols = seatLayout[0].length;\n List<int[]> selectedSeats = new ArrayList<>();\n for (int i = 0; i < numRows; i++) {\n for (int j = 0; j < numCols; j++) {\n if (seatLayout[i][j] == 0) {\n int consecutiveSeats = 0;\n for (int k = j; k < numCols; k++) {\n if (seatLayout[i][k] == 0) {\n consecutiveSeats++;\n if (consecutiveSeats == numSeats) {\n for (int l = k - numSeats + 1; l <= k; l++) {\n selectedSeats.add(new int[]{i, l});\n }\n break;\n }\n } else {\n consecutiveSeats = 0;\n }\n }\n if (!selectedSeats.isEmpty()) {\n break;\n }\n }\n }\n if (!selectedSeats.isEmpty()) {\n break;\n }\n }\n if (CollUtil.isEmpty(selectedSeats)) {\n return null;\n }\n int[][] actualSeat = new int[numSeats][2];\n int i = 0;\n for (int[] seat : selectedSeats) {\n int row = seat[0] + 1;\n int col = seat[1] + 1;\n actualSeat[i][0] = row;\n actualSeat[i][1] = col;\n i++;\n }\n return actualSeat;\n }\n\n public static int[][] nonAdjacent(int numSeats, int[][] seatLayout) {\n int numRows = seatLayout.length;\n int numCols = seatLayout[0].length;\n List<int[]> selectedSeats = new ArrayList<>();\n for (int i = 0; i < numRows; i++) {\n for (int j = 0; j < numCols; j++) {\n if (seatLayout[i][j] == 0) {\n selectedSeats.add(new int[]{i, j});\n if (selectedSeats.size() == numSeats) {\n break;\n }\n }\n }\n if (selectedSeats.size() == numSeats) {\n break;\n }\n }\n return convertToActualSeat(selectedSeats);\n }\n\n private static int[][] convertToActualSeat(List<int[]> selectedSeats) {\n int[][] actualSeat = new int[selectedSeats.size()][2];\n for (int i = 0; i < selectedSeats.size(); i++) {\n int[] seat = selectedSeats.get(i);\n int row = seat[0] + 1;\n int col = seat[1] + 1;\n actualSeat[i][0] = row;\n actualSeat[i][1] = col;\n }\n return actualSeat;\n }\n\n public static void main(String[] args) {\n int[][] seatLayout = {\n {1, 1, 1, 1},\n {1, 1, 1, 0},\n {1, 1, 1, 0},\n {0, 0, 0, 0}\n };\n int[][] select = adjacent(2, seatLayout);\n System.out.println(\"成功预订相邻座位,座位位置为:\");\n assert select != null;\n for (int[] ints : select) {\n System.out.printf(\"第 %d 排,第 %d 列%n\", ints[0], ints[1]);\n }\n\n int[][] seatLayoutTwo = {\n {1, 0, 1, 1},\n {1, 1, 0, 0},\n {1, 1, 1, 0},\n {0, 0, 0, 0}\n };\n int[][] selectTwo = nonAdjacent(3, seatLayoutTwo);\n System.out.println(\"成功预订不相邻座位,座位位置为:\");\n for (int[] ints : selectTwo) {\n System.out.printf(\"第 %d 排,第 %d 列%n\", ints[0], ints[1]);\n }\n }\n}"
},
{
"identifier": "SeatNumberUtil",
"path": "services/ticket-service/src/main/java/org/opengoofy/index12306/biz/ticketservice/toolkit/SeatNumberUtil.java",
"snippet": "public final class SeatNumberUtil {\n\n /**\n * 复兴号-商务座\n */\n private static final Map<Integer, String> TRAIN_BUSINESS_CLASS_SEAT_NUMBER_MAP = new HashMap<>();\n\n /**\n * 复兴号-一等座\n */\n private static final Map<Integer, String> TRAIN_FIRST_CLASS_SEAT_NUMBER_MAP = new HashMap<>();\n\n /**\n * 复兴号-二等座\n */\n private static final Map<Integer, String> TRAIN_SECOND_CLASS_SEAT_NUMBER_MAP = new HashMap<>();\n\n static {\n TRAIN_BUSINESS_CLASS_SEAT_NUMBER_MAP.put(1, \"A\");\n TRAIN_BUSINESS_CLASS_SEAT_NUMBER_MAP.put(2, \"C\");\n TRAIN_BUSINESS_CLASS_SEAT_NUMBER_MAP.put(3, \"F\");\n TRAIN_FIRST_CLASS_SEAT_NUMBER_MAP.put(1, \"A\");\n TRAIN_FIRST_CLASS_SEAT_NUMBER_MAP.put(2, \"C\");\n TRAIN_FIRST_CLASS_SEAT_NUMBER_MAP.put(3, \"D\");\n TRAIN_FIRST_CLASS_SEAT_NUMBER_MAP.put(4, \"F\");\n TRAIN_SECOND_CLASS_SEAT_NUMBER_MAP.put(1, \"A\");\n TRAIN_SECOND_CLASS_SEAT_NUMBER_MAP.put(2, \"B\");\n TRAIN_SECOND_CLASS_SEAT_NUMBER_MAP.put(3, \"C\");\n TRAIN_SECOND_CLASS_SEAT_NUMBER_MAP.put(4, \"D\");\n TRAIN_SECOND_CLASS_SEAT_NUMBER_MAP.put(5, \"F\");\n }\n\n /**\n * 根据类型转换座位号\n *\n * @param type 列车座位类型\n * @param num 座位号\n * @return 座位编号\n */\n public static String convert(int type, int num) {\n String serialNumber = null;\n switch (type) {\n case 0 -> serialNumber = TRAIN_BUSINESS_CLASS_SEAT_NUMBER_MAP.get(num);\n case 1 -> serialNumber = TRAIN_FIRST_CLASS_SEAT_NUMBER_MAP.get(num);\n case 2 -> serialNumber = TRAIN_SECOND_CLASS_SEAT_NUMBER_MAP.get(num);\n }\n return serialNumber;\n }\n}"
},
{
"identifier": "ServiceException",
"path": "frameworks/convention/src/main/java/org/opengoofy/index12306/framework/starter/convention/exception/ServiceException.java",
"snippet": "public class ServiceException extends AbstractException {\n\n public ServiceException(String message) {\n this(message, null, BaseErrorCode.SERVICE_ERROR);\n }\n\n public ServiceException(IErrorCode errorCode) {\n this(null, errorCode);\n }\n\n public ServiceException(String message, IErrorCode errorCode) {\n this(message, null, errorCode);\n }\n\n public ServiceException(String message, Throwable throwable, IErrorCode errorCode) {\n super(Optional.ofNullable(message).orElse(errorCode.message()), throwable, errorCode);\n }\n\n @Override\n public String toString() {\n return \"ServiceException{\" +\n \"code='\" + errorCode + \"',\" +\n \"message='\" + errorMessage + \"'\" +\n '}';\n }\n}"
}
] | import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.lang.Pair;
import com.google.common.collect.Lists;
import lombok.RequiredArgsConstructor;
import org.opengoofy.index12306.biz.ticketservice.common.enums.VehicleSeatTypeEnum;
import org.opengoofy.index12306.biz.ticketservice.common.enums.VehicleTypeEnum;
import org.opengoofy.index12306.biz.ticketservice.dto.domain.PurchaseTicketPassengerDetailDTO;
import org.opengoofy.index12306.biz.ticketservice.dto.domain.TrainSeatBaseDTO;
import org.opengoofy.index12306.biz.ticketservice.service.SeatService;
import org.opengoofy.index12306.biz.ticketservice.service.handler.ticket.base.AbstractTrainPurchaseTicketTemplate;
import org.opengoofy.index12306.biz.ticketservice.service.handler.ticket.dto.SelectSeatDTO;
import org.opengoofy.index12306.biz.ticketservice.service.handler.ticket.dto.TrainPurchaseTicketRespDTO;
import org.opengoofy.index12306.biz.ticketservice.service.handler.ticket.select.SeatSelection;
import org.opengoofy.index12306.biz.ticketservice.toolkit.SeatNumberUtil;
import org.opengoofy.index12306.framework.starter.convention.exception.ServiceException;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger; | 6,047 | /*
* 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.opengoofy.index12306.biz.ticketservice.service.handler.ticket;
/**
* 高铁二等座购票组件
*
* @公众号:马丁玩编程,回复:加群,添加马哥微信(备注:12306)获取项目资料
*/
@Component
@RequiredArgsConstructor
public class TrainSecondClassPurchaseTicketHandler extends AbstractTrainPurchaseTicketTemplate {
private final SeatService seatService;
private static final Map<Character, Integer> SEAT_Y_INT = Map.of('A', 0, 'B', 1, 'C', 2, 'D', 3, 'F', 4);
@Override
public String mark() {
return VehicleTypeEnum.HIGH_SPEED_RAIN.getName() + VehicleSeatTypeEnum.SECOND_CLASS.getName();
}
@Override
protected List<TrainPurchaseTicketRespDTO> selectSeats(SelectSeatDTO requestParam) {
String trainId = requestParam.getRequestParam().getTrainId();
String departure = requestParam.getRequestParam().getDeparture();
String arrival = requestParam.getRequestParam().getArrival();
List<PurchaseTicketPassengerDetailDTO> passengerSeatDetails = requestParam.getPassengerSeatDetails();
List<String> trainCarriageList = seatService.listUsableCarriageNumber(trainId, requestParam.getSeatType(), departure, arrival);
List<Integer> trainStationCarriageRemainingTicket = seatService.listSeatRemainingTicket(trainId, departure, arrival, trainCarriageList);
int remainingTicketSum = trainStationCarriageRemainingTicket.stream().mapToInt(Integer::intValue).sum();
if (remainingTicketSum < passengerSeatDetails.size()) { | /*
* 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.opengoofy.index12306.biz.ticketservice.service.handler.ticket;
/**
* 高铁二等座购票组件
*
* @公众号:马丁玩编程,回复:加群,添加马哥微信(备注:12306)获取项目资料
*/
@Component
@RequiredArgsConstructor
public class TrainSecondClassPurchaseTicketHandler extends AbstractTrainPurchaseTicketTemplate {
private final SeatService seatService;
private static final Map<Character, Integer> SEAT_Y_INT = Map.of('A', 0, 'B', 1, 'C', 2, 'D', 3, 'F', 4);
@Override
public String mark() {
return VehicleTypeEnum.HIGH_SPEED_RAIN.getName() + VehicleSeatTypeEnum.SECOND_CLASS.getName();
}
@Override
protected List<TrainPurchaseTicketRespDTO> selectSeats(SelectSeatDTO requestParam) {
String trainId = requestParam.getRequestParam().getTrainId();
String departure = requestParam.getRequestParam().getDeparture();
String arrival = requestParam.getRequestParam().getArrival();
List<PurchaseTicketPassengerDetailDTO> passengerSeatDetails = requestParam.getPassengerSeatDetails();
List<String> trainCarriageList = seatService.listUsableCarriageNumber(trainId, requestParam.getSeatType(), departure, arrival);
List<Integer> trainStationCarriageRemainingTicket = seatService.listSeatRemainingTicket(trainId, departure, arrival, trainCarriageList);
int remainingTicketSum = trainStationCarriageRemainingTicket.stream().mapToInt(Integer::intValue).sum();
if (remainingTicketSum < passengerSeatDetails.size()) { | throw new ServiceException("站点余票不足,请尝试更换座位类型或选择其它站点"); | 10 | 2023-11-23 07:59:11+00:00 | 8k |
estkme-group/infineon-lpa-mirror | app/src/main/java/com/infineon/esim/lpa/lpa/task/ProfileActionTask.java | [
{
"identifier": "ProfileActionType",
"path": "core/src/main/java/com/infineon/esim/lpa/core/dtos/enums/ProfileActionType.java",
"snippet": "public enum ProfileActionType {\n PROFILE_ACTION_ENABLE,\n PROFILE_ACTION_DELETE,\n PROFILE_ACTION_DISABLE,\n PROFILE_ACTION_SET_NICKNAME,\n}"
},
{
"identifier": "ProfileMetadata",
"path": "core/src/main/java/com/infineon/esim/lpa/core/dtos/profile/ProfileMetadata.java",
"snippet": "final public class ProfileMetadata implements Parcelable {\n private static final String TAG = ProfileMetadata.class.getName();\n\n public static final String STATE_ENABLED = \"Enabled\";\n public static final String STATE_DISABLED = \"Disabled\";\n\n private static final String ICCID = \"ICCID\";\n private static final String STATE = \"STATE\";\n private static final String NAME = \"NAME\";\n private static final String PROVIDER_NAME = \"PROVIDER_NAME\";\n private static final String NICKNAME = \"NICKNAME\";\n private static final String ICON = \"ICON\";\n\n private final Map<String, String> profileMetadataMap;\n\n static public String formatIccidUserString(String iccidRawString) {\n // swap the odd/even characters to form a new string\n // ignoring the second last char\n int i = 0;\n StringBuilder newText = new StringBuilder();\n\n while(i < iccidRawString.length() - 1) {\n newText.append(iccidRawString.charAt(i + 1));\n newText.append(iccidRawString.charAt(i));\n i += 2;\n }\n return newText.toString();\n }\n\n public ProfileMetadata(Map<String, String> profileMetadataMap) {\n this.profileMetadataMap = new HashMap<>(profileMetadataMap);\n }\n\n public ProfileMetadata(@NonNull String iccid,\n @NonNull String profileState,\n @NonNull String profileName,\n @NonNull String serviceProviderName,\n @Nullable String profileNickname,\n @Nullable String icon) {\n profileMetadataMap = new HashMap<>();\n initialize(iccid, profileState, profileName, serviceProviderName, profileNickname, icon);\n }\n\n public ProfileMetadata(@NonNull Iccid iccid,\n @NonNull ProfileState profileState,\n @NonNull BerUTF8String profileName,\n @NonNull BerUTF8String serviceProviderName,\n @Nullable BerUTF8String profileNickname,\n @Nullable BerOctetString icon) {\n profileMetadataMap = new HashMap<>();\n\n String nicknameString = null;\n String iconString = null;\n if(profileNickname != null) {\n nicknameString = profileNickname.toString();\n }\n if(icon != null) {\n iconString = icon.toString();\n }\n initialize(iccid.toString(),\n ProfileStates.getString(profileState),\n profileName.toString(),\n serviceProviderName.toString(),\n nicknameString,\n iconString);\n }\n\n public ProfileMetadata(@NonNull ProfileInfo profileInfo) {\n this(profileInfo.getIccid(),\n profileInfo.getProfileState(),\n profileInfo.getProfileName(),\n profileInfo.getServiceProviderName(),\n profileInfo.getProfileNickname(),\n profileInfo.getIcon());\n }\n\n public ProfileMetadata(StoreMetadataRequest storeMetadataRequest) {\n this(storeMetadataRequest.getIccid(),\n new ProfileState(0),\n storeMetadataRequest.getProfileName(),\n storeMetadataRequest.getServiceProviderName(),\n null,\n null);\n }\n\n private void initialize(@NonNull String iccid,\n @NonNull String state,\n @NonNull String name,\n @NonNull String provider,\n @Nullable String nickname,\n @Nullable String icon) {\n\n profileMetadataMap.put(NAME, name);\n profileMetadataMap.put(ICCID, iccid);\n profileMetadataMap.put(STATE, state);\n profileMetadataMap.put(PROVIDER_NAME, provider);\n\n if(nickname != null) {\n profileMetadataMap.put(NICKNAME, nickname);\n }\n if(icon != null) {\n profileMetadataMap.put(ICON, icon);\n }\n }\n\n public Boolean hasNickname() {\n return (getNickname() != null) && (!getNickname().equals(\"\"));\n }\n\n public void setEnabled(boolean isEnabled) {\n if(isEnabled) {\n profileMetadataMap.replace(STATE, STATE_ENABLED);\n } else {\n profileMetadataMap.replace(STATE, STATE_DISABLED);\n }\n }\n\n public Boolean isEnabled() {\n return getState().equals(STATE_ENABLED);\n }\n\n public String getName() {\n return profileMetadataMap.get(NAME);\n }\n\n public String getIccid() {\n return profileMetadataMap.get(ICCID);\n }\n\n public String getState() {\n return profileMetadataMap.get(STATE);\n }\n\n public String getProvider() {\n return profileMetadataMap.get(PROVIDER_NAME);\n }\n\n public String getNickname() {\n return profileMetadataMap.get(NICKNAME);\n }\n\n private String getIconString() {\n return profileMetadataMap.get(ICON);\n }\n\n public void setNickname(String nickname) {\n profileMetadataMap.put(NICKNAME, nickname);\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n @Override\n public void writeToParcel(Parcel out, int flags) {\n out.writeString(getName());\n out.writeString(getIccid());\n out.writeString(getState());\n out.writeString(getProvider());\n out.writeString(getNickname());\n out.writeString(getIconString());\n }\n\n public static final Parcelable.Creator<ProfileMetadata> CREATOR = new Parcelable.Creator<ProfileMetadata>() {\n public ProfileMetadata createFromParcel(Parcel in) {\n return new ProfileMetadata(in);\n }\n\n public ProfileMetadata[] newArray(int size) {\n return new ProfileMetadata[size];\n }\n };\n\n private ProfileMetadata(Parcel in) {\n profileMetadataMap = new HashMap<>();\n profileMetadataMap.put(NAME, in.readString());\n profileMetadataMap.put(ICCID, in.readString());\n profileMetadataMap.put(STATE, in.readString());\n profileMetadataMap.put(PROVIDER_NAME, in.readString());\n profileMetadataMap.put(NICKNAME, in.readString());\n profileMetadataMap.put(ICON, in.readString());\n }\n\n @NonNull\n @Override\n public String toString() {\n return \"Profile{\" +\n \"profileMetadataMap=\" + profileMetadataMap +\n '}';\n }\n\n public Icon getIcon() {\n String iconBytesHex = profileMetadataMap.get(ICON);\n\n if(iconBytesHex != null) {\n byte[] iconBytes = Bytes.decodeHexString(iconBytesHex);\n return Icon.createWithData(iconBytes, 0, iconBytes.length);\n } else {\n return null;\n }\n }\n}"
},
{
"identifier": "EnableResult",
"path": "core/src/main/java/com/infineon/esim/lpa/core/dtos/result/local/EnableResult.java",
"snippet": "public class EnableResult implements OperationResult {\n public static final int OK = 0;\n public static final int ICCID_OR_AID_NOT_FOUND = 1;\n public static final int PROFILE_NOT_IN_DISABLED_STATE = 2;\n public static final int DISALLOWED_BY_POLICY = 3;\n public static final int WRONG_PROFILE_REENABLING = 4;\n public static final int CAT_BUSY = 5;\n public static final int UNDEFINED_ERROR = 127;\n public static final int NONE = 128;\n\n private static final HashMap<Integer, String> lookup;\n\n static {\n lookup = new HashMap<>();\n lookup.put(OK,\"OK\");\n lookup.put(ICCID_OR_AID_NOT_FOUND, \"ICCID or AID not found.\");\n lookup.put(PROFILE_NOT_IN_DISABLED_STATE, \"Profile not in disabled state.\");\n lookup.put(DISALLOWED_BY_POLICY, \"Disallowed by policy.\");\n lookup.put(WRONG_PROFILE_REENABLING, \"Wrong profile reenabling.\");\n lookup.put(CAT_BUSY, \"CAT busy.\");\n lookup.put(UNDEFINED_ERROR, \"Undefined error.\");\n lookup.put(NONE, \"No error code available.\");\n }\n\n private final int value;\n\n public EnableResult(int result) {\n this.value = result;\n }\n\n @Override\n public boolean isOk() {\n return value == OK;\n }\n\n @Override\n public boolean equals(int value) {\n return this.value == value;\n }\n\n @Override\n public String getDescription() {\n return lookup.get(value);\n }\n}"
},
{
"identifier": "OperationResult",
"path": "core/src/main/java/com/infineon/esim/lpa/core/dtos/result/local/OperationResult.java",
"snippet": "public interface OperationResult {\n\n boolean isOk();\n boolean equals(int value);\n String getDescription();\n}"
},
{
"identifier": "HandleNotificationsResult",
"path": "core/src/main/java/com/infineon/esim/lpa/core/dtos/result/remote/HandleNotificationsResult.java",
"snippet": "public class HandleNotificationsResult extends RemoteOperationResult {\n\n public HandleNotificationsResult() {\n super();\n }\n\n public HandleNotificationsResult(RemoteError remoteError) {\n super(remoteError);\n }\n}"
},
{
"identifier": "LocalProfileAssistant",
"path": "app/src/main/java/com/infineon/esim/lpa/lpa/LocalProfileAssistant.java",
"snippet": "public final class LocalProfileAssistant extends LocalProfileAssistantCoreImpl implements EuiccConnectionConsumer, InternetConnectionConsumer {\n private static final String TAG = LocalProfileAssistant.class.getName();\n\n private final StatusAndEventHandler statusAndEventHandler;\n private final MutableLiveData<ProfileList> profileList;\n private final NetworkStatusBroadcastReceiver networkStatusBroadcastReceiver;\n\n private EuiccConnection euiccConnection;\n\n private EuiccInfo euiccInfo;\n private AuthenticateResult authenticateResult;\n private DownloadResult downloadResult;\n private CancelSessionResult cancelSessionResult;\n\n public LocalProfileAssistant(EuiccManager euiccManager, StatusAndEventHandler statusAndEventHandler) {\n super();\n Log.debug(TAG,\"Creating LocalProfileAssistant...\");\n\n this.networkStatusBroadcastReceiver = new NetworkStatusBroadcastReceiver(this);\n this.statusAndEventHandler = statusAndEventHandler;\n this.profileList = new MutableLiveData<>();\n\n networkStatusBroadcastReceiver.registerReceiver();\n euiccManager.setEuiccConnectionConsumer(this);\n }\n\n public MutableLiveData<ProfileList> getProfileListLiveData() {\n return profileList;\n }\n\n public EuiccInfo getEuiccInfo() {\n return euiccInfo;\n }\n\n public AuthenticateResult getAuthenticateResult() {\n return authenticateResult;\n }\n\n public DownloadResult getDownloadResult() {\n return downloadResult;\n }\n\n public CancelSessionResult getCancelSessionResult() {\n return cancelSessionResult;\n }\n\n public Boolean resetEuicc() throws Exception {\n if(euiccConnection == null) {\n throw new Exception(\"Error: eUICC connection not available to LPA.\");\n } else {\n return euiccConnection.resetEuicc();\n }\n }\n\n public void refreshProfileList() {\n Log.debug(TAG,\"Refreshing profile list.\");\n statusAndEventHandler.onStatusChange(ActionStatus.GET_PROFILE_LIST_STARTED);\n\n new TaskRunner().executeAsync(new GetProfileListTask(this),\n result -> {\n statusAndEventHandler.onStatusChange(ActionStatus.GET_PROFILE_LIST_FINISHED);\n profileList.setValue(result);\n },\n e -> statusAndEventHandler.onError(new Error(\"Exception during getting of profile list.\", e.getMessage())));\n }\n\n public void refreshEuiccInfo() {\n Log.debug(TAG, \"Refreshing eUICC info.\");\n statusAndEventHandler.onStatusChange(ActionStatus.GETTING_EUICC_INFO_STARTED);\n\n new TaskRunner().executeAsync(new GetEuiccInfoTask(this),\n result -> {\n euiccInfo = result;\n statusAndEventHandler.onStatusChange(ActionStatus.GETTING_EUICC_INFO_FINISHED);\n },\n e -> statusAndEventHandler.onError(new Error(\"Exception during getting of eUICC info.\", e.getMessage())));\n }\n\n public void enableProfile(ProfileMetadata profile) {\n statusAndEventHandler.onStatusChange(ActionStatus.ENABLE_PROFILE_STARTED);\n\n if(profile.isEnabled()) {\n Log.debug(TAG, \"Profile already enabled!\");\n statusAndEventHandler.onStatusChange(ActionStatus.ENABLE_PROFILE_FINISHED);\n return;\n }\n\n new TaskRunner().executeAsync(new ProfileActionTask(this,\n ProfileActionType.PROFILE_ACTION_ENABLE,\n profile),\n result -> statusAndEventHandler.onStatusChange(ActionStatus.ENABLE_PROFILE_FINISHED),\n e -> statusAndEventHandler.onError(new Error(\"Error during enabling profile.\", e.getMessage())));\n }\n\n public void disableProfile(ProfileMetadata profile) {\n statusAndEventHandler.onStatusChange(ActionStatus.DISABLE_PROFILE_STARTED);\n\n if(!profile.isEnabled()) {\n Log.debug(TAG, \"Profile already disabled!\");\n statusAndEventHandler.onStatusChange(ActionStatus.DISABLE_PROFILE_FINISHED);\n return;\n }\n\n new TaskRunner().executeAsync(new ProfileActionTask(this,\n ProfileActionType.PROFILE_ACTION_DISABLE,\n profile),\n result -> statusAndEventHandler.onStatusChange(ActionStatus.DISABLE_PROFILE_FINISHED),\n e -> statusAndEventHandler.onError(new Error(\"Error during disabling of profile.\", e.getMessage())));\n }\n\n public void deleteProfile(ProfileMetadata profile) {\n statusAndEventHandler.onStatusChange(ActionStatus.DELETE_PROFILE_STARTED);\n\n new TaskRunner().executeAsync(new ProfileActionTask(this,\n ProfileActionType.PROFILE_ACTION_DELETE,\n profile),\n result -> statusAndEventHandler.onStatusChange(ActionStatus.DELETE_PROFILE_FINISHED),\n e -> statusAndEventHandler.onError(new Error(\"Error during deleting of profile.\", e.getMessage())));\n }\n\n\n public void setNickname(ProfileMetadata profile) {\n statusAndEventHandler.onStatusChange(ActionStatus.SET_NICKNAME_STARTED);\n\n ProfileActionTask profileActionTask = new ProfileActionTask(this,\n ProfileActionType.PROFILE_ACTION_SET_NICKNAME,\n profile);\n\n new TaskRunner().executeAsync(profileActionTask,\n result -> statusAndEventHandler.onStatusChange(ActionStatus.SET_NICKNAME_FINISHED),\n e -> statusAndEventHandler.onError(new Error(\"Error during setting nickname of profile.\", e.getMessage())));\n }\n\n public void handleAndClearAllNotifications() {\n statusAndEventHandler.onStatusChange(ActionStatus.CLEAR_ALL_NOTIFICATIONS_STARTED);\n\n HandleAndClearAllNotificationsTask handleAndClearAllNotificationsTask = new HandleAndClearAllNotificationsTask(this);\n\n new TaskRunner().executeAsync(handleAndClearAllNotificationsTask,\n result -> statusAndEventHandler.onStatusChange(ActionStatus.CLEAR_ALL_NOTIFICATIONS_FINISHED),\n e -> statusAndEventHandler.onError(new Error(\"Error during clearing of all eUICC notifications.\", e.getMessage())));\n }\n\n public void startAuthentication(ActivationCode activationCode) {\n authenticateResult = null;\n statusAndEventHandler.onStatusChange(ActionStatus.AUTHENTICATE_DOWNLOAD_STARTED);\n\n AuthenticateTask authenticateTask = new AuthenticateTask(\n this,\n activationCode);\n\n new TaskRunner().executeAsync(authenticateTask,\n authenticateResult -> {\n postProcessAuthenticate(authenticateResult);\n statusAndEventHandler.onStatusChange(ActionStatus.AUTHENTICATE_DOWNLOAD_FINISHED);\n },\n e -> statusAndEventHandler.onError(new Error(\"Error authentication of profile download.\", e.getMessage())));\n }\n\n public void postProcessAuthenticate(AuthenticateResult authenticateResult) {\n this.authenticateResult = authenticateResult;\n\n if(authenticateResult.getSuccess()) {\n // Check if there is a matching profile already installed\n ProfileMetadata newProfile = authenticateResult.getProfileMetadata();\n ProfileMetadata matchingProfile = null;\n if (newProfile != null) {\n ProfileList profileList = this.profileList.getValue();\n if(profileList != null) {\n matchingProfile = profileList.findMatchingProfile(newProfile.getIccid());\n }\n if ((matchingProfile != null) && (matchingProfile.getNickname() != null)) {\n Log.debug(TAG, \"Profile already installed: \" + matchingProfile.getNickname());\n String errorMessage = \"Profile with this ICCID already installed: \" + matchingProfile.getNickname();\n statusAndEventHandler.onError(new Error(\"Profile already installed!\", errorMessage));\n }\n }\n }\n }\n\n public void startProfileDownload(String confirmationCode) {\n downloadResult = null;\n statusAndEventHandler.onStatusChange(ActionStatus.DOWNLOAD_PROFILE_STARTED);\n\n new TaskRunner().executeAsync(\n new DownloadTask(this, confirmationCode),\n downloadResult -> {\n postProcessDownloadProfile(downloadResult);\n statusAndEventHandler.onStatusChange(ActionStatus.DOWNLOAD_PROFILE_FINISHED);\n },\n e -> statusAndEventHandler.onError(new Error(\"Error during download of profile.\", e.getMessage())));\n }\n\n\n private void postProcessDownloadProfile(DownloadResult downloadResult) {\n this.downloadResult = downloadResult;\n ProfileList profileList = this.profileList.getValue();\n\n Log.debug(TAG, \"Post processing new profile. download success: \" + downloadResult.getSuccess());\n if(downloadResult.getSuccess() && (profileList != null)) {\n ProfileMetadata profileMetadata = authenticateResult.getProfileMetadata();\n Log.debug(TAG, \"Post processing new profile: \" + profileMetadata);\n\n Log.debug(TAG, \"Profile nickname: \\\"\" + profileMetadata.getNickname() + \"\\\"\");\n if(!profileMetadata.hasNickname()) {\n String nickname = profileList.getUniqueNickname(profileMetadata);\n\n Log.debug(TAG, \"Profile does not have a nickname. So set a new one: \\\"\" + nickname + \"\\\"\");\n profileMetadata.setNickname(nickname);\n setNickname(profileMetadata);\n }\n }\n }\n\n public void startCancelSession(long cancelSessionReason) {\n Log.debug(TAG, \"Cancel session: \" + cancelSessionReason);\n\n statusAndEventHandler.onStatusChange(ActionStatus.CANCEL_SESSION_STARTED);\n\n CancelSessionTask cancelSessionTask = new CancelSessionTask(\n this,\n cancelSessionReason);\n\n new TaskRunner().executeAsync(cancelSessionTask,\n result -> {\n cancelSessionResult = result;\n statusAndEventHandler.onStatusChange(ActionStatus.CANCEL_SESSION_FINISHED);\n },\n e -> statusAndEventHandler.onError(new Error(\"Error cancelling session.\", e.getMessage())));\n }\n\n @Override\n public void onEuiccConnectionUpdate(EuiccConnection euiccConnection) {\n Log.debug(TAG, \"Updated eUICC connection.\");\n this.euiccConnection = euiccConnection;\n super.setEuiccChannel(euiccConnection);\n\n if(euiccConnection != null) {\n refreshProfileList();\n }\n }\n\n @Override\n public void onConnected() {\n Log.debug(TAG, \"Internet connection established.\");\n super.enableEs9PlusInterface();\n }\n\n @Override\n public void onDisconnected() {\n Log.debug(TAG, \"Internet connection lost.\");\n super.disableEs9PlusInterface();\n }\n\n @Override\n protected void finalize() throws Throwable {\n super.finalize();\n networkStatusBroadcastReceiver.unregisterReceiver();\n }\n}"
},
{
"identifier": "Log",
"path": "app/src/test/java/com/infineon/esim/util/Log.java",
"snippet": "final public class Log {\n\n // Ref:\n // https://stackoverflow.com/questions/8355632/how-do-you-usually-tag-log-entries-android\n public static String getFileLineNumber() {\n String info = \"\";\n final StackTraceElement[] ste = Thread.currentThread().getStackTrace();\n for (int i = 0; i < ste.length; i++) {\n if (ste[i].getMethodName().equals(\"getFileLineNumber\")) {\n info = \"(\"+ste[i + 1].getFileName() + \":\" + ste[i + 1].getLineNumber()+\")\";\n }\n }\n return info;\n }\n\n public static void verbose(final String tag, final String msg) {\n System.out.println(\"V - \" + tag + \": \" + msg);\n }\n\n public static void debug(final String tag, final String msg) {\n System.out.println(\"D - \" + tag + \": \" + msg);\n }\n\n public static void info(final String tag, final String msg) {\n System.out.println(\"I- \" + tag + \": \" + msg);\n }\n\n public static void error(final String msg) {\n System.out.println(\"E- \" + msg);\n }\n\n public static void error(final String tag, final String msg) {\n System.out.println(\"E- \" + tag + \": \" + msg);\n }\n\n public static void error(final String tag, final String msg, final Throwable error) {\n System.out.println(\"E- \" + tag + \": \" + msg);\n error.printStackTrace();\n }\n}"
}
] | import java.util.concurrent.Callable;
import com.infineon.esim.lpa.core.dtos.enums.ProfileActionType;
import com.infineon.esim.lpa.core.dtos.profile.ProfileMetadata;
import com.infineon.esim.lpa.core.dtos.result.local.EnableResult;
import com.infineon.esim.lpa.core.dtos.result.local.OperationResult;
import com.infineon.esim.lpa.core.dtos.result.remote.HandleNotificationsResult;
import com.infineon.esim.lpa.lpa.LocalProfileAssistant;
import com.infineon.esim.util.Log; | 5,301 | /*
* THE SOURCE CODE AND ITS RELATED DOCUMENTATION IS PROVIDED "AS IS". INFINEON
* TECHNOLOGIES MAKES NO OTHER WARRANTY OF ANY KIND,WHETHER EXPRESS,IMPLIED OR,
* STATUTORY AND DISCLAIMS ANY AND ALL IMPLIED WARRANTIES OF MERCHANTABILITY,
* SATISFACTORY QUALITY, NON INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE.
*
* THE SOURCE CODE AND DOCUMENTATION MAY INCLUDE ERRORS. INFINEON TECHNOLOGIES
* RESERVES THE RIGHT TO INCORPORATE MODIFICATIONS TO THE SOURCE CODE IN LATER
* REVISIONS OF IT, AND TO MAKE IMPROVEMENTS OR CHANGES IN THE DOCUMENTATION OR
* THE PRODUCTS OR TECHNOLOGIES DESCRIBED THEREIN AT ANY TIME.
*
* INFINEON TECHNOLOGIES SHALL NOT BE LIABLE FOR ANY DIRECT, INDIRECT OR
* CONSEQUENTIAL DAMAGE OR LIABILITY ARISING FROM YOUR USE OF THE SOURCE CODE OR
* ANY DOCUMENTATION, INCLUDING BUT NOT LIMITED TO, LOST REVENUES, DATA OR
* PROFITS, DAMAGES OF ANY SPECIAL, INCIDENTAL OR CONSEQUENTIAL NATURE, PUNITIVE
* DAMAGES, LOSS OF PROPERTY OR LOSS OF PROFITS ARISING OUT OF OR IN CONNECTION
* WITH THIS AGREEMENT, OR BEING UNUSABLE, EVEN IF ADVISED OF THE POSSIBILITY OR
* PROBABILITY OF SUCH DAMAGES AND WHETHER A CLAIM FOR SUCH DAMAGE IS BASED UPON
* WARRANTY, CONTRACT, TORT, NEGLIGENCE OR OTHERWISE.
*
* (C)Copyright INFINEON TECHNOLOGIES All rights reserved
*/
package com.infineon.esim.lpa.lpa.task;
public class ProfileActionTask implements Callable<Void> {
private static final String TAG = ProfileActionTask.class.getName();
private final LocalProfileAssistant lpa; | /*
* THE SOURCE CODE AND ITS RELATED DOCUMENTATION IS PROVIDED "AS IS". INFINEON
* TECHNOLOGIES MAKES NO OTHER WARRANTY OF ANY KIND,WHETHER EXPRESS,IMPLIED OR,
* STATUTORY AND DISCLAIMS ANY AND ALL IMPLIED WARRANTIES OF MERCHANTABILITY,
* SATISFACTORY QUALITY, NON INFRINGEMENT AND FITNESS FOR A PARTICULAR PURPOSE.
*
* THE SOURCE CODE AND DOCUMENTATION MAY INCLUDE ERRORS. INFINEON TECHNOLOGIES
* RESERVES THE RIGHT TO INCORPORATE MODIFICATIONS TO THE SOURCE CODE IN LATER
* REVISIONS OF IT, AND TO MAKE IMPROVEMENTS OR CHANGES IN THE DOCUMENTATION OR
* THE PRODUCTS OR TECHNOLOGIES DESCRIBED THEREIN AT ANY TIME.
*
* INFINEON TECHNOLOGIES SHALL NOT BE LIABLE FOR ANY DIRECT, INDIRECT OR
* CONSEQUENTIAL DAMAGE OR LIABILITY ARISING FROM YOUR USE OF THE SOURCE CODE OR
* ANY DOCUMENTATION, INCLUDING BUT NOT LIMITED TO, LOST REVENUES, DATA OR
* PROFITS, DAMAGES OF ANY SPECIAL, INCIDENTAL OR CONSEQUENTIAL NATURE, PUNITIVE
* DAMAGES, LOSS OF PROPERTY OR LOSS OF PROFITS ARISING OUT OF OR IN CONNECTION
* WITH THIS AGREEMENT, OR BEING UNUSABLE, EVEN IF ADVISED OF THE POSSIBILITY OR
* PROBABILITY OF SUCH DAMAGES AND WHETHER A CLAIM FOR SUCH DAMAGE IS BASED UPON
* WARRANTY, CONTRACT, TORT, NEGLIGENCE OR OTHERWISE.
*
* (C)Copyright INFINEON TECHNOLOGIES All rights reserved
*/
package com.infineon.esim.lpa.lpa.task;
public class ProfileActionTask implements Callable<Void> {
private static final String TAG = ProfileActionTask.class.getName();
private final LocalProfileAssistant lpa; | private final ProfileActionType profileActionType; | 0 | 2023-11-22 07:46:30+00:00 | 8k |
idaoyu/iot-project-java | iotp-device/iotp-device-biz/src/main/java/com/bbkk/project/module/product/service/ProductInfoManageService.java | [
{
"identifier": "BizException",
"path": "iotp-dependency/iotp-dependency-web/src/main/java/com/bbkk/project/exception/BizException.java",
"snippet": "public class BizException extends RuntimeException {\n\n public BizException(String message) {\n super(message);\n }\n}"
},
{
"identifier": "IDeviceEvidencePoolService",
"path": "iotp-device/iotp-device-biz/src/main/java/com/bbkk/project/module/device/service/IDeviceEvidencePoolService.java",
"snippet": "public interface IDeviceEvidencePoolService extends IService<DeviceEvidencePool> {\n\n /**\n * 生成设备认证密钥并绑定\n *\n * @param productId 产品id\n * @param deviceId 设备id\n */\n void generateAuthKeyAndBind(Long productId, String deviceId);\n\n /**\n * 根据设备id 删除对应的认证凭据\n *\n * @param deviceId 设备id\n * @return 成功返回 true\n */\n boolean removeByDeviceId(String deviceId);\n\n}"
},
{
"identifier": "ProductAuthType",
"path": "iotp-device/iotp-device-biz/src/main/java/com/bbkk/project/module/product/constant/ProductAuthType.java",
"snippet": "@Getter\n@AllArgsConstructor\npublic enum ProductAuthType {\n\n /**\n * 一个产品一个密钥\n */\n BIND_PRODUCT(\"product\"),\n /**\n * 一个设备一个密钥\n */\n BIND_DEVICE(\"device\"),\n ;\n\n\n private final String type;\n\n}"
},
{
"identifier": "TslTypeConstant",
"path": "iotp-device/iotp-device-biz/src/main/java/com/bbkk/project/module/product/constant/TslTypeConstant.java",
"snippet": "@Getter\n@AllArgsConstructor\npublic enum TslTypeConstant {\n\n /**\n * 属性\n */\n PROPERTY(\"property\"),\n /**\n * 方法\n */\n METHOD(\"method\"),\n /**\n * 事件\n */\n EVENT(\"event\"),\n ;\n\n private final String value;\n\n}"
},
{
"identifier": "ProductInfoConvert",
"path": "iotp-device/iotp-device-biz/src/main/java/com/bbkk/project/module/product/convert/ProductInfoConvert.java",
"snippet": "@Mapper(componentModel = MappingConstants.ComponentModel.SPRING)\npublic interface ProductInfoConvert {\n\n ProductInfoConvert INSTANCE = Mappers.getMapper(ProductInfoConvert.class);\n\n @Mapping(source = \"name\", target = \"name\")\n @Mapping(source = \"description\", target = \"description\")\n @Mapping(source = \"imageUrl\", target = \"imageUrl\")\n @Mapping(source = \"type\", target = \"type\")\n @Mapping(source = \"needAuth\", target = \"needAuth\")\n @Mapping(source = \"authType\", target = \"authType\")\n @Mapping(target = \"id\", ignore = true)\n @Mapping(target = \"status\", ignore = true)\n @Mapping(target = \"createTime\", expression = \"java(new java.util.Date())\")\n @Mapping(target = \"updateTime\", expression = \"java(new java.util.Date())\")\n ProductInfo operationProductInfoParams2ProductInfo(OperationProductInfoParams params);\n\n\n GetProductInfoDTO productInfo2GetProductInfoDTO(ProductInfo productInfo);\n\n\n}"
},
{
"identifier": "OperationProductInfoParams",
"path": "iotp-device/iotp-device-biz/src/main/java/com/bbkk/project/module/product/data/OperationProductInfoParams.java",
"snippet": "@Data\npublic class OperationProductInfoParams {\n\n @NotNull(message = \"id不能为空\", groups = {ValidatedGroup.UpdateGroup.class})\n private Long id;\n\n /**\n * 产品名字\n */\n @NotEmpty(message = \"产品名字不能为空\", groups = {ValidatedGroup.UpdateGroup.class, ValidatedGroup.CreateGroup.class})\n private String name;\n\n /**\n * 产品描述\n */\n @NotEmpty(message = \"产品描述不能为空\", groups = {ValidatedGroup.UpdateGroup.class, ValidatedGroup.CreateGroup.class})\n private String description;\n\n /**\n * 产品图片地址\n */\n @NotEmpty(message = \"产品图片url不能为空\", groups = {ValidatedGroup.UpdateGroup.class, ValidatedGroup.CreateGroup.class})\n private String imageUrl;\n\n /**\n * 是否需要存储设备上报的属性\n */\n @NotNull(message = \"needSaveProperty不能为空\", groups = {ValidatedGroup.UpdateGroup.class})\n private Boolean needSaveProperty;\n\n /**\n * 需要认证\n */\n @NotNull(message = \"needAuth 不能为空\", groups = {ValidatedGroup.UpdateGroup.class, ValidatedGroup.CreateGroup.class})\n private Boolean needAuth;\n\n /**\n * 认证类型\n */\n @NotEmpty(message = \"认证类型不能为空\", groups = {ValidatedGroup.UpdateGroup.class, ValidatedGroup.CreateGroup.class})\n private String authType;\n\n /**\n * 产品状态\n */\n private String status;\n\n /**\n * 产品分类(存放分类表id)\n */\n private Long type;\n\n @Valid\n @NotEmpty(message = \"关联物模型不能为空\", groups = {ValidatedGroup.UpdateGroup.class, ValidatedGroup.CreateGroup.class})\n private List<ProductInfoAndTslDTO> tslList;\n\n}"
},
{
"identifier": "PageGetProductInfoParams",
"path": "iotp-device/iotp-device-biz/src/main/java/com/bbkk/project/module/product/data/PageGetProductInfoParams.java",
"snippet": "@Data\n@EqualsAndHashCode(callSuper = true)\npublic class PageGetProductInfoParams extends PageParams {\n\n /**\n * 产品名字,支持模糊查询\n */\n private String name;\n\n}"
},
{
"identifier": "PageGetProductInfoVO",
"path": "iotp-device/iotp-device-biz/src/main/java/com/bbkk/project/module/product/data/PageGetProductInfoVO.java",
"snippet": "@Data\n@Builder\npublic class PageGetProductInfoVO {\n\n private Long id;\n\n /**\n * 产品名字\n */\n private String name;\n\n /**\n * 产品描述\n */\n private String description;\n\n /**\n * 产品图片地址\n */\n private String imageUrl;\n\n /**\n * 是否需要存储设备上报的属性\n */\n private Boolean needSaveProperty;\n\n /**\n * 产品分类\n */\n private String type;\n\n /**\n * 创建时间\n */\n private Date createTime;\n\n /**\n * 修改时间\n */\n private Date updateTime;\n\n}"
},
{
"identifier": "ProductInfoAndTslDTO",
"path": "iotp-device/iotp-device-biz/src/main/java/com/bbkk/project/module/product/data/ProductInfoAndTslDTO.java",
"snippet": "@Data\npublic class ProductInfoAndTslDTO {\n\n /**\n * 物模型id\n */\n @NotEmpty(message = \"物模型id不能为空\", groups = {ValidatedGroup.UpdateGroup.class, ValidatedGroup.CreateGroup.class})\n private String tslId;\n\n /**\n * 物模型类别(属性、方法、事件)\n */\n @NotEmpty(message = \"物模型类别不能为空\", groups = {ValidatedGroup.UpdateGroup.class, ValidatedGroup.CreateGroup.class})\n private String type;\n\n}"
},
{
"identifier": "ProductInfo",
"path": "iotp-device/iotp-device-biz/src/main/java/com/bbkk/project/module/product/entity/ProductInfo.java",
"snippet": "@Data\n@Builder\n@AllArgsConstructor\n@NoArgsConstructor\n@TableName(value = \"product_info\")\npublic class ProductInfo {\n\n @TableId(value = \"id\", type = IdType.AUTO)\n private Long id;\n\n /**\n * 产品名字\n */\n @TableField(value = \"`name`\")\n private String name;\n\n /**\n * 产品描述\n */\n @TableField(value = \"description\")\n private String description;\n\n /**\n * 产品图片地址\n */\n @TableField(value = \"image_url\")\n private String imageUrl;\n\n /**\n * 产品分类(存放分类表id)\n */\n @TableField(value = \"`type`\")\n private Long type;\n\n /**\n * 是否需要存储设备上报的属性\n */\n @TableField(value = \"need_save_property\")\n private Boolean needSaveProperty;\n\n /**\n * 需要认证\n */\n @TableField(value = \"need_auth\")\n private Boolean needAuth;\n\n /**\n * 认证类型\n */\n @TableField(value = \"auth_type\")\n private String authType;\n\n /**\n * 产品状态\n */\n @TableField(value = \"`status`\")\n private String status;\n\n /**\n * 创建时间\n */\n @TableField(value = \"create_time\")\n private Date createTime;\n\n /**\n * 修改时间\n */\n @TableField(value = \"update_time\")\n private Date updateTime;\n}"
},
{
"identifier": "ProductInfoTsl",
"path": "iotp-device/iotp-device-biz/src/main/java/com/bbkk/project/module/product/entity/ProductInfoTsl.java",
"snippet": "@Data\n@Builder\n@AllArgsConstructor\n@NoArgsConstructor\n@TableName(value = \"product_info_tsl\")\npublic class ProductInfoTsl {\n\n /**\n * 产品id\n */\n @TableField(value = \"product_id\")\n private Long productId;\n\n /**\n * 物模型id\n */\n @TableField(value = \"tsl_id\")\n private String tslId;\n\n /**\n * 物模型类型(属性、方法、事件)\n */\n @TableField(value = \"tsl_type\")\n private String tslType;\n}"
},
{
"identifier": "ProductType",
"path": "iotp-device/iotp-device-biz/src/main/java/com/bbkk/project/module/product/entity/ProductType.java",
"snippet": "@Data\n@Builder\n@AllArgsConstructor\n@NoArgsConstructor\n@TableName(value = \"product_type\")\npublic class ProductType {\n\n @TableId(value = \"id\", type = IdType.INPUT)\n private Long id;\n\n /**\n * 类目名字\n */\n @TableField(value = \"`name`\")\n private String name;\n\n /**\n * 类目描述\n */\n @TableField(value = \"description\")\n private String description;\n\n /**\n * 创建时间\n */\n @TableField(value = \"create_time\")\n private Date createTime;\n\n /**\n * 修改时间\n */\n @TableField(value = \"update_time\")\n private Date updateTime;\n}"
},
{
"identifier": "ITslEventService",
"path": "iotp-device/iotp-device-biz/src/main/java/com/bbkk/project/module/tsl/service/ITslEventService.java",
"snippet": "public interface ITslEventService extends IService<TslEvent> {\n\n /**\n * 分页查询物模型事件\n *\n * @param params PageGetTslEventParams\n * @return IPage<PageGetTslEventVO>\n */\n IPage<TslEvent> pageGetTslEvent(PageGetTslEventParams params);\n}"
},
{
"identifier": "ITslMethodService",
"path": "iotp-device/iotp-device-biz/src/main/java/com/bbkk/project/module/tsl/service/ITslMethodService.java",
"snippet": "public interface ITslMethodService extends IService<TslMethod> {\n\n /**\n * 分页查询物模型方法\n *\n * @param params PageGetTslMethodParams\n * @return IPage<TslMethod>\n */\n IPage<TslMethod> pageGetTslMethod(PageGetTslMethodParams params);\n}"
},
{
"identifier": "ITslPropertyService",
"path": "iotp-device/iotp-device-biz/src/main/java/com/bbkk/project/module/tsl/service/ITslPropertyService.java",
"snippet": "public interface ITslPropertyService extends IService<TslProperty> {\n\n /**\n * 分页查询\n *\n * @param params PageGetTslPropertyParams\n * @return IPage<TslProperty>\n */\n IPage<TslProperty> pageByParams(PageGetTslPropertyParams params);\n\n /**\n * 修改物模型属性\n *\n * @param tslProperty 原来的物模型属性\n * @param params 修改入参\n * @param id 要修改的 id\n * @return 成功返回 true\n */\n Boolean updateTslProperty(TslProperty tslProperty, UpdateTslPropertyParams params, String id);\n\n /**\n * 根据id list 查询属性\n *\n * @param idList id list\n * @return List<TslProperty>\n */\n List<TslProperty> listByIdList(List<String> idList);\n\n}"
}
] | import com.baomidou.mybatisplus.core.metadata.IPage;
import com.bbkk.project.exception.BizException;
import com.bbkk.project.module.device.service.IDeviceEvidencePoolService;
import com.bbkk.project.module.product.constant.ProductAuthType;
import com.bbkk.project.module.product.constant.TslTypeConstant;
import com.bbkk.project.module.product.convert.ProductInfoConvert;
import com.bbkk.project.module.product.data.OperationProductInfoParams;
import com.bbkk.project.module.product.data.PageGetProductInfoParams;
import com.bbkk.project.module.product.data.PageGetProductInfoVO;
import com.bbkk.project.module.product.data.ProductInfoAndTslDTO;
import com.bbkk.project.module.product.entity.ProductInfo;
import com.bbkk.project.module.product.entity.ProductInfoTsl;
import com.bbkk.project.module.product.entity.ProductType;
import com.bbkk.project.module.tsl.service.ITslEventService;
import com.bbkk.project.module.tsl.service.ITslMethodService;
import com.bbkk.project.module.tsl.service.ITslPropertyService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date; | 4,021 | package com.bbkk.project.module.product.service;
/**
* 产品信息管理接口 业务逻辑
*
* @author 一条秋刀鱼zz [email protected]
* @since 2023-12-12 19:27
**/
@Service
@RequiredArgsConstructor
public class ProductInfoManageService {
private final IProductInfoService productInfoService;
private final IProductTypeService productTypeService;
private final IProductInfoTslService productInfoTslService;
private final ITslPropertyService tslPropertyService;
private final ITslMethodService tslMethodService;
private final ITslEventService tslEventService;
private final IDeviceEvidencePoolService deviceEvidencePoolService;
private final ProductInfoConvert productInfoConvert;
public IPage<PageGetProductInfoVO> pageGetProductInfo(PageGetProductInfoParams params) {
// todo 待重构 需要考虑物模型、认证方式等数据的展示方法
IPage<ProductInfo> page = productInfoService.pageGetProductInfo(params);
return page.convert(v -> {
PageGetProductInfoVO.PageGetProductInfoVOBuilder builder = PageGetProductInfoVO.builder();
builder.id(v.getId());
builder.name(v.getName());
builder.description(v.getDescription());
builder.imageUrl(v.getImageUrl());
builder.needSaveProperty(v.getNeedSaveProperty());
builder.createTime(v.getCreateTime());
builder.updateTime(v.getUpdateTime());
if (v.getType() != null) {
ProductType productType = productTypeService.getById(v.getType());
builder.type(productType != null ? productType.getName() : "其他");
} else {
builder.type("其他");
}
return builder.build();
});
}
@Transactional(rollbackFor = Exception.class)
public String createProductInfo(OperationProductInfoParams params) {
ProductInfo productInfo = productInfoConvert.operationProductInfoParams2ProductInfo(params);
// 如果未指定是否需要保存设备上报的属性 则 默认为不保存
if (params.getNeedSaveProperty() == null) {
productInfo.setNeedSaveProperty(false);
} else {
productInfo.setNeedSaveProperty(params.getNeedSaveProperty());
}
if (params.getType() != null) {
ProductType productType = productTypeService.getOptById(params.getType()).orElseThrow(() -> new BizException("产品类目错误"));
productInfo.setType(productType.getId());
}
// 默认的状态就是开发中,除非用户手动指定状态
if (StringUtils.isNotBlank(params.getStatus())) {
productInfo.setStatus(params.getStatus());
} else {
// todo 懒得写枚举了,如果后续状态有业务逻辑意义再写吧
productInfo.setStatus("dev");
}
boolean save = productInfoService.save(productInfo);
if (!save) {
throw new BizException("创建产品失败,请稍后重试");
}
// 需要认证,并且认证类型为一个产品一个密钥时,在创建产品时生成密钥
if (productInfo.getNeedAuth() && productInfo.getAuthType().equals(ProductAuthType.BIND_PRODUCT.getType())) {
deviceEvidencePoolService.generateAuthKeyAndBind(productInfo.getId(), null);
}
for (ProductInfoAndTslDTO productInfoAndTslDTO : params.getTslList()) {
String type = productInfoAndTslDTO.getType();
String tslId = productInfoAndTslDTO.getTslId(); | package com.bbkk.project.module.product.service;
/**
* 产品信息管理接口 业务逻辑
*
* @author 一条秋刀鱼zz [email protected]
* @since 2023-12-12 19:27
**/
@Service
@RequiredArgsConstructor
public class ProductInfoManageService {
private final IProductInfoService productInfoService;
private final IProductTypeService productTypeService;
private final IProductInfoTslService productInfoTslService;
private final ITslPropertyService tslPropertyService;
private final ITslMethodService tslMethodService;
private final ITslEventService tslEventService;
private final IDeviceEvidencePoolService deviceEvidencePoolService;
private final ProductInfoConvert productInfoConvert;
public IPage<PageGetProductInfoVO> pageGetProductInfo(PageGetProductInfoParams params) {
// todo 待重构 需要考虑物模型、认证方式等数据的展示方法
IPage<ProductInfo> page = productInfoService.pageGetProductInfo(params);
return page.convert(v -> {
PageGetProductInfoVO.PageGetProductInfoVOBuilder builder = PageGetProductInfoVO.builder();
builder.id(v.getId());
builder.name(v.getName());
builder.description(v.getDescription());
builder.imageUrl(v.getImageUrl());
builder.needSaveProperty(v.getNeedSaveProperty());
builder.createTime(v.getCreateTime());
builder.updateTime(v.getUpdateTime());
if (v.getType() != null) {
ProductType productType = productTypeService.getById(v.getType());
builder.type(productType != null ? productType.getName() : "其他");
} else {
builder.type("其他");
}
return builder.build();
});
}
@Transactional(rollbackFor = Exception.class)
public String createProductInfo(OperationProductInfoParams params) {
ProductInfo productInfo = productInfoConvert.operationProductInfoParams2ProductInfo(params);
// 如果未指定是否需要保存设备上报的属性 则 默认为不保存
if (params.getNeedSaveProperty() == null) {
productInfo.setNeedSaveProperty(false);
} else {
productInfo.setNeedSaveProperty(params.getNeedSaveProperty());
}
if (params.getType() != null) {
ProductType productType = productTypeService.getOptById(params.getType()).orElseThrow(() -> new BizException("产品类目错误"));
productInfo.setType(productType.getId());
}
// 默认的状态就是开发中,除非用户手动指定状态
if (StringUtils.isNotBlank(params.getStatus())) {
productInfo.setStatus(params.getStatus());
} else {
// todo 懒得写枚举了,如果后续状态有业务逻辑意义再写吧
productInfo.setStatus("dev");
}
boolean save = productInfoService.save(productInfo);
if (!save) {
throw new BizException("创建产品失败,请稍后重试");
}
// 需要认证,并且认证类型为一个产品一个密钥时,在创建产品时生成密钥
if (productInfo.getNeedAuth() && productInfo.getAuthType().equals(ProductAuthType.BIND_PRODUCT.getType())) {
deviceEvidencePoolService.generateAuthKeyAndBind(productInfo.getId(), null);
}
for (ProductInfoAndTslDTO productInfoAndTslDTO : params.getTslList()) {
String type = productInfoAndTslDTO.getType();
String tslId = productInfoAndTslDTO.getTslId(); | if (type.equals(TslTypeConstant.PROPERTY.getValue())) { | 3 | 2023-11-25 06:59:20+00:00 | 8k |
MattiDragon/JsonPatcherLang | src/test/java/io/github/mattidragon/jsonpatcher/lang/test/TestUtils.java | [
{
"identifier": "Value",
"path": "src/main/java/io/github/mattidragon/jsonpatcher/lang/runtime/Value.java",
"snippet": "public sealed interface Value {\n ThreadLocal<Set<Value>> TO_STRING_RECURSION_TRACKER = ThreadLocal.withInitial(HashSet::new);\n\n boolean asBoolean();\n\n @NotNull\n static Value convertNull(@Nullable Value value) {\n return value == null ? NullValue.NULL : value;\n }\n\n record ObjectValue(Map<String, Value> value) implements Value {\n public ObjectValue {\n value = new LinkedHashMap<>(value);\n }\n\n public ObjectValue() {\n this(Map.of());\n }\n\n public Value get(String key, @Nullable SourceSpan pos) {\n if (!value.containsKey(key)) throw new EvaluationException(\"Object %s has no key %s\".formatted(this, key), pos);\n return value.get(key);\n }\n\n public void set(String key, Value value, @Nullable SourceSpan pos) {\n this.value.put(key, value);\n }\n\n public void remove(String key, SourceSpan pos) {\n if (!value.containsKey(key)) throw new EvaluationException(\"Object %s has no key %s\".formatted(this, key), pos);\n value.remove(key);\n }\n\n @Override\n public boolean asBoolean() {\n return !value.isEmpty();\n }\n\n @Override\n public String toString() {\n if (TO_STRING_RECURSION_TRACKER.get().contains(this)) return \"{...}\";\n try {\n TO_STRING_RECURSION_TRACKER.get().add(this);\n return value.toString();\n } finally {\n TO_STRING_RECURSION_TRACKER.get().remove(this);\n }\n }\n\n @Override\n public boolean equals(Object obj) {\n return this == obj;\n }\n\n @Override\n public int hashCode() {\n return System.identityHashCode(this);\n }\n }\n\n record ArrayValue(List<Value> value) implements Value {\n public ArrayValue {\n value = new ArrayList<>(value);\n }\n\n public ArrayValue() {\n this(List.of());\n }\n\n public Value get(int index, @Nullable SourceSpan pos) {\n return this.value.get(fixIndex(index, pos));\n }\n\n public void set(int index, Value value, @Nullable SourceSpan pos) {\n this.value.set(fixIndex(index, pos), value);\n }\n\n public void remove(int index, SourceSpan pos) {\n value.remove(fixIndex(index, pos));\n }\n\n private int fixIndex(int index, @Nullable SourceSpan pos) {\n if (index >= value.size() || index < -value.size())\n throw new EvaluationException(\"Array index out of bounds (index: %s, size: %s)\".formatted(index, value.size()), pos);\n if (index < 0) return value.size() + index;\n return index;\n }\n\n @Override\n public boolean asBoolean() {\n return !value.isEmpty();\n }\n\n @Override\n public String toString() {\n if (TO_STRING_RECURSION_TRACKER.get().contains(this)) return \"[...]\";\n try {\n TO_STRING_RECURSION_TRACKER.get().add(this);\n return value.toString();\n } finally {\n TO_STRING_RECURSION_TRACKER.get().remove(this);\n }\n }\n\n @Override\n public boolean equals(Object obj) {\n return this == obj;\n }\n\n @Override\n public int hashCode() {\n return System.identityHashCode(this);\n }\n }\n\n record FunctionValue(PatchFunction function) implements Value {\n @Override\n public boolean asBoolean() {\n return true;\n }\n\n @Override\n public boolean equals(Object obj) {\n return this == obj;\n }\n\n @Override\n public int hashCode() {\n return System.identityHashCode(this);\n }\n\n @Override\n public String toString() {\n return \"<function>\";\n }\n }\n\n sealed interface Primitive extends Value {}\n\n record StringValue(String value) implements Primitive {\n @Override\n public boolean asBoolean() {\n return !value.isEmpty();\n }\n\n @Override\n public String toString() {\n return value;\n }\n }\n\n record NumberValue(double value) implements Primitive {\n @Override\n public boolean asBoolean() {\n return value != 0;\n }\n\n @Override\n public String toString() {\n return String.valueOf(value);\n }\n }\n\n enum BooleanValue implements Primitive {\n TRUE, FALSE;\n\n public static BooleanValue of(boolean value) {\n return value ? TRUE : FALSE;\n }\n\n public boolean value() {\n return this == TRUE;\n }\n\n @Override\n public boolean asBoolean() {\n return value();\n }\n\n @Override\n public String toString() {\n return String.valueOf(value());\n }\n }\n\n enum NullValue implements Primitive {\n NULL;\n\n @Override\n public boolean asBoolean() {\n return false;\n }\n\n @Override\n public String toString() {\n return \"null\";\n }\n }\n}"
},
{
"identifier": "Expression",
"path": "src/main/java/io/github/mattidragon/jsonpatcher/lang/runtime/expression/Expression.java",
"snippet": "public interface Expression {\n Value evaluate(EvaluationContext context);\n SourceSpan pos();\n\n default EvaluationException error(String message) {\n return new EvaluationException(message, pos());\n }\n}"
},
{
"identifier": "PatchFunction",
"path": "src/main/java/io/github/mattidragon/jsonpatcher/lang/runtime/function/PatchFunction.java",
"snippet": "public sealed interface PatchFunction {\n Value execute(EvaluationContext context, List<Value> args, SourceSpan callPos);\n\n default PatchFunction bind(Value value) {\n return Libraries.FunctionsLibrary.bind(new Value.FunctionValue(this), value).function();\n }\n\n @FunctionalInterface\n non-sealed interface BuiltInPatchFunction extends PatchFunction {\n default BuiltInPatchFunction argCount(int count) {\n return (context, args, callPos) -> {\n if (args.size() != count) {\n throw new EvaluationException(\"Incorrect function argument count: expected %s but found %s\".formatted(count, args.size()), callPos);\n }\n return execute(context, args, callPos);\n };\n }\n }\n\n record DefinedPatchFunction(Statement body, List<Optional<String>> args, EvaluationContext context) implements PatchFunction {\n public DefinedPatchFunction {\n args = List.copyOf(args);\n }\n\n @Override\n public Value execute(EvaluationContext context, List<Value> args, SourceSpan callPos) {\n if (this.args.size() != args.size()) {\n throw new EvaluationException(\"Incorrect function argument count: expected %s but found %s\".formatted(this.args.size(), args.size()), callPos);\n }\n\n // We use the context the function was created in, not the one it was called in.\n // This allows for closures if we ever allow a function to escape its original scope\n var functionContext = this.context.newScope();\n\n var rootIndex = this.args.indexOf(Optional.<String>empty());\n if (rootIndex != -1) {\n if (args.get(rootIndex) instanceof Value.ObjectValue root) {\n functionContext = functionContext.withRoot(root);\n } else {\n throw new EvaluationException(\"Only objects can be used in apply statements, tried to use %s\".formatted(args.get(rootIndex)), callPos);\n }\n }\n\n var variables = functionContext.variables();\n for (int i = 0; i < args.size(); i++) {\n var argName = this.args.get(i);\n var argVal = args.get(i);\n argName.ifPresent(s -> variables.createVariableUnsafe(s, argVal, false));\n }\n\n try {\n body.run(functionContext);\n } catch (ReturnException r) {\n return r.value;\n } catch (EvaluationException e) {\n throw new EvaluationException(\"Error while executing function\", callPos, e);\n }\n\n return Value.NullValue.NULL;\n }\n }\n}"
},
{
"identifier": "Statement",
"path": "src/main/java/io/github/mattidragon/jsonpatcher/lang/runtime/statement/Statement.java",
"snippet": "public interface Statement {\n void run(EvaluationContext context);\n SourceSpan getPos();\n\n default EvaluationException error(String message) {\n return new EvaluationException(message, getPos());\n }\n\n}"
},
{
"identifier": "LibraryBuilder",
"path": "src/main/java/io/github/mattidragon/jsonpatcher/lang/runtime/stdlib/LibraryBuilder.java",
"snippet": "public class LibraryBuilder {\n private final Class<?> libraryClass;\n private final Object instance;\n private final HashMap<String, PatchFunction.BuiltInPatchFunction> functions = new HashMap<>();\n private final HashMap<String, Value> constants = new HashMap<>();\n private final Class<? extends Annotation> filterAnnotation;\n\n public LibraryBuilder(Class<?> libraryClass) {\n this(libraryClass, (Class<? extends Annotation>) null);\n }\n\n public LibraryBuilder(Class<?> libraryClass, Class<? extends Annotation> filterAnnotation) {\n this.libraryClass = libraryClass;\n this.filterAnnotation = filterAnnotation;\n try {\n this.instance = libraryClass.getConstructor().newInstance();\n } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {\n throw new IllegalStateException(\"Failed to build library object\", e);\n }\n buildFunctions();\n buildConstants();\n }\n\n public <T> LibraryBuilder(Class<T> libraryClass, T instance) {\n this(libraryClass, instance, null);\n }\n\n public <T> LibraryBuilder(Class<T> libraryClass, T instance, Class<? extends Annotation> filterAnnotation) {\n this.libraryClass = libraryClass;\n this.filterAnnotation = filterAnnotation;\n this.instance = instance;\n buildFunctions();\n buildConstants();\n }\n\n private void buildFunctions() {\n var methods = findMethods();\n\n methods.forEach((name, overloads) -> {\n var byArgCount = groupOverloadsByArgCount(name, overloads);\n\n functions.put(name, (context, args, callPos) -> {\n var overload = byArgCount.get(args.size());\n if (overload == null) throw new EvaluationException(\"No overload of %s with %s arguments\".formatted(name, args.size()), callPos);\n\n var hasContext = overload.getParameterTypes()[0] == FunctionContext.class;\n\n for (int i = 0; i < args.size(); i++) {\n var arg = args.get(i);\n var param = overload.getParameterTypes()[hasContext ? i + 1 : i];\n if (!param.isInstance(arg)) throw new EvaluationException(\"Expected argument %s to be %s, was %s\".formatted(i, param, arg), callPos);\n }\n\n try {\n Object[] argsArray;\n if (hasContext) {\n argsArray = new Object[args.size() + 1];\n System.arraycopy(args.toArray(), 0, argsArray, 1, args.size());\n argsArray[0] = new FunctionContext(context, callPos);\n } else {\n argsArray = args.toArray();\n }\n\n var result = overload.invoke(instance, argsArray);\n\n if (result == null) return Value.NullValue.NULL;\n if (result instanceof Value value) return value;\n throw new IllegalStateException(\"Unexpected return value from library function %s: %s\".formatted(name, result));\n } catch (InvocationTargetException e) {\n if (e.getCause() instanceof EvaluationException e1) {\n throw new EvaluationException(\"Error while calling builtin function %s: %s\".formatted(name, e1.getMessage()), callPos);\n } else {\n throw new RuntimeException(\"Unexpected error while calling builtin function %s\".formatted(name), e);\n }\n } catch (IllegalAccessException e) {\n throw new IllegalStateException(\"Library function %s is not accessible\".formatted(name), e);\n } catch (IllegalArgumentException e) {\n throw new IllegalStateException(\"Library function argument checks failed for %s\".formatted(name), e);\n }\n });\n });\n }\n\n private static HashMap<Integer, Method> groupOverloadsByArgCount(String name, List<Method> overloads) {\n var byArgCount = new HashMap<Integer, Method>();\n for (var overload : overloads) {\n var argCount = overload.getParameterCount();\n if (argCount >= 1 && overload.getParameterTypes()[0] == FunctionContext.class) {\n argCount--;\n }\n\n if (byArgCount.containsKey(argCount)) {\n throw new IllegalStateException(\"Library function %s has multiple overloads with the same number of arguments\".formatted(name));\n }\n byArgCount.put(argCount, overload);\n }\n return byArgCount;\n }\n\n private HashMap<String, List<Method>> findMethods() {\n var methods = new HashMap<String, List<Method>>();\n\n for (var method : libraryClass.getDeclaredMethods()) {\n if ((method.getModifiers() & Modifier.PUBLIC) == 0) continue;\n if (method.getAnnotation(DontBind.class) != null) continue;\n if (filterAnnotation != null && method.getAnnotation(filterAnnotation) == null) continue;\n if (method.isVarArgs()) throw new IllegalStateException(\"Library functions cannot be varargs (yet), %s is\".formatted(method));\n\n var parameterTypes = method.getParameterTypes();\n for (int i = 0; i < parameterTypes.length; i++) {\n var type = parameterTypes[i];\n\n // Allow context as first argument\n if (i == 0 && type == FunctionContext.class) {\n continue;\n }\n\n if (!Value.class.isAssignableFrom(type)) {\n throw new IllegalStateException(\"Library function parameters must be of subclass Value, %s from %s is not\".formatted(type, method));\n }\n }\n\n if (method.getReturnType() != void.class && !Value.class.isAssignableFrom(method.getReturnType())) {\n throw new IllegalStateException(\"Library function return type must be of subclass Value or void, %s from %s is not\".formatted(method.getReturnType(), method));\n }\n\n var methodName = method.getName();\n var nameOverride = method.getAnnotation(FunctionName.class);\n if (nameOverride != null) methodName = nameOverride.value();\n\n methods.computeIfAbsent(methodName, name -> new ArrayList<>()).add(method);\n }\n return methods;\n }\n\n private void buildConstants() {\n for (var field : libraryClass.getDeclaredFields()) {\n if ((field.getModifiers() & Modifier.PUBLIC) == 0) continue;\n if (field.getAnnotation(DontBind.class) != null) continue;\n if (filterAnnotation != null && field.getAnnotation(filterAnnotation) == null) continue;\n if (!Value.class.isAssignableFrom(field.getType())) throw new IllegalStateException(\"Library constants must be of subclass Value, %s from %s is not\".formatted(field.getType(), field));\n try {\n constants.put(field.getName(), (Value) field.get(instance));\n } catch (IllegalAccessException e) {\n throw new IllegalStateException(\"Library constant %s is not accessible\".formatted(field), e);\n }\n }\n }\n\n public HashMap<String, PatchFunction.BuiltInPatchFunction> getFunctions() {\n return functions;\n }\n\n public Value.ObjectValue build() {\n var object = new Value.ObjectValue();\n functions.forEach((name, function) -> object.value().put(name, new Value.FunctionValue(function)));\n constants.forEach(object.value()::put);\n return object;\n }\n\n public record FunctionContext(EvaluationContext context, SourceSpan callPos) {\n }\n}"
},
{
"identifier": "parseExpression",
"path": "src/main/java/io/github/mattidragon/jsonpatcher/lang/parse/Parser.java",
"snippet": "@VisibleForTesting\npublic static Expression parseExpression(List<PositionedToken<?>> tokens) throws ParseException {\n var parser = new Parser(tokens);\n var errors = parser.errors;\n Expression expression = null;\n try {\n expression = parser.expression();\n } catch (EndParsingException ignored) {\n } catch (ParseException e) {\n errors.add(e);\n }\n if (!errors.isEmpty()) {\n var error = new RuntimeException(\"Expected successful parse\");\n errors.forEach(error::addSuppressed);\n throw error;\n }\n return expression;\n}"
}
] | import io.github.mattidragon.jsonpatcher.lang.parse.*;
import io.github.mattidragon.jsonpatcher.lang.runtime.EvaluationContext;
import io.github.mattidragon.jsonpatcher.lang.runtime.Value;
import io.github.mattidragon.jsonpatcher.lang.runtime.expression.Expression;
import io.github.mattidragon.jsonpatcher.lang.runtime.expression.ValueExpression;
import io.github.mattidragon.jsonpatcher.lang.runtime.function.PatchFunction;
import io.github.mattidragon.jsonpatcher.lang.runtime.statement.BlockStatement;
import io.github.mattidragon.jsonpatcher.lang.runtime.statement.Statement;
import io.github.mattidragon.jsonpatcher.lang.runtime.statement.UnnecessarySemicolonStatement;
import io.github.mattidragon.jsonpatcher.lang.runtime.stdlib.LibraryBuilder;
import org.junit.jupiter.api.AssertionFailureBuilder;
import org.junit.jupiter.api.Assertions;
import java.util.List;
import java.util.function.Consumer;
import static io.github.mattidragon.jsonpatcher.lang.parse.Parser.parseExpression;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertNotNull; | 4,473 | package io.github.mattidragon.jsonpatcher.lang.test;
public class TestUtils {
public static final SourceFile FILE = new SourceFile("test file", "00");
public static final SourceSpan POS = new SourceSpan(new SourcePos(FILE, 1, 1), new SourcePos(FILE, 1, 2));
public static final Consumer<Value> EMPTY_DEBUG_CONSUMER = (value) -> {};
public static EvaluationContext createTestContext() {
return EvaluationContext.builder().debugConsumer(EMPTY_DEBUG_CONSUMER).build();
}
public static LibraryBuilder.FunctionContext createTestFunctionContext() {
return new LibraryBuilder.FunctionContext(createTestContext(), POS);
}
public static void testCode(String code, Value expected) {
var result = Parser.parse(Lexer.lex(code, "test file").tokens());
if (!(result instanceof Parser.Result.Success success)) {
var error = new RuntimeException("Expected successful parse");
((Parser.Result.Fail) result).errors().forEach(error::addSuppressed);
AssertionFailureBuilder.assertionFailure()
.message("Expected successful parse")
.cause(error)
.buildAndThrow();
return;
}
var program = success.program();
var output = new Value[1];
var context = EvaluationContext.builder()
.debugConsumer(EMPTY_DEBUG_CONSUMER)
.variable("testResult", new Value.FunctionValue((PatchFunction.BuiltInPatchFunction) (ctx, args, pos) -> {
output[0] = args.get(0);
return Value.NullValue.NULL;
}))
.build();
program.execute(context);
Assertions.assertNotEquals(null, output[0], "testResult should be called");
assertEquals(expected, output[0]);
}
public static void testExpression(String code, Value expected) { | package io.github.mattidragon.jsonpatcher.lang.test;
public class TestUtils {
public static final SourceFile FILE = new SourceFile("test file", "00");
public static final SourceSpan POS = new SourceSpan(new SourcePos(FILE, 1, 1), new SourcePos(FILE, 1, 2));
public static final Consumer<Value> EMPTY_DEBUG_CONSUMER = (value) -> {};
public static EvaluationContext createTestContext() {
return EvaluationContext.builder().debugConsumer(EMPTY_DEBUG_CONSUMER).build();
}
public static LibraryBuilder.FunctionContext createTestFunctionContext() {
return new LibraryBuilder.FunctionContext(createTestContext(), POS);
}
public static void testCode(String code, Value expected) {
var result = Parser.parse(Lexer.lex(code, "test file").tokens());
if (!(result instanceof Parser.Result.Success success)) {
var error = new RuntimeException("Expected successful parse");
((Parser.Result.Fail) result).errors().forEach(error::addSuppressed);
AssertionFailureBuilder.assertionFailure()
.message("Expected successful parse")
.cause(error)
.buildAndThrow();
return;
}
var program = success.program();
var output = new Value[1];
var context = EvaluationContext.builder()
.debugConsumer(EMPTY_DEBUG_CONSUMER)
.variable("testResult", new Value.FunctionValue((PatchFunction.BuiltInPatchFunction) (ctx, args, pos) -> {
output[0] = args.get(0);
return Value.NullValue.NULL;
}))
.build();
program.execute(context);
Assertions.assertNotEquals(null, output[0], "testResult should be called");
assertEquals(expected, output[0]);
}
public static void testExpression(String code, Value expected) { | var expression = new Expression[1]; | 1 | 2023-11-23 14:17:00+00:00 | 8k |
quarkusio/conversational-release-action | src/main/java/io/quarkus/bot/release/step/SyncCoreRelease.java | [
{
"identifier": "ReleaseInformation",
"path": "src/main/java/io/quarkus/bot/release/ReleaseInformation.java",
"snippet": "public class ReleaseInformation {\n\n private final String branch;\n private final String qualifier;\n private final boolean major;\n\n private String version;\n private boolean maintenance;\n\n @JsonCreator\n public ReleaseInformation(String version, String branch, String qualifier, boolean major, boolean maintenance) {\n this.version = version;\n this.branch = branch;\n this.qualifier = qualifier;\n this.major = major;\n this.maintenance = maintenance;\n }\n\n public String getVersion() {\n return version;\n }\n\n public String getBranch() {\n return branch;\n }\n\n public String getQualifier() {\n return qualifier;\n }\n\n public boolean isMaintenance() {\n return maintenance;\n }\n\n public void setVersion(String version) {\n this.version = version;\n }\n\n public void setMaintenance(boolean maintenance) {\n this.maintenance = maintenance;\n }\n\n @JsonIgnore\n public boolean isFinal() {\n return qualifier == null || qualifier.isBlank() || qualifier.equals(\"Final\");\n }\n\n @JsonIgnore\n public boolean isFirstFinal() {\n if (version == null) {\n throw new IllegalStateException(\"Unable to know if the version is the first final at this stage\");\n }\n\n return version.endsWith(\".0\") || version.endsWith(\".0.Final\");\n }\n\n @JsonIgnore\n public boolean isFirstCR() {\n return \"CR1\".equalsIgnoreCase(qualifier);\n }\n\n public boolean isMajor() {\n return major;\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(branch, major, qualifier);\n }\n\n @Override\n public boolean equals(Object obj) {\n if (this == obj)\n return true;\n if (obj == null)\n return false;\n if (getClass() != obj.getClass())\n return false;\n ReleaseInformation other = (ReleaseInformation) obj;\n return Objects.equals(version, this.version) && Objects.equals(branch, other.branch) && major == other.major\n && Objects.equals(qualifier, other.qualifier);\n }\n\n @Override\n public String toString() {\n return \"ReleaseInformation [version=\" + version + \", branch=\" + branch + \", qualifier=\" + qualifier + \", major=\" + major + \",maintenance=\" + maintenance\n + \"]\";\n }\n}"
},
{
"identifier": "ReleaseStatus",
"path": "src/main/java/io/quarkus/bot/release/ReleaseStatus.java",
"snippet": "public class ReleaseStatus {\n\n private final Status status;\n private final Step currentStep;\n private final StepStatus currentStepStatus;\n private final Long workflowRunId;\n private final Instant date;\n\n @JsonCreator\n public ReleaseStatus(Status status, Step currentStep, StepStatus currentStepStatus, Long workflowRunId) {\n this.status = status;\n this.currentStep = currentStep;\n this.currentStepStatus = currentStepStatus;\n this.workflowRunId = workflowRunId;\n this.date = Instant.now();\n }\n\n public Status getStatus() {\n return status;\n }\n\n public Step getCurrentStep() {\n return currentStep;\n }\n\n public StepStatus getCurrentStepStatus() {\n return currentStepStatus;\n }\n\n public Long getWorkflowRunId() {\n return workflowRunId;\n }\n\n public Instant getDate() {\n return date;\n }\n\n @JsonIgnore\n public ReleaseStatus progress(Long workflowRunId) {\n return new ReleaseStatus(this.status, this.currentStep, this.currentStepStatus, workflowRunId);\n }\n\n @JsonIgnore\n public ReleaseStatus progress(Step updatedStep) {\n return new ReleaseStatus(this.status, updatedStep, StepStatus.INIT, this.workflowRunId);\n }\n\n @JsonIgnore\n public ReleaseStatus progress(StepStatus updatedStepStatus) {\n return new ReleaseStatus(this.status, this.currentStep, updatedStepStatus, this.workflowRunId);\n }\n\n @JsonIgnore\n public ReleaseStatus progress(Status status, StepStatus updatedStepStatus) {\n return new ReleaseStatus(status, this.currentStep, updatedStepStatus, this.workflowRunId);\n }\n\n @JsonIgnore\n public ReleaseStatus progress(Status status) {\n return new ReleaseStatus(status, this.currentStep, this.currentStepStatus, this.workflowRunId);\n }\n\n @Override\n public int hashCode() {\n return Objects.hash(currentStep, currentStepStatus, workflowRunId);\n }\n\n @Override\n public boolean equals(Object obj) {\n if (this == obj)\n return true;\n if (obj == null)\n return false;\n if (getClass() != obj.getClass())\n return false;\n ReleaseStatus other = (ReleaseStatus) obj;\n return currentStep == other.currentStep && currentStepStatus == other.currentStepStatus\n && Objects.equals(workflowRunId, other.workflowRunId);\n }\n\n @Override\n public String toString() {\n return \"ReleaseStatus [currentStep=\" + currentStep + \", currentStepStatus=\" + currentStepStatus + \", workflowRunId=\"\n + workflowRunId + \"]\";\n }\n}"
},
{
"identifier": "Branches",
"path": "src/main/java/io/quarkus/bot/release/util/Branches.java",
"snippet": "public class Branches {\n\n public static final String MAIN = \"main\";\n public static final List<String> LTS_BRANCHES = List.of(\"3.2\", \"2.13\");\n\n public static String getPlatformPreparationBranch(ReleaseInformation releaseInformation) {\n if (releaseInformation.isFinal() && !releaseInformation.isFirstFinal()) {\n return releaseInformation.getBranch();\n }\n\n return MAIN;\n }\n\n public static String getPlatformReleaseBranch(ReleaseInformation releaseInformation) {\n if (releaseInformation.isFinal()) {\n return releaseInformation.getBranch();\n }\n\n return MAIN;\n }\n\n private Branches() {\n }\n}"
},
{
"identifier": "Command",
"path": "src/main/java/io/quarkus/bot/release/util/Command.java",
"snippet": "public enum Command {\n\n YES(\"yes\"),\n AUTO(\"auto\"),\n MANUAL(\"manual\"),\n CONTINUE(\"continue\"),\n RETRY(\"retry\");\n\n private final String[] commands;\n\n Command(String... commands) {\n this.commands = commands;\n }\n\n public boolean matches(String body) {\n for (String command : commands) {\n if (body.toLowerCase(Locale.ENGLISH).startsWith(\"@\" + Users.QUARKUS_BOT + \" \" + command)) {\n return true;\n }\n }\n\n return false;\n }\n\n public String getFullCommand() {\n return \"@\" + Users.QUARKUS_BOT + \" \" + commands[0];\n }\n}"
},
{
"identifier": "MonitorArtifactPublicationInputKeys",
"path": "src/main/java/io/quarkus/bot/release/util/MonitorArtifactPublicationInputKeys.java",
"snippet": "public class MonitorArtifactPublicationInputKeys {\n\n public static final String GROUP_ID = \"group-id\";\n public static final String ARTIFACT_ID = \"artifact-id\";\n public static final String VERSION = \"version\";\n public static final String ISSUE_NUMBER = \"issue-number\";\n public static final String MESSAGE_IF_PUBLISHED = \"message-if-published\";\n public static final String MESSAGE_IF_NOT_PUBLISHED = \"message-if-not-published\";\n public static final String INITIAL_DELAY = \"initial-delay\";\n public static final String POLL_DELAY = \"poll-delay\";\n public static final String POLL_ITERATIONS = \"poll-iterations\";\n public static final String POST_DELAY = \"post-delay\";\n\n private MonitorArtifactPublicationInputKeys() {\n }\n}"
},
{
"identifier": "Outputs",
"path": "src/main/java/io/quarkus/bot/release/util/Outputs.java",
"snippet": "public final class Outputs {\n\n public static final String BRANCH = \"branch\";\n public static final String VERSION = \"version\";\n public static final String QUALIFIER = \"qualifier\";\n public static final String MAJOR = \"major\";\n public static final String JDK = \"jdk\";\n\n public static final String STATUS = \"status\";\n public static final String CURRENT_STEP = \"current-step\";\n public static final String CURRENT_STEP_STATUS = \"current-step-status\";\n public static final String WORKFLOW_RUN_ID = \"workflow-run-id\";\n public static final String DATE = \"date\";\n\n public static final String INTERACTION_COMMENT = \"interaction-comment\";\n\n private Outputs() {\n }\n}"
},
{
"identifier": "Progress",
"path": "src/main/java/io/quarkus/bot/release/util/Progress.java",
"snippet": "public final class Progress {\n\n private Progress() {\n }\n\n public static String youAreHere(ReleaseInformation releaseInformation, ReleaseStatus releaseStatus) {\n return \"---\\n\\n<details><summary>Where am I?</summary>\\n\\n\" +\n Arrays.stream(Step.values())\n .filter(s -> releaseInformation.isFinal() || !s.isForFinalReleasesOnly())\n .map(s -> {\n StringBuilder sb = new StringBuilder();\n sb.append(\"[\");\n if (releaseStatus.getCurrentStep().ordinal() > s.ordinal() ||\n (releaseStatus.getCurrentStep() == s\n && (releaseStatus.getCurrentStepStatus() == StepStatus.COMPLETED || releaseStatus.getCurrentStepStatus() == StepStatus.SKIPPED))) {\n sb.append(\"X\");\n } else {\n sb.append(\" \");\n }\n sb.append(\"] \").append(s.getDescription());\n\n if (releaseStatus.getCurrentStep() == s) {\n sb.append(\" \");\n switch (releaseStatus.getCurrentStepStatus()) {\n case INIT:\n case STARTED:\n sb.append(\":gear:\");\n break;\n case COMPLETED:\n // should never happen\n sb.append(\":white_check_mark:\");\n break;\n case SKIPPED:\n // should never happen\n sb.append(\":zzz:\");\n break;\n case INIT_FAILED:\n case FAILED:\n sb.append(\":rotating_light:\");\n break;\n case PAUSED:\n sb.append(\":pause_button:\");\n break;\n }\n sb.append(\" ☚ You are here\");\n } else if (releaseStatus.getCurrentStepStatus() == StepStatus.SKIPPED) {\n sb.append(\" :zzz:\");\n }\n return sb.toString();\n }).collect(Collectors.joining(\"\\n- \", \"- \", \"\"))\n + \"</details>\";\n }\n}"
},
{
"identifier": "UpdatedIssueBody",
"path": "src/main/java/io/quarkus/bot/release/util/UpdatedIssueBody.java",
"snippet": "public class UpdatedIssueBody {\n\n private String body;\n\n public UpdatedIssueBody(String body) {\n this.body = body;\n }\n\n public String getBody() {\n return body;\n }\n\n public boolean contains(String section) {\n if (isBlank()) {\n return false;\n }\n\n return body.contains(section);\n }\n\n public String append(String append) {\n this.body = (this.body != null ? this.body + \"\\n\\n\" : \"\") + append;\n return this.body;\n }\n\n public String replace(Pattern pattern, String replacement) {\n this.body = pattern.matcher(body).replaceFirst(replacement);\n return this.body;\n }\n\n public boolean isBlank() {\n return body == null || body.isBlank();\n }\n\n @Override\n public String toString() {\n return body;\n }\n}"
},
{
"identifier": "Versions",
"path": "src/main/java/io/quarkus/bot/release/util/Versions.java",
"snippet": "public final class Versions {\n\n public static final ComparableVersion MAIN = new ComparableVersion(\"999-SNAPSHOT\");\n public static final ComparableVersion VERSION_3_2 = new ComparableVersion(\"3.2\");\n public static final ComparableVersion VERSION_3_6 = new ComparableVersion(\"3.6\");\n public static final ComparableVersion VERSION_3_7 = new ComparableVersion(\"3.7\");\n\n private Versions() {\n }\n\n public static ComparableVersion getVersion(String version) {\n if (Branches.MAIN.equals(version)) {\n return MAIN;\n }\n\n return new ComparableVersion(version);\n }\n\n public static ComparableVersion getBranch(String version) {\n String[] elements = version.split(\"\\\\.\");\n\n if (elements.length < 2) {\n return getVersion(version);\n }\n\n return getVersion(elements[0] + \".\" + elements[1]);\n }\n\n public static String getPreviousMinorBranch(NavigableSet<ComparableVersion> existingBranches, ComparableVersion currentBranch) {\n String previousMinor = null;\n\n for (ComparableVersion branchCandidate : existingBranches.descendingSet()) {\n if (branchCandidate.compareTo(currentBranch) >= 0) {\n continue;\n }\n\n previousMinor = branchCandidate.toString();\n break;\n }\n\n if (previousMinor == null) {\n throw new IllegalStateException(\"Unable to determine previous minor for current branch \" + currentBranch\n + \" and existing branches \" + existingBranches);\n }\n\n return previousMinor;\n }\n}"
}
] | import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import jakarta.inject.Singleton;
import org.kohsuke.github.GHIssue;
import org.kohsuke.github.GHIssueComment;
import org.kohsuke.github.GitHub;
import io.quarkiverse.githubaction.Commands;
import io.quarkiverse.githubaction.Context;
import io.quarkus.arc.Unremovable;
import io.quarkus.bot.release.ReleaseInformation;
import io.quarkus.bot.release.ReleaseStatus;
import io.quarkus.bot.release.util.Branches;
import io.quarkus.bot.release.util.Command;
import io.quarkus.bot.release.util.MonitorArtifactPublicationInputKeys;
import io.quarkus.bot.release.util.Outputs;
import io.quarkus.bot.release.util.Progress;
import io.quarkus.bot.release.util.UpdatedIssueBody;
import io.quarkus.bot.release.util.Versions; | 4,132 | package io.quarkus.bot.release.step;
@Singleton
@Unremovable
public class SyncCoreRelease implements StepHandler {
@Override
public boolean shouldPause(Context context, Commands commands, GitHub quarkusBotGitHub,
ReleaseInformation releaseInformation, ReleaseStatus releaseStatus, GHIssue issue, GHIssueComment issueComment) {
StringBuilder comment = new StringBuilder();
comment.append("The core artifacts have been pushed to `s01.oss.sonatype.org`.\n\n");
comment.append(
"**IMPORTANT** You need to wait for them to be synced to Maven Central before continuing with the release:\n\n");
try {
Map<String, Object> inputs = new HashMap<>();
inputs.put(MonitorArtifactPublicationInputKeys.GROUP_ID, "io.quarkus");
inputs.put(MonitorArtifactPublicationInputKeys.ARTIFACT_ID, "quarkus-bom");
inputs.put(MonitorArtifactPublicationInputKeys.VERSION, releaseInformation.getVersion());
inputs.put(MonitorArtifactPublicationInputKeys.ISSUE_NUMBER, String.valueOf(issue.getNumber()));
inputs.put(MonitorArtifactPublicationInputKeys.MESSAGE_IF_PUBLISHED,
Command.CONTINUE.getFullCommand() + "\n\nWe have detected that the core artifacts have been synced to Maven Central.");
inputs.put(MonitorArtifactPublicationInputKeys.MESSAGE_IF_NOT_PUBLISHED,
"The core artifacts don't seem to have been synced to Maven Central.\n\n"
+ "Please check the situation by yourself:\n\n"
+ "* Check that https://repo1.maven.org/maven2/io/quarkus/quarkus-bom/"
+ releaseInformation.getVersion() + "/"
+ " does not return a 404\n"
+ "* Wait some more if it still returns a 404.\n\n"
+ "Once the artifact is available, wait for an additional 20 minutes then you can continue with the release by adding a `"
+ Command.CONTINUE.getFullCommand() + "` comment.");
inputs.put(MonitorArtifactPublicationInputKeys.INITIAL_DELAY, "30");
inputs.put(MonitorArtifactPublicationInputKeys.POLL_ITERATIONS, "3");
inputs.put(MonitorArtifactPublicationInputKeys.POLL_DELAY, "10");
inputs.put(MonitorArtifactPublicationInputKeys.POST_DELAY, "20");
issue.getRepository().getWorkflow("monitor-artifact-publication.yml").dispatch(Branches.MAIN, inputs);
comment.append("The publication of the core artifacts will take 60-80 minutes.\n\n"
+ "**We started a separate workflow to monitor the situation for you. It will automatically continue the release process once it detects the artifacts have been synced to Maven Central.**\n\n");
comment.append("---\n\n");
comment.append("<details><summary>If things go south</summary>\n\n");
comment.append("If things go south, you can monitor the situation manually:\n\n");
comment.append("* Wait for 1 hour (starting from the time of this comment)\n");
comment.append("* Check that https://repo1.maven.org/maven2/io/quarkus/quarkus-bom/"
+ releaseInformation.getVersion() + "/"
+ " does not return a 404\n\n");
comment.append(
"Once these two conditions are met, you can continue with the release by adding a `"
+ Command.CONTINUE.getFullCommand() + "` comment.\n\n");
comment.append("</details>");
} catch (Exception e) {
comment.append("We were unable to start the core artifacts monitoring workflow, so please monitor the situation manually:\n\n");
comment.append("* Wait for 1 hour (starting from the time of this comment)\n");
comment.append("* Check that https://repo1.maven.org/maven2/io/quarkus/quarkus-bom/"
+ releaseInformation.getVersion() + "/"
+ " does not return a 404\n\n");
comment.append(
"Once these two conditions are met, you can continue with the release by adding a `"
+ Command.CONTINUE.getFullCommand() + "` comment.");
}
| package io.quarkus.bot.release.step;
@Singleton
@Unremovable
public class SyncCoreRelease implements StepHandler {
@Override
public boolean shouldPause(Context context, Commands commands, GitHub quarkusBotGitHub,
ReleaseInformation releaseInformation, ReleaseStatus releaseStatus, GHIssue issue, GHIssueComment issueComment) {
StringBuilder comment = new StringBuilder();
comment.append("The core artifacts have been pushed to `s01.oss.sonatype.org`.\n\n");
comment.append(
"**IMPORTANT** You need to wait for them to be synced to Maven Central before continuing with the release:\n\n");
try {
Map<String, Object> inputs = new HashMap<>();
inputs.put(MonitorArtifactPublicationInputKeys.GROUP_ID, "io.quarkus");
inputs.put(MonitorArtifactPublicationInputKeys.ARTIFACT_ID, "quarkus-bom");
inputs.put(MonitorArtifactPublicationInputKeys.VERSION, releaseInformation.getVersion());
inputs.put(MonitorArtifactPublicationInputKeys.ISSUE_NUMBER, String.valueOf(issue.getNumber()));
inputs.put(MonitorArtifactPublicationInputKeys.MESSAGE_IF_PUBLISHED,
Command.CONTINUE.getFullCommand() + "\n\nWe have detected that the core artifacts have been synced to Maven Central.");
inputs.put(MonitorArtifactPublicationInputKeys.MESSAGE_IF_NOT_PUBLISHED,
"The core artifacts don't seem to have been synced to Maven Central.\n\n"
+ "Please check the situation by yourself:\n\n"
+ "* Check that https://repo1.maven.org/maven2/io/quarkus/quarkus-bom/"
+ releaseInformation.getVersion() + "/"
+ " does not return a 404\n"
+ "* Wait some more if it still returns a 404.\n\n"
+ "Once the artifact is available, wait for an additional 20 minutes then you can continue with the release by adding a `"
+ Command.CONTINUE.getFullCommand() + "` comment.");
inputs.put(MonitorArtifactPublicationInputKeys.INITIAL_DELAY, "30");
inputs.put(MonitorArtifactPublicationInputKeys.POLL_ITERATIONS, "3");
inputs.put(MonitorArtifactPublicationInputKeys.POLL_DELAY, "10");
inputs.put(MonitorArtifactPublicationInputKeys.POST_DELAY, "20");
issue.getRepository().getWorkflow("monitor-artifact-publication.yml").dispatch(Branches.MAIN, inputs);
comment.append("The publication of the core artifacts will take 60-80 minutes.\n\n"
+ "**We started a separate workflow to monitor the situation for you. It will automatically continue the release process once it detects the artifacts have been synced to Maven Central.**\n\n");
comment.append("---\n\n");
comment.append("<details><summary>If things go south</summary>\n\n");
comment.append("If things go south, you can monitor the situation manually:\n\n");
comment.append("* Wait for 1 hour (starting from the time of this comment)\n");
comment.append("* Check that https://repo1.maven.org/maven2/io/quarkus/quarkus-bom/"
+ releaseInformation.getVersion() + "/"
+ " does not return a 404\n\n");
comment.append(
"Once these two conditions are met, you can continue with the release by adding a `"
+ Command.CONTINUE.getFullCommand() + "` comment.\n\n");
comment.append("</details>");
} catch (Exception e) {
comment.append("We were unable to start the core artifacts monitoring workflow, so please monitor the situation manually:\n\n");
comment.append("* Wait for 1 hour (starting from the time of this comment)\n");
comment.append("* Check that https://repo1.maven.org/maven2/io/quarkus/quarkus-bom/"
+ releaseInformation.getVersion() + "/"
+ " does not return a 404\n\n");
comment.append(
"Once these two conditions are met, you can continue with the release by adding a `"
+ Command.CONTINUE.getFullCommand() + "` comment.");
}
| comment.append("\n\n" + Progress.youAreHere(releaseInformation, releaseStatus)); | 6 | 2023-11-20 10:33:48+00:00 | 8k |
wssun/AST4PLU | data-process/process/src/main/java/process/SplitAST_for_csn.java | [
{
"identifier": "GenerateAST",
"path": "data-process/process/src/main/java/JDT/GenerateAST.java",
"snippet": "public class GenerateAST {\n\tprivate static String ast;\n\tprivate static String masked_ast;\n\t\n\tpublic static class astVisitor extends ASTVisitor{\n\t\tpublic void preVisit(ASTNode node) {\n\t\t\tString type=node.nodeClassForType(node.getNodeType()).getSimpleName();\n\t\t\tif(node.nodeClassForType(node.getNodeType())==SimpleName.class)\n\t\t\t{\n\t\t\t\tSimpleName simpleName=(SimpleName)node;\n\t\t\t\tString value=simpleName.getIdentifier();\n\t\t\t\tast = ast+ \"(\"+type+\"(\"+value+\")\";\n\t\t\t}else if(node.nodeClassForType(node.getNodeType())==Modifier.class)\n\t\t\t{\n\t\t\t\tModifier modifier=(Modifier)node;\n\t\t\t\tString value=modifier.getKeyword().toString();\n\t\t\t\tast = ast+ \"(\"+type+\"(\"+value+\")\";\n\t\t\t}\n\t\t\telse if(node.nodeClassForType(node.getNodeType())==NumberLiteral.class)\n\t\t\t{\n\t\t\t\tNumberLiteral numberLiteral=(NumberLiteral)node;\n\t\t\t\tString value=numberLiteral.getToken();\n\t\t\t\tast = ast+ \"(\"+type+\"(\"+value+\")\";\n\t\t\t}\n\t\t\telse if(node.nodeClassForType(node.getNodeType())==StringLiteral.class)\n\t\t\t{\n\t\t\t\tStringLiteral stringLiteral=(StringLiteral)node;\n\t\t\t\tString value=stringLiteral.getLiteralValue();\n\t\t\t\tvalue=value.replaceAll(\" \",\"\");\n\t\t\t\tast = ast+ \"(\"+type+\"(\"+value+\")\";\n\t\t\t}\n\t\t\telse if(node.nodeClassForType(node.getNodeType())==CharacterLiteral.class)\n\t\t\t{\n\t\t\t\tCharacterLiteral characterLiteral=(CharacterLiteral)node;\n\t\t\t\tchar value=characterLiteral.charValue();\n\t\t\t\tast = ast+ \"(\"+type+\"(\"+value+\")\";\n\t\t\t}\n\t\t\telse if(node.nodeClassForType(node.getNodeType())==BooleanLiteral.class)\n\t\t\t{\n\t\t\t\tBooleanLiteral booleanLiteral=(BooleanLiteral)node;\n\t\t\t\tString value=booleanLiteral.toString();\n\t\t\t\tast = ast+ \"(\"+type+\"(\"+value+\")\";\n\t\t\t}\n\t\t\telse if(node.nodeClassForType(node.getNodeType())==InfixExpression.class)\n\t\t\t{\n\t\t\t\tInfixExpression infixExpression=(InfixExpression)node;\n\t\t\t\tString value=infixExpression.getOperator().toString();\n\t\t\t\tast = ast+ \"(\"+type+\"(\"+value+\")\";\n\t\t\t}\n\t\t\telse if(node.nodeClassForType(node.getNodeType())==PrefixExpression.class)\n\t\t\t{\n\t\t\t\tPrefixExpression prefixExpression=(PrefixExpression)node;\n\t\t\t\tString value=prefixExpression.getOperator().toString();\n\t\t\t\tast = ast+ \"(\"+type+\"(\"+value+\")\";\n\t\t\t}\n\t\t\telse if(node.nodeClassForType(node.getNodeType())==PostfixExpression.class)\n\t\t\t{\n\t\t\t\tPostfixExpression postfixExpression=(PostfixExpression)node;\n\t\t\t\tString value=postfixExpression.getOperator().toString();\n\t\t\t\tast = ast+ \"(\"+type+\"(\"+value+\")\";\n\t\t\t}\n\t\t\telse if(node.nodeClassForType(node.getNodeType())==PrimitiveType.class)\n\t\t\t{\n\t\t\t\tPrimitiveType primitiveType=(PrimitiveType)node;\n\t\t\t\tString value=primitiveType.getPrimitiveTypeCode().toString();\n\t\t\t\tast = ast+ \"(\"+type+\"(\"+value+\")\";\n\t\t\t}\n\t\t\telse ast = ast+ \"(\"+type;\n\t\t}\n\t\t\n\t\tpublic void postVisit(ASTNode node) {\n\t\t\tast = ast+ \")\";\n\t\t}\n\t}\n\t\n\tpublic static String getAST(String code){\n\t\tast=\"\";\n ASTParser parser = ASTParser.newParser(AST.JLS8);\n Map options = JavaCore.getOptions();\n JavaCore.setComplianceOptions(JavaCore.VERSION_1_8, options);\n parser.setCompilerOptions(options);\n parser.setSource(code.toCharArray());\n// \tparser.setKind(ASTParser.K_COMPILATION_UNIT);\n// parser.setKind(ASTParser.K_STATEMENTS); //split ast\n// parser.setKind(ASTParser.K_EXPRESSION);\n parser.setKind(ASTParser.K_CLASS_BODY_DECLARATIONS);\n \n //debug\n// ASTNode result = parser.createAST(new NullProgressMonitor());\n// if(result.nodeClassForType(result.getNodeType())==CompilationUnit.class)\n// {\n// \t CompilationUnit tmp = (CompilationUnit)result;\n// \t Message[] m = tmp.getMessages();\n// \t for(int i=0;i<m.length;++i)\n// \t {\n// \t\t System.out.println(m[i].getMessage());\n// \t }\n// }\n \n// CompilationUnit result = (CompilationUnit) parser.createAST(new NullProgressMonitor());\n// Block result = (Block) parser.createAST(new NullProgressMonitor());\n// CompilationUnit result = (CompilationUnit) parser.createAST(new NullProgressMonitor());\n TypeDeclaration result = (TypeDeclaration) parser.createAST(new NullProgressMonitor());\n result.accept(new astVisitor());\n return ast.substring(37);\n// return ast;\n\t}\n\t\n\tpublic static String getAST(String code,int kind) throws Exception{\n\t\tast=\"\";\n ASTParser parser = ASTParser.newParser(AST.JLS8);\n Map options = JavaCore.getOptions();\n JavaCore.setComplianceOptions(JavaCore.VERSION_1_8, options);\n parser.setCompilerOptions(options);\n parser.setSource(code.toCharArray());\n if(kind==0)\n \t{\n \tparser.setKind(ASTParser.K_COMPILATION_UNIT);\n \tCompilationUnit result = (CompilationUnit) parser.createAST(new NullProgressMonitor());\n \tresult.accept(new astVisitor());\n \treturn ast.substring(37);\n \t}\n else if(kind==1)\n \t{\n \tparser.setKind(ASTParser.K_STATEMENTS); //split ast\n \tBlock result = (Block) parser.createAST(new NullProgressMonitor());\n \tresult.accept(new astVisitor());\n \treturn ast;\n \t}\n else\n {\n \tSystem.out.println(\"wrong kind code\");\n \tthrow new Exception();\n }\n\t}\n\t\n\tpublic static class maskedVisitor extends ASTVisitor{\n\t\tpublic void preVisit(ASTNode node) {\n\t\t\tString type=node.nodeClassForType(node.getNodeType()).getSimpleName();\n\t\t\tif(node.nodeClassForType(node.getNodeType())==SimpleName.class)\n\t\t\t{\n\t\t\t\tast = ast+ \"(\"+type+\"(<mask>)\";\n\t\t\t}else if(node.nodeClassForType(node.getNodeType())==Modifier.class)\n\t\t\t{\n\t\t\t\tast = ast+ \"(\"+type+\"(<mask>)\";\n\t\t\t}\n\t\t\telse if(node.nodeClassForType(node.getNodeType())==NumberLiteral.class)\n\t\t\t{\n\t\t\t\tast = ast+ \"(\"+type+\"(<mask>)\";\n\t\t\t}\n\t\t\telse if(node.nodeClassForType(node.getNodeType())==StringLiteral.class)\n\t\t\t{\n\t\t\t\tast = ast+ \"(\"+type+\"(<mask>)\";\n\t\t\t}\n\t\t\telse if(node.nodeClassForType(node.getNodeType())==CharacterLiteral.class)\n\t\t\t{\n\t\t\t\tast = ast+ \"(\"+type+\"(<mask>)\";\n\t\t\t}\n\t\t\telse if(node.nodeClassForType(node.getNodeType())==BooleanLiteral.class)\n\t\t\t{\n\t\t\t\tast = ast+ \"(\"+type+\"(<mask>)\";\n\t\t\t}\n\t\t\telse if(node.nodeClassForType(node.getNodeType())==InfixExpression.class)\n\t\t\t{\n\t\t\t\tast = ast+ \"(\"+type+\"(<mask>)\";\n\t\t\t}\n\t\t\telse if(node.nodeClassForType(node.getNodeType())==PrefixExpression.class)\n\t\t\t{\n\t\t\t\tast = ast+ \"(\"+type+\"(<mask>)\";\n\t\t\t}\n\t\t\telse if(node.nodeClassForType(node.getNodeType())==PostfixExpression.class)\n\t\t\t{\n\t\t\t\tast = ast+ \"(\"+type+\"(<mask>)\";\n\t\t\t}\n\t\t\telse if(node.nodeClassForType(node.getNodeType())==PrimitiveType.class)\n\t\t\t{\n\t\t\t\tast = ast+ \"(\"+type+\"(<mask>)\";\n\t\t\t}\n\t\t\telse ast = ast+ \"(\"+type;\n\t\t}\n\t\t\n\t\tpublic void postVisit(ASTNode node) {\n\t\t\tast = ast+ \")\";\n\t\t}\n\t}\n\t\n\tpublic static String getMaskedAST(String code){\n\t\tast=\"\";\n ASTParser parser = ASTParser.newParser(AST.JLS8);\n Map options = JavaCore.getOptions();\n JavaCore.setComplianceOptions(JavaCore.VERSION_1_8, options);\n parser.setCompilerOptions(options);\n parser.setSource(code.toCharArray());\n parser.setKind(ASTParser.K_CLASS_BODY_DECLARATIONS);\n TypeDeclaration result = (TypeDeclaration) parser.createAST(new NullProgressMonitor());\n result.accept(new maskedVisitor());\n return ast.substring(37);\n// return ast;\n\t}\n}"
},
{
"identifier": "Tree",
"path": "data-process/process/src/main/java/tree/Tree.java",
"snippet": "public class Tree{\n\tprivate String root;\n\tprivate Tree father;\n\tprivate List<Tree> children;\n\tprivate HashSet<String> utp;\n\tprivate HashSet<String> utk;\n\tprivate long nonleaf;\n\tprivate long sum_children;\n\t\n\tpublic Tree()\n\t{\n\t\troot=\"\";\n\t\tchildren=new ArrayList<Tree>();\n\t\tfather=null;\n\t}\n\t\n\tpublic String getRoot() {\n\t\treturn root;\n\t}\n\n\tpublic void setRoot(String root) {\n\t\tthis.root = root;\n\t}\n\t\n\tpublic Boolean isRoot() {\n\t\tif(father==null)return true;\n\t\treturn false;\n\t}\n\t\n\tpublic Tree getFather() {\n\t\treturn father;\n\t}\n\n\tpublic void setfather(Tree fa) {\n\t\tthis.father = fa;\n\t}\n\t\n\tpublic List<Tree> getChildren(){\n\t\treturn children;\n\t}\n\t\n\tpublic void addChild(Tree child)\n\t{\n\t\tchild.setfather(this);\n\t\tchildren.add(child);\n\t}\n\t\n\tpublic boolean isLeaf()\n\t{\n\t\treturn children.size()==0;\n\t}\n\t\n\tpublic long getTreeSize()\n\t{\n\t\tif(root==\"\")return 0;\n\t\t\n\t\tlong ts=1;\n\t\tint sz=children.size();\n\t\tfor(int i=0;i<sz;++i)\n\t\t{\n\t\t\tts+=children.get(i).getTreeSize();\n\t\t}\n\t\treturn ts;\n\t}\n\t\n\tpublic long getTreeDepth()\n\t{\n\t\tif(root==\"\")return 0;\n\t\t\n\t\tlong td=1;\n\t\tint sz=children.size();\n\t\tfor(int i=0;i<sz;++i)\n\t\t{\n\t\t\tlong tmp=children.get(i).getTreeDepth()+1;\n\t\t\tif(tmp>td)td=tmp;\n\t\t}\n\t\treturn td;\n\t}\n\t\n\t//BF:branching factor — mean number of children in nonleaf vertices of a tree\n\tprivate void countBF(Tree tree)\n\t{\n\t\tif(tree.isLeaf())return;\n\t\tnonleaf+=1;\n\t\t\n\t\tList<Tree> c=tree.getChildren();\n\t\tint sz=c.size();\n\t\tsum_children+=sz;\n\t\t\n\t\tfor(int i=0;i<sz;++i)\n\t\t{\n\t\t\tcountBF(c.get(i));\n\t\t}\n\t}\n\n\tpublic long getBF()\n\t{\n\t\tnonleaf=0;\n\t\tsum_children=0;\n\t\tcountBF(this);\n\t\tif(nonleaf==0)return 0;\n\t\telse return Math.round(sum_children*1.0/nonleaf);\n\t}\n\t\n\t//UTP:unique types — number of unique types of intermediate nodes used in an AST\n\tprivate void countUTP(Tree tree)\n\t{\n\t\tif(tree.isLeaf())return;\n\t\tutp.add(tree.getRoot());\n\t\t\n\t\tList<Tree> c=tree.getChildren();\n\t\tint sz=c.size();\n\t\tfor(int i=0;i<sz;++i)\n\t\t{\n\t\t\tcountUTP(c.get(i));\n\t\t}\n\t}\n\n\tpublic long getUTP()\n\t{\n\t\tutp=new HashSet<String>();\n\t\tcountUTP(this);\n\t\treturn utp.size();\n\t}\n\t\n\tprivate static String[] splitCamelCase(String input) {\n\t\tPattern pattern = Pattern.compile(\"(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])\");\n Matcher matcher = pattern.matcher(input);\n return matcher.replaceAll(\" \").split(\" \");\n }\n\t\n\tprivate static String[] splitSnakeCase(String input) {\n return input.split(\"_\");\n }\n\t\n\t//UTK:unique tokens — number of unique sub-tokens in AST leaves\n\tprivate void countUTK(Tree tree, int flg)\n\t{\n\t\tif(tree.isLeaf()) \n\t\t{\n\t\t\tif(tree.getRoot()!=\"\")\n\t\t\t{\n\t\t\t\tString[] subtokens;\n\t\t\t\tif(flg==0)subtokens = splitCamelCase(tree.getRoot());\n\t\t\t\telse subtokens = splitSnakeCase(tree.getRoot());\n\t\t\t\tfor(int i=0;i<subtokens.length;++i) {\n\t\t\t\t\tutk.add(subtokens[i]);\n//\t\t\t\t\tSystem.out.println(subtokens[i]);\n\t\t\t\t}\n//\t\t\t\tSystem.out.println();\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tList<Tree> c=tree.getChildren();\n\t\tint sz=c.size();\n\t\tfor(int i=0;i<sz;++i)\n\t\t{\n\t\t\tcountUTK(c.get(i), flg);\n\t\t}\n\t}\n\n\tpublic long getUTK(int flg) //flg==0: camelCaseSplitting; fLg==1: snake_case_splitting\n\t{\n\t\tutk=new HashSet<String>();\n\t\tcountUTK(this, flg);\n\t\treturn utk.size();\n\t}\n}"
},
{
"identifier": "TreeToJSON",
"path": "data-process/process/src/main/java/utils/TreeToJSON.java",
"snippet": "public class TreeToJSON {\n\t//添加fastjson依赖\n\tprivate static JSONArray nodes;\n\tprivate static Integer globalIndex;\n\t\n\tpublic static void toJSON(Tree tree,int startIndex)\n\t{\n\t\tnodes=new JSONArray();\n\t\tglobalIndex=startIndex;\n\t\taddTree(tree);\n\t}\n\t\n\tprivate static Integer addTree(Tree tree)\n\t{\n\t\tInteger currentIndex=globalIndex;\n\t\t++globalIndex;\n\t\t\n\t\tList<Tree> children=tree.getChildren();\n\t\tList<Integer> childrenIndex=new ArrayList<Integer>();\n\t\tif(children.size()!=0)\n\t\t{\n\t\t\tfor(int i=0;i<children.size();++i)\n\t\t\t{\n\t\t\t\tchildrenIndex.add(addTree(children.get(i)));\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tchildrenIndex.add(-1);\n\t\t}\n\t\t\n\t\t\n\t\tJSONObject root = new JSONObject();\n\t\ttry {\n root.put(\"id\", currentIndex);\n root.put(\"label\", tree.getRoot());\n root.put(\"children\", childrenIndex);\n nodes.add(root);\n } catch (Exception e) {\n e.printStackTrace();\n }\n\t\t\n\t\treturn currentIndex;\n\t}\n\t\n\tpublic static JSONArray getJSONArray()\n\t{\n\t\treturn nodes;\n\t}\n\t\n\tpublic static String getJSONString()\n\t{\n\t\treturn nodes.toJSONString();\n\t}\n}"
},
{
"identifier": "TreeTools",
"path": "data-process/process/src/main/java/utils/TreeTools.java",
"snippet": "public class TreeTools {\n\t\n\tprivate static String sbt;\n\tprivate static List<String> sbt_no_brk;\n\tprivate static List<String> sbt_brk;\n\tprivate static List<String> non_leaf;\n\tprivate static Queue<Tree> que;\n\tprivate static List<String> ast_path;\n\t\n\tpublic static Tree stringToTree(String ast)\n\t{\n\t\treturn buildTree(ast.substring(1,ast.length()-1));\n\t}\n\t\n\tprivate static Tree buildTree(String ast)\n\t{\n\t\tTree tree=new Tree();\n\t\t//字符串\n\t\tif(ast.charAt(0)=='\\\"'||ast.charAt(0)=='\\'')\n\t\t{\n\t\t\ttree.setRoot(ast);\n\t\t\treturn tree;\n\t\t}\n\t\t//根节点\n\t\tint p=1;\n\t\twhile(p<ast.length()&&ast.charAt(p)!='(')++p;\n\t\tString rt=ast.substring(0,p);\n\t\tif(rt.equals(\"<left_bracket_5175241>\"))rt=\"(\";\n\t\tif(rt.equals(\"<right_bracket_5175241>\"))rt=\")\";\n\t\ttree.setRoot(rt);\n\t\tif(p>=ast.length())return tree;\n\t\t//子节点\n\t\twhile(p<ast.length()&&ast.charAt(p)=='(')\n\t\t{\n\t\t\t//ast[p~q]表示一个子节点\n\t\t\tBoolean in1=false,in2=false,pre=false;\n\t\t\tint cnt=0,q=p;\n\t\t\tfor(;q<ast.length();++q)\n\t\t\t{\n\t\t\t\tif(in1||in2)\n\t\t\t\t{\n\t\t\t\t\tif(ast.charAt(q)=='\"')in1=false;\n\t\t\t\t\tif(ast.charAt(q)=='\\'')in2=false;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tif(ast.charAt(q)=='\"')in1=true;\n\t\t\t\telse if(ast.charAt(q)=='\\'')in2=true;\n\t\t\t\t\n\t\t\t\tif(pre)\n\t\t\t\t{\n\t\t\t\t\tpre=false;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif(ast.charAt(q)=='(')\n\t\t\t\t{\n\t\t\t\t\t++cnt;\n\t\t\t\t\tpre=true;\n\t\t\t\t}\n\t\t\t\telse if(ast.charAt(q)==')')--cnt;\n\t\t\t\tif(cnt==0)break;\n\t\t\t}\n\t\t\ttree.addChild(buildTree(ast.substring(p+1,q)));\n\t\t\tp=q+1;\n\t\t}\n\t\treturn tree;\n\t}\n\t\n\tpublic static Tree stringToTreeJDT(String ast)\n\t{\n\t\treturn buildTreeJDT(ast.substring(1,ast.length()-1));\n\t}\n\t\n\tprivate static Tree buildTreeJDT(String ast)\n\t{\n\t\tTree tree=new Tree();\n\t\t//根节点\n\t\tint p=1;\n\t\twhile(p<ast.length()&&ast.charAt(p)!='(')++p;\n\t\ttree.setRoot(ast.substring(0,p));\n\t\tif(p>=ast.length())return tree;\n\t\t//子节点\n\t\twhile(p<ast.length()&&ast.charAt(p)=='(')\n\t\t{\n\t\t\t//ast[p~q]表示一个子节点\n\t\t\tint cnt=0,q=p;\n\t\t\tfor(;q<ast.length();++q)\n\t\t\t{\n\t\t\t\tif(ast.charAt(q)=='(')++cnt;\n\t\t\t\telse if(ast.charAt(q)==')')--cnt;\n\t\t\t\tif(cnt==0)break;\n\t\t\t}\n\t\t\tif(p+1<q)tree.addChild(buildTreeJDT(ast.substring(p+1,q)));\n\t\t\telse tree.addChild(buildTreeJDT(\"\\\"\\\"\"));\n\t\t\tp=q+1;\n\t\t}\n\t\treturn tree;\n\t}\n\t\n\tprivate static void traverse_sbt(Tree tree)\n\t{\n\t\tString root=tree.getRoot();\n\t\tsbt=sbt+\"(\"+root;\n\t\t\n\t\tList<Tree> children=tree.getChildren();\n\t\tint len=children.size();\n\t\tfor(int i=0;i<len;++i)\n\t\t{\n\t\t\ttraverse_sbt(children.get(i));\n\t\t}\n\t\t\n\t\tsbt=sbt+\")\"+root;\n\t}\n\t\n\tpublic static String treeToSBT(Tree tree)\n\t{\n\t\tsbt=\"\";\n\t\ttraverse_sbt(tree);\n\t\treturn sbt;\n\t}\n\t\n\tprivate static void traverse_sbt_array_no_brackets(Tree tree)\n\t{\n\t\tString root=tree.getRoot();\n\t\tsbt_no_brk.add(root);\n\t\t\n\t\tList<Tree> children=tree.getChildren();\n\t\tint len=children.size();\n\t\tfor(int i=0;i<len;++i)\n\t\t{\n\t\t\ttraverse_sbt_array_no_brackets(children.get(i));\n\t\t}\n\t\t\n\t\tsbt_no_brk.add(root);\n\t}\n\t\n\tpublic static List<String> treeToSBTArrayNoBrackets(Tree tree)\n\t{\n\t\tsbt_no_brk=new ArrayList<String>();\n\t\ttraverse_sbt_array_no_brackets(tree);\n\t\treturn sbt_no_brk;\n\t}\n\t\n\tprivate static void traverse_sbt_array_brackets(Tree tree)\n\t{\n\t\tString root=tree.getRoot();\n\t\tsbt_brk.add(\"(\");\n\t\tsbt_brk.add(root);\n\t\t\n\t\tList<Tree> children=tree.getChildren();\n\t\tint len=children.size();\n\t\tfor(int i=0;i<len;++i)\n\t\t{\n\t\t\ttraverse_sbt_array_brackets(children.get(i));\n\t\t}\n\t\t\n\t\tsbt_brk.add(\")\");\n\t\tsbt_brk.add(root);\n\t}\n\t\n\tpublic static List<String> treeToSBTArrayBrackets(Tree tree)\n\t{\n\t\tsbt_brk=new ArrayList<String>();\n\t\ttraverse_sbt_array_brackets(tree);\n\t\treturn sbt_brk;\n\t}\n\t\n\tpublic static String treeToBFS(Tree tree)\n\t{\n\t\tString bfs=\"\";\n\t\tBoolean fir=true;\n\t\tque=new LinkedList<Tree>();\n\t\t\n\t\tque.offer(tree);\n\t\twhile(que.size()!=0)\n\t\t{\n\t\t\tTree top=que.poll();\n\t\t\tif(!fir)bfs+=\" \";\n\t\t\tbfs+=top.getRoot();\n\t\t\tfir=false;\n\t\t\t\n\t\t\tList<Tree> children=top.getChildren();\n\t\t\tint len=children.size();\n\t\t\tfor(int i=0;i<len;++i)\n\t\t\t{\n\t\t\t\tque.offer(children.get(i));\n\t\t\t}\n\t\t}\n\t\treturn bfs;\n\t}\n\t\n\tprivate static void traverse_non_leaf(Tree tree)\n\t{\n\t\tString root=tree.getRoot();\n\t\tList<Tree> children=tree.getChildren();\n\t\tif(children.size()==0)return;\n\t\t\n\t\tnon_leaf.add(root);\n\t\tint len=children.size();\n\t\tfor(int i=0;i<len;++i)\n\t\t{\n\t\t\ttraverse_non_leaf(children.get(i));\n\t\t}\n\t}\n\t\n\tpublic static List<String> treeToNonLeaf(Tree tree)\n\t{\n\t\tnon_leaf=new ArrayList<String>();\n\t\ttraverse_non_leaf(tree);\n\t\treturn non_leaf;\n\t}\n\t\n\tprivate static void findRightLeaf(Tree root,int len,String path)\n\t{\n\t\tList<Tree> children = root.getChildren();\n\t\tif(children.size()==0)\n\t\t{\n\t\t\tpath=path+\"<sep>\"+root.getRoot(); //\",\"不能作为分隔符(有values(?,?,?)这样的sql语句,分隔符换成<sep>)\n\t\t\tast_path.add(path);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif(len<=0)return; //已经到了ast path最大长度\n\t\t\tint sz=children.size();\n\t\t\tfor(int i=0;i<sz;++i)\n\t\t\t{\n\t\t\t\tString new_path=path+\"|\"+root.getRoot();\n\t\t\t\tfindRightLeaf(children.get(i),len-1,new_path);\n\t\t\t}\n\t\t}\n\t}\n\t\n\tprivate static void findPathForLeaf(Tree leaf, int maxLen, int maxWid)\n\t{\n\t\tString path=leaf.getRoot()+\"<sep>\";\n\t\tTree top=leaf, pre=leaf;\n\t\tint len=-1; //length of the ast path: number of nonleaf nodes - 1\n\t\twhile(!top.isRoot()) //判断是否是根节点\n\t\t{\n\t\t\tpre=top;\n\t\t\ttop=top.getFather();\n\t\t\tif(len!=-1)path+=\"|\";\n\t\t\tpath+=top.getRoot();\n\t\t\t++len;\n\t\t\tif(len>maxLen)break;\n\t\t\t\n\t\t\tList<Tree> children = top.getChildren();\n\t\t\tint sz=children.size(),j=0;\n\t\t\tfor(;j<sz;++j)\n\t\t\t{\n\t\t\t\tif(children.get(j)==pre) break;\n\t\t\t}\n\t\t\tfor(int i=j+1;i<sz&&i-j<=maxWid;++i)\n\t\t\t{\n\t\t\t\tfindRightLeaf(children.get(i),maxLen-len,path);\n\t\t\t}\n\t\t\n\t\t}\n\t}\n\t\n\tprivate static void findLeftLeaf(Tree root,int maxLen,int maxWid)\n\t{\n\t\tList<Tree> children = root.getChildren();\n\t\tif(children.size()==0)\n\t\t{\n\t\t\tfindPathForLeaf(root,maxLen,maxWid);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tint sz=children.size();\n\t\t\tfor(int i=0;i<sz;++i)\n\t\t\t{\n\t\t\t\tfindLeftLeaf(children.get(i),maxLen,maxWid);\n\t\t\t}\n\t\t}\n\t}\n\t\n\tpublic static List<String> getASTPath(Tree tree, int maxLen, int maxWid)\n\t{\n\t\tast_path=new ArrayList<String>();\n\t\tfindLeftLeaf(tree, maxLen, maxWid);\n\t\treturn ast_path;\n\t}\n\n\t\n\tpublic static BinaryTree TreeToBinary(Tree tree)\n\t{\n\t\tBinaryTree bt;\n\t\tList<Tree> children = tree.getChildren();\n\t\tif(children.size()==0)\n\t\t{\n\t\t\tbt = new BinaryTree();\n\t\t\tbt.setRoot(tree.getRoot());\n\t\t}\n\t\telse if(children.size()==1)bt = TreeToBinary(children.get(0));\n\t\telse if(children.size()==2)\n\t\t{\n\t\t\tbt = new BinaryTree();\n\t\t\tbt.setRoot(tree.getRoot());\n\t\t\tbt.setLeftChild(TreeToBinary(children.get(0)));\n\t\t\tbt.setRightChild(TreeToBinary(children.get(1)));\n\t\t}\n\t\telse // children.size() > 2\n\t\t{\n\t\t\tbt = new BinaryTree();\n\t\t\tbt.setRoot(tree.getRoot());\n\t\t\tbt.setLeftChild(TreeToBinary(children.get(0)));\n\t\t\t\n\t\t\tTree right = new Tree();\n\t\t\tright.setRoot(\"Temp\");\n\t\t\tfor(int i=1;i<children.size();++i)right.addChild(children.get(i));\n\t\t\tbt.setRightChild(TreeToBinary(right));\n\t\t}\n\t\treturn bt;\n\t}\n}"
}
] | import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import JDT.GenerateAST;
import tree.Tree;
import utils.TreeToJSON;
import utils.TreeTools; | 6,480 | package process;
public class SplitAST_for_csn {
private static String AST_FILE_PATH="D:\\ast_dataset\\csn\\split_ast\\train_ast.jsonl";
private static String JSON_FILE_PATH="D:\\ast_dataset\\csn\\split_ast\\train.jsonl";
// use Tree-sitter
public static void main(String[] args) throws IOException {
FileReader fr = null;
BufferedReader br = null;
File jsonFile = null;
FileWriter fileWriter = null;
BufferedWriter bw = null;
try {
fr = new FileReader(AST_FILE_PATH);
br = new BufferedReader(fr);
jsonFile = new File(JSON_FILE_PATH);
if (!jsonFile.exists()) {
jsonFile.createNewFile();
}
fileWriter = new FileWriter(jsonFile.getAbsoluteFile());
bw = new BufferedWriter(fileWriter);
String line = "";
//读取每一行的数据
int cnt=1;
while ( (line = br.readLine()) != null) {
JSONObject lineJson = JSONObject.parseObject(line);
String repo=lineJson.getString("repo");
String path=lineJson.getString("path");
String func_name=lineJson.getString("func_name");
String original_string=lineJson.getString("original_string");
String language=lineJson.getString("language");
String original_code=lineJson.getString("code");
JSONArray code_tokens=lineJson.getJSONArray("code_tokens");
String docstring=lineJson.getString("docstring");
JSONArray docstring_tokens=lineJson.getJSONArray("docstring_tokens");
JSONArray asts=lineJson.getJSONArray("asts");
List<String> ast_seqs = JSONObject.parseArray(asts.toJSONString(),String.class);
int sz=ast_seqs.size();
JSONArray new_asts=new JSONArray();
for(int i=0;i<sz;++i)
{
Tree ast=TreeTools.stringToTree(ast_seqs.get(i)); | package process;
public class SplitAST_for_csn {
private static String AST_FILE_PATH="D:\\ast_dataset\\csn\\split_ast\\train_ast.jsonl";
private static String JSON_FILE_PATH="D:\\ast_dataset\\csn\\split_ast\\train.jsonl";
// use Tree-sitter
public static void main(String[] args) throws IOException {
FileReader fr = null;
BufferedReader br = null;
File jsonFile = null;
FileWriter fileWriter = null;
BufferedWriter bw = null;
try {
fr = new FileReader(AST_FILE_PATH);
br = new BufferedReader(fr);
jsonFile = new File(JSON_FILE_PATH);
if (!jsonFile.exists()) {
jsonFile.createNewFile();
}
fileWriter = new FileWriter(jsonFile.getAbsoluteFile());
bw = new BufferedWriter(fileWriter);
String line = "";
//读取每一行的数据
int cnt=1;
while ( (line = br.readLine()) != null) {
JSONObject lineJson = JSONObject.parseObject(line);
String repo=lineJson.getString("repo");
String path=lineJson.getString("path");
String func_name=lineJson.getString("func_name");
String original_string=lineJson.getString("original_string");
String language=lineJson.getString("language");
String original_code=lineJson.getString("code");
JSONArray code_tokens=lineJson.getJSONArray("code_tokens");
String docstring=lineJson.getString("docstring");
JSONArray docstring_tokens=lineJson.getJSONArray("docstring_tokens");
JSONArray asts=lineJson.getJSONArray("asts");
List<String> ast_seqs = JSONObject.parseArray(asts.toJSONString(),String.class);
int sz=ast_seqs.size();
JSONArray new_asts=new JSONArray();
for(int i=0;i<sz;++i)
{
Tree ast=TreeTools.stringToTree(ast_seqs.get(i)); | TreeToJSON.toJSON(ast,0); | 2 | 2023-11-23 06:08:43+00:00 | 8k |
CaoBaoQi/homework-android | work-course-table-v2/src/main/java/jz/cbq/work_course_table_v2/ui/slideshow/SlideshowFragment.java | [
{
"identifier": "MainActivity",
"path": "work-course-table-v2/src/main/java/jz/cbq/work_course_table_v2/MainActivity.java",
"snippet": "public class MainActivity extends AppCompatActivity {\n\n private AppBarConfiguration mAppBarConfiguration;\n public static int courseflag = 0;\n public static int examflag = 0;\n private static final int noticecourseid = 22;\n private static final int noticeexamid = 26;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n Toolbar toolbar = findViewById(R.id.toolbar);\n setSupportActionBar(toolbar);//菜单栏\n FloatingActionButton fab = findViewById(R.id.fab);//进入添加课程考试界面\n fab.setOnClickListener(new View.OnClickListener() {\n /**\n * 添加考试课程选择界面\n * @param view\n */\n @Override\n public void onClick(View view) {//选择考试or课程\n AlertDialog.Builder courseexamdialog = new AlertDialog.Builder(MainActivity.this).setTitle(\"请选择需要添加的对象\").setPositiveButton(\"课程\", new DialogInterface.OnClickListener() {\n @Override\n public void onClick(DialogInterface dialogInterface, int i) {//进入课程添加\n Intent addcourseintent = new Intent(MainActivity.this, addcourse.class);\n startActivity(addcourseintent);\n }\n }).setNegativeButton(\"考试\", new DialogInterface.OnClickListener() {\n @Override\n public void onClick(DialogInterface dialogInterface, int i) {//进入考试添加界面\n Intent addexamintent = new Intent(MainActivity.this,addexam.class);\n startActivity(addexamintent);\n }\n });\n courseexamdialog.create().show();\n }\n });\n DrawerLayout drawer = findViewById(R.id.drawer_layout);\n NavigationView navigationView = findViewById(R.id.nav_view);\n // Passing each menu ID as a set of Ids because each\n // menu should be considered as top level destinations.\n mAppBarConfiguration = new AppBarConfiguration.Builder(\n R.id.nav_home, R.id.nav_gallery, R.id.nav_slideshow)\n .setDrawerLayout(drawer)\n .build();\n NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);\n NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);\n NavigationUI.setupWithNavController(navigationView, navController);\n\n\n }\n\n @Override\n public boolean onCreateOptionsMenu(Menu menu) {\n // Inflate the menu; this adds items to the action bar if it is present.\n getMenuInflater().inflate(R.menu.main, menu);\n return true;\n }\n\n @Override\n public boolean onOptionsItemSelected(MenuItem item){\n if (item.getItemId() == R.id.action_settings){\n Intent settingsintent = new Intent(MainActivity.this,settings.class);//进入设置界面\n startActivity(settingsintent);\n }\n\n return super.onOptionsItemSelected(item);\n }\n\n @Override\n public boolean onSupportNavigateUp() {\n NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);\n return NavigationUI.navigateUp(navController, mAppBarConfiguration)\n || super.onSupportNavigateUp();\n }\n\n /**\n *结束前发出提醒\n */\n @RequiresApi(api = Build.VERSION_CODES.O)\n @Override\n public void onDestroy() {\n super.onDestroy();\n if (courseflag == 1) {\n Intent noticeintent = new Intent(this, noticeactivity.class);\n PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, noticeintent, PendingIntent.FLAG_IMMUTABLE);\n NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {\n NotificationChannel notificationChannel = new NotificationChannel(getString(R.string.app_name), getString(R.string.app_name), NotificationManager.IMPORTANCE_DEFAULT);\n manager.createNotificationChannel(notificationChannel);\n Notification notification = new Notification.Builder(this, getString(R.string.app_name))\n .setContentTitle(\"课程提醒\").setContentText(\"今天有课,记住时间地点了吗?\").setWhen(System.currentTimeMillis())\n .setSmallIcon(R.drawable.logo).setContentIntent(pendingIntent).setAutoCancel(true).build();\n manager.notify(noticecourseid, notification);\n } else {\n Notification notification = new Notification.Builder(this, getString(R.string.app_name))\n .setContentTitle(\"课程提醒\").setContentText(\"今天有课,记住时间地点了吗?\").setWhen(System.currentTimeMillis())\n .setSmallIcon(R.drawable.logo).setContentIntent(pendingIntent).setAutoCancel(true).build();\n manager.notify(noticecourseid, notification);\n }\n }\n if (examflag == 1) {\n Intent noticeintent = new Intent(this, noticeactivity.class);\n PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, noticeintent, PendingIntent.FLAG_IMMUTABLE);\n NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {\n NotificationChannel notificationChannel = new NotificationChannel(getString(R.string.app_name), getString(R.string.app_name), NotificationManager.IMPORTANCE_DEFAULT);\n manager.createNotificationChannel(notificationChannel);\n Notification notification = new Notification.Builder(this, getString(R.string.app_name))\n .setContentTitle(\"考试提醒\").setContentText(\"今天有考试,记住地点了吗?\").setWhen(System.currentTimeMillis())\n .setSmallIcon(R.drawable.logo).setContentIntent(pendingIntent).setAutoCancel(true).build();\n manager.notify(noticecourseid, notification);\n } else {\n Notification notification = new Notification.Builder(this, getString(R.string.app_name))\n .setContentTitle(\"考试提醒\").setContentText(\"今天有考试,记住地点了吗?\").setWhen(System.currentTimeMillis())\n .setSmallIcon(R.drawable.logo).setContentIntent(pendingIntent).setAutoCancel(true).build();\n manager.notify(noticecourseid, notification);\n }\n }\n }\n\n}"
},
{
"identifier": "addexam",
"path": "work-course-table-v2/src/main/java/jz/cbq/work_course_table_v2/addexam.java",
"snippet": "public class addexam extends MainActivity{\n\n private List<String> monthlist = new ArrayList<String>();\n private ArrayAdapter<String> exammonthspinneradapter;\n private List<String> daylist = new ArrayList<String>();\n private ArrayAdapter<String> examdayspinneradapter;\n private databasehelper examtimedbhelper;\n int month =0, day = 0;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.addexam);\n examtimedbhelper = new databasehelper(addexam.this,\"database.db\",null,1);\n final SQLiteDatabase examdatabase = examtimedbhelper.getWritableDatabase();\n monthlist.add(\" 1 \");\n monthlist.add(\" 2 \");\n monthlist.add(\" 3 \");\n monthlist.add(\" 4 \");\n monthlist.add(\" 5 \");\n monthlist.add(\" 6 \");\n monthlist.add(\" 7 \");\n monthlist.add(\" 8 \");\n monthlist.add(\" 9 \");\n monthlist.add(\" 10 \");\n monthlist.add(\" 11 \");\n monthlist.add(\" 12 \");\n Spinner exammonthspinner = findViewById(R.id.examtimemonth_spinner);//以下为选择考试月份\n exammonthspinneradapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,monthlist);\n exammonthspinneradapter.setDropDownViewResource(android.R.layout.select_dialog_singlechoice);\n exammonthspinner.setAdapter(exammonthspinneradapter);\n exammonthspinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener(){\n\n @Override\n public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {\n month = position + 1;\n }\n\n @Override\n public void onNothingSelected(AdapterView<?> adapterView) {\n Toast.makeText(addexam.this,\"你没选中任何选项\",Toast.LENGTH_SHORT).show();\n }\n });\n\n daylist.add(\" 1 \");\n daylist.add(\" 2 \");\n daylist.add(\" 3 \");\n daylist.add(\" 4 \");\n daylist.add(\" 5 \");\n daylist.add(\" 6 \");\n daylist.add(\" 7 \");\n daylist.add(\" 8 \");\n daylist.add(\" 9 \");\n daylist.add(\" 10 \");\n daylist.add(\" 11 \");\n daylist.add(\" 12 \");\n daylist.add(\" 13 \");\n daylist.add(\" 14 \");\n daylist.add(\" 15 \");\n daylist.add(\" 16 \");\n daylist.add(\" 17 \");\n daylist.add(\" 18 \");\n daylist.add(\" 19 \");\n daylist.add(\" 20 \");\n daylist.add(\" 21 \");\n daylist.add(\" 22 \");\n daylist.add(\" 23 \");\n daylist.add(\" 24 \");\n daylist.add(\" 25 \");\n daylist.add(\" 26 \");\n daylist.add(\" 27 \");\n daylist.add(\" 28 \");\n daylist.add(\" 29 \");\n daylist.add(\" 30 \");\n daylist.add(\" 31 \");\n Spinner examdayspinner = findViewById(R.id.examtimeday_spinner);//以下为选择考试日期\n examdayspinneradapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,daylist);\n examdayspinneradapter.setDropDownViewResource(android.R.layout.select_dialog_singlechoice);\n examdayspinner.setAdapter(examdayspinneradapter);\n examdayspinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener(){\n\n @Override\n public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {\n day = position + 1;\n }\n\n @Override\n public void onNothingSelected(AdapterView<?> adapterView) {\n Toast.makeText(addexam.this,\"你没选中任何选项\",Toast.LENGTH_SHORT).show();\n }\n });\n final EditText examnameedittext = findViewById(R.id.examname_edittext);//读取考试名称\n final EditText examroomedittext = findViewById(R.id.examroom_edittext);//读取考试地点\n Button add = findViewById(R.id.examadd_button);//点击提交\n add.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View view) {\n String examname = examnameedittext.getText().toString();//只能写在里面才能赋值,不懂为啥\n String examroom = examroomedittext.getText().toString();\n ContentValues examvalues = new ContentValues();//添加考试到数据库\n examvalues.put(\"examname\",examname);\n examvalues.put(\"month\",month);\n examvalues.put(\"day\",day);\n examvalues.put(\"examroom\",examroom);\n examdatabase.insert(\"Exam\",null,examvalues);\n Toast.makeText(addexam.this,\"添加成功\",Toast.LENGTH_SHORT).show();\n examvalues.clear();\n finish();\n }\n });\n Button back = findViewById(R.id.examfinish_button);\n back.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View view) {\n finish();\n }\n });\n }\n}"
},
{
"identifier": "databasehelper",
"path": "work-course-table-v2/src/main/java/jz/cbq/work_course_table_v2/databasehelper.java",
"snippet": "public class databasehelper extends SQLiteOpenHelper {\n public static final String createexamdb = \"create table Exam(\" + \"examname varchar,\"+\"month integer,\"+\"day integer,\"+\"examroom varchar)\";\n public static final String createcoursedb = \"create table Course(\" + \"coursename varchar,\"+\"weekstart integer,\"+\"weekend integer,\"+\"ofweek integer,\"+\"timestart integer,\"+\"timeend integer,\"+\"courseteacher varchar,\"+\"courseroom varchar)\";\n private Context mContext;\n\n public databasehelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {\n super(context, name, factory, version);\n mContext = context;\n }\n\n @Override\n public void onCreate(SQLiteDatabase sqLiteDatabase) {\n sqLiteDatabase.execSQL(createexamdb);\n sqLiteDatabase.execSQL(createcoursedb);\n }\n\n @Override\n public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {\n\n }\n}"
},
{
"identifier": "examcardadapter",
"path": "work-course-table-v2/src/main/java/jz/cbq/work_course_table_v2/examcardadapter.java",
"snippet": "public class examcardadapter extends ArrayAdapter<examcarditem> {\n\n private int resourceId;\n\n public examcardadapter(Context context, int textViewResourceId, List<examcarditem> objects){\n super(context, textViewResourceId, objects);\n resourceId = textViewResourceId;\n }\n\n @Override\n public View getView(int position, View convertView, ViewGroup parent){\n examcarditem examcarditem = getItem(position);\n View view;\n view = LayoutInflater.from(getContext()).inflate(resourceId, parent, false);\n TextView examcardname = view.findViewById(R.id.examcardname_textview);\n TextView examcardcontent = view.findViewById(R.id.examcardcontent_textview);//包括考试时间加地点\n examcardname.setText(examcarditem.getExamname());\n int month = examcarditem.getMonth();\n String months = \"\" + month;\n int day = examcarditem.getDay();\n String days = \"\" + day;\n String room = examcarditem.getExamroom();\n examcardcontent.setText(\"时间:\"+months+\"月\"+days+\"日\\n地点:\"+room);\n return view;\n }\n}"
},
{
"identifier": "examcarditem",
"path": "work-course-table-v2/src/main/java/jz/cbq/work_course_table_v2/examcarditem.java",
"snippet": "public class examcarditem {\n private String examname , examroom;\n private int month , day;\n public examcarditem(String examname, int month, int day, String examroom){//考试界面listitem\n this.examname = examname;\n this.month = month;\n this.day = day;\n this.examroom = examroom;\n }\n\n public String getExamname(){\n return examname;\n }\n\n public int getMonth(){\n return month;\n }\n\n public int getDay(){\n return day;\n }\n\n public String getExamroom(){\n return examroom;\n }\n}"
},
{
"identifier": "examcalendarremind",
"path": "work-course-table-v2/src/main/java/jz/cbq/work_course_table_v2/examcalendarremind.java",
"snippet": "public class examcalendarremind {\n private static String calenderurl = \"content://com.android.calendar/calendars\";\n private static String calendereventurl = \"content://com.android.calendar/events\";\n private static String calenderreminderurl = \"content://com.android.calendar/reminders\";\n private static String calendarsname = \"crisgy\";\n private static String calendarsaccountname = \"[email protected]\";\n private static String calendarsaccounttype = \"com.android.boohee\";\n private static String calendarsdispalyname = \"crisgy考试提醒\";\n\n private static int checkAndAddCalendarAccount(Context context) {//添加日历账户\n int oldId = checkCalendarAccount(context);\n if( oldId >= 0 ){\n return oldId;\n }else{\n long addId = addCalendarAccount(context);\n if (addId >= 0) {\n return checkCalendarAccount(context);\n } else {\n return -1;\n }\n }\n }\n\n private static int checkCalendarAccount(Context context) {//查询存在账户\n Cursor userCursor = context.getContentResolver().query(Uri.parse(calenderurl), null, null, null, null);\n try {\n if (userCursor == null) { //查询返回空值\n return -1;\n }\n int count = userCursor.getCount();\n if (count > 0) { //存在现有账户,取第一个账户的id返回\n userCursor.moveToFirst();\n return userCursor.getInt(userCursor.getColumnIndex(CalendarContract.Calendars._ID));\n } else {\n return -1;\n }\n } finally {\n if (userCursor != null) {\n userCursor.close();\n }\n }\n }\n\n private static long addCalendarAccount(Context context) {//添加日历账户\n TimeZone timeZone = TimeZone.getDefault();\n ContentValues value = new ContentValues();\n value.put(CalendarContract.Calendars.NAME, calendarsname);\n value.put(CalendarContract.Calendars.ACCOUNT_NAME, calendarsaccountname);\n value.put(CalendarContract.Calendars.ACCOUNT_TYPE, calendarsaccounttype);\n value.put(CalendarContract.Calendars.CALENDAR_DISPLAY_NAME, calendarsdispalyname);\n value.put(CalendarContract.Calendars.VISIBLE, 1);\n value.put(CalendarContract.Calendars.CALENDAR_COLOR, Color.BLUE);\n value.put(CalendarContract.Calendars.CALENDAR_ACCESS_LEVEL, CalendarContract.Calendars.CAL_ACCESS_OWNER);\n value.put(CalendarContract.Calendars.SYNC_EVENTS, 1);\n value.put(CalendarContract.Calendars.CALENDAR_TIME_ZONE, timeZone.getID());\n value.put(CalendarContract.Calendars.OWNER_ACCOUNT, calendarsaccountname);\n value.put(CalendarContract.Calendars.CAN_ORGANIZER_RESPOND, 0);\n\n Uri calendarUri = Uri.parse(calenderurl);\n calendarUri = calendarUri.buildUpon()\n .appendQueryParameter(CalendarContract.CALLER_IS_SYNCADAPTER, \"true\")\n .appendQueryParameter(CalendarContract.Calendars.ACCOUNT_NAME, calendarsaccountname)\n .appendQueryParameter(CalendarContract.Calendars.ACCOUNT_TYPE, calendarsaccounttype)\n .build();\n\n Uri result = context.getContentResolver().insert(calendarUri, value);\n long id = result == null ? -1 : ContentUris.parseId(result);\n return id;\n }\n\n public static boolean addCalendarEvent(Context context, String title, String description, int month, int day) {\n if (context == null) {\n return false;\n }\n int calId = checkAndAddCalendarAccount(context); //获取日历账户的id\n if (calId < 0) { //获取账户id失败直接返回,添加日历事件失败\n return false;\n }\n\n //添加日历事件\n Calendar mCalendar = Calendar.getInstance();\n int year = mCalendar.get(Calendar.YEAR);\n mCalendar.set(year, month - 1 , day);\n long start = mCalendar.getTime().getTime();\n mCalendar.set(year, month - 1, day + 1);//LOG发现start与end相同,实际使用时end提前一天,可能是华为的bug,应该不影响使用\n long end = mCalendar.getTime().getTime();\n ContentValues event = new ContentValues();\n event.put(\"title\", title);\n event.put(\"description\", description);\n event.put(\"calendar_id\", calId); //插入账户的id\n event.put(\"allDay\", true);\n event.put(CalendarContract.Events.DTSTART, start);\n event.put(CalendarContract.Events.DTEND, end);\n event.put(CalendarContract.Events.HAS_ALARM, 1);//设置有闹钟提醒\n event.put(CalendarContract.Events.EVENT_TIMEZONE, \"Asia/Shanghai\");//时区\n Uri newEvent = context.getContentResolver().insert(Uri.parse(calendereventurl), event); //添加事件\n if (newEvent == null) { //添加日历事件失败直接返回\n return false;\n }\n ContentValues values = new ContentValues();//设定事件提醒\n values.put(CalendarContract.Reminders.EVENT_ID, ContentUris.parseId(newEvent));\n values.put(CalendarContract.Reminders.MINUTES, 1 * 24 * 60);// 提前1天提醒\n values.put(CalendarContract.Reminders.METHOD, CalendarContract.Reminders.METHOD_ALERT);\n Uri uri = context.getContentResolver().insert(Uri.parse(calenderreminderurl), values);\n if(uri == null) { //添加事件提醒失败直接返回\n return false;\n }\n return true;\n }\n}"
}
] | import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import java.util.ArrayList;
import java.util.Calendar;
import jz.cbq.work_course_table_v2.MainActivity;
import jz.cbq.work_course_table_v2.R;
import jz.cbq.work_course_table_v2.addexam;
import jz.cbq.work_course_table_v2.databasehelper;
import jz.cbq.work_course_table_v2.examcardadapter;
import jz.cbq.work_course_table_v2.examcarditem;
import jz.cbq.work_course_table_v2.examcalendarremind; | 5,149 | package jz.cbq.work_course_table_v2.ui.slideshow;
@SuppressLint("Range")
public class SlideshowFragment extends Fragment {
private SlideshowViewModel slideshowViewModel;
private databasehelper examtimedbhelper;
ArrayList<examcarditem> examlist = new ArrayList<>();
public View onCreateView(@NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
slideshowViewModel =
ViewModelProviders.of(this).get(SlideshowViewModel.class);
View root = inflater.inflate(R.layout.fragment_slideshow, container, false);
examtimedbhelper = new databasehelper(getActivity(),"database.db",null,1);
final SQLiteDatabase examdatabase = examtimedbhelper.getWritableDatabase();
initexamitemcard();//初始化考试LISTVIEW | package jz.cbq.work_course_table_v2.ui.slideshow;
@SuppressLint("Range")
public class SlideshowFragment extends Fragment {
private SlideshowViewModel slideshowViewModel;
private databasehelper examtimedbhelper;
ArrayList<examcarditem> examlist = new ArrayList<>();
public View onCreateView(@NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
slideshowViewModel =
ViewModelProviders.of(this).get(SlideshowViewModel.class);
View root = inflater.inflate(R.layout.fragment_slideshow, container, false);
examtimedbhelper = new databasehelper(getActivity(),"database.db",null,1);
final SQLiteDatabase examdatabase = examtimedbhelper.getWritableDatabase();
initexamitemcard();//初始化考试LISTVIEW | examcardadapter examcardadapter = new examcardadapter(getActivity(), R.layout.examitem, examlist); | 3 | 2023-11-20 17:30:01+00:00 | 8k |
tommyskeff/futur4j | futur-api/src/main/java/dev/tommyjs/futur/impl/SimplePromiseFactory.java | [
{
"identifier": "AbstractPromise",
"path": "futur-api/src/main/java/dev/tommyjs/futur/promise/AbstractPromise.java",
"snippet": "public abstract class AbstractPromise<T> implements Promise<T> {\n\n private final Collection<PromiseListener<T>> listeners;\n\n private @Nullable PromiseCompletion<T> completion;\n\n public AbstractPromise() {\n this.listeners = new ConcurrentLinkedQueue<>();\n this.completion = null;\n }\n \n protected abstract ScheduledExecutorService getExecutor();\n\n protected abstract Logger getLogger();\n\n @Override\n public T join(long interval, long timeout) throws TimeoutException {\n long start = System.currentTimeMillis();\n while (!isCompleted()) {\n if (System.currentTimeMillis() > start + timeout)\n throw new TimeoutException(\"Promise timed out after \" + timeout + \"ms\");\n\n try {\n Thread.sleep(interval);\n } catch (InterruptedException e) {\n throw new RuntimeException(e);\n }\n }\n\n PromiseCompletion<T> completion = getCompletion();\n if (completion == null) {\n throw new IllegalStateException();\n }\n\n if (completion.isError()) {\n throw new RuntimeException(completion.getException());\n }\n\n return completion.getResult();\n }\n\n @Override\n public @NotNull Promise<Void> thenRunSync(@NotNull ExceptionalRunnable task) {\n return thenApplySync(result -> {\n task.run();\n return null;\n });\n }\n\n @Override\n public @NotNull Promise<Void> thenRunDelayedSync(@NotNull ExceptionalRunnable task, long delay, @NotNull TimeUnit unit) {\n return thenApplyDelayedSync(result -> {\n task.run();\n return null;\n }, delay, unit);\n }\n\n @Override\n public @NotNull Promise<Void> thenConsumeSync(@NotNull ExceptionalConsumer<T> task) {\n return thenApplySync(result -> {\n task.accept(result);\n return null;\n });\n }\n\n @Override\n public @NotNull Promise<Void> thenConsumeDelayedSync(@NotNull ExceptionalConsumer<T> task, long delay, @NotNull TimeUnit unit) {\n return thenApplyDelayedSync(result -> {\n task.accept(result);\n return null;\n }, delay, unit);\n }\n\n @Override\n public <V> @NotNull Promise<V> thenSupplySync(@NotNull ExceptionalSupplier<V> task) {\n return thenApplySync(result -> task.get());\n }\n\n @Override\n public <V> @NotNull Promise<V> thenSupplyDelayedSync(@NotNull ExceptionalSupplier<V> task, long delay, @NotNull TimeUnit unit) {\n return thenApplyDelayedSync(result -> task.get(), delay, unit);\n }\n \n @Override\n public <V> @NotNull Promise<V> thenApplySync(@NotNull ExceptionalFunction<T, V> task) {\n Promise<V> promise = getFactory().unresolved();\n addListener(ctx -> {\n if (ctx.isError()) {\n //noinspection ConstantConditions\n promise.completeExceptionally(ctx.getException());\n return;\n }\n\n Runnable runnable = createRunnable(ctx, promise, task);\n getExecutor().submit(runnable);\n });\n\n return promise;\n }\n\n @Override\n public <V> @NotNull Promise<V> thenApplyDelayedSync(@NotNull ExceptionalFunction<T, V> task, long delay, @NotNull TimeUnit unit) {\n Promise<V> promise = getFactory().unresolved();\n addListener(ctx -> {\n if (ctx.isError()) {\n //noinspection ConstantConditions\n promise.completeExceptionally(ctx.getException());\n return;\n }\n\n Runnable runnable = createRunnable(ctx, promise, task);\n getExecutor().schedule(runnable, delay, unit);\n });\n\n return promise;\n }\n\n @Override\n public <V> @NotNull Promise<V> thenComposeSync(@NotNull ExceptionalFunction<T, @NotNull Promise<V>> task) {\n Promise<V> promise = getFactory().unresolved();\n thenApplySync(task).thenConsumeAsync(nestedPromise -> {\n nestedPromise.addListener(ctx1 -> {\n if (ctx1.isError()) {\n //noinspection ConstantConditions\n promise.completeExceptionally(ctx1.getException());\n return;\n }\n\n promise.complete(ctx1.getResult());\n });\n }).addListener(ctx2 -> {\n if (ctx2.isError()) {\n //noinspection ConstantConditions\n promise.completeExceptionally(ctx2.getException());\n }\n });\n\n return promise;\n }\n\n @Override\n public @NotNull Promise<Void> thenRunAsync(@NotNull ExceptionalRunnable task) {\n return thenApplyAsync(result -> {\n task.run();\n return null;\n });\n }\n\n @Override\n public @NotNull Promise<Void> thenRunDelayedAsync(@NotNull ExceptionalRunnable task, long delay, @NotNull TimeUnit unit) {\n return thenApplyDelayedAsync(result -> {\n task.run();\n return null;\n }, delay, unit);\n }\n\n @Override\n public @NotNull Promise<Void> thenConsumeAsync(@NotNull ExceptionalConsumer<T> task) {\n return thenApplyAsync(result -> {\n task.accept(result);\n return null;\n });\n }\n\n @Override\n public @NotNull Promise<Void> thenConsumeDelayedAsync(@NotNull ExceptionalConsumer<T> task, long delay, @NotNull TimeUnit unit) {\n return thenApplyDelayedAsync(result -> {\n task.accept(result);\n return null;\n }, delay, unit);\n }\n\n @Override\n public <V> @NotNull Promise<V> thenSupplyAsync(@NotNull ExceptionalSupplier<V> task) {\n return thenApplyAsync(result -> task.get());\n }\n\n @Override\n public <V> @NotNull Promise<V> thenSupplyDelayedAsync(@NotNull ExceptionalSupplier<V> task, long delay, @NotNull TimeUnit unit) {\n return thenApplyDelayedAsync(result -> task.get(), delay, unit);\n }\n\n @Override\n public @NotNull Promise<T> thenPopulateReference(@NotNull AtomicReference<T> reference) {\n return thenApplyAsync((result) -> {\n reference.set(result);\n return result;\n });\n }\n\n @Override\n public <V> @NotNull Promise<V> thenApplyAsync(@NotNull ExceptionalFunction<T, V> task) {\n Promise<V> promise = getFactory().unresolved();\n addListener(ctx -> {\n if (ctx.isError()) {\n //noinspection ConstantConditions\n promise.completeExceptionally(ctx.getException());\n return;\n }\n\n Runnable runnable = createRunnable(ctx, promise, task);\n getExecutor().submit(runnable);\n });\n\n return promise;\n }\n\n @Override\n public <V> @NotNull Promise<V> thenApplyDelayedAsync(@NotNull ExceptionalFunction<T, V> task, long delay, @NotNull TimeUnit unit) {\n Promise<V> promise = getFactory().unresolved();\n addListener(ctx -> {\n Runnable runnable = createRunnable(ctx, promise, task);\n getExecutor().schedule(runnable, delay, unit);\n });\n\n return promise;\n }\n\n @Override\n public <V> @NotNull Promise<V> thenComposeAsync(@NotNull ExceptionalFunction<T, Promise<V>> task) {\n Promise<V> promise = getFactory().unresolved();\n thenApplyAsync(task).thenConsumeAsync(nestedPromise -> {\n nestedPromise.addListener(ctx1 -> {\n if (ctx1.isError()) {\n //noinspection ConstantConditions\n promise.completeExceptionally(ctx1.getException());\n return;\n }\n\n promise.complete(ctx1.getResult());\n });\n }).addListener(ctx2 -> {\n if (ctx2.isError()) {\n //noinspection ConstantConditions\n promise.completeExceptionally(ctx2.getException());\n }\n });\n\n return promise;\n }\n\n private <V> @NotNull Runnable createRunnable(@NotNull PromiseCompletion<T> ctx, @NotNull Promise<V> promise, @NotNull ExceptionalFunction<T, V> task) {\n return () -> {\n if (ctx.isError()) {\n //noinspection ConstantConditions\n promise.completeExceptionally(ctx.getException());\n return;\n }\n\n try {\n V result = task.apply(ctx.getResult());\n promise.complete(result);\n } catch (Throwable e) {\n promise.completeExceptionally(e);\n }\n };\n }\n\n @Override\n public @NotNull Promise<T> logExceptions() {\n return addListener(ctx -> {\n if (ctx.isError()) {\n getLogger().error(\"Exception caught in promise chain\", ctx.getException());\n }\n });\n }\n\n @Override\n public @NotNull Promise<T> addListener(@NotNull PromiseListener<T> listener) {\n if (isCompleted()) {\n getExecutor().submit(() -> {\n try {\n //noinspection ConstantConditions\n listener.handle(getCompletion());\n } catch (Exception e) {\n getLogger().error(\"Exception caught in promise listener\", e);\n }\n });\n } else {\n getListeners().add(listener);\n }\n\n return this;\n }\n\n @Override\n public @NotNull Promise<T> timeout(long time, @NotNull TimeUnit unit) {\n getExecutor().schedule(() -> {\n if (!isCompleted()) {\n completeExceptionally(new TimeoutException(\"Promise timed out after \" + time + \" \" + unit));\n }\n }, time, unit);\n\n return this;\n }\n\n @Override\n public @NotNull Promise<T> timeout(long ms) {\n return timeout(ms, TimeUnit.MILLISECONDS);\n }\n\n protected void handleCompletion(@NotNull PromiseCompletion<T> ctx) {\n if (this.isCompleted()) return;\n setCompletion(ctx);\n\n getExecutor().submit(() -> {\n for (PromiseListener<T> listener : getListeners()) {\n if (!ctx.isActive()) return;\n\n try {\n listener.handle(ctx);\n } catch (Exception e) {\n e.printStackTrace();\n getLogger().error(\"Exception caught in promise listener\", e);\n }\n }\n });\n }\n\n @Override\n public void complete(@Nullable T result) {\n handleCompletion(new PromiseCompletion<>(result));\n }\n\n @Override\n public void completeExceptionally(@NotNull Throwable result) {\n handleCompletion(new PromiseCompletion<>(result));\n }\n\n @Override\n public boolean isCompleted() {\n return getCompletion() != null;\n }\n\n protected Collection<PromiseListener<T>> getListeners() {\n return listeners;\n }\n\n @Override\n public @Nullable PromiseCompletion<T> getCompletion() {\n return completion;\n }\n\n protected void setCompletion(@NotNull PromiseCompletion<T> completion) {\n this.completion = completion;\n }\n\n}"
},
{
"identifier": "Promise",
"path": "futur-api/src/main/java/dev/tommyjs/futur/promise/Promise.java",
"snippet": "public interface Promise<T> {\n\n static <T> @NotNull Promise<T> resolve(T value, PromiseFactory factory) {\n return factory.resolve(value);\n }\n\n static <T> @NotNull Promise<T> error(Throwable error, PromiseFactory factory) {\n return factory.error(error);\n }\n\n static <T> @NotNull Promise<T> unresolved(PromiseFactory factory) {\n return factory.unresolved();\n }\n\n static @NotNull Promise<Void> start(PromiseFactory factory) {\n return factory.resolve(null);\n }\n\n PromiseFactory getFactory();\n\n T join(long interval, long timeout) throws TimeoutException;\n\n @NotNull Promise<Void> thenRunSync(@NotNull ExceptionalRunnable task);\n\n @NotNull Promise<Void> thenRunDelayedSync(@NotNull ExceptionalRunnable task, long delay, @NotNull TimeUnit unit);\n\n @NotNull Promise<Void> thenConsumeSync(@NotNull ExceptionalConsumer<T> task);\n\n @NotNull Promise<Void> thenConsumeDelayedSync(@NotNull ExceptionalConsumer<T> task, long delay, @NotNull TimeUnit unit);\n\n <V> @NotNull Promise<V> thenSupplySync(@NotNull ExceptionalSupplier<V> task);\n\n <V> @NotNull Promise<V> thenSupplyDelayedSync(@NotNull ExceptionalSupplier<V> task, long delay, @NotNull TimeUnit unit);\n\n <V> @NotNull Promise<V> thenApplySync(@NotNull ExceptionalFunction<T, V> task);\n\n <V> @NotNull Promise<V> thenApplyDelayedSync(@NotNull ExceptionalFunction<T, V> task, long delay, @NotNull TimeUnit unit);\n\n <V> @NotNull Promise<V> thenComposeSync(@NotNull ExceptionalFunction<T, @NotNull Promise<V>> task);\n\n @NotNull Promise<Void> thenRunAsync(@NotNull ExceptionalRunnable task);\n\n @NotNull Promise<Void> thenRunDelayedAsync(@NotNull ExceptionalRunnable task, long delay, @NotNull TimeUnit unit);\n\n @NotNull Promise<Void> thenConsumeAsync(@NotNull ExceptionalConsumer<T> task);\n\n @NotNull Promise<Void> thenConsumeDelayedAsync(@NotNull ExceptionalConsumer<T> task, long delay, @NotNull TimeUnit unit);\n\n <V> @NotNull Promise<V> thenSupplyAsync(@NotNull ExceptionalSupplier<V> task);\n\n <V> @NotNull Promise<V> thenSupplyDelayedAsync(@NotNull ExceptionalSupplier<V> task, long delay, @NotNull TimeUnit unit);\n\n @NotNull Promise<T> thenPopulateReference(@NotNull AtomicReference<T> reference);\n\n <V> @NotNull Promise<V> thenApplyAsync(@NotNull ExceptionalFunction<T, V> task);\n\n <V> @NotNull Promise<V> thenApplyDelayedAsync(@NotNull ExceptionalFunction<T, V> task, long delay, @NotNull TimeUnit unit);\n\n <V> @NotNull Promise<V> thenComposeAsync(@NotNull ExceptionalFunction<T, Promise<V>> task);\n\n @NotNull Promise<T> logExceptions();\n\n @NotNull Promise<T> addListener(@NotNull PromiseListener<T> listener);\n\n @NotNull Promise<T> timeout(long time, @NotNull TimeUnit unit);\n\n @NotNull Promise<T> timeout(long ms);\n\n void complete(@Nullable T result);\n\n void completeExceptionally(@NotNull Throwable result);\n\n boolean isCompleted();\n\n @Nullable PromiseCompletion<T> getCompletion();\n\n}"
},
{
"identifier": "PromiseFactory",
"path": "futur-api/src/main/java/dev/tommyjs/futur/promise/PromiseFactory.java",
"snippet": "public interface PromiseFactory {\n\n <T> @NotNull Promise<T> resolve(T value);\n\n <T> @NotNull Promise<T> unresolved();\n\n <T> @NotNull Promise<T> error(Throwable error);\n\n static PromiseFactory create(ScheduledExecutorService executor, Logger logger) {\n return new SimplePromiseFactory(executor, logger);\n }\n\n static PromiseFactory create(ScheduledExecutorService executor) {\n return create(executor, LoggerFactory.getLogger(SimplePromiseFactory.class));\n }\n\n static PromiseFactory create(int threadPoolSize) {\n return create(Executors.newScheduledThreadPool(threadPoolSize));\n }\n\n static PromiseFactory create() {\n return create(Runtime.getRuntime().availableProcessors());\n }\n\n}"
}
] | import dev.tommyjs.futur.promise.AbstractPromise;
import dev.tommyjs.futur.promise.Promise;
import dev.tommyjs.futur.promise.PromiseFactory;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import java.util.concurrent.ScheduledExecutorService; | 3,732 | package dev.tommyjs.futur.impl;
public class SimplePromiseFactory implements PromiseFactory {
private final ScheduledExecutorService executor;
private final Logger logger;
public SimplePromiseFactory(ScheduledExecutorService executor, Logger logger) {
this.executor = executor;
this.logger = logger;
}
@Override
public @NotNull <T> Promise<T> resolve(T value) { | package dev.tommyjs.futur.impl;
public class SimplePromiseFactory implements PromiseFactory {
private final ScheduledExecutorService executor;
private final Logger logger;
public SimplePromiseFactory(ScheduledExecutorService executor, Logger logger) {
this.executor = executor;
this.logger = logger;
}
@Override
public @NotNull <T> Promise<T> resolve(T value) { | AbstractPromise<T> promise = new SimplePromise<>(executor, logger, this); | 0 | 2023-11-19 20:56:51+00:00 | 8k |
phamdung2209/FAP | src/main/java/com/persons/Administrator.java | [
{
"identifier": "Course",
"path": "src/main/java/com/course/Course.java",
"snippet": "public class Course {\n private String id;\n private String courseName;\n private String description;\n private long cost;\n private Student student;\n private Lecturer lecturer;\n private List<Schedule> schedules = new ArrayList<Schedule>();\n\n public Course() {\n }\n\n public Course(String id, String courseName, String description, long cost) {\n this.id = id;\n this.courseName = courseName;\n this.description = description;\n this.cost = cost;\n }\n \n public Course(String id, String courseName, String description, long cost, Student student, Lecturer lecturer) {\n this.id = id;\n this.courseName = courseName;\n this.description = description;\n this.cost = cost;\n this.student = student;\n this.lecturer = lecturer;\n }\n\n public String getId() {\n return id;\n }\n\n public void setId(String id) {\n this.id = id;\n }\n\n public String getCourseName() {\n return courseName;\n }\n\n public void setCourseName(String courseName) {\n this.courseName = courseName;\n }\n\n public String getDescription() {\n return description;\n }\n\n public void setDescription(String description) {\n this.description = description;\n }\n\n public long getCost() {\n return cost;\n }\n\n public void setCost(long cost) {\n this.cost = cost;\n }\n\n public Student getStudent() {\n return student;\n }\n\n public void setStudent(Student student) {\n this.student = student;\n }\n\n public Lecturer getLecturer() {\n return lecturer;\n }\n\n public void setLecturer(Lecturer lecturer) {\n this.lecturer = lecturer;\n }\n\n public void reg() {\n }\n\n public void cancelReg() {\n }\n\n @Override\n public String toString() {\n return \"Course [id=\" + id + \", courseName=\" + courseName + \", description=\" + description + \", cost=\" + cost\n + \", student=\" + student + \", lecturer=\" + lecturer + \"]\";\n }\n\n public void addSchedule(Schedule schedule) {\n this.schedules.add(schedule);\n }\n\n public void removeSchedule(Schedule schedule) {\n this.schedules.remove(schedule);\n }\n\n public Schedule getSchedule(int index) {\n return this.schedules.get(index);\n }\n\n public List<Schedule> getAllSchedules() {\n return this.schedules;\n }\n\n public List<Schedule> getSchedules() {\n return schedules;\n }\n\n public void setSchedules(List<Schedule> schedules) {\n this.schedules = schedules;\n }\n\n //getSchedule()\n public Schedule getSchedule() {\n Schedule sch = null;\n for (Schedule schedule : schedules) {\n sch = schedule;\n }\n return sch;\n }\n}"
},
{
"identifier": "DateOfBirth",
"path": "src/main/java/com/Date/DateOfBirth.java",
"snippet": "public class DateOfBirth {\n private int day;\n private int month;\n private int year;\n\n public DateOfBirth() {\n }\n\n public DateOfBirth(int day, int month, int year) {\n this.day = day;\n this.month = month;\n this.year = year;\n }\n\n public int getDay() {\n return day;\n }\n\n public void setDay(int day) {\n this.day = day;\n }\n\n public int getMonth() {\n return month;\n }\n\n public void setMonth(int month) {\n this.month = month;\n }\n\n public int getYear() {\n return year;\n }\n\n public void setYear(int year) {\n this.year = year;\n }\n\n}"
},
{
"identifier": "Grade",
"path": "src/main/java/com/func/Grade.java",
"snippet": "public class Grade extends Observable {\n\n // observer pattern\n private String currentGrade;\n\n public void updateGrade(String newGrade) {\n this.currentGrade = newGrade;\n setChanged();\n notifyObservers(newGrade);\n }\n\n public String getCurrentGrade() {\n return currentGrade;\n }\n\n // end observer pattern\n\n private int id = 100;\n private Student student;\n private Lecturer lecturer;\n private Course course;\n private int gradeAsm;\n\n public Grade() {\n }\n\n public Grade(Student student, Lecturer lecturer, Course course, int gradeAsm) {\n this.id += 1;\n this.student = student;\n this.lecturer = lecturer;\n this.gradeAsm = gradeAsm;\n this.course = course;\n course.getId();\n }\n\n public int getId() {\n return id;\n }\n\n public void setId(int id) {\n this.id = id;\n }\n\n public Student getStudent() {\n return student;\n }\n\n public void setStudent(Student student) {\n this.student = student;\n }\n\n public Lecturer getLecturer() {\n return lecturer;\n }\n\n public void setLecturer(Lecturer lecturer) {\n this.lecturer = lecturer;\n }\n\n public int getGradeAsm() {\n return gradeAsm;\n }\n\n public void setGradeAsm(int gradeAsm) {\n this.gradeAsm = gradeAsm;\n }\n\n public Course getCourse() {\n return course;\n }\n\n public void setCourse(Course course) {\n this.course = course;\n }\n\n @Override\n public String toString() {\n return \"Grade [id=\" + id + \", student=\" + student + \", lecturer=\" + lecturer + \", course=\" + course\n + \", gradeAsm=\" + gradeAsm + \"]\";\n }\n\n}"
},
{
"identifier": "Classroom",
"path": "src/main/java/com/func/ClassroomHandler/Classroom.java",
"snippet": "public class Classroom {\n private String id = \"D\";\n private String name;\n private String lecturerId;\n\n public Classroom() {\n }\n\n public Classroom(String id, String name, String lecturerId) {\n this.id += id;\n this.name = name;\n this.lecturerId = lecturerId;\n }\n\n public String getId() {\n return id;\n }\n\n public void setId(String id) {\n this.id = id;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getLecturerId() {\n return lecturerId;\n }\n\n public void setLecturerId(String lecturerId) {\n this.lecturerId = lecturerId;\n }\n}"
},
{
"identifier": "PersonType",
"path": "src/main/java/com/persons/personType/PersonType.java",
"snippet": "public enum PersonType {\n ADMINISTRATOR, STUDENT, LECTURER, STAFF, PARENT\n}"
}
] | import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import com.course.Course;
import com.date.DateOfBirth;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.func.Grade;
import com.func.ClassroomHandler.Classroom;
import com.persons.personType.PersonType; | 4,095 |
// Print the lecture data
System.out.format("%-10s %-25s %-25s %-10s\n",
"ID", "Course Name", "Description", "Cost"/*
* , "Student", "Lecturer", "Start Date", "End Date",
* "Status"
*/);
for (Map<String, String> course : courses) {
System.out.format("%-10s %-25s %-25s %-10s\n",
course.get("id"), course.get("name"), course.get("description"), course.get("cost")
/*
* ,course.getStudent().getFullName(), course.getLecturer().getFullName(),
* course.getStartDate().getDay() + "/" + course.getStartDate().getMonth() + "/"
* + course.getStartDate().getYear(),
* course.getEndDate().getDay() + "/" + course.getEndDate().getMonth() + "/"
* + course.getEndDate().getYear(),
* course.getStatus()
*/ + "\n");
}
} catch (IOException e) {
System.err.println("Error reading file: " + e.getMessage());
e.printStackTrace();
}
}
// update course
public boolean updateCourse(String id, Course... courses) {
try {
ObjectMapper objectMapper = new ObjectMapper();
File file = new File(filePath);
TypeReference<Map<String, Object>> typeRef = new TypeReference<Map<String, Object>>() {
};
Map<String, Object> data = objectMapper.readValue(file, typeRef);
List<Map<String, String>> courseList = (List<Map<String, String>>) data.get("courses");
for (Course course : courses) {
for (Map<String, String> courseMap : courseList) {
if (id.equals(courseMap.get("id"))) {
courseMap.put("name", course.getCourseName());
courseMap.put("description", course.getDescription());
courseMap.put("cost", Long.toString(course.getCost()));
break;
}
}
}
// Update the "courses" key in the data map
data.put("courses", courseList);
objectMapper.writeValue(file, data);
System.out.println("Course with ID " + id + " updated successfully.");
return true;
} catch (IOException e) {
System.err.println("Error reading/writing file: " + e.getMessage());
e.printStackTrace();
}
return false;
}
// delete course
public boolean deleteCourse(String id) {
try {
ObjectMapper objectMapper = new ObjectMapper();
File file = new File(filePath);
TypeReference<Map<String, Object>> typeRef = new TypeReference<Map<String, Object>>() {
};
Map<String, Object> data = objectMapper.readValue(file, typeRef);
List<Map<String, String>> courses = (List<Map<String, String>>) data.get("courses");
List<Map<String, String>> grades = (List<Map<String, String>>) data.get("grades");
grades.removeIf(grade -> id.equals(grade.get("courseId")));
courses.removeIf(course -> id.equals(course.get("id")));
data.put("grades", grades);
data.put("courses", courses);
objectMapper.writeValue(file, data);
return true;
} catch (IOException e) {
System.err.println("Error reading/writing file: " + e.getMessage());
e.printStackTrace();
}
return false;
}
// check course
public boolean checkCourse(String courseId) {
try {
ObjectMapper objectMapper = new ObjectMapper();
File file = new File(filePath);
TypeReference<Map<String, Object>> typeRef = new TypeReference<Map<String, Object>>() {
};
Map<String, Object> data = objectMapper.readValue(file, typeRef);
// Extract data from the "courses" key
List<Map<String, String>> courses = (List<Map<String, String>>) data.get("courses");
for (Map<String, String> course : courses) {
if (course.get("id").equals(courseId)) {
return true;
}
}
} catch (IOException e) {
System.err.println("Error reading file: " + e.getMessage());
e.printStackTrace();
}
return false;
}
// ==================== Grade ====================
// add grade | package com.persons;
// Component interface
interface getNotify {
void display();
}
class AdministratorGroup implements getNotify {
private List<getNotify> administrators = new ArrayList<>();
public AdministratorGroup() {
}
public void addAdministrator(getNotify administrator) {
administrators.add(administrator);
}
@Override
public void display() {
System.out.println("Administrator Group");
administrators.forEach(getNotify::display);
}
}
public class Administrator extends User implements getNotify {
// Composite pattern - Structural Pattern
@Override
public void display() {
System.out.println("Administrator" + getFullName() + "has been added");
}
public static final String filePath = "C:\\Users\\ACER\\Documents\\Course\\Advance Programming\\Assignment 2\\Project\\FAP\\src\\main\\java\\service\\data.json";
// ThreadSafe Singleton Pattern - Creational Pattern
private Administrator() {
}
private static Administrator admin;
public static synchronized Administrator getAdministrator() {
if (admin == null) {
admin = new Administrator();
}
return admin;
}
// iterator pattern - Behavioral Pattern
public void viewStudents(){
Student student1 = new Student("Dung Pham");
Student student2 = new Student("John Wick");
Student student3 = new Student("Tony Stark");
List<Student> students = new ArrayList<>();
students.add(student1);
students.add(student2);
students.add(student3);
Iterator student = students.iterator();
while(student.hasNext()){
Student std = (Student) student.next();
System.out.println(std.getFullName());
}
}
// person type
public PersonType getPersonType() {
return PersonType.ADMINISTRATOR;
}
// ==================== Student ====================
// save student to file json.data
public boolean addStudent(Student student) {
try {
// Read existing data from file
ObjectMapper objectMapper = new ObjectMapper();
File file = new File(filePath);
// Deserialize JSON file into a Map
TypeReference<HashMap<String, Object>> typeRef = new TypeReference<HashMap<String, Object>>() {
};
HashMap<String, Object> data = objectMapper.readValue(file, typeRef);
// Extract the "students" key and add a new student
List<Map<String, String>> students = (List<Map<String, String>>) data.get("students");
if (students == null) {
students = new ArrayList<>();
}
Map<String, String> newStudent = new HashMap<>();
newStudent.put("id", student.getId());
newStudent.put("name", student.getFullName());
newStudent.put("address", student.getAddress());
newStudent.put("gender", String.valueOf(student.getGender()));
newStudent.put("day", String.valueOf(student.getDateOfBirth().getDay()));
newStudent.put("month", String.valueOf(student.getDateOfBirth().getMonth()));
newStudent.put("year", String.valueOf(student.getDateOfBirth().getYear()));
newStudent.put("years", String.valueOf(student.getYear()));
newStudent.put("major", student.getMajor());
newStudent.put("phone", student.getPhoneNumber());
newStudent.put("email", student.getEmail());
students.add(newStudent);
data.put("students", students);
// Write the updated data back to the file
objectMapper.writeValue(file, data);
System.out.println("Student added successfully.");
return true;
} catch (IOException e) {
System.err.println("Error reading/writing to file: " + e.getMessage());
e.printStackTrace();
}
return false;
}
// view student
public void viewStudent() {
try {
// Read JSON file into a Map
ObjectMapper objectMapper = new ObjectMapper();
File file = new File(filePath);
// Deserialize JSON file into a Map
TypeReference<Map<String, Object>> typeRef = new TypeReference<Map<String, Object>>() {
};
Map<String, Object> data = objectMapper.readValue(file, typeRef);
// Extract data from the "students" key
List<Map<String, String>> students = (List<Map<String, String>>) data.get("students");
// Print the student data
System.out.format("%-10s %-15s %-15s %-10s %-10s %-15s %-20s %-15s %-5s\n",
"ID", "Name", "Date of birth", "Gender", "Address", "Phone number", "Email", "Major", "Year");
for (Map<String, String> student : students) {
System.out.format("%-10s %-15s %-15s %-10s %-10s %-15s %-20s %-15s %-5s\n",
student.get("id"), student.get("name"),
student.get("day") + "/" + student.get("month") + "/"
+ student.get("year"),
student.get("gender"), student.get("address"), student.get("phone"), student.get("email"),
student.get("major"), student.get("years") + "\n");
}
} catch (IOException e) {
System.err.println("Error reading file: " + e.getMessage());
e.printStackTrace();
}
}
// delete student
public boolean deleteStudent(String studentId) {
try {
ObjectMapper objectMapper = new ObjectMapper();
File file = new File(filePath);
TypeReference<Map<String, Object>> typeRef = new TypeReference<Map<String, Object>>() {
};
Map<String, Object> data = objectMapper.readValue(file, typeRef);
List<Map<String, String>> students = (List<Map<String, String>>) data.get("students");
//
List<Map<String, String>> grades = (List<Map<String, String>>) data.get("grades");
grades.removeIf(grade -> studentId.equals(grade.get("studentId")));
data.put("grades", grades);
List<Map<String, String>> classList = (List<Map<String, String>>) data.get("classList");
classList.removeIf(std -> studentId.equals(std.get("studentId")));
data.put("classList", classList);
//
students.removeIf(student -> studentId.equals(student.get("id")));
data.put("students", students);
objectMapper.writeValue(file, data);
return true;
} catch (IOException e) {
System.err.println("Error reading/writing file: " + e.getMessage());
e.printStackTrace();
}
return false;
}
public boolean checkStudent(String studentId) {
try {
ObjectMapper objectMapper = new ObjectMapper();
File file = new File(filePath);
TypeReference<Map<String, Object>> typeRef = new TypeReference<Map<String, Object>>() {
};
Map<String, Object> data = objectMapper.readValue(file, typeRef);
// Extract data from the "students" key
List<Map<String, String>> students = (List<Map<String, String>>) data.get("students");
for (Map<String, String> student : students) {
if (student.get("id").equals(studentId)) {
return true;
}
}
} catch (IOException e) {
System.err.println("Error reading file: " + e.getMessage());
e.printStackTrace();
}
return false;
}
// Update information of student by id and save to file json.data
public boolean updateStudent(String id, Student... students) {
try {
ObjectMapper objectMapper = new ObjectMapper();
File file = new File(filePath);
TypeReference<Map<String, Object>> typeRef = new TypeReference<Map<String, Object>>() {
};
Map<String, Object> data = objectMapper.readValue(file, typeRef);
List<Map<String, String>> studentList = (List<Map<String, String>>) data.get("students");
for (Student student : students) {
for (Map<String, String> studentMap : studentList) {
if (id.equals(studentMap.get("id"))) {
studentMap.put("name", student.getFullName());
studentMap.put("address", student.getAddress());
studentMap.put("gender", String.valueOf(student.getGender()));
studentMap.put("day", String.valueOf(student.getDateOfBirth().getDay()));
studentMap.put("month", String.valueOf(student.getDateOfBirth().getMonth()));
studentMap.put("year", String.valueOf(student.getDateOfBirth().getYear()));
studentMap.put("years", String.valueOf(student.getYear()));
studentMap.put("major", student.getMajor());
studentMap.put("phone", student.getPhoneNumber());
studentMap.put("email", student.getEmail());
break;
}
}
}
// Update the "students" key in the data map
data.put("students", studentList);
objectMapper.writeValue(file, data);
System.out.println("Student with ID " + id + " updated successfully.");
return true;
} catch (IOException e) {
System.err.println("Error reading/writing file: " + e.getMessage());
e.printStackTrace();
}
return false;
}
// ==================== Lecturer ====================
public boolean addLecturer(Lecturer lecturer) {
try {
ObjectMapper objectMapper = new ObjectMapper();
File file = new File(filePath);
TypeReference<HashMap<String, Object>> typeRef = new TypeReference<HashMap<String, Object>>() {
};
HashMap<String, Object> data = objectMapper.readValue(file, typeRef);
List<Map<String, String>> lectures = (List<Map<String, String>>) data.get("lectures");
if (lectures == null) {
lectures = new ArrayList<>();
}
Map<String, String> newLecture = new HashMap<>();
newLecture.put("id", lecturer.getId());
newLecture.put("name", lecturer.getFullName());
newLecture.put("address", lecturer.getAddress());
newLecture.put("gender", String.valueOf(lecturer.getGender()));
newLecture.put("day", String.valueOf(lecturer.getDateOfBirth().getDay()));
newLecture.put("month", String.valueOf(lecturer.getDateOfBirth().getMonth()));
newLecture.put("year", String.valueOf(lecturer.getDateOfBirth().getYear()));
newLecture.put("phone", lecturer.getPhoneNumber());
newLecture.put("email", lecturer.getEmail());
newLecture.put("department", lecturer.getDepartment());
lectures.add(newLecture);
data.put("lectures", lectures);
objectMapper.writeValue(file, data);
System.out.println("Lecture added successfully.");
return true;
} catch (IOException e) {
System.err.println("Error reading/writing to file: " + e.getMessage());
e.printStackTrace();
}
return false;
}
// view lecturer
public void viewLecture() {
try {
ObjectMapper objectMapper = new ObjectMapper();
File file = new File(filePath);
TypeReference<Map<String, Object>> typeRef = new TypeReference<Map<String, Object>>() {
};
Map<String, Object> data = objectMapper.readValue(file, typeRef);
List<Map<String, String>> lectures = (List<Map<String, String>>) data.get("lectures");
// Print the lecture data
System.out.format("%-10s %-15s %-15s %-10s %-10s %-15s %-20s %-15s\n",
"ID", "Full Name", "Date Of Birth", "Gender", "Address", "Phone Number", "Email", "Department");
for (Map<String, String> lecture : lectures) {
System.out.format("%-10s %-15s %-15s %-10s %-10s %-15s %-20s %-15s\n",
lecture.get("id"), lecture.get("name"),
lecture.get("day") + "/" + lecture.get("month") + "/" + lecture.get("year"),
lecture.get("gender"), lecture.get("address"), lecture.get("phone"), lecture.get("email"),
lecture.get("department") + "\n");
}
} catch (IOException e) {
System.err.println("Error reading file: " + e.getMessage());
e.printStackTrace();
}
}
public boolean updateLecturer(String id, Lecturer... lectures) {
try {
ObjectMapper objectMapper = new ObjectMapper();
File file = new File(filePath);
TypeReference<Map<String, Object>> typeRef = new TypeReference<Map<String, Object>>() {
};
Map<String, Object> data = objectMapper.readValue(file, typeRef);
List<Map<String, String>> lectureList = (List<Map<String, String>>) data.get("lectures");
for (Lecturer lecture : lectures) {
for (Map<String, String> lectureMap : lectureList) {
if (id.equals(lectureMap.get("id"))) {
lectureMap.put("name", lecture.getFullName());
lectureMap.put("address", lecture.getAddress());
lectureMap.put("gender", String.valueOf(lecture.getGender()));
lectureMap.put("day", String.valueOf(lecture.getDateOfBirth().getDay()));
lectureMap.put("month", String.valueOf(lecture.getDateOfBirth().getMonth()));
lectureMap.put("year", String.valueOf(lecture.getDateOfBirth().getYear()));
lectureMap.put("phone", lecture.getPhoneNumber());
lectureMap.put("email", lecture.getEmail());
lectureMap.put("department", lecture.getDepartment());
break;
}
}
}
// Update the "lectures" key in the data map
data.put("lectures", lectureList);
objectMapper.writeValue(file, data);
System.out.println("Lecture with ID " + id + " updated successfully.");
return true;
} catch (IOException e) {
System.err.println("Error reading/writing file: " + e.getMessage());
e.printStackTrace();
}
return false;
}
// delete Lecture
public boolean deleteLecture(String lectureId) {
try {
ObjectMapper objectMapper = new ObjectMapper();
File file = new File(filePath);
TypeReference<Map<String, Object>> typeRef = new TypeReference<Map<String, Object>>() {
};
Map<String, Object> data = objectMapper.readValue(file, typeRef);
List<Map<String, String>> lectures = (List<Map<String, String>>) data.get("lectures");
//
List<Map<String, String>> grades = (List<Map<String, String>>) data.get("grades");
grades.removeIf(grade -> lectureId.equals(grade.get("lecturerId")));
data.put("grades", grades);
//
lectures.removeIf(lecture -> lectureId.equals(lecture.get("id")));
data.put("lectures", lectures);
objectMapper.writeValue(file, data);
return true;
} catch (IOException e) {
System.err.println("Error reading/writing file: " + e.getMessage());
e.printStackTrace();
}
return false;
}
public boolean checkLecture(String lectureId) {
try {
ObjectMapper objectMapper = new ObjectMapper();
File file = new File(filePath);
TypeReference<Map<String, Object>> typeRef = new TypeReference<Map<String, Object>>() {
};
Map<String, Object> data = objectMapper.readValue(file, typeRef);
// Extract data from the "lectures" key
List<Map<String, String>> lectures = (List<Map<String, String>>) data.get("lectures");
for (Map<String, String> lecture : lectures) {
if (lecture.get("id").equals(lectureId)) {
return true;
}
}
} catch (IOException e) {
System.err.println("Error reading file: " + e.getMessage());
e.printStackTrace();
}
return false;
}
// ==================== Course ====================
// add course
public boolean addCourse(Course course) {
try {
ObjectMapper objectMapper = new ObjectMapper();
File file = new File(filePath);
TypeReference<HashMap<String, Object>> typeRef = new TypeReference<HashMap<String, Object>>() {
};
HashMap<String, Object> data = objectMapper.readValue(file, typeRef);
List<Map<String, String>> courses = (List<Map<String, String>>) data.get("courses");
if (courses == null) {
courses = new ArrayList<>();
}
Map<String, String> newCourse = new HashMap<>();
newCourse.put("id", course.getId());
newCourse.put("name", course.getCourseName());
newCourse.put("description", course.getDescription());
newCourse.put("cost", Long.toString(course.getCost()));
courses.add(newCourse);
data.put("courses", courses);
objectMapper.writeValue(file, data);
System.out.println("Course added successfully.");
return true;
} catch (IOException e) {
System.err.println("Error reading/writing to file: " + e.getMessage());
e.printStackTrace();
}
return false;
}
// view course
public void viewCourse() {
try {
ObjectMapper objectMapper = new ObjectMapper();
File file = new File(filePath);
TypeReference<Map<String, Object>> typeRef = new TypeReference<Map<String, Object>>() {
};
Map<String, Object> data = objectMapper.readValue(file, typeRef);
List<Map<String, String>> courses = (List<Map<String, String>>) data.get("courses");
// Print the lecture data
System.out.format("%-10s %-25s %-25s %-10s\n",
"ID", "Course Name", "Description", "Cost"/*
* , "Student", "Lecturer", "Start Date", "End Date",
* "Status"
*/);
for (Map<String, String> course : courses) {
System.out.format("%-10s %-25s %-25s %-10s\n",
course.get("id"), course.get("name"), course.get("description"), course.get("cost")
/*
* ,course.getStudent().getFullName(), course.getLecturer().getFullName(),
* course.getStartDate().getDay() + "/" + course.getStartDate().getMonth() + "/"
* + course.getStartDate().getYear(),
* course.getEndDate().getDay() + "/" + course.getEndDate().getMonth() + "/"
* + course.getEndDate().getYear(),
* course.getStatus()
*/ + "\n");
}
} catch (IOException e) {
System.err.println("Error reading file: " + e.getMessage());
e.printStackTrace();
}
}
// update course
public boolean updateCourse(String id, Course... courses) {
try {
ObjectMapper objectMapper = new ObjectMapper();
File file = new File(filePath);
TypeReference<Map<String, Object>> typeRef = new TypeReference<Map<String, Object>>() {
};
Map<String, Object> data = objectMapper.readValue(file, typeRef);
List<Map<String, String>> courseList = (List<Map<String, String>>) data.get("courses");
for (Course course : courses) {
for (Map<String, String> courseMap : courseList) {
if (id.equals(courseMap.get("id"))) {
courseMap.put("name", course.getCourseName());
courseMap.put("description", course.getDescription());
courseMap.put("cost", Long.toString(course.getCost()));
break;
}
}
}
// Update the "courses" key in the data map
data.put("courses", courseList);
objectMapper.writeValue(file, data);
System.out.println("Course with ID " + id + " updated successfully.");
return true;
} catch (IOException e) {
System.err.println("Error reading/writing file: " + e.getMessage());
e.printStackTrace();
}
return false;
}
// delete course
public boolean deleteCourse(String id) {
try {
ObjectMapper objectMapper = new ObjectMapper();
File file = new File(filePath);
TypeReference<Map<String, Object>> typeRef = new TypeReference<Map<String, Object>>() {
};
Map<String, Object> data = objectMapper.readValue(file, typeRef);
List<Map<String, String>> courses = (List<Map<String, String>>) data.get("courses");
List<Map<String, String>> grades = (List<Map<String, String>>) data.get("grades");
grades.removeIf(grade -> id.equals(grade.get("courseId")));
courses.removeIf(course -> id.equals(course.get("id")));
data.put("grades", grades);
data.put("courses", courses);
objectMapper.writeValue(file, data);
return true;
} catch (IOException e) {
System.err.println("Error reading/writing file: " + e.getMessage());
e.printStackTrace();
}
return false;
}
// check course
public boolean checkCourse(String courseId) {
try {
ObjectMapper objectMapper = new ObjectMapper();
File file = new File(filePath);
TypeReference<Map<String, Object>> typeRef = new TypeReference<Map<String, Object>>() {
};
Map<String, Object> data = objectMapper.readValue(file, typeRef);
// Extract data from the "courses" key
List<Map<String, String>> courses = (List<Map<String, String>>) data.get("courses");
for (Map<String, String> course : courses) {
if (course.get("id").equals(courseId)) {
return true;
}
}
} catch (IOException e) {
System.err.println("Error reading file: " + e.getMessage());
e.printStackTrace();
}
return false;
}
// ==================== Grade ====================
// add grade | public boolean addGrade(Student student, Lecturer lecturer, Course course, Grade grade) { | 2 | 2023-11-23 18:42:19+00:00 | 8k |
morihofi/acmeserver | src/main/java/de/morihofi/acmeserver/certificate/acme/api/Provisioner.java | [
{
"identifier": "Main",
"path": "src/main/java/de/morihofi/acmeserver/Main.java",
"snippet": "public class Main {\n\n /**\n * Logger\n */\n public static final Logger log = LogManager.getLogger(Main.class);\n\n /**\n * `serverdata` directory as an absolute path\n */\n public static final Path FILES_DIR = Paths.get(Objects.requireNonNull(AppDirectoryHelper.getAppDirectory())).resolve(\"serverdata\").toAbsolutePath();\n\n public static CryptoStoreManager cryptoStoreManager;\n\n //Build Metadata\n public static String buildMetadataVersion;\n public static String buildMetadataBuildTime;\n public static String buildMetadataGitCommit;\n\n public static Config appConfig;\n\n public static enum MODE {\n NORMAL, POSTSETUP, KEYSTORE_MIGRATION_PEM2KS\n }\n\n public static MODE selectedMode = MODE.NORMAL;\n\n public static void main(String[] args) throws Exception {\n Gson configGson = new GsonBuilder()\n .registerTypeAdapter(AlgorithmParams.class, new AlgorithmParamsDeserializer())\n .registerTypeAdapter(KeyStoreParams.class, new KeyStoreParamsDeserializer())\n .create();\n\n printBanner();\n\n System.setProperty(\"java.util.logging.manager\", \"org.apache.logging.log4j.jul.LogManager\");\n SLF4JBridgeHandler.removeHandlersForRootLogger();\n SLF4JBridgeHandler.install();\n\n //Register Bouncy Castle Provider\n log.info(\"Register Bouncy Castle Security Provider\");\n Security.addProvider(new BouncyCastleProvider());\n log.info(\"Register Bouncy Castle JSSE Security Provider\");\n Security.addProvider(new BouncyCastleJsseProvider());\n\n log.info(\"Initializing directories\");\n Path configPath = FILES_DIR.resolve(\"settings.json\");\n ensureFilesDirectoryExists(configPath);\n\n log.info(\"Loading server configuration\");\n appConfig = configGson.fromJson(Files.readString(configPath), Config.class);\n\n loadBuildAndGitMetadata();\n\n\n //Parse CLI Arguments\n final String argPrefix = \"--\";\n final char splitCharacter = '=';\n\n for (String arg : args) {\n CLIArgument cliArgument = new CLIArgument(argPrefix, splitCharacter, arg);\n\n if (cliArgument.getParameterName().equals(\"normal\")) {\n selectedMode = MODE.NORMAL;\n }\n if (cliArgument.getParameterName().equals(\"migrate-pem-to-keystore\")) {\n selectedMode = MODE.KEYSTORE_MIGRATION_PEM2KS;\n }\n if (cliArgument.getParameterName().equals(\"postsetup\")) {\n selectedMode = MODE.POSTSETUP;\n }\n }\n\n switch (selectedMode) {\n case NORMAL -> {\n initializeCoreComponents();\n log.info(\"Starting normally\");\n AcmeApiServer.startServer(cryptoStoreManager, appConfig);\n }\n case POSTSETUP -> {\n //Do not init core components, due to changing passwords in UI\n log.info(\"Starting Post Setup\");\n PostSetup.run(cryptoStoreManager, appConfig, FILES_DIR, args);\n }\n case KEYSTORE_MIGRATION_PEM2KS -> {\n initializeCoreComponents();\n log.info(\"Starting in KeyStore migration Mode (PEM to KeyStore)\");\n KSMigrationTool.run(args, cryptoStoreManager, appConfig, FILES_DIR);\n }\n\n }\n\n\n }\n\n\n /**\n * Prints a banner with a stylized text art representation.\n */\n private static void printBanner() {\n System.out.println(\"\"\"\n _ ____ \\s\n / \\\\ ___ _ __ ___ ___/ ___| ___ _ ____ _____ _ __\\s\n / _ \\\\ / __| '_ ` _ \\\\ / _ \\\\___ \\\\ / _ \\\\ '__\\\\ \\\\ / / _ \\\\ '__|\n / ___ \\\\ (__| | | | | | __/___) | __/ | \\\\ V / __/ | \\s\n /_/ \\\\_\\\\___|_| |_| |_|\\\\___|____/ \\\\___|_| \\\\_/ \\\\___|_| \\s\n \"\"\");\n }\n\n private static boolean coreComponentsInitialized = false;\n\n private static void initializeCoreComponents() throws ClassNotFoundException, CertificateException, IOException, NoSuchAlgorithmException, KeyStoreException, NoSuchProviderException, InvocationTargetException, InstantiationException, IllegalAccessException, NoSuchMethodException {\n if (coreComponentsInitialized) {\n return;\n }\n\n initializeDatabaseDrivers();\n\n {\n //Initialize KeyStore\n\n if (appConfig.getKeyStore() instanceof PKCS11KeyStoreParams pkcs11KeyStoreParams) {\n\n cryptoStoreManager = new CryptoStoreManager(\n new PKCS11KeyStoreConfig(\n Paths.get(pkcs11KeyStoreParams.getLibraryLocation()),\n pkcs11KeyStoreParams.getSlot(),\n pkcs11KeyStoreParams.getPassword()\n )\n );\n }\n if (appConfig.getKeyStore() instanceof PKCS12KeyStoreParams pkcs12KeyStoreParams) {\n\n cryptoStoreManager = new CryptoStoreManager(\n new PKCS12KeyStoreConfig(\n Paths.get(pkcs12KeyStoreParams.getLocation()),\n pkcs12KeyStoreParams.getPassword()\n )\n );\n }\n if (cryptoStoreManager == null) {\n throw new IllegalArgumentException(\"Could not create CryptoStoreManager, due to unsupported KeyStore configuration\");\n }\n\n coreComponentsInitialized = true;\n }\n }\n\n /**\n * Ensures that the necessary files directory and configuration file exist.\n *\n * @throws IOException If an I/O error occurs while creating directories or checking for the configuration file.\n */\n private static void ensureFilesDirectoryExists(Path configPath) throws IOException {\n if (!Files.exists(FILES_DIR)) {\n log.info(\"First run detected, creating settings directory\");\n Files.createDirectories(FILES_DIR);\n }\n if (!Files.exists(configPath)) {\n log.fatal(\"No configuration was found. Please create a file called \\\"settings.json\\\" in \\\"{}\\\". Then try again\", FILES_DIR.toAbsolutePath());\n System.exit(1);\n }\n }\n\n /**\n * Loads build and Git metadata from resource files and populates corresponding variables.\n */\n private static void loadBuildAndGitMetadata() {\n try (InputStream is = Main.class.getResourceAsStream(\"/build.properties\")) {\n if (is != null) {\n Properties buildMetadataProperties = new Properties();\n buildMetadataProperties.load(is);\n buildMetadataVersion = buildMetadataProperties.getProperty(\"build.version\");\n buildMetadataBuildTime = buildMetadataProperties.getProperty(\"build.date\") + \" UTC\";\n } else {\n log.warn(\"Unable to load build metadata\");\n }\n } catch (Exception e) {\n log.error(\"Unable to load build metadata\", e);\n }\n try (InputStream is = Main.class.getResourceAsStream(\"/git.properties\")) {\n if (is != null) {\n Properties gitMetadataProperties = new Properties();\n gitMetadataProperties.load(is);\n buildMetadataGitCommit = gitMetadataProperties.getProperty(\"git.commit.id.full\");\n } else {\n log.warn(\"Unable to load git metadata\");\n }\n\n } catch (Exception e) {\n log.error(\"Unable to load git metadata\", e);\n }\n }\n\n /**\n * Initializes database drivers for MariaDB and H2.\n *\n * @throws ClassNotFoundException If a database driver class is not found.\n */\n private static void initializeDatabaseDrivers() throws ClassNotFoundException {\n log.info(\"Loading MariaDB JDBC driver\");\n Class.forName(\"org.mariadb.jdbc.Driver\");\n log.info(\"Loading H2 JDBC driver\");\n Class.forName(\"org.h2.Driver\");\n }\n\n\n /**\n * Initializes the Certificate Authority (CA) by generating or loading the CA certificate and key pair.\n *\n * @throws NoSuchAlgorithmException If the specified algorithm is not available.\n * @throws CertificateException If an issue occurs during certificate generation or loading.\n * @throws IOException If an I/O error occurs while creating directories or writing files.\n * @throws OperatorCreationException If there's an issue with operator creation during certificate generation.\n * @throws NoSuchProviderException If the specified security provider is not available.\n * @throws InvalidAlgorithmParameterException If there's an issue with algorithm parameters during key pair generation.\n */\n static void initializeCA(CryptoStoreManager cryptoStoreManager) throws NoSuchAlgorithmException, CertificateException, IOException, OperatorCreationException, NoSuchProviderException, InvalidAlgorithmParameterException, KeyStoreException {\n\n\n KeyStore caKeyStore = cryptoStoreManager.getKeyStore();\n if (!caKeyStore.containsAlias(CryptoStoreManager.KEYSTORE_ALIAS_ROOTCA)) {\n\n\n // Create CA\n\n KeyPair caKeyPair = null;\n if (appConfig.getRootCA().getAlgorithm() instanceof RSAAlgorithmParams rsaParams) {\n log.info(\"Using RSA algorithm\");\n log.info(\"Generating RSA {} bit Key Pair for Root CA\", rsaParams.getKeySize());\n caKeyPair = KeyPairGenerator.generateRSAKeyPair(rsaParams.getKeySize(), caKeyStore.getProvider().getName());\n }\n if (appConfig.getRootCA().getAlgorithm() instanceof EcdsaAlgorithmParams ecdsaAlgorithmParams) {\n log.info(\"Using ECDSA algorithm (Elliptic curves\");\n\n log.info(\"Generating ECDSA Key Pair using curve {} for Root CA\", ecdsaAlgorithmParams.getCurveName());\n caKeyPair = KeyPairGenerator.generateEcdsaKeyPair(ecdsaAlgorithmParams.getCurveName(), caKeyStore.getProvider().getName());\n\n }\n if (caKeyPair == null) {\n throw new IllegalArgumentException(\"Unknown algorithm \" + appConfig.getRootCA().getAlgorithm() + \" used for root certificate\");\n }\n\n log.info(\"Creating CA\");\n X509Certificate caCertificate = CertificateAuthorityGenerator.generateCertificateAuthorityCertificate(appConfig.getRootCA(), caKeyPair);\n\n // Dumping CA Certificate to HDD, so other clients can install it\n log.info(\"Writing CA to keystore\");\n caKeyStore.setKeyEntry(CryptoStoreManager.KEYSTORE_ALIAS_ROOTCA, caKeyPair.getPrivate(), \"\".toCharArray(), //No password\n new X509Certificate[]{caCertificate});\n // Save CA in Keystore\n log.info(\"Saving keystore\");\n cryptoStoreManager.saveKeystore();\n }\n\n }\n\n}"
},
{
"identifier": "CertificateExpiration",
"path": "src/main/java/de/morihofi/acmeserver/config/CertificateExpiration.java",
"snippet": "public class CertificateExpiration implements Serializable {\n private Integer months;\n private Integer days;\n private Integer years;\n\n /**\n * Get the number of months until expiration.\n * @return The number of months.\n */\n public Integer getMonths() {\n return this.months;\n }\n\n /**\n * Set the number of months until expiration.\n * @param months The number of months to set.\n */\n public void setMonths(Integer months) {\n this.months = months;\n }\n\n /**\n * Get the number of days until expiration.\n * @return The number of days.\n */\n public Integer getDays() {\n return this.days;\n }\n\n /**\n * Set the number of days until expiration.\n * @param days The number of days to set.\n */\n public void setDays(Integer days) {\n this.days = days;\n }\n\n /**\n * Get the number of years until expiration.\n * @return The number of years.\n */\n public Integer getYears() {\n return this.years;\n }\n\n /**\n * Set the number of years until expiration.\n * @param years The number of years to set.\n */\n public void setYears(Integer years) {\n this.years = years;\n }\n}"
},
{
"identifier": "DomainNameRestrictionConfig",
"path": "src/main/java/de/morihofi/acmeserver/config/DomainNameRestrictionConfig.java",
"snippet": "public class DomainNameRestrictionConfig implements Serializable {\n private List<String> mustEndWith;\n private Boolean enabled;\n\n /**\n * Get the list of required suffixes that domain names must end with.\n * @return The list of required suffixes.\n */\n public List<String> getMustEndWith() {\n return this.mustEndWith;\n }\n\n /**\n * Set the list of required suffixes that domain names must end with.\n * @param mustEndWith The list of required suffixes to set.\n */\n public void setMustEndWith(List<String> mustEndWith) {\n this.mustEndWith = mustEndWith;\n }\n\n /**\n * Check if domain name restrictions are enabled.\n * @return True if enabled, false otherwise.\n */\n public Boolean getEnabled() {\n return this.enabled;\n }\n\n /**\n * Set the enabled status of domain name restrictions.\n * @param enabled The enabled status to set.\n */\n public void setEnabled(Boolean enabled) {\n this.enabled = enabled;\n }\n}"
},
{
"identifier": "MetadataConfig",
"path": "src/main/java/de/morihofi/acmeserver/config/MetadataConfig.java",
"snippet": "public class MetadataConfig implements Serializable {\n private String website;\n private String tos;\n\n /**\n * Get the URL of the system's website.\n * @return The website URL.\n */\n public String getWebsite() {\n return website;\n }\n\n /**\n * Set the URL of the system's website.\n * @param website The website URL to set.\n */\n public void setWebsite(String website) {\n this.website = website;\n }\n\n /**\n * Get the terms of service (TOS) information for the system.\n * @return The TOS information.\n */\n public String getTos() {\n return tos;\n }\n\n /**\n * Set the terms of service (TOS) information for the system.\n * @param tos The TOS information to set.\n */\n public void setTos(String tos) {\n this.tos = tos;\n }\n}"
},
{
"identifier": "CryptoStoreManager",
"path": "src/main/java/de/morihofi/acmeserver/tools/certificate/cryptoops/CryptoStoreManager.java",
"snippet": "public class CryptoStoreManager {\n\n /**\n * Alias for the root certificate authority in the keystore.\n */\n public static final String KEYSTORE_ALIAS_ROOTCA = \"rootCA\";\n\n /**\n * Alias for the ACME API certificate in the keystore.\n */\n public static final String KEYSTORE_ALIAS_ACMEAPI = \"serverAcmeApi\";\n\n /**\n * Prefix for aliases of intermediate certificate authorities in the keystore.\n */\n public static final String KEYSTORE_ALIASPREFIX_INTERMEDIATECA = \"intermediateCA_\";\n\n /**\n * Logger for logging messages and events.\n */\n public final Logger log = LogManager.getLogger(getClass());\n\n /**\n * Key store configuration, including type and parameters.\n */\n private final IKeyStoreConfig keyStoreConfig;\n\n /**\n * The loaded keystore instance for cryptographic operations.\n */\n private KeyStore keyStore;\n\n public static String getKeyStoreAliasForProvisionerIntermediate(String provisioner) {\n return KEYSTORE_ALIASPREFIX_INTERMEDIATECA + provisioner;\n }\n\n /**\n * Constructs a CryptoStoreManager with the specified key store configuration.\n *\n * @param keyStoreConfig The key store configuration to use.\n * @throws CertificateException If there is an issue with certificates.\n * @throws IOException If there is an I/O error.\n * @throws NoSuchAlgorithmException If a required cryptographic algorithm is not available.\n * @throws KeyStoreException If there is an issue with the keystore.\n * @throws ClassNotFoundException If a required class is not found.\n * @throws InvocationTargetException If there is an issue with invoking a method.\n * @throws InstantiationException If there is an issue with instantiating a class.\n * @throws IllegalAccessException If there is an issue with accessing a class or method.\n * @throws NoSuchMethodException If a required method is not found.\n * @throws NoSuchProviderException If a cryptographic provider is not found.\n */\n public CryptoStoreManager(IKeyStoreConfig keyStoreConfig) throws CertificateException, IOException, NoSuchAlgorithmException, KeyStoreException, ClassNotFoundException, InvocationTargetException, InstantiationException, IllegalAccessException, NoSuchMethodException, NoSuchProviderException {\n this.keyStoreConfig = keyStoreConfig;\n\n if (keyStoreConfig instanceof PKCS11KeyStoreConfig pkcs11Config) {\n String libraryLocation = pkcs11Config.getLibraryPath().toAbsolutePath().toString();\n\n log.info(\"Using PKCS#11 KeyStore with native library at {} with slot {}\", libraryLocation, pkcs11Config.getSlot());\n keyStore = PKCS11KeyStoreLoader.loadPKCS11Keystore(pkcs11Config.getPassword(), pkcs11Config.getSlot(), libraryLocation);\n }\n if (keyStoreConfig instanceof PKCS12KeyStoreConfig pkcs12Config) {\n log.info(\"Using PKCS#12 KeyStore at {}\", pkcs12Config.getPath().toAbsolutePath().toString());\n keyStore = KeyStore.getInstance(\"PKCS12\", BouncyCastleProvider.PROVIDER_NAME);\n if (Files.exists(pkcs12Config.getPath())) {\n // If the file exists, load the existing KeyStore\n log.info(\"KeyStore does exist, loading existing into memory\");\n try (InputStream is = Files.newInputStream(pkcs12Config.getPath())) {\n keyStore.load(is, pkcs12Config.getPassword().toCharArray());\n }\n } else {\n // Otherwise, initialize a new KeyStore\n log.info(\"KeyStore does not exist, creating new KeyStore\");\n keyStore.load(null, pkcs12Config.getPassword().toCharArray());\n }\n }\n }\n\n /**\n * Retrieves the key pair for the root certificate authority from the keystore.\n *\n * @return The key pair associated with the root certificate authority.\n * @throws UnrecoverableKeyException If the key is unrecoverable.\n * @throws KeyStoreException If there is an issue with the keystore.\n * @throws NoSuchAlgorithmException If a required cryptographic algorithm is not available.\n */\n public KeyPair getCerificateAuthorityKeyPair() throws UnrecoverableKeyException, KeyStoreException, NoSuchAlgorithmException {\n return KeyStoreUtil.getKeyPair(KEYSTORE_ALIAS_ROOTCA, keyStore);\n }\n\n /**\n * Retrieves the key pair for an intermediate certificate authority from the keystore.\n *\n * @param intermediateCaName The name of the intermediate certificate authority.\n * @return The key pair associated with the intermediate certificate authority.\n * @throws UnrecoverableKeyException If the key is unrecoverable.\n * @throws KeyStoreException If there is an issue with the keystore.\n * @throws NoSuchAlgorithmException If a required cryptographic algorithm is not available.\n */\n public KeyPair getIntermediateCerificateAuthorityKeyPair(String intermediateCaName) throws UnrecoverableKeyException, KeyStoreException, NoSuchAlgorithmException {\n return KeyStoreUtil.getKeyPair(getKeyStoreAliasForProvisionerIntermediate(intermediateCaName), keyStore);\n }\n\n /**\n * Retrieves the loaded keystore for cryptographic operations.\n *\n * @return The loaded keystore.\n */\n @SuppressFBWarnings(\"EI_EXPOSE_REP\")\n public KeyStore getKeyStore() {\n return keyStore;\n }\n\n /**\n * Retrieves the password associated with the keystore configuration.\n *\n * @return The password for the keystore.\n */\n public String getKeyStorePassword() {\n return keyStoreConfig.getPassword();\n }\n\n /**\n * Saves the keystore to the specified location, if it is a PKCS#12 keystore configuration.\n *\n * @throws IOException If there is an I/O error.\n * @throws CertificateException If there is an issue with certificates.\n * @throws KeyStoreException If there is an issue with the keystore.\n * @throws NoSuchAlgorithmException If a required cryptographic algorithm is not available.\n */\n public void saveKeystore() throws IOException, CertificateException, KeyStoreException, NoSuchAlgorithmException {\n if (keyStoreConfig instanceof PKCS12KeyStoreConfig pkcs12Config) {\n\n try (OutputStream fos = Files.newOutputStream(pkcs12Config.getPath())) {\n keyStore.store(fos, pkcs12Config.getPassword().toCharArray());\n }\n }\n }\n\n\n}"
}
] | import de.morihofi.acmeserver.Main;
import de.morihofi.acmeserver.config.CertificateExpiration;
import de.morihofi.acmeserver.config.DomainNameRestrictionConfig;
import de.morihofi.acmeserver.config.MetadataConfig;
import de.morihofi.acmeserver.tools.certificate.cryptoops.CryptoStoreManager;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.security.*;
import java.security.cert.X509Certificate; | 5,069 | package de.morihofi.acmeserver.certificate.acme.api;
/**
* Represents a Provisioner in a certificate management system.
* This class encapsulates all the necessary configurations and behaviors associated with a provisioner.
* It includes details such as the provisioner's name, ACME metadata configuration, certificate expiration settings,
* domain name restrictions, wildcard allowance, and manages cryptographic store operations.
* <p>
* The Provisioner class is responsible for handling various aspects of certificate provisioning and management,
* ensuring adherence to specified security and operational policies.
*/
public class Provisioner {
/**
* Get the ACME Server URL, reachable from other Hosts
*
* @return Full url (including HTTPS prefix) and port to this server
*/
public String getApiURL() { | package de.morihofi.acmeserver.certificate.acme.api;
/**
* Represents a Provisioner in a certificate management system.
* This class encapsulates all the necessary configurations and behaviors associated with a provisioner.
* It includes details such as the provisioner's name, ACME metadata configuration, certificate expiration settings,
* domain name restrictions, wildcard allowance, and manages cryptographic store operations.
* <p>
* The Provisioner class is responsible for handling various aspects of certificate provisioning and management,
* ensuring adherence to specified security and operational policies.
*/
public class Provisioner {
/**
* Get the ACME Server URL, reachable from other Hosts
*
* @return Full url (including HTTPS prefix) and port to this server
*/
public String getApiURL() { | return "https://" + Main.appConfig.getServer().getDnsName() + ":" + Main.appConfig.getServer().getPorts().getHttps() + "/" + provisionerName; | 0 | 2023-11-22 15:54:36+00:00 | 8k |
sakura-ryoko/afkplus | src/main/java/io/github/sakuraryoko/afkplus/AfkPlusMod.java | [
{
"identifier": "CommandManager",
"path": "src/main/java/io/github/sakuraryoko/afkplus/commands/CommandManager.java",
"snippet": "public class CommandManager {\n public static void register() {\n if (CONFIG.afkPlusOptions.enableAfkCommand) {\n AfkCommand.register();\n }\n if (CONFIG.afkPlusOptions.enableAfkInfoCommand) {\n AfkInfoCommand.register();\n }\n if (CONFIG.afkPlusOptions.enableAfkExCommand) {\n AfkExCommand.register();\n }\n AfkPlusCommand.register();\n }\n}"
},
{
"identifier": "ConfigManager",
"path": "src/main/java/io/github/sakuraryoko/afkplus/config/ConfigManager.java",
"snippet": "public class ConfigManager {\n public static ConfigData CONFIG = new ConfigData();\n\n public static void initConfig() {\n CONFIG.afkPlusOptions.afkPlusCommandPermissions = 3;\n CONFIG.afkPlusOptions.enableAfkCommand = true;\n CONFIG.afkPlusOptions.enableAfkInfoCommand = true;\n CONFIG.afkPlusOptions.enableAfkExCommand = true;\n CONFIG.afkPlusOptions.afkCommandPermissions = 0;\n CONFIG.afkPlusOptions.afkExCommandPermissions = 0;\n CONFIG.afkPlusOptions.afkInfoCommandPermissions = 2;\n CONFIG.afkPlusOptions.afkTimeoutString = \"<i><gray>timeout<r>\";\n CONFIG.packetOptions.resetOnLook = false;\n CONFIG.packetOptions.resetOnMovement = false;\n CONFIG.packetOptions.timeoutSeconds = 240;\n CONFIG.packetOptions.disableDamage = false;\n CONFIG.packetOptions.disableDamageCooldown = 15;\n CONFIG.PlaceholderOptions.afkPlaceholder = \"<i><gray>[AFK%afkplus:invulnerable%]<r>\";\n CONFIG.PlaceholderOptions.afkPlusNamePlaceholder = \"%player:displayname%\";\n CONFIG.PlaceholderOptions.afkPlusNamePlaceholderAfk = \"<i><gray>[AFK%afkplus:invulnerable%] %player:displayname_unformatted%<r>\";\n CONFIG.PlaceholderOptions.afkDurationPlaceholderFormatting = \"<green>\";\n CONFIG.PlaceholderOptions.afkTimePlaceholderFormatting = \"<green>\";\n CONFIG.PlaceholderOptions.afkReasonPlaceholderFormatting = \"\";\n CONFIG.PlaceholderOptions.afkDurationPretty = false;\n CONFIG.PlaceholderOptions.afkInvulnerablePlaceholder = \":<red>I<r>\";\n CONFIG.playerListOptions.afkPlayerName = \"<i><gray>[AFK%afkplus:invulnerable%] %player:displayname%<r>\";\n CONFIG.playerListOptions.enableListDisplay = true;\n CONFIG.messageOptions.enableMessages = true;\n CONFIG.messageOptions.whenAfk = \"%player:displayname% <yellow>is now AFK<r>\";\n CONFIG.messageOptions.whenReturn = \"%player:displayname% <yellow>is no longer AFK<r>\";\n CONFIG.messageOptions.prettyDuration = true;\n CONFIG.messageOptions.defaultReason = \"<gray>poof!<r>\";\n CONFIG.messageOptions.whenDamageDisabled = \"%player:displayname% <yellow>is marked as <red>Invulnerable.<r>\";\n CONFIG.messageOptions.whenDamageEnabled = \"%player:displayname% <yellow>is no longer <red>Invulnerable.<r>\";\n AfkPlusLogger.debug(\"Default config initialized.\");\n }\n public static void testConfig() {\n // Checks for invalid values\n if (CONFIG.afkPlusOptions.afkPlusCommandPermissions < 0 || CONFIG.afkPlusOptions.afkPlusCommandPermissions > 4)\n CONFIG.afkPlusOptions.afkPlusCommandPermissions = 3;\n //CONFIG.afkPlusOptions.enableAfkCommand = true;\n //CONFIG.afkPlusOptions.enableAfkInfoCommand = true;\n //CONFIG.afkPlusOptions.enableAfkExCommand = true;\n if (CONFIG.afkPlusOptions.afkCommandPermissions < 0 || CONFIG.afkPlusOptions.afkCommandPermissions > 4)\n CONFIG.afkPlusOptions.afkCommandPermissions = 0;\n if (CONFIG.afkPlusOptions.afkInfoCommandPermissions < 0 || CONFIG.afkPlusOptions.afkInfoCommandPermissions > 4)\n CONFIG.afkPlusOptions.afkInfoCommandPermissions = 2;\n if (CONFIG.afkPlusOptions.afkExCommandPermissions < 0 || CONFIG.afkPlusOptions.afkExCommandPermissions > 4)\n CONFIG.afkPlusOptions.afkExCommandPermissions = 0;\n if (CONFIG.afkPlusOptions.afkTimeoutString == null)\n CONFIG.afkPlusOptions.afkTimeoutString = \"<i><gray>timeout<r>\";\n //CONFIG.packetOptions.resetOnLook = false;\n //CONFIG.packetOptions.resetOnMovement = true;\n if (CONFIG.packetOptions.timeoutSeconds < -1 || CONFIG.packetOptions.timeoutSeconds > 3600)\n CONFIG.packetOptions.timeoutSeconds = 240;\n //CONFIG.packetOptions.disableDamage = false;\n if (CONFIG.packetOptions.disableDamageCooldown < -1 || CONFIG.packetOptions.disableDamageCooldown > 3600)\n CONFIG.packetOptions.disableDamageCooldown = 15;\n if (CONFIG.PlaceholderOptions.afkPlaceholder == null)\n CONFIG.PlaceholderOptions.afkPlaceholder = \"<i><gray>[AFK%afkplus:invulnerable%]<r>\";\n if (CONFIG.PlaceholderOptions.afkPlusNamePlaceholder == null)\n CONFIG.PlaceholderOptions.afkPlusNamePlaceholder = \"%player:displayname%\";\n if (CONFIG.PlaceholderOptions.afkPlusNamePlaceholderAfk == null)\n CONFIG.PlaceholderOptions.afkPlusNamePlaceholderAfk = \"<i><gray>[AFK%afkplus:invulnerable%] %player:displayname_unformatted%<r>\";\n if (CONFIG.PlaceholderOptions.afkDurationPlaceholderFormatting == null)\n CONFIG.PlaceholderOptions.afkDurationPlaceholderFormatting = \"<green>\";\n if (CONFIG.PlaceholderOptions.afkTimePlaceholderFormatting == null)\n CONFIG.PlaceholderOptions.afkTimePlaceholderFormatting = \"<green>\";\n if (CONFIG.PlaceholderOptions.afkReasonPlaceholderFormatting == null)\n CONFIG.PlaceholderOptions.afkReasonPlaceholderFormatting = \"\";\n //CONFIG.PlaceholderOptions.afkDurationPretty = false;\n if (CONFIG.PlaceholderOptions.afkInvulnerablePlaceholder == null)\n CONFIG.PlaceholderOptions.afkInvulnerablePlaceholder = \":<red>I<r>\";\n if (CONFIG.playerListOptions.afkPlayerName == null)\n CONFIG.playerListOptions.afkPlayerName = \"<i><gray>[AFK%afkplus:invulnerable%] %player:displayname%<r>\";\n //CONFIG.playerListOptions.enableListDisplay = true;\n //CONFIG.messageOptions.enableMessages = true;\n if (CONFIG.messageOptions.whenAfk == null)\n CONFIG.messageOptions.whenAfk = \"%player:displayname% <yellow>is now AFK<r>\";\n if (CONFIG.messageOptions.whenReturn == null)\n CONFIG.messageOptions.whenReturn = \"%player:displayname% <yellow>is no longer AFK<r>\";\n //CONFIG.messageOptions.prettyDuration = true;\n if (CONFIG.messageOptions.defaultReason == null)\n CONFIG.messageOptions.defaultReason = \"<gray>poof!<r>\";\n if (CONFIG.messageOptions.whenDamageDisabled == null)\n CONFIG.messageOptions.whenDamageDisabled = \"%player:displayname% <yellow>is marked as <red>Invulnerable.<r>\";\n if (CONFIG.messageOptions.whenDamageEnabled == null)\n CONFIG.messageOptions.whenDamageEnabled = \"%player:displayname% <yellow>is no longer <red>Invulnerable.<r>\";\n AfkPlusLogger.debug(\"Config checked for null values.\");\n }\n\n public static void loadConfig() {\n File conf = FabricLoader.getInstance().getConfigDir().resolve(AFK_MOD_ID + \".toml\").toFile();\n try {\n if (conf.exists()) {\n CONFIG = new Toml().read(conf).to(ConfigData.class);\n } else {\n AfkPlusLogger.info(\"Config \" + AFK_MOD_ID + \".toml not found, creating new file.\");\n //initConfig();\n try {\n if (!conf.createNewFile()) {\n AfkPlusLogger.error(\"Error creating config file \" + AFK_MOD_ID + \".toml .\");\n }\n } catch (Exception ignored) {\n }\n }\n testConfig();\n new TomlWriter().write(CONFIG, conf);\n } catch (Exception ex) {\n throw new RuntimeException(ex);\n }\n }\n\n public static void reloadConfig() {\n AfkPlusLogger.info(\"Reloading Config.\");\n loadConfig();\n }\n}"
},
{
"identifier": "ServerEvents",
"path": "src/main/java/io/github/sakuraryoko/afkplus/events/ServerEvents.java",
"snippet": "public class ServerEvents {\n static private Collection<String> dpCollection;\n\n public static void starting(MinecraftServer server) {\n AfkPlusLogger.debug(\"Server is starting. \" + server.getName());\n }\n\n public static void started(MinecraftServer server) {\n dpCollection = server.getDataPackManager().getEnabledNames();\n if (!AfkPlusConflicts.checkDatapacks(dpCollection))\n AfkPlusLogger.warn(\"MOD Data Pack test has FAILED.\");\n AfkPlusLogger.debug(\"Server has started. \" + server.getName());\n }\n\n public static void dpReload(MinecraftServer server) {\n dpCollection = server.getDataPackManager().getEnabledNames();\n if (!AfkPlusConflicts.checkDatapacks(dpCollection))\n AfkPlusLogger.warn(\"MOD Data Pack test has FAILED.\");\n AfkPlusLogger.debug(\"Server has reloaded it's data packs. \" + server.getName());\n }\n\n public static void stopping(MinecraftServer server) {\n AfkPlusLogger.debug(\"Server is stopping. \" + server.getName());\n }\n\n public static void stopped(MinecraftServer server) {\n AfkPlusLogger.debug(\"Server has stopped. \" + server.getName());\n }\n}"
},
{
"identifier": "NodeManager",
"path": "src/main/java/io/github/sakuraryoko/afkplus/nodes/NodeManager.java",
"snippet": "public class NodeManager {\n public static List<MoreColorNode> COLORS = new ArrayList<>();\n\n private static void initColors() {\n COLORS.add(new MoreColorNode(\"brown\", \"#632C04\"));\n COLORS.add(new MoreColorNode(\"burnt_orange\",\"#FF7034\"));\n COLORS.add(new MoreColorNode(\"canary\", \"#FFFF99\"));\n COLORS.add(new MoreColorNode(\"cool_mint\", \"#DDEBEC\"));\n COLORS.add(new MoreColorNode(\"copper\", \"#DA8A67\"));\n COLORS.add(new MoreColorNode(\"cyan\",\"#2D7C9D\"));\n COLORS.add(new MoreColorNode(\"dark_brown\",\"#421F05\"));\n COLORS.add(new MoreColorNode(\"dark_pink\",\"#DE8BB4\"));\n COLORS.add(new MoreColorNode(\"light_blue\",\"#82ACE7\"));\n COLORS.add(new MoreColorNode(\"light_brown\",\"#7A4621\"));\n COLORS.add(new MoreColorNode(\"light_gray\",\"#BABAC1\", List.of(\"light_grey\")));\n COLORS.add(new MoreColorNode(\"light_pink\",\"#F7B4D6\"));\n COLORS.add(new MoreColorNode(\"lime\",\"#76C610\"));\n COLORS.add(new MoreColorNode(\"magenta\",\"#CB69C5\"));\n //COLORS.add(new MoreColorNode(\"orange\",\"#E69E34\"));\n //COLORS.add(new MoreColorNode(\"pink\",\"#EDA7CB\"));\n COLORS.add(new MoreColorNode(\"powder_blue\", \"#C0D5F0\"));\n COLORS.add(new MoreColorNode(\"purple\",\"#A453CE\"));\n COLORS.add(new MoreColorNode(\"royal_purple\", \"#6B3FA0\"));\n COLORS.add(new MoreColorNode(\"salmon\", \"#FF91A4\", List.of(\"pink_salmon\")));\n COLORS.add(new MoreColorNode(\"shamrock\",\"#33CC99\"));\n COLORS.add(new MoreColorNode(\"tickle_me_pink\", \"#FC80A5\"));\n }\n private static void registerColors() {\n final Iterator<MoreColorNode> iterator = COLORS.iterator();\n MoreColorNode iColorNode;\n while (iterator.hasNext()) {\n iColorNode = iterator.next();\n // DataResult checked at initialization\n TextColor finalIColorNode = iColorNode.getColor();\n if (iColorNode.getAliases() != null) {\n TextParserV1.registerDefault(\n TextParserV1.TextTag.of(\n iColorNode.getName(),\n iColorNode.getAliases(),\n \"color\",\n true,\n wrap((nodes, arg) -> new ColorNode(nodes, finalIColorNode))\n )\n );\n } else {\n TextParserV1.registerDefault(\n TextParserV1.TextTag.of(\n iColorNode.getName(),\n List.of(\"\"),\n \"color\",\n true,\n wrap((nodes, arg) -> new ColorNode(nodes, finalIColorNode))\n )\n );\n }\n }\n }\n public static void initNodes() {\n initColors();\n }\n public static void registerNodes() {\n registerColors();\n }\n\n // Copied wrap() from TextTags.java\n private static TextParserV1.TagNodeBuilder wrap(Wrapper wrapper) {\n return (tag, data, input, handlers, endAt) -> {\n var out = TextParserImpl.recursiveParsing(input, handlers, endAt);\n return new TextParserV1.TagNodeValue(wrapper.wrap(out.nodes(), data), out.length());\n };\n }\n interface Wrapper {\n TextNode wrap(TextNode[] nodes, String arg);\n }\n}"
},
{
"identifier": "PlaceholderManager",
"path": "src/main/java/io/github/sakuraryoko/afkplus/placeholders/PlaceholderManager.java",
"snippet": "public class PlaceholderManager {\n public static void register() {\n AfkPlusPlaceholders.register();\n }\n}"
},
{
"identifier": "AfkPlusConflicts",
"path": "src/main/java/io/github/sakuraryoko/afkplus/util/AfkPlusConflicts.java",
"snippet": "public class AfkPlusConflicts {\n public static boolean checkMods() {\n String modTarget;\n String modVer;\n String modName;\n ModMetadata modData;\n boolean modCheck = true;\n\n AfkPlusLogger.debug(\"Checking for conflicting mods.\");\n\n // Check for svrutil --> /afk command primarily, the rest is ok\n modTarget = \"svrutil\";\n if (FabricLoader.getInstance().isModLoaded(modTarget)) {\n modData = FabricLoader.getInstance().getModContainer(modTarget).get().getMetadata();\n modVer = modData.getVersion().getFriendlyString();\n modName = modData.getName();\n AfkPlusLogger.warn(modName + \"-\" + modVer\n + \" has been found, please verify that the /afk command is disabled under config/svrutil/commands.json.\");\n modCheck = false;\n }\n\n // Check for antilogout --> /afk command, and changes timeout behavior's\n // (Remove)\n modTarget = \"antilogout\";\n if (FabricLoader.getInstance().isModLoaded(modTarget)) {\n modData = FabricLoader.getInstance().getModContainer(modTarget).get().getMetadata();\n modVer = modData.getVersion().getFriendlyString();\n modName = modData.getName();\n AfkPlusLogger.warn(modName + \"-\" + modVer\n + \" has been found, please remove this mod to avoid AFK timeout confusion.\");\n modCheck = false;\n }\n\n // Check for autoafk --> afk timeout / damage disabling\n modTarget = \"autoafk\";\n if (FabricLoader.getInstance().isModLoaded(modTarget)) {\n modData = FabricLoader.getInstance().getModContainer(modTarget).get().getMetadata();\n modVer = modData.getVersion().getFriendlyString();\n modName = modData.getName();\n AfkPlusLogger.warn(modName + \"-\" + modVer\n + \" has been found, please remove this mod to avoid AFK timeout confusion.\");\n modCheck = false;\n }\n\n // Check for sessility --> changes timeout behavior's (Remove)\n modTarget = \"sessility\";\n if (FabricLoader.getInstance().isModLoaded(modTarget)) {\n modData = FabricLoader.getInstance().getModContainer(modTarget).get().getMetadata();\n modVer = modData.getVersion().getFriendlyString();\n modName = modData.getName();\n AfkPlusLogger.warn(modName + \"-\" + modVer\n + \" has been found, please remove this mod to avoid AFK timeout confusion.\");\n modCheck = false;\n }\n // Check for playtime-tracker --> changes timeout behavior's (Remove)\n modTarget = \"playtime-tracker\";\n if (FabricLoader.getInstance().isModLoaded(modTarget)) {\n modData = FabricLoader.getInstance().getModContainer(modTarget).get().getMetadata();\n modVer = modData.getVersion().getFriendlyString();\n modName = modData.getName();\n AfkPlusLogger.warn(modName + \"-\" + modVer\n + \" has been found, please remove this mod to avoid AFK timeout/player list confusion.\");\n modCheck = false;\n }\n\n // Check for afkdisplay --> this is literary an outdated version of this afkplus\n modTarget = \"afkdisplay\";\n if (FabricLoader.getInstance().isModLoaded(modTarget)) {\n modData = FabricLoader.getInstance().getModContainer(modTarget).get().getMetadata();\n modVer = modData.getVersion().getFriendlyString();\n modName = modData.getName();\n AfkPlusLogger.warn(modName + \"-\" + modVer\n + \" has been found, please remove this mod to avoid AFK timeout/player list confusion.\");\n modCheck = false;\n }\n\n return modCheck;\n }\n\n public static boolean checkDatapacks(Collection<String> dpCollection) {\n boolean dpCheck = true;\n // Check for any data packs matching with \"afk\"\n AfkPlusLogger.debug(\"Data pack reload detected. Checking for conflicting data packs.\");\n for (String dpString : dpCollection) {\n if (dpString.contains(\"afk\") || dpString.contains(\"Afk\") || dpString.contains(\"AFK\")) {\n AfkPlusLogger.warn(\n \"Possible conflict found with data pack: \" + dpString + \" -- please remove/disable it.\");\n dpCheck = false;\n }\n }\n return dpCheck;\n }\n}"
},
{
"identifier": "AfkPlusInfo",
"path": "src/main/java/io/github/sakuraryoko/afkplus/util/AfkPlusInfo.java",
"snippet": "public class AfkPlusInfo {\n private static final FabricLoader AFK_INST = FabricLoader.getInstance();\n private static final ModContainer AFK_CONTAINER = AFK_INST.getModContainer(AFK_MOD_ID).get();\n\n public static void initModInfo() {\n AFK_MC_VERSION = FabricLoader.getInstance().getModContainer(\"minecraft\").get().getMetadata().getVersion()\n .getFriendlyString();\n AFK_ENV = AFK_INST.getEnvironmentType();\n ModMetadata AFK_METADATA = AFK_CONTAINER.getMetadata();\n AFK_VERSION = AFK_METADATA.getVersion().getFriendlyString();\n AFK_NAME = AFK_METADATA.getName();\n AFK_DESC = AFK_METADATA.getDescription();\n AFK_AUTHOR = AFK_METADATA.getAuthors();\n AFK_CONTRIB = AFK_METADATA.getContributors();\n AFK_CONTACTS = AFK_METADATA.getContact();\n AFK_LICENSES = AFK_METADATA.getLicense();\n AFK_AUTHO_STRING = getAuthoString();\n AFK_CONTRIB_STRING = getContribString();\n AFK_LICENSES_STRING = getLicenseString();\n AFK_HOMEPAGE_STRING = getHomepageString();\n AFK_SOURCES_STRING = getSourcesString();\n }\n\n public static void displayModInfo() {\n AfkPlusLogger.info(AFK_NAME + \"-\" + AFK_MC_VERSION + \"-\" + AFK_VERSION);\n AfkPlusLogger.info(\"Author: \" + AFK_AUTHO_STRING);\n }\n\n public static Text getModInfoText() {\n String modInfo = AFK_NAME + \"-\" + AFK_MC_VERSION + \"-\" + AFK_VERSION\n + \"\\nAuthor: <pink>\" + AFK_AUTHO_STRING + \"</pink>\"\n + \"\\nLicense: <yellow>\" + AFK_LICENSES_STRING + \"</yellow>\"\n + \"\\nHomepage: <cyan><url:'\" + AFK_HOMEPAGE_STRING + \"'>\" + AFK_HOMEPAGE_STRING + \"</url></cyan>\"\n + \"\\nSource: <cyan><url:'\" + AFK_SOURCES_STRING + \"'>\" + AFK_SOURCES_STRING + \"</url></cyan>\"\n + \"\\nDescription: <light_blue>\" + AFK_DESC;\n Text info = TextParserUtils.formatText(modInfo);\n AfkPlusLogger.debug(modInfo);\n return info;\n }\n\n public static boolean isServer() {\n return AFK_ENV == EnvType.SERVER;\n }\n\n public static boolean isClient() {\n return AFK_ENV == EnvType.CLIENT;\n }\n\n private static String getAuthoString() {\n StringBuilder authoString = new StringBuilder();\n if (AFK_AUTHOR.isEmpty())\n return authoString.toString();\n else {\n final Iterator<Person> iterator = AFK_AUTHOR.iterator();\n while (iterator.hasNext()) {\n if (authoString.isEmpty())\n authoString = new StringBuilder(iterator.next().getName());\n else\n authoString.append(\", \").append(iterator.next().getName());\n }\n return authoString.toString();\n }\n }\n\n private static String getContribString() {\n StringBuilder contribString = new StringBuilder();\n if (AFK_CONTRIB.isEmpty())\n return contribString.toString();\n else {\n final Iterator<Person> iterator = AFK_CONTRIB.iterator();\n while (iterator.hasNext()) {\n if (contribString.isEmpty())\n contribString = new StringBuilder(iterator.next().getName());\n else\n contribString.append(\", \").append(iterator.next().getName());\n }\n return contribString.toString();\n }\n }\n\n private static String getLicenseString() {\n StringBuilder licsenseString = new StringBuilder();\n if (AFK_LICENSES.isEmpty())\n return licsenseString.toString();\n else {\n final Iterator<String> iterator = AFK_LICENSES.iterator();\n while (iterator.hasNext()) {\n if (licsenseString.isEmpty())\n licsenseString = new StringBuilder(iterator.next());\n else\n licsenseString.append(\", \").append(iterator.next());\n }\n return licsenseString.toString();\n }\n }\n\n private static String getHomepageString() {\n String homepageString = AFK_CONTACTS.asMap().get(\"homepage\");\n if (homepageString.isEmpty())\n return \"\";\n else\n return homepageString;\n }\n\n private static String getSourcesString() {\n String sourcesString = AFK_CONTACTS.asMap().get(\"sources\");\n if (sourcesString.isEmpty())\n return \"\";\n else\n return sourcesString;\n }\n}"
},
{
"identifier": "AfkPlusLogger",
"path": "src/main/java/io/github/sakuraryoko/afkplus/util/AfkPlusLogger.java",
"snippet": "public class AfkPlusLogger {\n private static Logger LOGGER;\n private static boolean log;\n\n public static void initLogger() {\n LOGGER = LogManager.getLogger(AFK_MOD_ID);\n log = true;\n LOGGER.debug(\"[{}] Logger initalized.\", AFK_MOD_ID);\n }\n\n public static void debug(String msg) {\n if (log) {\n if (AFK_DEBUG)\n LOGGER.info(\"[{}:DEBUG] \" + msg, AFK_MOD_ID);\n else\n LOGGER.debug(\"[{}] \" + msg, AFK_MOD_ID);\n }\n }\n\n public static void info(String msg) {\n if (log)\n LOGGER.info(\"[{}] \" + msg, AFK_MOD_ID);\n }\n\n public static void warn(String msg) {\n if (log)\n LOGGER.warn(\"[{}] \" + msg, AFK_MOD_ID);\n }\n\n public static void error(String msg) {\n if (log)\n LOGGER.error(\"[{}] \" + msg, AFK_MOD_ID);\n }\n\n public static void fatal(String msg) {\n if (log)\n LOGGER.fatal(\"[{}] \" + msg, AFK_MOD_ID);\n }\n}"
}
] | import io.github.sakuraryoko.afkplus.commands.CommandManager;
import io.github.sakuraryoko.afkplus.config.ConfigManager;
import io.github.sakuraryoko.afkplus.events.ServerEvents;
import io.github.sakuraryoko.afkplus.nodes.NodeManager;
import io.github.sakuraryoko.afkplus.placeholders.PlaceholderManager;
import io.github.sakuraryoko.afkplus.util.AfkPlusConflicts;
import io.github.sakuraryoko.afkplus.util.AfkPlusInfo;
import io.github.sakuraryoko.afkplus.util.AfkPlusLogger;
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents; | 5,894 | package io.github.sakuraryoko.afkplus;
public class AfkPlusMod {
// Generic Mod init
public static void init() {
AfkPlusLogger.initLogger();
AfkPlusLogger.debug("Initializing Mod.");
AfkPlusInfo.initModInfo();
AfkPlusInfo.displayModInfo();
if (AfkPlusInfo.isClient()) {
AfkPlusLogger.info("MOD is running in a CLIENT Environment.");
}
if (!AfkPlusConflicts.checkMods())
AfkPlusLogger.warn("Mod conflicts check has FAILED.");
AfkPlusLogger.debug("Config Initializing.");
ConfigManager.initConfig();
AfkPlusLogger.debug("Loading Config.");
ConfigManager.loadConfig();
AfkPlusLogger.debug("Initializing nodes."); | package io.github.sakuraryoko.afkplus;
public class AfkPlusMod {
// Generic Mod init
public static void init() {
AfkPlusLogger.initLogger();
AfkPlusLogger.debug("Initializing Mod.");
AfkPlusInfo.initModInfo();
AfkPlusInfo.displayModInfo();
if (AfkPlusInfo.isClient()) {
AfkPlusLogger.info("MOD is running in a CLIENT Environment.");
}
if (!AfkPlusConflicts.checkMods())
AfkPlusLogger.warn("Mod conflicts check has FAILED.");
AfkPlusLogger.debug("Config Initializing.");
ConfigManager.initConfig();
AfkPlusLogger.debug("Loading Config.");
ConfigManager.loadConfig();
AfkPlusLogger.debug("Initializing nodes."); | NodeManager.initNodes(); | 3 | 2023-11-22 00:21:36+00:00 | 8k |
AzFyXi/slotMachine | SlotMachine/src/main/java/Main.java | [
{
"identifier": "User",
"path": "SlotMachine/src/main/java/User/User.java",
"snippet": "public class User {\n private String name;\n private int money;\n private int moneyBet;\n private int totalEarn;\n List<FreeAttempt> freeAttempts;\n\n //Constructor\n public User(String name, int money) {\n this.name = name;\n this.money = money;\n this.freeAttempts = new ArrayList<>();\n this.moneyBet= 0;\n this.totalEarn= -1;\n }\n\n //Getters and Setters\n public String getName() {\n return name;\n }\n public int getMoney() {\n return money;\n }\n public List<FreeAttempt> getFreeAttempts() {\n return freeAttempts;\n }\n public void setName(String name) {\n this.name = name;\n }\n public void setMoney(int money) {\n this.money = money;\n }\n public void setFreeAttempts(List<FreeAttempt> freeAttempts) {\n this.freeAttempts = freeAttempts;\n }\n public void setFreeAttempts(int multiplier, int rowRemaining) {\n FreeAttempt newFreeAttempt = new FreeAttempt(multiplier, rowRemaining);\n freeAttempts.add(newFreeAttempt);\n }\n public int getMoneyBet() {\n return moneyBet;\n }\n public void setMoneyBet(int moneyBet) {\n this.moneyBet = moneyBet;\n }\n public int getTotalEarn() {\n return totalEarn;\n }\n public void setTotalEarn(int totalEarn) {\n this.totalEarn = totalEarn;\n }\n\n //toString\n @Override\n public String toString() {\n return \"User{\" +\n \"name='\" + name + '\\'' +\n \", money=\" + money +\n \", moneyBet=\" + moneyBet +\n \", totalEarn=\" + totalEarn +\n \", freeAttempts=\" + freeAttempts +\n '}';\n }\n\n // Methods\n public void takeMoneyBet(int moneyBet) {\n this.money = this.money - moneyBet;\n }\n public void betMoreMoney() {\n if (this.moneyBet == 0) { this.moneyBet = 2000; }\n else if (this.moneyBet == 2000) { this.moneyBet = 4000; }\n else if (this.moneyBet == 4000) { this.moneyBet = 6000; }\n else if (this.moneyBet == 6000) { this.moneyBet = 10000; }\n else if (this.moneyBet == 10000) {\n }\n }\n\n public void betLessMoney() {\n if (this.moneyBet == 10000) { this.moneyBet = 6000; }\n else if (this.moneyBet == 6000) { this.moneyBet = 4000; }\n else if (this.moneyBet == 4000) { this.moneyBet = 2000; }\n else if (this.moneyBet == 2000) { this.moneyBet = 0; }\n else if (this.moneyBet == 0) {\n }\n }\n\n public boolean haveFreeAttempts() {\n return freeAttempts != null && !freeAttempts.isEmpty();\n }\n public boolean useFreeAttempt() {\n if (haveFreeAttempts()) {\n if (freeAttempts.isEmpty()) {\n return false; // retourne false si freeAttempts est vide\n }\n FreeAttempt currentFreeAttempt = freeAttempts.iterator().next();\n currentFreeAttempt.useRow();\n if (currentFreeAttempt.getRowRemaining() == 0) {\n this.freeAttempts.remove(currentFreeAttempt);\n } else if(currentFreeAttempt.getRowRemaining() > 0) {\n currentFreeAttempt.setRowRemaining(currentFreeAttempt.getRowRemaining());\n //this.freeAttempts.remove(currentFreeAttempt);\n this.freeAttempts.set(0, currentFreeAttempt);\n }\n\n return true;\n }\n return false;\n }\n\n\n public int getCurrentRowRemaining() {\n Iterator<FreeAttempt> iterator = freeAttempts.iterator();\n if(this.freeAttempts != null && iterator.hasNext()) {\n FreeAttempt currentFreeAttempt = this.freeAttempts.iterator().next();\n int rowRemaining = currentFreeAttempt.getRowRemaining();\n return rowRemaining;\n }\n return 0;\n }\n\n public int getCurrentMultimultiplier() {\n if(this.freeAttempts != null) {\n FreeAttempt currentFreeAttempt = this.freeAttempts.iterator().next();\n int multiplier = currentFreeAttempt.getMultiplier();\n return multiplier;\n }\n return 1;\n }\n}"
},
{
"identifier": "SlotMachine",
"path": "SlotMachine/src/main/java/SlotMachine/SlotMachine.java",
"snippet": "public class SlotMachine {\n private Collection<Column> columns;\n private static int numberColumns;\n private static Symbol finalSymbol;\n\n public SlotMachine(Collection<Column> columns, int numberColumns) {\n this.columns = columns;\n SlotMachine.numberColumns = numberColumns;\n finalSymbol = new Symbol(0);\n }\n\n public Collection<Column> getColumns() {\n return columns;\n }\n\n public void setColumns(Collection<Column> columns) {\n this.columns = columns;\n }\n\n public int getNumberColumns() {\n return numberColumns;\n }\n\n public void setNumberColumns(int numberColumns) {\n SlotMachine.numberColumns = numberColumns;\n }\n\n public static Symbol getFinalSymbol() {\n return finalSymbol;\n }\n public static void setFinalSymbol(Symbol finalSymbol) {\n SlotMachine.finalSymbol = finalSymbol;\n }\n\n public boolean startMachine(User mainUser, Collection<Column> columns) { //function to start the SlotMachine\n SlotMachineGUI gui = new SlotMachineGUI();\n Iterator<Column> iteratorColumns = columns.iterator();\n List<Column> columnList = new ArrayList<>(columns);\n Symbol finalSymbol = new Symbol(0);\n Collection<Column> columnsWithWinningSymbol = null;\n boolean isWin = false;\n\n while(finalSymbol != null) {\n finalSymbol = findWinningSymbol(columns); //Retrieving the winning symbol\n int numberWinningColumn = 0;\n\n if(finalSymbol != null) {\n SlotMachine.finalSymbol = finalSymbol;\n isWin = true;\n columnsWithWinningSymbol = new ArrayList<>(); //Create an ArrayList with to store the winning columns\n\n //Add the 3 winning columns (with findWinningSymbol we know that the first 3 columns are winning)\n for (int i = 0; i < columnList.get(0).getPrintNumberLine() && iteratorColumns.hasNext(); i++) {\n numberWinningColumn++;\n columnsWithWinningSymbol.add(iteratorColumns.next());\n }\n\n //Search for other winning columns\n for(int i = 3; i <= columns.size(); i++) {\n if(iteratorColumns.hasNext()) {\n Column nextColumn = iteratorColumns.next();\n if(isSymbolInColumn(nextColumn, finalSymbol)) {\n numberWinningColumn++;\n columnsWithWinningSymbol.add(nextColumn);\n } else {\n break;\n }\n }\n }\n\n //System.out.println(mainUser.getCurrentRowRemaining() + \"\" + mainUser.getCurrentMultimultiplier());\n //Search if the winning symbol is a special symbol\n if(finalSymbol.getId() > 3) { //Not special symbol\n calculatedMoney(mainUser, finalSymbol.getId(), numberWinningColumn);\n gui.showWinImage(mainUser);\n } else if (finalSymbol.getId() == 2) { //Symbol Free\n System.out.println(\"2 FRREE\");\n\n SlotMachineGUI.showFreeAttemptMenu(mainUser, SlotMachineGUI.getMainFrame());\n break;\n } else if (finalSymbol.getId() == 1) { //Symbol Bonus\n System.out.println(\"1 BONUS\");\n break;\n }\n\n //Replace winning Symbol\n replaceSymbol(numberWinningColumn, finalSymbol, columns);\n } else {\n if(!isWin) {\n gui.showLoseImage();\n }\n }\n } //Repeat as long as there is a winning symbol.\n return isWin;\n }\n\n\n public Symbol findWinningSymbol(Collection<Column> columns) { //Search the first three columns to find the winning symbol\n Iterator<Column> iterator = columns.iterator();\n Column column1 = iterator.next(); // First columns\n Column column2 = iterator.next(); // Second columns\n Column column3 = iterator.next(); // Third columns\n\n // Start the position of the first element displayed\n int startPositionFirstColumn = column1.getLinesNumber() - column1.getPrintNumberLine();\n int startPositionSecondColumn = column2.getLinesNumber() - column2.getPrintNumberLine();\n int startPositionThirdColumn = column3.getLinesNumber() - column3.getPrintNumberLine();\n Symbol foundSymbol = null;\n\n for (int i = startPositionFirstColumn; i < column1.getLinesNumber(); i++) {\n Symbol symbolToFirstColumn = column1.getSymbol(i);\n\n for (int j = startPositionSecondColumn; j < column2.getLinesNumber(); j++) {\n if (symbolToFirstColumn.equals(column2.getSymbol(j)) || column2.getSymbol(j).getId() == 1 || symbolToFirstColumn.getId() ==1) {\n foundSymbol = symbolToFirstColumn.getId() != 1 ? symbolToFirstColumn: column2.getSymbol(j); //For the symbol Super\n\n for (int k = startPositionThirdColumn; k < column3.getLinesNumber(); k++) {\n\n if (foundSymbol.equals(column3.getSymbol(k)) || foundSymbol.getId() == 1) {\n foundSymbol = foundSymbol.getId() == 1 ? column3.getSymbol(k) : foundSymbol;\n return foundSymbol;\n }\n }\n }\n }\n }\n return null;\n }\n public void replaceSymbol(int numberWinningColumn, Symbol foundSymbol, Collection<Column> columns) {\n for(Column column : columns) {\n if(column.getNumberColumn() <= numberWinningColumn) {\n List<Symbol> symbolsList = new ArrayList<>(column.getSymbol()); // Create a list of all the symbols in the column\n int foundPosition = -1;\n int linesNumber = column.getLinesNumber(); // Number of elements in the column\n int startPositionFirstElementDisplayed = linesNumber - column.getPrintNumberLine();\n\n for (int i = startPositionFirstElementDisplayed; i < linesNumber; i++) {\n if (symbolsList.get(i).equals(foundSymbol) || symbolsList.get(i).getId() == 1) {\n foundPosition = i;\n break;\n }\n }\n if (foundPosition != -1) {\n for (int i = foundPosition; i > 0; i--) {\n symbolsList.set(i, symbolsList.get(i - 1));\n }\n column.setSymbols(symbolsList);\n }\n }\n }\n }\n\n public boolean isSymbolInColumn(Column column, Symbol targetSymbol) { // Check if the symbol winners find is present in the other columns\n boolean symbolFound = false;\n\n for (int i = column.getLinesNumber() - column.getPrintNumberLine(); i < column.getLinesNumber(); i++) {\n Symbol currentSymbol = column.getSymbol(i);\n\n if (currentSymbol.equals(targetSymbol) || currentSymbol.getId() == 1) {\n symbolFound = true;\n break;\n }\n }\n\n return symbolFound;\n }\n\n public void calculatedMoney(User mainUser, int symbolId, int numberWinningColumn) { //Calculates the user's gain\n int moneyWin = 0;\n int multiplier = 1;\n int moneyBet = mainUser.getMoneyBet();\n\n if(moneyBet == 4000) multiplier = 2;\n else if(moneyBet == 6000) multiplier = 3;\n else if(moneyBet == 10000) multiplier = 5;\n\n switch (symbolId) {\n case 2:\n //Free Symbol\n case 3:\n //Bonus Symbol\n case 4:\n if(numberWinningColumn == 3) {\n moneyWin = 1000;\n } else if(numberWinningColumn == 4) {\n moneyWin = 2000;\n } else if(numberWinningColumn == 5) {\n moneyWin = 4000;\n } else {\n moneyWin = 1000;\n }\n break;\n case 5:\n if(numberWinningColumn == 3) {\n moneyWin = 750;\n } else if(numberWinningColumn == 4) {\n moneyWin = 1500;\n } else if(numberWinningColumn == 5) {\n moneyWin = 3000;\n } else {\n moneyWin = 750;\n }\n break;\n case 6,7:\n if(numberWinningColumn == 3) {\n moneyWin = 500;\n } else if(numberWinningColumn == 4) {\n moneyWin = 750;\n } else if(numberWinningColumn == 5) {\n moneyWin = 1500;\n }else {\n moneyWin = 500;\n }\n break;\n default:\n if(numberWinningColumn == 3) {\n moneyWin = 300;\n } else if(numberWinningColumn == 4) {\n moneyWin = 500;\n } else if(numberWinningColumn == 5) {\n moneyWin = 1000;\n }else {\n moneyWin = 300;\n }\n break;\n }\n moneyWin *= multiplier;\n mainUser.setTotalEarn(moneyWin);\n moneyWin +=mainUser.getMoney();\n mainUser.setMoney(moneyWin);\n }\n\n public void findFreeSymbol(User mainUser) { //Manage the appearance of the Symbol Free\n System.out.println(\"Le symbole Free est apparu, choissisez entre c'est 3 options \");\n System.out.println(\"1/ 15 lancers, multiplicateur de gain x 2\");\n System.out.println(\"2/ 10 lancers, x3\");\n System.out.println(\"3/ 5 lancers x6\");\n Scanner scanner = new Scanner(System.in);\n int userInput = scanner.nextInt();\n switch(userInput) {\n case 1 :\n mainUser.setFreeAttempts(2, 15);\n break;\n case 2 :\n mainUser.setFreeAttempts(3, 10);\n break;\n case 3 :\n mainUser.setFreeAttempts(6, 5);\n break;\n\n }\n }\n\n public static Collection<Column> createColumnsCollection(int printNumberLine, Collection<Symbol> symbols) {\n //Create the SlotMachine by default\n Collection<Column> columns = new ArrayList<>();\n\n for (int i = 1; i <= 5; i++) {\n Column column;\n\n if (i < 5) {\n column = new Column(generateSymbols(symbols, 30), i, 30, true, printNumberLine);\n } else {\n column = new Column(generateSymbols(symbols, 41), i, 41, true, printNumberLine);\n }\n\n columns.add(column);\n }\n\n return columns;\n }\n\n public static Collection<Symbol> generateSymbols(Collection<Symbol> symbols, int symbolsNumber) {\n List<Symbol> generatedSymbols = new ArrayList<>();\n Random random = new Random();\n int symbolsSize = symbols.size();\n\n for (int i = 0; i < symbolsNumber; i++) {\n int randomNumber = random.nextInt(symbolsSize);\n Symbol randomSymbol = symbols.stream().skip(randomNumber).findFirst().orElse(null);\n\n if (randomSymbol != null) {\n generatedSymbols.add(randomSymbol);\n }\n }\n return generatedSymbols;\n }\n\n public static Collection<Symbol> generateSymbols(Collection<Symbol> symbols, int symbolsNumber, Column column) {\n List<Symbol> generatedSymbols = new ArrayList<>();\n Random random = new Random();\n int symbolsSize = symbols.size();\n if(column.getNumberColumn() == 3) {\n List<Symbol> filteredSymbols = symbols.stream()\n .filter(symbol -> symbol.getId() != 1)\n .collect(Collectors.toList());\n\n int symbolsSizeWithoutOneSymbol = filteredSymbols.size();\n\n for (int i = 0; i < symbolsNumber; i++) {\n int randomNumber = random.nextInt(symbolsSizeWithoutOneSymbol);\n Symbol randomSymbol = filteredSymbols.get(randomNumber);\n generatedSymbols.add(randomSymbol);\n }\n } else if (column.getNumberColumn() == 2 || column.getNumberColumn() == 4) {\n List<Symbol> filteredSymbols = symbols.stream()\n .filter(symbol -> symbol.getId() != 2)\n .collect(Collectors.toList());\n\n int symbolsSizeWithoutOneSymbol = filteredSymbols.size();\n\n for (int i = 0; i < symbolsNumber; i++) {\n int randomNumber = random.nextInt(symbolsSizeWithoutOneSymbol);\n Symbol randomSymbol = filteredSymbols.get(randomNumber);\n generatedSymbols.add(randomSymbol);\n }\n } else {\n for (int i = 0; i < symbolsNumber; i++) {\n int randomNumber = random.nextInt(symbolsSize);\n Symbol randomSymbol = symbols.stream().skip(randomNumber).findFirst().orElse(null);\n\n if (randomSymbol != null) {\n generatedSymbols.add(randomSymbol);\n }\n }\n }\n return generatedSymbols;\n }\n public static Collection<Symbol> getSymbolsCollection(){\n JSONObject parsedSymbols = Config.parseSymbols();\n assert parsedSymbols != null;\n\n return Config.createSymbolsCollection(parsedSymbols);\n }\n\n}"
}
] | import SlotMachine.*;
import User.User;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Collection;
import static SlotMachine.SlotMachine.*; | 4,324 |
public class Main {
public static void main(String[] args) {
Collection<Symbol> symbols = getSymbolsCollection();
Collection<Column> columns = createColumnsCollection(3, symbols);
|
public class Main {
public static void main(String[] args) {
Collection<Symbol> symbols = getSymbolsCollection();
Collection<Column> columns = createColumnsCollection(3, symbols);
| User mainUser = new User("First User", 250000); | 0 | 2023-11-22 09:39:59+00:00 | 8k |
clover/clover-tr34-host | src/test/java/com/clover/tr34/Tr34AscX9Test.java | [
{
"identifier": "AscSampleTr34KeyStoreData",
"path": "src/test/java/com/clover/tr34/samples/AscSampleTr34KeyStoreData.java",
"snippet": "public class AscSampleTr34KeyStoreData extends Tr34KeyStoreData {\n\n public static final String SAMPLE_ROOT_CERT_PEM = \"-----BEGIN CERTIFICATE-----\\n\" +\n \"MIIDPDCCAiSgAwIBAgIFNAAAAAEwDQYJKoZIhvcNAQELBQAwPzELMAkGA1UEBhMC\\n\" +\n \"VVMxFTATBgNVBAoTDFRSMzQgU2FtcGxlczEZMBcGA1UEAxMQVFIzNCBTYW1wbGUg\\n\" +\n \"Um9vdDAeFw0xMDExMDIwMDAwMDBaFw0zMDEwMjcyMzU5NTlaMD8xCzAJBgNVBAYT\\n\" +\n \"AlVTMRUwEwYDVQQKEwxUUjM0IFNhbXBsZXMxGTAXBgNVBAMTEFRSMzQgU2FtcGxl\\n\" +\n \"IFJvb3QwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDeZ10uwGLGQWI4\\n\" +\n \"AG+CbKUnGCWD8q3S/owdgeatXsHoWzm+r5cIlNsrTyJ3OXlUHBIj1RqCth/1QYwe\\n\" +\n \"XzZ5J8m6qsMvPhYgVdB3bsOSQiXD30LCI4/5qqo+ikcocVKs48ypFH1fgiC+c0hL\\n\" +\n \"CN7XQ/ekPubrmGGZ0RFFC2oV8FB6tOBy3bjbFpbIAB/XmWd+g185anJp6twtesIK\\n\" +\n \"vaod2I3UhW/xGhdqfDlAvH1gmszJ88Ud0AF8P+3Zx70L/er6CwkWH5xx6SrnOvF1\\n\" +\n \"rbFTy+/OLDoPzeo5TEQjCjf4LtxEjrmwZp/ILpQ15pmprjGRrU7qXc0dLNw75sdR\\n\" +\n \"B45sE4afAgMBAAGjPzA9MA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFIKDHIan\\n\" +\n \"OuC29C5MzvfJw6JPSsnsMAsGA1UdDwQEAwIBBjANBgkqhkiG9w0BAQsFAAOCAQEA\\n\" +\n \"zP2PtLg0ePSOxWB47oKHmrHUaBAaaC1RKYzcEyyTXwOdR1NuH0sB7Z5Si2nFJgsv\\n\" +\n \"eFu2hixQLnhuXGP4gTOP/Mu5Kf5O4wi1D2xzGt6JVQIKW//eBgjeUd+GzRiHMPvM\\n\" +\n \"TAb1DVf1DQRQ37kiJY6FlpxBBolmFzwmZkPp50vu3bgjSs1nAnG//PUXq03wqojh\\n\" +\n \"Rqp1Q9MtGGpOnCv/mFyw3hR16Eqg9YVgTWg3wq+H74JZiWrTBq33kT9NMYf1jIMo\\n\" +\n \"A1exxP5BvJaTBE2wcEPVAAdzjmeoFqUjWZGoBff8hT2KqDo01SC46Aa6z1bQZWhO\\n\" +\n \"kCETYhPBMp8I9cRBZQS2/g==\\n\" +\n \"-----END CERTIFICATE-----\";\n\n // B.2.1.7 TR34 Sample KRD 1 Key\n public static final String SAMPLE_KRD_1_PRIVATE_KEY_PEM = \"-----BEGIN PRIVATE KEY-----\\n\" +\n \"MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQDUXDDLb7sdOUzl\\n\" +\n \"qHtJ223PFDSw+k4Ko3H4UO6Lrn8tw8VI1Ry9o90B8NZVO/t5hR5zFUOYSyLjYrT8\\n\" +\n \"HdPW3oI3fSATLMY5Zd0K0t1onphSkWE1QPMOdaVY+RWy6eQN1CHKxr23RZD0Qoq0\\n\" +\n \"aE7LQpTTutIS9mYiAO733cMBMW+6Z2txIPuRiTwroxGoT3OvIWO1YEQF/XYLsVJo\\n\" +\n \"nPUgTyDLvZdiO125bM9ro4Jqw4eQ08LGbNfr/VyfHnDLx39Vj5VQGpqctKs9/aJl\\n\" +\n \"0BCkmrcCoAFd8PbgjQzjYzBkHE3HXqj+fdXqaze9ZDKFd/hVDT8BWqVvGrXyXlX1\\n\" +\n \"k0CvU/lVAgMBAAECggEBAIRrIDoa59CnRF4ImyhI3cY80UZyLmvP02eF/9m167P7\\n\" +\n \"2W87BHr0TQHCzcPEbWEvMveMEORMJesoR7bWWpwnj4dOTMvoJYrxC86OAmYUTuNd\\n\" +\n \"qAHvCCDCF2LNn0w7MGu3FYM+Plqj1GmbfKZWTJvOXsNQQWJ1puYZMun4rHp3+zV9\\n\" +\n \"2JxeSS/jeY+gZCtNEtFTB59e/XePM0GyCgogLi+Zswd7WdBdLBVJviP5uvZZSfLG\\n\" +\n \"zZsw0GABv4/mzce+64XtD7cTe7GFJ+JSB3nDWpqHZ7t6cM9OwSuuZSUrB02rIiby\\n\" +\n \"6PoO0dweO3fpG0TIFV8/eJQCVb2qDWszt5R35Ze7tNkCgYEA89cBvXQP+sHjbvqf\\n\" +\n \"euBcQaOYke2oUeAecBVp1tTfLP8qZK4juNjq11x0GDS1oVoYzP2Nwkks2LZDZDMe\\n\" +\n \"WYKtXkXImkmOZaGBNI0/5/F3C/tFPt3W7/QT249sWayMJkkuDKl6kmSDX/Bg7/sr\\n\" +\n \"MaJDxgSTyOjvjNieSy6GBvLBwf8CgYEA3vNLzDPe9HEqeCubKTD1doxevLDg5Pg1\\n\" +\n \"1a61U+Tgrp7XuONh2VtnP6zpFcq7Psd1L2EeQdhGIBhf+zP2d55ib76dNOBrG85d\\n\" +\n \"EiY5Qdu1FnHZDDvSnDN6AHsqZD//nHX6FgSN64PmhHvV2SyTjNUPdZU1WqN2TRzm\\n\" +\n \"ebS5sipQnKsCgYEAkWgQkJJqiQUgA+kOOy8ZtMbCz5qiOhjk7b/HOqX8ZA/RjvJN\\n\" +\n \"OQiZmk12qYydFxfsHCnDZC1QwfaGX3UgTw5fJg2FH4RnlvFlZBorFrxmWk2/sEqH\\n\" +\n \"xtWNFewEF8GOXbJb9I8IGc44jXiBxfnIezOhKK9IFZHab+opEvouUGxo4K8CgYA0\\n\" +\n \"tYRoBKNjWxXVT0nhlSeTHWCQb6jbuSrRF/ramLPd1MPffDJ39roUPcblVgaqsvEr\\n\" +\n \"gGRs4LrDf7/BXemZIiLXlFMKWzw3WLR8Q/kpbs4DPms4DzSdpTXkwzmkddTyopm7\\n\" +\n \"dtwuoAJxs+086OMBWqXLALmacibX2EtM3sNAMezY/QKBgQCjMcS9aViitfs68dA8\\n\" +\n \"mazoZvUP4JjBguspTnpz31lMQiDn7HnK+vwWsmzgEhF4suuVf6+4f4mjr4AVg7E4\\n\" +\n \"L1IdBgvzFM2hXXmgsTlazousJ/uE+513nwrNMqm2/O/iZe1yvCjMevBSVo+4CDa0\\n\" +\n \"WETw0cEkmteh/Z9Z2IOVOoj82Q==\\n\" +\n \"-----END PRIVATE KEY-----\";\n\n public static final String SAMPLE_KRD_1_CERT_PEM = \"-----BEGIN CERTIFICATE-----\\n\" +\n \"MIIDOTCCAiGgAwIBAgIFNAAAAAcwDQYJKoZIhvcNAQELBQAwQTELMAkGA1UEBhMC\\n\" +\n \"VVMxFTATBgNVBAoTDFRSMzQgU2FtcGxlczEbMBkGA1UEAxMSVFIzNCBTYW1wbGUg\\n\" +\n \"Q0EgS1JEMB4XDTEwMTEwMjAwMDAwMFoXDTIwMTAyOTIzNTk1OVowQDELMAkGA1UE\\n\" +\n \"BhMCVVMxFTATBgNVBAoTDFRSMzQgU2FtcGxlczEaMBgGA1UEAxMRVFIzNCBTYW1w\\n\" +\n \"bGUgS1JEIDEwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDUXDDLb7sd\\n\" +\n \"OUzlqHtJ223PFDSw+k4Ko3H4UO6Lrn8tw8VI1Ry9o90B8NZVO/t5hR5zFUOYSyLj\\n\" +\n \"YrT8HdPW3oI3fSATLMY5Zd0K0t1onphSkWE1QPMOdaVY+RWy6eQN1CHKxr23RZD0\\n\" +\n \"Qoq0aE7LQpTTutIS9mYiAO733cMBMW+6Z2txIPuRiTwroxGoT3OvIWO1YEQF/XYL\\n\" +\n \"sVJonPUgTyDLvZdiO125bM9ro4Jqw4eQ08LGbNfr/VyfHnDLx39Vj5VQGpqctKs9\\n\" +\n \"/aJl0BCkmrcCoAFd8PbgjQzjYzBkHE3HXqj+fdXqaze9ZDKFd/hVDT8BWqVvGrXy\\n\" +\n \"XlX1k0CvU/lVAgMBAAGjOTA3MAkGA1UdEwQCMAAwHQYDVR0OBBYEFA1yBTypguLB\\n\" +\n \"ic5HIFDTTQRamlnTMAsGA1UdDwQEAwIEMDANBgkqhkiG9w0BAQsFAAOCAQEADZ7T\\n\" +\n \"nJfS4XvwcTTbQLoaSs7XKtaP1RnePiL5uMtqUYBbX81DjxxzCX5pmfBcwG+8e/I/\\n\" +\n \"yxJBEo4KedeTUWAGhRjRimUw+0hjN8l/DK1xjKHcJIHyHB994D7FaxLOqCvIHr30\\n\" +\n \"lEJ1b/PamS0owURXR6sQIfHBT/5D0IUo5mjgQG3/UA1VXYI7nwtRxLvbR8bxezAn\\n\" +\n \"R5tci+RIQnbtC3HNrcHCSUa20YZGjIV047jR6hUf2JQiG9v0wuc8lAXXlee3/eIZ\\n\" +\n \"muMxdtOucq2oDZUQIE8MhwV3t/dS3EebKdUBITkcz8qBeMhrGq12m1hOaBfhYrBa\\n\" +\n \"MRkw+KTx3ddSdCDXsQ==\\n\" +\n \"-----END CERTIFICATE-----\";\n\n public static final String SAMPLE_KDH_1_CERT_PEM = \"-----BEGIN CERTIFICATE-----\\n\" +\n \"MIIDUTCCAjmgAwIBAgIFNAAAAAYwDQYJKoZIhvcNAQELBQAwQTELMAkGA1UEBhMC\\n\" +\n \"VVMxFTATBgNVBAoTDFRSMzQgU2FtcGxlczEbMBkGA1UEAxMSVFIzNCBTYW1wbGUg\\n\" +\n \"Q0EgS0RIMB4XDTEwMTEwMjAwMDAwMFoXDTIwMTAyOTIzNTk1OVowQDELMAkGA1UE\\n\" +\n \"BhMCVVMxFTATBgNVBAoTDFRSMzQgU2FtcGxlczEaMBgGA1UEAxMRVFIzNCBTYW1w\\n\" +\n \"bGUgS0RIIDEwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDD648pBL7L\\n\" +\n \"b5Hvyjjbt13ZGTHKj+IRZj9Ib8q6B6DC7YfLUobFCNotHw7e3cCn21xgXby5q3PR\\n\" +\n \"YbsaDxsO5VV4D697yrpeBt/viJ5R9o/mXcIa8AA6hvFwbkYeFQK+pFh3uuICZY+8\\n\" +\n \"ouvtVpIBhjV/cU5b7slwoeqICKn0Ji8vZEOCedh8ZMF+ObpxMPR7SqRBNkP4aphi\\n\" +\n \"o1rZNz2OLSjFksilIXMbqVyORDJ6uw7OUL+ubOjq9JNOlIxqO4vr4mimknvIfhrn\\n\" +\n \"ktUxUzmbS4KILJp55DHRDc5YQHBTuSv21tZyKbtyquAQgn5xJtdXBAbKqp9NtPKM\\n\" +\n \"S9ZKnvyYoOrNAgMBAAGjUTBPMAkGA1UdEwQCMAAwCwYDVR0PBAQDAgbAMAkGA1Ud\\n\" +\n \"EwQCMAAwHQYDVR0OBBYEFA8RoQrHXhlpbL0WonoyGxhajYcHMAsGA1UdDwQEAwIG\\n\" +\n \"wDANBgkqhkiG9w0BAQsFAAOCAQEAjadCTzoj3bOETDwaxSm3rRO/pbKj86kUVQL7\\n\" +\n \"rFQIgqZTkIGY/ljVwlJpNReYCVeJKAnpNEDw1+IWO/QoLDLy1XyZhGj4luLGqO4v\\n\" +\n \"HrdsA8g9j4Wj60+G7I+P/RJuP2orslSLV7JTiKwvrMI8jPUv0I3Q7ADbDH7MCCHG\\n\" +\n \"gd+ubgVCWWt0vYXIbzfXpB6Q0bMjjHlQAklqq4oAGrvEr/mcVNbNAXR2Ind+IPQB\\n\" +\n \"SBAjlWsUN87K5SkeSTO+EU/OG4I+TFFVy7gxQr0VQ4KbCK4fTIcYcZgtiorW6If0\\n\" +\n \"C1gvjNMu6DCl1aTjAzp6QV/rkYG+1Lk91eN8BF5jKBPOQMScrA==\\n\" +\n \"-----END CERTIFICATE-----\";\n\n // B.4 CAKDH – Certificate Authority – KDH Certificate\n public static final String SAMPLE_CA_KDH_CERT_PEM = \"-----BEGIN CERTIFICATE-----\\n\" +\n \"MIIDPjCCAiagAwIBAgIFNAAAAAUwDQYJKoZIhvcNAQELBQAwPzELMAkGA1UEBhMC\\n\" +\n \"VVMxFTATBgNVBAoTDFRSMzQgU2FtcGxlczEZMBcGA1UEAxMQVFIzNCBTYW1wbGUg\\n\" +\n \"Um9vdDAeFw0xMDExMDIwMDAwMDBaFw0yNTEwMjgyMzU5NTlaMEExCzAJBgNVBAYT\\n\" +\n \"AlVTMRUwEwYDVQQKEwxUUjM0IFNhbXBsZXMxGzAZBgNVBAMTElRSMzQgU2FtcGxl\\n\" +\n \"IENBIEtESDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAK76HXOWw9uk\\n\" +\n \"meVdeqUHFKxedcEnHZAA6u7SoAerZGZwUV9DISyKILwyy2exzV1xL2Z3b3dtWLxf\\n\" +\n \"gXMMU5Y2IitEKMiq/PzQDLzoSXBwZsGUbQ6vsjMTtqatvyPpIvWV0e5XpsS+AU1q\\n\" +\n \"ZOXZxFQpySBBDh8Swl5VAAZdSXpHeM8DVg3oEYbO1+W3R0odRwPqr5RAajxzFE34\\n\" +\n \"yXH4ec8zro6YSN5QUbRgKaYslJe86GrxUkYLOUOuJM/5zoj1pQSF2hSz0x3Txp3y\\n\" +\n \"QQXSUmJT6jiJ/hxv2DOoE69D/sQMQPiC2t5O6/5YAUSN3L2d5Pu2nVaggQ4IK3Mq\\n\" +\n \"NeoqFnByhv8CAwEAAaM/MD0wDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUuCpY\\n\" +\n \"Cg159koHx1irw5NlY183yhgwCwYDVR0PBAQDAgEGMA0GCSqGSIb3DQEBCwUAA4IB\\n\" +\n \"AQCb+yPhlvcoHPANAfIV6DVxd7CoPzLihuz4VjE24OQZ8LvIa5l++fmeD3mwonKO\\n\" +\n \"CVAu1zBO1qzguAP1nybImPeoFPpMGUq0A+HpmY0cFhUW5HcYrFp4UnUyPqOtmKVA\\n\" +\n \"7kr2W5qMPoMcuDO778vNQXNDyeskBOi+LMfdVy1OFIW7OS+L9xp5L2k4koMCyjse\\n\" +\n \"65sUl87YMe+EOqVYWCImFmgjilnAn2uF3cn9BheEXstxyPJ7RNxLFPNqv7lFQkgm\\n\" +\n \"SfKTqvfEYirqrAinZBVp9uU6ZOEE+C84pKCXZDrcuQf8EVJK9HLX0NCQcxfD32OU\\n\" +\n \"7N32YnGn+yrjDPjVgXyDVt+D\\n\" +\n \"-----END CERTIFICATE-----\";\n\n private final X509Certificate rootCert;\n private final X509Certificate krdCaCert;\n private final X509Certificate kdhCaCert;\n private final X509Certificate kdhCert;\n\n private final PrivateKey krdCaPrivateKey;\n private final PrivateKey kdhCaPrivateKey;\n private final PrivateKey kdhPrivateKey;\n\n private AscSampleTr34KeyStoreData(String kdhCertPem, String kdhPrivateKeyPem) {\n kdhCert = Tr34CryptoUtils.parseCert(kdhCertPem);\n if (kdhPrivateKeyPem != null) {\n kdhPrivateKey = Tr34CryptoUtils.parsePrivateKey(kdhPrivateKeyPem);\n } else {\n kdhPrivateKey = null;\n }\n\n rootCert = Tr34CryptoUtils.parseCert(SAMPLE_ROOT_CERT_PEM);\n kdhCaCert = Tr34CryptoUtils.parseCert(SAMPLE_CA_KDH_CERT_PEM);\n krdCaCert = null;\n\n kdhCaPrivateKey = null;\n krdCaPrivateKey = Tr34CryptoUtils.parsePrivateKey(SAMPLE_KRD_1_PRIVATE_KEY_PEM);\n }\n\n public static final Tr34KeyStoreData KDH_1 =\n new AscSampleTr34KeyStoreData(SAMPLE_KDH_1_CERT_PEM, null);\n\n @Override\n public X509Certificate getRootCert() {\n return rootCert;\n }\n\n @Override\n public X509Certificate getKdhCaCert() {\n return kdhCaCert;\n }\n\n @Override\n public X509Certificate getKdhCert() {\n return kdhCert;\n }\n\n @Override\n public X509Certificate getKrdCaCert() {\n return krdCaCert;\n }\n\n @Override\n public Tr34ScdKeyStoreData getKdhKeyStoreData() {\n return new Tr34ScdKeyStoreData(kdhCert, kdhPrivateKey);\n }\n\n @Override\n public Tr34ScdKeyStoreData getKdhCaKeyStoreData() {\n return new Tr34ScdKeyStoreData(kdhCaCert, kdhCaPrivateKey);\n }\n\n @Override\n public Tr34ScdKeyStoreData getKrdCaKeyStoreData() {\n return new Tr34ScdKeyStoreData(krdCaCert, krdCaPrivateKey);\n }\n\n @Override\n public List<Tr34KdhRevocation> getKdhRevocationList() {\n return Arrays.asList(\n new Tr34KdhRevocation(BigInteger.valueOf(223338299400L), new Date(1288718893000L), CRLReason.CESSATION_OF_OPERATION),\n new Tr34KdhRevocation(BigInteger.valueOf(223338299402L), new Date(1288719106000L), CRLReason.CESSATION_OF_OPERATION),\n new Tr34KdhRevocation(BigInteger.valueOf(223338299403L), new Date(1288719205000L), CRLReason.CESSATION_OF_OPERATION)\n );\n }\n\n @Override\n public int nextCrlUpdateDays() {\n return 30;\n }\n}"
},
{
"identifier": "AscSampleTr34Messages",
"path": "src/test/java/com/clover/tr34/samples/AscSampleTr34Messages.java",
"snippet": "public final class AscSampleTr34Messages {\n\n /**\n * B.12 RTKRD – KRD Random Number Token\n */\n public static final String RKRD_PEM =\n \"redacted\";\n\n /**\n * ASC X9 TR 34-2019 Corrigendum (Errata)\n * B.9.1 2 Pass Key Token\n * <p>\n * BouncyCastle CMS verify doesn't work on this sample:\n * <br>\n * See <a href=\"https://github.com/bcgit/bc-java/issues/1484\">bc-java issue 1484</a>\n * <br>\n * See <a href=\"https://github.com/openssl/openssl/issues/22120\">openssl issue 22120</a>\n * <p>\n * Furthermore, something is wrong with the encryption, bouncy castle fails with\n * the error \"Not a valid OAEP Parameter encoding\".\n */\n public static final String SAMPLE_KDH_KT_2_PASS_FOR_KRD_1_CMS =\n \"redacted\";\n\n /**\n * B.11 RBTKDH – KDH Rebind Token\n * <p>\n * This particular sample is encoded incorrectly. The eContent is not a SignedData\n * sequence but is instead the streamed guts of a SignedData without the sequence.\n * Best assumption is that it is malformed by accident since it really isn't valid\n * ASN.1 as it is, and also since the description at B.11 RBTKDH – KDH Rebind Token\n * specifically says it should be a SEQUENCE, notice:\n * <pre>\n * eContentType ContentType, -- id-signedData\n * eContent [0] EXPLICIT OCTET STRING OPTIONAL {\n * SignedData ::= SEQUENCE {\n * version Version (v3 | vx9-73, ...),\n * digestAlgorithms DigestAlgorithmIdentifiers, -- no digest algorithms\n * -- ...\n * }\n * }\n * </pre>\n */\n public static final String SAMPLE_REBIND_KDH_TOKEN_PEM =\n \"redacted\";\n\n /**\n * Extracted from B.6 CTKDH – The KDH Credential Token\n */\n public static final String SAMPLE_KDH_1_PUB_KEY_PEM =\n \"redacted\";\n\n /**\n * B.2.2.2.4 Sample AES Key Block Using IssuerAndSerialNumber\n */\n public static final String SAMPLE_CLEAR_AES_KEY_BLOCK =\n \"redacted\";\n\n /**\n * B.6 CTKDH – The KDH Credential Token\n */\n public static final String SAMPLE_CT_KDH_PEM =\n \"redacted\";\n\n /**\n * B.14 UBTKDH – KDH Unbind Token\n */\n public static final String SAMPLE_UBT_KDH_PEM =\n \"redacted\";\n\n /**\n * B.13 UBTCA_UNBIND – Higher Level Authority Unbind Token\n */\n public static final String SAMPLE_UBT_CA_PEM =\n \"redacted\";\n\n /**\n * B.10 RBTCA_UNBIND – Higher Level Authority Rebind Token\n * <p>\n * This particular sample is encoded incorrectly. The eContent is not a SignedData\n * sequence but is instead the streamed guts of a SignedData without the sequence.\n * <p>\n * Same problem as {@link #SAMPLE_REBIND_KDH_TOKEN_PEM}.\n */\n public static final String SAMPLE_RBT_CA_PEM =\n \"redacted\";\n\n /**\n * B.7 CTKRD - The KRD Credential Token\n */\n public static final String SAMPLE_CT_KRD_PEM =\n \"redacted\";\n}"
}
] | import com.clover.tr34.samples.AscSampleTr34KeyStoreData;
import com.clover.tr34.samples.AscSampleTr34Messages;
import org.bouncycastle.asn1.ASN1Encodable;
import org.bouncycastle.asn1.ASN1Encoding;
import org.bouncycastle.asn1.ASN1OctetString;
import org.bouncycastle.asn1.DLSet;
import org.bouncycastle.asn1.cms.CMSAttributes;
import org.bouncycastle.asn1.pkcs.Attribute;
import org.bouncycastle.cert.X509CRLHolder;
import org.bouncycastle.cert.X509CertificateHolder;
import org.bouncycastle.cms.CMSSignedData;
import org.bouncycastle.util.Properties;
import org.bouncycastle.util.Selector;
import org.bouncycastle.util.encoders.Hex;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import java.security.MessageDigest;
import java.security.PublicKey;
import java.security.Signature;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.Collection;
import static org.junit.Assert.assertArrayEquals; | 7,156 | package com.clover.tr34;
@Ignore("Enable after populating redacted ASC X9 TR-34 sample messages")
public class Tr34AscX9Test {
@Before
public void setup() {
// ASC X9 TR 34 sample certs sometimes include repeated extensions
Properties.setThreadOverride("org.bouncycastle.x509.ignore_repeated_extensions", true);
}
@Test
public void ascSampleRandomTokenParse() { | package com.clover.tr34;
@Ignore("Enable after populating redacted ASC X9 TR-34 sample messages")
public class Tr34AscX9Test {
@Before
public void setup() {
// ASC X9 TR 34 sample certs sometimes include repeated extensions
Properties.setThreadOverride("org.bouncycastle.x509.ignore_repeated_extensions", true);
}
@Test
public void ascSampleRandomTokenParse() { | byte[] rand = Tr34RandomToken.create(AscSampleTr34Messages.RKRD_PEM).getRandomNumber().getOctets(); | 1 | 2023-11-22 06:30:40+00:00 | 8k |
trgpnt/java-class-jacksonizer | src/main/java/com/aggregated/inline_tests/intricate_tests/existing_ctor_test/hierarchical_test/BaseClass.java | [
{
"identifier": "StringUtils",
"path": "src/main/java/com/aggregated/StringUtils.java",
"snippet": "public class StringUtils {\n private static final Logger LOG = LoggerFactory.getLogger(StringUtils.class);\n\n private static final String OPEN_PAREN = \"(\";\n private static final String CLOSE_PAREN = \")\";\n private static final String AT = \"@\";\n private static final String COMMA = \",\";\n private static final String DOT = \".\";\n private static final String EQUAL = \" = \";\n private static final String SPACE = \" \";\n private static final char SEMICOLON = ';';\n private static final String SINGLE_BREAK = \"\\n\";\n private static final Map<String, String> rawImportToResovled = new HashMap<>();\n\n public static boolean isNotEmpty(String input) {\n return !isEmpty(input);\n }\n\n public static boolean isEmpty(String input) {\n return Objects.isNull(input) || input.isEmpty();\n }\n\n public static boolean isNoneBlank(String input) {\n if (isEmpty(input)) {\n return false;\n }\n int l = 0;\n int r = input.length() - 1;\n char[] inpArr = input.toCharArray();\n while (l <= r) {\n char left = inpArr[l];\n char right = inpArr[r];\n if (Character.isLetterOrDigit(left) || Character.isLetterOrDigit(right)) {\n return true;\n }\n l++;\n r--;\n }\n return false;\n }\n\n public static boolean isBlank(String inp) {\n return !isNoneBlank(inp);\n }\n\n public static boolean containsAny(String toCheck, String... args) {\n AtomicBoolean res = new AtomicBoolean();\n Arrays.stream(args)\n .parallel()\n .forEach(\n each -> {\n if (res.get()) {\n return;\n }\n if (toCheck.contains(each)) {\n res.set(true);\n }\n });\n return res.get();\n }\n\n public static String resolveReplaces(String orig, String... fromToPairs) {\n final int PAIR_JUMP = 2;\n if (fromToPairs.length % 2 != 0) {\n LOG.error(\"Not enough data to perform action\");\n }\n for (int i = 0, n = fromToPairs.length; i < n; i += PAIR_JUMP) {\n orig = orig.replace(fromToPairs[i], fromToPairs[i + 1]);\n }\n // fishy, ensure single-dotted only.\n return orig.replaceAll(\"\\\\.+\", \".\");\n }\n\n public static boolean endsWithAny(String toCheck, String... args) {\n for (String each : args) {\n if (toCheck.endsWith(each) || toCheck.endsWith(each + \".java\")) {\n return true;\n }\n }\n return false;\n }\n\n public static String stripComments(String inp) {\n inp = inp.replaceAll(\"//.*\", \"\");\n Pattern pattern = Pattern.compile(\"/\\\\*.*?\\\\*/\", Pattern.DOTALL);\n Matcher matcher = pattern.matcher(inp);\n inp = matcher.replaceAll(\"\");\n\n return inp;\n }\n\n public static String appendIndentableBracketTo(String inp, String bracket, String indentVal) {\n if (inp.isEmpty() || inp.contains(String.valueOf(bracket))) {\n return inp;\n }\n StringBuilder resultBuilder = new StringBuilder(inp);\n if (!bracket.equalsIgnoreCase(\n String.valueOf(resultBuilder.charAt(resultBuilder.length() - 1)))) {\n resultBuilder.append(indentVal).append(bracket);\n }\n return resultBuilder.toString();\n }\n\n public static String stripUntilDollarSign(String inp) {\n for (int i = 0, n = inp.length(); i < n; i++) {\n if (inp.charAt(i) == '$') {\n return inp.substring(0, i);\n }\n }\n return inp;\n }\n\n public static String stripUntilClassPath(String inp, Character... toKeep) {\n List<Character> toKeeps = Arrays.asList(toKeep);\n StringBuilder sb = new StringBuilder();\n for (Character c : inp.toCharArray()) {\n if (Character.isLetterOrDigit(c) || toKeeps.contains(c)) {\n sb.append(c);\n }\n }\n return resolveReplaces(sb.toString(), \"/\", \"\");\n }\n\n public static DecorationLocalField makeFieldFromFieldTypeAndName(String inp) {\n int marker = 0;\n char[] charArr = inp.toCharArray();\n int n = charArr.length;\n for (int i = n - 1; i >= 0; i--) {\n if (Character.isSpaceChar(inp.charAt(i))) {\n marker = i;\n break;\n }\n }\n final String processedFieldName = new String(charArr, marker, n - marker);\n final String fieldType = new String(charArr, 0, marker);\n DecorationLocalField decorationLocalField = DecorationLocalField.createFrom(processedFieldName, fieldType, fieldType, fieldType, false);\n return decorationLocalField;\n }\n\n\n public static boolean isAllLowerCase(String inp) {\n for (Character c : inp.toCharArray()) {\n if (Character.isUpperCase(c)) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * Pincer-strip double-ended non alphanumeric chars from string, until meets character / digit\n * from both ends.\n *\n * @param inp\n * @return\n */\n public static String stripDoubleEndedNonAlphaNumeric(String inp) {\n if (StringUtils.isEmpty(inp)) {\n return \"\"; // avoid NPE\n }\n final int THRESHOLD = 200;\n final long start = System.currentTimeMillis();\n int left = 0, n = inp.length() - 1, right = n;\n while (left < right && left < inp.length() && !Character.isLetterOrDigit(inp.charAt(left))) {\n left++;\n }\n while (left < right && right > 0 && !Character.isLetterOrDigit(inp.charAt(right))) {\n right--;\n }\n // if unchanged.\n if (left >= right || (left == 0 && right == n)) {\n return inp;\n }\n\n while (true) {\n if (System.currentTimeMillis() - start >= THRESHOLD) {\n break;\n }\n try {\n return inp.substring(left, right + 1);\n } catch (Throwable t) {\n right -= 1;\n }\n }\n return inp;\n }\n\n public static int lastIndexOf(\n String inp, char x, Integer backwardFrom, Integer ordinalIndex, Boolean skipBreaker) {\n if (!inp.contains(String.valueOf(x))) {\n return -1;\n }\n if (Objects.isNull(skipBreaker)) {\n skipBreaker = true;\n }\n if (Objects.isNull(ordinalIndex)) {\n ordinalIndex = 1;\n }\n int n = inp.length() - 1;\n if (Objects.nonNull(backwardFrom)) {\n n = backwardFrom;\n }\n int matches = 0;\n int shrinkingI = n;\n for (int i = n; i >= 0; i--) {\n try {\n if (inp.charAt(i) == x) {\n matches++;\n if (ordinalIndex == -1) {\n shrinkingI = i;\n continue;\n }\n if (matches == ordinalIndex) {\n return i;\n }\n }\n if ((skipBreaker) && (inp.charAt(i) == '\\r' || inp.charAt(i) == '\\n')) {\n break;\n }\n } catch (Throwable t) {\n i--;\n }\n }\n return shrinkingI;\n }\n\n public static int countCharsFromEnd(String inp, char x) {\n int i = lastIndexOf(inp, x, null, null, null);\n int count = 0;\n while (i >= 0 && inp.charAt(i) == x) {\n i--;\n count++;\n }\n return count;\n }\n\n public static List<String> makeNonAlphaStringsFrom(String inp, boolean isUnique) {\n if (StringUtils.isEmpty(inp)) {\n return new ArrayList<>();\n }\n List<String> res = new ArrayList<>();\n char[] inpCharArr = inp.toCharArray();\n int l = 0;\n int n = inpCharArr.length;\n while (l < n) {\n while (l < n && !Character.isLetterOrDigit(inpCharArr[l])) {\n l++;\n }\n int r = l;\n while (r < n && Character.isLetterOrDigit(inpCharArr[r])) {\n r++;\n }\n final String toAdd = new String(inpCharArr, l, r - l);\n if (isUnique && !res.contains(toAdd) && StringUtils.isNotEmpty(toAdd)) {\n res.add(toAdd);\n }\n l = r + 1;\n }\n\n return res;\n }\n\n /**\n * @param inp\n * @return A spaced-string from list\n */\n public static String toStringFromList(List<String> inp, char connective) {\n if (CollectionUtils.isEmpty(inp)) {\n return \"\";\n }\n final int availableProcessors = Runtime.getRuntime().availableProcessors();\n Thread[] threads = new Thread[availableProcessors];\n int threadIdx = 0;\n int n = inp.size();\n int possibleThreads = n / availableProcessors;\n AtomicInteger start = new AtomicInteger(0);\n AtomicInteger decreaser = new AtomicInteger(availableProcessors);\n AtomicInteger end = new AtomicInteger(n / decreaser.get());\n AtomicReference<List<String>> atomicInp = new AtomicReference<>(inp);\n AtomicReference<StringBuffer> running = new AtomicReference<>(new StringBuffer());\n if (possibleThreads == 0) {\n end.set(n);\n Runnable runnable =\n (() -> {\n AtomicBoolean isFirst = new AtomicBoolean(true);\n for (; start.get() < end.get(); start.getAndIncrement()) {\n if (!isFirst.get()) {\n running.get().append(connective);\n }\n running.get().append(atomicInp.get().get(start.get()));\n isFirst.set(false);\n }\n });\n threads[threadIdx] = new Thread(runnable);\n } else {\n for (int i = 0; i < availableProcessors; i++) {\n Runnable runnable =\n (() -> {\n AtomicBoolean isFirst = new AtomicBoolean(true);\n for (; start.get() < end.get(); start.getAndIncrement()) {\n if (!isFirst.get()) {\n running.get().append(connective);\n }\n running.get().append(atomicInp.get().get(start.get()));\n isFirst.set(false);\n }\n });\n // update start, end\n start.set(end.get());\n end.set(n / decreaser.getAndDecrement());\n if (start.get() >= end.get()) {\n break;\n }\n threads[threadIdx++] = new Thread(runnable);\n }\n }\n ThreadUtils.executeAndJoinAll(threads);\n\n return running.get().toString();\n }\n\n public static String bulkCascadeRemoveSuffixedString(\n String inp, char suffix, Character... patternSplitterTeller) {\n final List<Character> teller = Arrays.asList(patternSplitterTeller);\n StringBuilder partitionCollector = new StringBuilder();\n StringBuilder removed = new StringBuilder();\n for (int i = 0, n = inp.length(); i < n; i++) {\n Character cur = inp.charAt(i);\n if (!teller.contains(cur)) {\n partitionCollector.append(cur);\n continue;\n }\n Character connective = cur;\n if (i == n - 1) {\n if (partitionCollector.length() > 0) {\n removed.append(cascadeRemoveSuffixedString(partitionCollector.toString(), suffix));\n }\n removed.append(connective);\n break;\n }\n removed.append(cascadeRemoveSuffixedString(partitionCollector.toString(), suffix));\n if (Objects.nonNull(connective)) {\n removed.append(connective);\n }\n partitionCollector.setLength(0);\n }\n String finalSwticher =\n removed.length() == 0 ? partitionCollector.toString() : removed.toString();\n if (finalSwticher.contains(String.valueOf(suffix))) {\n finalSwticher = cascadeRemoveSuffixedString(finalSwticher, suffix);\n }\n return finalSwticher;\n }\n\n /**\n * Should be used when ony \" ONE pattern range \" is present. This method will work for only 1\n * self-contained pattern. not work for multiple pattern ranges.\n *\n * <p>A suffixed string is a pattern containing: a word followed by a character. for example,\n * these are suffixed strings: string = java.util.List suffixed strings : java., util.\n * non-suffixed : List\n *\n * @param inp\n * @return a string having its suffixed ones removed.\n * <p>input : java.util.List output : List\n */\n public static String cascadeRemoveSuffixedString(String inp, char suffix) {\n if (!inp.contains(String.valueOf(suffix))) {\n return inp;\n }\n int n = inp.length();\n int i = n - 1;\n int rightBound = StringUtils.lastIndexOf(inp, suffix, i, 1, null);\n int leftBound = StringUtils.lastIndexOf(inp, suffix, i, -1, null);\n /**\n * 2 cases for words preceding leftBound _ a whole removable string _ a partial removable string\n * ( blocked by other words ).\n */\n i = leftBound - 1;\n for (; i >= 0 && Character.isLetterOrDigit(inp.charAt(i)); i--) {\n }\n leftBound = i;\n\n return StringUtils.ripRangeFromString(inp, leftBound, rightBound);\n }\n\n public static String ripRangeFromString(String inp, int exceptFrom, int exceptTo) {\n StringBuilder ripped = new StringBuilder();\n for (int i = 0, n = inp.length(); i < n; i++) {\n /** Exclusive left bound Inclusive right bound. */\n if (i > exceptFrom && i <= exceptTo) {\n continue;\n }\n ripped.append(inp.charAt(i));\n }\n return ripped.toString();\n }\n\n public static boolean isPrefixedWith(String prefix, String content) {\n int n = content.length();\n StringBuilder revRunner = new StringBuilder();\n for (int i = n - 1; i >= 0; i--) {\n Character cur = content.charAt(i);\n if (Character.isLetter(cur)) {\n revRunner.append(cur);\n }\n if (revRunner.length() == prefix.length()) {\n return revRunner.reverse().toString().equalsIgnoreCase(prefix);\n }\n }\n return false;\n }\n\n public static int firstIdxOfNonAlphanumeric(String x) {\n for (int i = 0, n = x.length(); i < n; i++) {\n if (Character.isLetterOrDigit(x.charAt(i))) {\n continue;\n }\n return i;\n }\n return -1;\n }\n\n public static String buildAnnotationPackage(String unresolvedPackage, String annotation) {\n return (SPACE + unresolvedPackage + DOT + annotation + SEMICOLON).replace(AT, \"\");\n }\n\n /**\n * Will stop when reaching the last separator.\n *\n * @param inp\n * @param separator\n * @return\n */\n public static String getLastWord(String inp, String separator) {\n NullabilityUtils.isAllNonEmpty(true, inp, separator);\n StringBuilder rev = new StringBuilder();\n for (int n = inp.length(), i = n - 1; i >= 0; i--) {\n Character cur = inp.charAt(i);\n if (separator.equalsIgnoreCase(String.valueOf(cur))) {\n break;\n }\n rev.append(cur);\n }\n return rev.reverse().toString();\n }\n\n /**\n * Separated by each dot, ensure no more than 1 word contains >= 1 upper-case characters.\n *\n * @param inp\n * @return\n */\n public static String correctifyImportString(String inp, Character sep) {\n if (StringUtils.isEmpty(inp) || !inp.contains(String.valueOf(sep))) {\n return inp;\n }\n if (!MapUtils.isEmpty(rawImportToResovled) && rawImportToResovled.containsKey(inp)) {\n return rawImportToResovled.get(inp);\n }\n StringBuilder res = new StringBuilder();\n StringBuilder each = new StringBuilder();\n boolean isMetUppercase = false;\n for (int i = 0, n = inp.length(); i < n && !isMetUppercase; i++) {\n Character curr = inp.charAt(i);\n if (curr != sep) {\n each.append(curr);\n continue;\n }\n if (each.length() > 0 && !res.toString().contains(each)) {\n if (res.length() > 0) {\n res.append(sep);\n }\n res.append(each);\n if (!isAllLowerCase(each.toString())) {\n isMetUppercase = true;\n }\n }\n each.setLength(0);\n }\n if (each.length() > 0 && !res.toString().contains(each)) {\n res.append(sep).append(each);\n }\n /** Ok time to hack */\n String toPut = \"\";\n if (inp.charAt(0) == '.' || inp.charAt(inp.length() - 1) == '.') {\n final String rawText = stripDoubleEndedNonAlphaNumeric(inp);\n toPut = \"java.util.\" + rawText;\n }\n rawImportToResovled.put(inp, toPut);\n return rawImportToResovled.get(inp);\n }\n\n public static boolean bidirectionalContains(String x, String y) {\n return x.contains(y) || y.contains(x);\n }\n\n public static int firstIndexOf(String inp, char x, int start, boolean isBackward) {\n if (isBackward) {\n for (int i = start; i >= 0; i--) {\n if (x == inp.charAt(i)) {\n return i;\n }\n }\n } else {\n for (int i = start, n = inp.length(); i < n; i++) {\n if (x == inp.charAt(i)) {\n return i;\n }\n }\n }\n return -1;\n }\n\n /**\n * Space is handled by the caller.\n *\n * @param key\n * @param value\n * @param operator\n * @return\n */\n public static String formKeyValuePair(String key, String value, String operator) {\n NullabilityUtils.isAllNonEmpty(true, key, value, operator);\n return key + operator + value;\n }\n\n public static String findPrependablePieceFrom(\n String content, int backwardFrom, Character breakingChar, boolean isSkipSpace) {\n if (Objects.isNull(breakingChar)) {\n breakingChar = '\\r';\n }\n StringBuilder rev = new StringBuilder();\n for (int i = backwardFrom; i >= 0; i--) {\n Character c = content.charAt(i);\n if (String.valueOf(content.charAt(i)).equalsIgnoreCase(SINGLE_BREAK)\n || content.charAt(i) == breakingChar) {\n break;\n }\n if (isSkipSpace && !Character.isLetterOrDigit(c)) {\n continue;\n }\n rev.append(c);\n }\n return rev.reverse().toString();\n }\n\n /**\n * @param c must be alphanumeric.\n * @param isRebounce use 0 as index.\n * @return\n */\n public static int asciiValueOf(char c, boolean isRebounce) {\n int asciiVal;\n if (!isRebounce || !Character.isLetter(c)) {\n return c;\n }\n if (Character.isLowerCase(c)) {\n asciiVal = c - 97;\n } else {\n asciiVal = c - 65;\n }\n return asciiVal;\n }\n\n /**\n * If existing ctor body covers all serializable fieldStrings.\n *\n * @param body\n * @return\n */\n public static boolean containsAllFields(String body, List<DecorationLocalField> scope) {\n AtomicBoolean atomicBoolean = new AtomicBoolean(true);\n Collections.synchronizedList(scope).parallelStream()\n .forEach(\n field -> {\n if (!atomicBoolean.get()) {\n return;\n }\n if (!field.getFieldName().contains(WEIRD_FIELD)\n && !body.contains(field.getFieldName())) {\n atomicBoolean.set(false);\n return;\n }\n });\n return atomicBoolean.get();\n }\n\n public static String extractLastSubStrAfter(char x, String inp, boolean isReversed) {\n try {\n StringBuilder sb = new StringBuilder();\n int n = inp.length();\n for (int i = n - 1; i >= 0; i--) {\n char curr = inp.charAt(i);\n if (x == curr) {\n break;\n }\n sb.append(curr);\n }\n if (isReversed) {\n return sb.reverse().toString();\n }\n return sb.toString();\n } catch (Exception exception) {\n throw new RuntimeException(exception);\n }\n }\n\n public static List<String> reduceToOnlyLastSubStrAfter(\n char x, List<String> input, boolean isModifiable) {\n List<String> res = new ArrayList<>();\n for (int idx = 0, n = input.size(); idx < n; idx++) {\n final String substringed = extractLastSubStrAfter(x, input.get(idx), true);\n if (!isModifiable) {\n res.add(substringed);\n } else {\n input.set(idx, substringed);\n }\n }\n if (CollectionUtils.isNotEmpty(res)) {\n return res;\n }\n return input;\n }\n\n public static boolean containsAllStrings(String body, List<String> scope) {\n AtomicBoolean atomicBoolean = new AtomicBoolean(true);\n Collections.synchronizedList(scope).parallelStream()\n .forEach(\n field -> {\n if (!atomicBoolean.get()) {\n return;\n }\n if (!field.contains(WEIRD_FIELD) && !body.contains(field)) {\n atomicBoolean.set(false);\n return;\n }\n });\n return atomicBoolean.get();\n }\n\n /**\n * Supports upper/lower-cased alphanumeric letters.\n *\n * @param x\n * @param y\n * @return\n */\n public static boolean isAnagram(String x, String y) {\n /** Set A = {Aa-Zz + 0 -> 9} -> nO of chars = 62 */\n int[] map1 = new int[62];\n int[] map2 = new int[62];\n Arrays.fill(map1, 0);\n Arrays.fill(map2, 0);\n int i = 0;\n int n = x.length();\n int m = y.length();\n for (; i < n && i < m; i++) {\n char c1 = x.charAt(i);\n char c2 = y.charAt(i);\n if (Character.isLetterOrDigit(c1)) {\n map1[asciiValueOf(c1, Boolean.TRUE)]++;\n }\n if (Character.isLetterOrDigit(c2)) {\n map2[asciiValueOf(c2, Boolean.TRUE)]++;\n }\n }\n\n for (; i < n; i++) {\n char c1 = x.charAt(i);\n if (Character.isLetterOrDigit(c1)) {\n map1[asciiValueOf(c1, Boolean.TRUE)]++;\n }\n }\n\n for (; i < m; i++) {\n char c2 = y.charAt(i);\n if (Character.isLetterOrDigit(c2)) {\n map2[asciiValueOf(c2, Boolean.TRUE)]++;\n }\n }\n\n /** Verify */\n for (int r = 0; r < 62; r++) {\n if (map1[r] == map2[r]) {\n continue;\n }\n return false;\n }\n return true;\n }\n\n /**\n * We only consume letter / digit character, except given characters. This will apply\n * #stripDoubleEndedNonAlphaNumeric's logic, and also ensure each pair of consecutive characters\n * are only one-spaced separated.\n *\n * @param inp\n * @return\n */\n public static String ensureOneWhitespace(String inp, Set<Character> consumable) {\n if (StringUtils.isEmpty(inp) || StringUtils.isBlank(inp)) {\n return \"\";\n }\n if (Objects.isNull(consumable)) {\n consumable = new HashSet<>();\n }\n inp = stripDoubleEndedNonAlphaNumeric(inp);\n StringBuilder runner = new StringBuilder();\n boolean isMetSpace = false;\n for (int i = 0, n = inp.length(); i < n; i++) {\n Character c = inp.charAt(i);\n if (Character.isLetterOrDigit(c) || consumable.contains(c)) {\n runner.append(c);\n isMetSpace = false;\n continue;\n }\n if (Character.isSpaceChar(c)) {\n if (i > 0 && !isMetSpace && runner.length() > 0) {\n runner.append(c);\n isMetSpace = true;\n }\n }\n }\n return runner.toString();\n }\n}"
},
{
"identifier": "DummyObject",
"path": "src/main/java/com/aggregated/inline_tests/intricate_tests/existing_ctor_test/fuzzy_class/DummyObject.java",
"snippet": "public class DummyObject {\n}"
},
{
"identifier": "DummyObject01",
"path": "src/main/java/com/aggregated/inline_tests/intricate_tests/existing_ctor_test/fuzzy_class/DummyObject01.java",
"snippet": "public class DummyObject01 {\n}"
},
{
"identifier": "DummyObject02",
"path": "src/main/java/com/aggregated/inline_tests/intricate_tests/existing_ctor_test/fuzzy_class/DummyObject02.java",
"snippet": "public class DummyObject02 {\n}"
},
{
"identifier": "HelloIImAnotherDummy",
"path": "src/main/java/com/aggregated/inline_tests/intricate_tests/existing_ctor_test/fuzzy_class/HelloIImAnotherDummy.java",
"snippet": "public class HelloIImAnotherDummy {\n}"
}
] | import com.aggregated.StringUtils;
import com.aggregated.inline_tests.intricate_tests.existing_ctor_test.fuzzy_class.DummyObject;
import com.aggregated.inline_tests.intricate_tests.existing_ctor_test.fuzzy_class.DummyObject01;
import com.aggregated.inline_tests.intricate_tests.existing_ctor_test.fuzzy_class.DummyObject02;
import com.aggregated.inline_tests.intricate_tests.existing_ctor_test.fuzzy_class.HelloIImAnotherDummy;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.SortedSet; | 6,447 | package com.aggregated.inline_tests.intricate_tests.existing_ctor_test.hierarchical_test;
public abstract class BaseClass<T> {
protected Integer x;
protected String text;
protected boolean y;
protected Map<String, Map<String, Map<SortedSet<Integer>, String>>> amIScary;
protected Map<String, Map<String, Map<SortedSet<Integer>, DummyObject02>>> amIScary02; | package com.aggregated.inline_tests.intricate_tests.existing_ctor_test.hierarchical_test;
public abstract class BaseClass<T> {
protected Integer x;
protected String text;
protected boolean y;
protected Map<String, Map<String, Map<SortedSet<Integer>, String>>> amIScary;
protected Map<String, Map<String, Map<SortedSet<Integer>, DummyObject02>>> amIScary02; | private DummyObject01 dummyObject01; | 2 | 2023-11-23 10:59:01+00:00 | 8k |
DewmithMihisara/car-rental-hibernate | src/main/java/lk/ijse/controller/RentFormController.java | [
{
"identifier": "BOFactory",
"path": "src/main/java/lk/ijse/bo/BOFactory.java",
"snippet": "public class BOFactory {\n private static BOFactory factory;\n private BOFactory(){}\n public static BOFactory getInstance(){\n return factory == null ? new BOFactory() : factory;\n }\n public enum BOTypes{\n CAR, CATEGORY, CUSTOMER, USER, RENT, ACTIVE_RENT\n }\n public <T extends SuperBO>T getBO(BOTypes types){\n switch (types){\n case CAR:\n return (T) new CarBOImpl();\n case CUSTOMER:\n return (T) new CustomerBOImpl();\n case CATEGORY:\n return (T) new CategoryBOImpl();\n case USER:\n return (T) new UserBOImpl();\n case RENT:\n return (T) new RentBOImpl();\n case ACTIVE_RENT:\n return (T) new ActiveRentBOImpl();\n default:\n return null;\n }\n }\n}"
},
{
"identifier": "CarBO",
"path": "src/main/java/lk/ijse/bo/custom/CarBO.java",
"snippet": "public interface CarBO extends SuperBO {\n List<CarDto> getAll();\n\n String getNewCarId();\n\n List<String> getCategories();\n\n boolean addCar(CarDto carDto);\n\n CarDto getCar(String text);\n\n boolean updateCar(CarDto carDto);\n\n boolean deleteCar(CarDto car);\n\n List<String> getIds();\n}"
},
{
"identifier": "CustomerBO",
"path": "src/main/java/lk/ijse/bo/custom/CustomerBO.java",
"snippet": "public interface CustomerBO extends SuperBO {\n List<CustomerDto> getAllCustomers();\n\n boolean saveCustomer(CustomerDto customerDto);\n\n String getNextId();\n\n CustomerDto getCustomer(String text);\n\n boolean updateCustomer(CustomerDto customerDto);\n\n boolean deleteCustomer(CustomerDto customerDto);\n\n List<String> getIds();\n}"
},
{
"identifier": "RentBO",
"path": "src/main/java/lk/ijse/bo/custom/RentBO.java",
"snippet": "public interface RentBO extends SuperBO {\n String getNewCarId();\n\n boolean placeRent(RentDto rentDto);\n\n RentDto getRent(String text);\n String closeRent(RentDto rentDto);\n}"
},
{
"identifier": "AlertTypes",
"path": "src/main/java/lk/ijse/controller/util/AlertTypes.java",
"snippet": "public enum AlertTypes {\n CONFORMATION, ERROR, WARNING, INFORMATION\n}"
},
{
"identifier": "PopUpAlerts",
"path": "src/main/java/lk/ijse/controller/util/PopUpAlerts.java",
"snippet": "public class PopUpAlerts {\n public static void popUps(AlertTypes alertTypes, String title, String test){\n Image img ;\n switch (alertTypes){\n case ERROR ->img=new Image(\"/img/alerts/close.png\");\n case WARNING -> img=new Image(\"/img/alerts/warning.png\");\n case INFORMATION -> img=new Image(\"/img/alerts/information-button.png\");\n case CONFORMATION -> img=new Image(\"/img/alerts/verified.png\");\n default -> throw new IllegalStateException(\"Unexpected value: \" + alertTypes);\n }\n Notifications notificationBuilder=Notifications.create()\n .title(title)\n .text(test)\n .graphic(new ImageView(img))\n .hideAfter(Duration.seconds(3))\n .position(Pos.CENTER_RIGHT)\n .onAction(new EventHandler<ActionEvent>() {\n @Override\n public void handle(ActionEvent actionEvent) {}\n });\n notificationBuilder.darkStyle();\n notificationBuilder.show();\n }\n}"
},
{
"identifier": "Validation",
"path": "src/main/java/lk/ijse/controller/util/Validation.java",
"snippet": "public class Validation {\n static Shake shake;\n public static boolean txtValidation(TextField txt, Line line) {\n if (txt.getText().matches(\"^$\")) {\n shakeLine(line);\n } else {\n defaultLine(line);\n return true;\n }\n return false;\n }\n public static boolean pwValidation(PasswordField pwTxt, Line line) {\n if (pwTxt.getText().matches(\"^$\")) {\n shakeLine(line);\n } else {\n defaultLine(line);\n return true;\n }\n return false;\n }\n public static boolean cNumValidation(TextField txt, Line line) {\n if (txt.getText().matches(\"[0-9+]+\")) {\n defaultLine(line);\n return true;\n } else {\n shakeLine(line);\n }\n return false;\n }\n public static boolean numberValidation(TextField txt, Line line) {\n if (txt.getText().matches(\"[0-9]+\")) {\n defaultLine(line);\n return true;\n } else {\n shakeLine(line);\n }\n return false;\n }\n public static boolean moneyValidation(TextField txt, Line line) {\n if (txt.getText().matches(\"\\\\d+(\\\\.\\\\d{1,2})?\")) {\n defaultLine(line);\n return true;\n } else {\n shakeLine(line);\n }\n return false;\n }\n public static void shakeLine(Line line){\n line.setStroke(Color.RED);\n shake=new Shake(line);\n shake.setOnFinished(actionEvent -> {\n defaultLine(line);\n });\n shake.play();\n }\n public static void defaultLine(Line line){\n line.setStroke(Color.BLACK);\n }\n\n public static boolean dateValidation(DatePicker date) {\n if (date.getValue()==null){\n shakeDate(date);\n }else {\n return true;\n }\n return false;\n }\n public static boolean comboValidation(ComboBox<String> idCmb) {\n if (idCmb.getValue() == null){\n shakeCmb(idCmb);\n }else {\n return true;\n }\n return false;\n }\n private static void shakeDate(DatePicker date) {\n date.setStyle(\n \"-fx-border-color: red; \" +\n \"-fx-border-width: 2px ;\" +\n \"-fx-background-color: tranceparent ;\" +\n \"-fx-text-fill : white;\"\n );\n shake=new Shake(date);\n shake.setOnFinished(actionEvent -> {\n defaultDate(date);\n });\n shake.play();\n }\n\n private static void defaultDate(DatePicker date) {\n date.setStyle(\n \"-fx-background-color:tranceparent; \" +\n \"-fx-text-fill: white\"\n );\n }\n private static void shakeCmb(ComboBox<String> idCmb) {\n idCmb.setStyle(\n \"-fx-border-color: red; \" +\n \"-fx-border-width: 2px ;\" +\n \"-fx-background-color: tranceparent ;\"\n );\n shake=new Shake(idCmb);\n shake.setOnFinished(actionEvent -> {\n defaultDate(idCmb);\n });\n shake.play();\n }\n private static void defaultDate(ComboBox<String> idCmb) {\n idCmb.setStyle(\n \"-fx-background-color:tranceparent; \"+\n \"-fx-border-color: black; \"+\n \"-fx-border-width: 2px ;\"\n );\n }\n}"
},
{
"identifier": "CarDto",
"path": "src/main/java/lk/ijse/dto/CarDto.java",
"snippet": "@AllArgsConstructor\n@NoArgsConstructor\n@Data\n\npublic class CarDto {\n\n private String id;\n private String number;\n private String brand;\n private String model;\n private Integer year;\n private Double rate;\n private String catId;\n private Boolean isRentable;\n private Double depositAmount;\n\n\n public CarDto(String number, String brand, String model, Integer year, Double rate, String catId) {\n this.number = number;\n this.brand = brand;\n this.model = model;\n this.year = year;\n this.rate = rate;\n this.catId = catId;\n }\n\n\n\n}"
},
{
"identifier": "CustomerDto",
"path": "src/main/java/lk/ijse/dto/CustomerDto.java",
"snippet": "@Data\n@AllArgsConstructor\n@NoArgsConstructor\n\npublic class CustomerDto {\n private String id;\n private String userName;\n private String email;\n private String firstName;\n private String lastName;\n private String street;\n private String city;\n private String district;\n private String postalCode;\n private String mobile;\n private LocalDate toReturn;\n\n public CustomerDto(String id,String userName, String email, String firstName, String lastName, String street, String city, String district, String postalCode, String mobile) {\n this.id = id;\n this.userName = userName;\n this.email = email;\n this.firstName = firstName;\n this.lastName = lastName;\n this.street = street;\n this.city = city;\n this.district = district;\n this.postalCode = postalCode;\n this.mobile = mobile;\n }\n}"
},
{
"identifier": "RentDto",
"path": "src/main/java/lk/ijse/dto/RentDto.java",
"snippet": "@AllArgsConstructor\n@NoArgsConstructor\n@Data\n\npublic class RentDto {\n\n private String id;\n private LocalDate rentDate;\n private LocalDate startDate;\n private LocalDate endDate;\n private Double advancePayment;\n private Double depositAmount;\n private String customerId;\n private String carCategory;\n private String carNumber;\n private Double rate;\n private Double total;\n private Boolean isActive;\n}"
},
{
"identifier": "RentTM",
"path": "src/main/java/lk/ijse/dto/tm/RentTM.java",
"snippet": "@AllArgsConstructor\n@NoArgsConstructor\n@Data\n\npublic class RentTM {\n private String rentId;\n private String cusName;\n private String carNumber;\n private String rate;\n private String nosDays;\n private String advance;\n private String deposit;\n private String totalAmount;\n private String balanceToPay;\n}"
}
] | import animatefx.animation.Shake;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.paint.Color;
import javafx.scene.shape.Line;
import javafx.util.Callback;
import lk.ijse.bo.BOFactory;
import lk.ijse.bo.custom.CarBO;
import lk.ijse.bo.custom.CustomerBO;
import lk.ijse.bo.custom.RentBO;
import lk.ijse.controller.util.AlertTypes;
import lk.ijse.controller.util.PopUpAlerts;
import lk.ijse.controller.util.Validation;
import lk.ijse.dto.CarDto;
import lk.ijse.dto.CustomerDto;
import lk.ijse.dto.RentDto;
import lk.ijse.dto.tm.RentTM;
import java.time.LocalDate;
import java.util.List; | 4,248 | stDt,
endDt,
Double.parseDouble(advance),
Double.parseDouble(depo),
cus,
car.getCatId(),
car.getNumber(),
car.getRate(),
car.getRate()*(stDt.toEpochDay()-endDt.toEpochDay()),
true
))){
PopUpAlerts.popUps(AlertTypes.CONFORMATION, "Rent", "CRent Placed Successfully!");
initUi();
setNull();
}else {
PopUpAlerts.popUps(AlertTypes.ERROR, "Rent", "Rent Not Placed!");
setNull();
}
}
void setNull(){
id=null;
advance=null;
depo=null;
cus=null;
carCmb=null;
stDt=null;
endDt=null;
}
@FXML
void stDateDatePickerOnAction(ActionEvent event) {
endDateDatePicker.setDisable(false);
setEndDate();
}
@FXML
void initialize(){
initUi();
setStartDate();
setValueFactory();
}
private void setStartDate() {
Callback<DatePicker, DateCell> callB = new Callback<DatePicker, DateCell>() {
@Override
public DateCell call(final DatePicker param) {
return new DateCell() {
@Override
public void updateItem(LocalDate item, boolean empty) {
super.updateItem(item, empty);
LocalDate today = LocalDate.now();
setDisable(empty || item.compareTo(today) < 0);
}
};
}
};
stDateDatePicker.setDayCellFactory(callB);
}
private void setEndDate() {
LocalDate startDate = stDateDatePicker.getValue();
if (startDate != null) {
endDateDatePicker.setDayCellFactory(picker -> new DateCell() {
@Override
public void updateItem(LocalDate item, boolean empty) {
super.updateItem(item, empty);
setDisable(item.isBefore(startDate) || item.isAfter(startDate.plusDays(29)));
}
});
}
}
private void loadCarIds() {
ObservableList<String> categories = FXCollections.observableArrayList();
categories.addAll(carBO.getIds());
carIdCmb.setItems(categories);
}
private void loadCusIds() {
ObservableList<String> categories = FXCollections.observableArrayList();
categories.addAll(customerBO.getIds());
CusIdCmb.setItems(categories);
}
private void initUi() {
stDateDatePicker.getEditor().clear();
endDateDatePicker.getEditor().clear();
AdvancedTxt.setText("");
carNoTxt1.setText("");
cusNameLbl.setText("");
availableLbl.setText("");
aligibleLbl.setText("");
loadCusIds();
loadCarIds();
carIdCmb.getSelectionModel().clearSelection();
CusIdCmb.getSelectionModel().clearSelection();
cusNameLbl.setVisible(false);
availableLbl.setVisible(false);
rentBtn.setDisable(true);
aligibleLbl.setVisible(false);
carNoTxt1.setDisable(true);
endDateDatePicker.setDisable(true);
addBtn.setDisable(false);
clearTable();
}
private void clearTable() {
try {
ObservableList<RentTM> dataList = newRentTbl.getItems();
dataList.clear();
} catch (Exception e) {
throw e;
}
}
private boolean validation() {
stDate=false;
endDate=false;
cusId=false;
carId=false;
advanced=false;
| package lk.ijse.controller;
public class RentFormController {
@FXML
private TextField AdvancedTxt;
@FXML
private ComboBox<String> CusIdCmb;
@FXML
private Line DepoLine;
@FXML
private Button addBtn;
@FXML
private TableColumn<?, ?> advancedClm;
@FXML
private Line advancedLine;
@FXML
private Label aligibleLbl;
@FXML
private Label availableLbl;
@FXML
private TableColumn<?, ?> balanceClm;
@FXML
private ComboBox<String> carIdCmb;
@FXML
private TableColumn<?, ?> carNoClm;
@FXML
private TextField carNoTxt1;
@FXML
private Label cusNameLbl;
@FXML
private TableColumn<?, ?> cusNameClm;
@FXML
private TableColumn<?, ?> depoClm;
@FXML
private DatePicker endDateDatePicker;
@FXML
private TableView<RentTM> newRentTbl;
@FXML
private TableColumn<?, ?> nosDaysClm;
@FXML
private TableColumn<?, ?> rateClm;
@FXML
private Button rentBtn;
@FXML
private DatePicker stDateDatePicker;
@FXML
private TableColumn<?, ?> ttlClm;
private final CarBO carBO = BOFactory.getInstance().getBO(BOFactory.BOTypes.CAR);
private final CustomerBO customerBO = BOFactory.getInstance().getBO(BOFactory.BOTypes.CUSTOMER);
private final RentBO rentBO = BOFactory.getInstance().getBO(BOFactory.BOTypes.RENT);
boolean stDate, endDate, cusId, carId, advanced;
String id, advance, depo, cus, carCmb;
LocalDate stDt, endDt;
{
id=null;
advance=null;
depo=null;
cus=null;
carCmb=null;
stDt=null;
endDt=null;
}
@FXML
void AdvancedTxtOnAction(ActionEvent event) {
addBtn.requestFocus();
}
@FXML
void CusIdCmbOnAction(ActionEvent event) {
CustomerDto customer=customerBO.getCustomer(CusIdCmb.getSelectionModel().getSelectedItem());
if (customer!=null){
cusNameLbl.setVisible(true);
cusNameLbl.setText(customer.getFirstName()+" "+customer.getLastName());
if (customer.getToReturn()==null){
aligibleLbl.setVisible(true);
aligibleLbl.setText("Yes");
}else {
aligibleLbl.setVisible(true);
aligibleLbl.setText("No");
}
}
}
@FXML
void addNewBtnOnAction(ActionEvent event) {
if (validation()){
if (isCanCus()){
if (isCanCar()){
if(advanceMatch()){
CarDto car=carBO.getCar(carIdCmb.getSelectionModel().getSelectedItem());
CustomerDto customer=customerBO.getCustomer(CusIdCmb.getSelectionModel().getSelectedItem());
long nosDates=endDateDatePicker.getValue().toEpochDay()-stDateDatePicker.getValue().toEpochDay();
double total=car.getRate()*nosDates;
id=rentBO.getNewCarId();
stDt=stDateDatePicker.getValue();
endDt=endDateDatePicker.getValue();
advance=AdvancedTxt.getText();
depo = carNoTxt1.getText();
cus = CusIdCmb.getSelectionModel().getSelectedItem();
carCmb = carIdCmb.getSelectionModel().getSelectedItem();
ObservableList<RentTM>observableList= FXCollections.observableArrayList();
observableList.add(new RentTM(
id,
customer.getFirstName() + " " + customer.getLastName(),
car.getNumber(),
String.valueOf(car.getRate()),
String.valueOf(nosDates),
AdvancedTxt.getText(),
carNoTxt1.getText(),
String.valueOf(total),
String .valueOf(total-Double.parseDouble(AdvancedTxt.getText()))
));
newRentTbl.setItems(observableList);
// initUi();
if (newRentTbl.getItems() != null && !newRentTbl.getItems().isEmpty()) {
rentBtn.setDisable(false);
addBtn.setDisable(true);
}
}
}
}
}
}
@FXML
void carIdCmbOnAction(ActionEvent event) {
CarDto car=carBO.getCar(carIdCmb.getSelectionModel().getSelectedItem());
if (car!=null){
if (car.getIsRentable()){
availableLbl.setVisible(true);
availableLbl.setText("Yes");
rentBtn.setDisable(false);
carNoTxt1.setText(car.getDepositAmount().toString());
}else {
availableLbl.setVisible(true);
availableLbl.setText("No");
rentBtn.setDisable(true);
}
}
}
@FXML
void endDateDatePickerOnAction(ActionEvent event) {
AdvancedTxt.requestFocus();
}
@FXML
void rentBtnOnAction(ActionEvent event) {
CarDto car=carBO.getCar(carCmb);
if (rentBO.placeRent(new RentDto(
id,
LocalDate.now(),
stDt,
endDt,
Double.parseDouble(advance),
Double.parseDouble(depo),
cus,
car.getCatId(),
car.getNumber(),
car.getRate(),
car.getRate()*(stDt.toEpochDay()-endDt.toEpochDay()),
true
))){
PopUpAlerts.popUps(AlertTypes.CONFORMATION, "Rent", "CRent Placed Successfully!");
initUi();
setNull();
}else {
PopUpAlerts.popUps(AlertTypes.ERROR, "Rent", "Rent Not Placed!");
setNull();
}
}
void setNull(){
id=null;
advance=null;
depo=null;
cus=null;
carCmb=null;
stDt=null;
endDt=null;
}
@FXML
void stDateDatePickerOnAction(ActionEvent event) {
endDateDatePicker.setDisable(false);
setEndDate();
}
@FXML
void initialize(){
initUi();
setStartDate();
setValueFactory();
}
private void setStartDate() {
Callback<DatePicker, DateCell> callB = new Callback<DatePicker, DateCell>() {
@Override
public DateCell call(final DatePicker param) {
return new DateCell() {
@Override
public void updateItem(LocalDate item, boolean empty) {
super.updateItem(item, empty);
LocalDate today = LocalDate.now();
setDisable(empty || item.compareTo(today) < 0);
}
};
}
};
stDateDatePicker.setDayCellFactory(callB);
}
private void setEndDate() {
LocalDate startDate = stDateDatePicker.getValue();
if (startDate != null) {
endDateDatePicker.setDayCellFactory(picker -> new DateCell() {
@Override
public void updateItem(LocalDate item, boolean empty) {
super.updateItem(item, empty);
setDisable(item.isBefore(startDate) || item.isAfter(startDate.plusDays(29)));
}
});
}
}
private void loadCarIds() {
ObservableList<String> categories = FXCollections.observableArrayList();
categories.addAll(carBO.getIds());
carIdCmb.setItems(categories);
}
private void loadCusIds() {
ObservableList<String> categories = FXCollections.observableArrayList();
categories.addAll(customerBO.getIds());
CusIdCmb.setItems(categories);
}
private void initUi() {
stDateDatePicker.getEditor().clear();
endDateDatePicker.getEditor().clear();
AdvancedTxt.setText("");
carNoTxt1.setText("");
cusNameLbl.setText("");
availableLbl.setText("");
aligibleLbl.setText("");
loadCusIds();
loadCarIds();
carIdCmb.getSelectionModel().clearSelection();
CusIdCmb.getSelectionModel().clearSelection();
cusNameLbl.setVisible(false);
availableLbl.setVisible(false);
rentBtn.setDisable(true);
aligibleLbl.setVisible(false);
carNoTxt1.setDisable(true);
endDateDatePicker.setDisable(true);
addBtn.setDisable(false);
clearTable();
}
private void clearTable() {
try {
ObservableList<RentTM> dataList = newRentTbl.getItems();
dataList.clear();
} catch (Exception e) {
throw e;
}
}
private boolean validation() {
stDate=false;
endDate=false;
cusId=false;
carId=false;
advanced=false;
| stDate= Validation.dateValidation(stDateDatePicker); | 6 | 2023-11-27 17:28:48+00:00 | 8k |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.